Skip to content

Heterogeneous household demand by utility and by elasticities

Hamill and Gilbert's heterogeneous households.

  • Class: HouseholdDemandSystem
  • Import: from skcomplex.systems.economics.markets import HouseholdDemandSystem
  • Field: economics/markets
  • Topics: demand, heterogeneity, agents, price elasticity, income distribution, discrete map
  • References:
    • Hamill and Gilbert 2016

Use this system

The block imports the class and simulates the system with its default parameters and its tuned run settings.

from skcomplex.systems.economics.markets import HouseholdDemandSystem

trajectory = HouseholdDemandSystem().prepare().simulate()

Parameters

The model parameters take these defaults, and set_params changes them.

Parameter Default
n_households 1000
demand 'cobb-douglas'
shares (0.15, 0.13, 0.12, 0.1, 0.08)
share_deviation 0.02
elasticities (-0.6, -0.6, -0.5, -0.4, -0.3)
elasticity_deviation 0.1
minimum 33.333333333333336
change 0.1
random_state 0
solver 'auto'
backend 'auto'

Tags

The system with its default parameters has these capability tags, which solvers and analyses check.

Tag Values
Time discrete
Space none
Laws update
Randomness deterministic
Domains real
Structure fixed

Class

The source of the class shows how it builds its components from its model parameters.

class HouseholdDemandSystem(BaseSystem):
    """Hamill and Gilbert's heterogeneous households.

    Their demand for food traces a curve as its price rises. Every household has a budget drawn from an exponential law
    shifted right by a minimum and normalized to a mean of 100, which gives a Gini coefficient of about a third and a
    P90/P10 ratio just over 4, and a budget share of food drawn around the mean of its budget quintile, from 15 percent
    for the poorest to 8 percent for the richest. Every step the price rises by the share `change`, from 1. With the
    Cobb-Douglas utility of Section 3.2 of Hamill and Gilbert (2016) the demand is `alpha m / p`, the own-price
    elasticity is -1, the expenditure stays the same, and the poorest lose the most utility. With the practical model of
    Section 3.3 the households also have own-price elasticities drawn around the means of their quintiles, from -0.6 to
    -0.3, so a price rise of 10 percent lowers the demand by about 4.4 percent and raises the expenditure by about 5.1
    percent, more for the richest.

    The system has the group `households` of the demands `households.demand`, the expenditures `households.expenditure`,
    the utilities `households.utility`, and the prices `households.price`. The observables of the system are
    `total_demand`, `total_expenditure`, and `mean_utility`.

    Args:
        n_households:
            The number of households.

        demand:
            `'cobb-douglas'` for the utility model, `'elasticity'` for the practical model.

        shares:
            The mean budget share of the good of every budget quintile, from the poorest.

        share_deviation:
            The standard deviation of the budget shares within a quintile.

        elasticities:
            The mean own-price elasticity of every budget quintile, from the poorest.

        elasticity_deviation:
            The standard deviation of the elasticities within a quintile.

        minimum:
            The shift of the exponential law of the budgets before normalization.

        change:
            The relative rise of the price every step.

        random_state:
            The seed or generator of the budgets, shares, and elasticities.

        label:
            The label of the system, which names it when it is nested in another one.

        solver:
            The solver of the problem, or `'auto'` for the one the system chooses.

        backend:
            The backend that evaluates the compiled functions, or `'auto'` for the one the system chooses.

    Examples:
        >>> from skcomplex.systems.economics.markets import HouseholdDemandSystem
        >>> HouseholdDemandSystem(10).prepare().system_.elements[0].size
        10
    """

    field = 'economics/markets'
    topics = ('demand', 'heterogeneity', 'agents', 'price elasticity', 'income distribution', 'discrete map')
    references = ('Hamill and Gilbert 2016',)
    until = 10
    observables = (
        Observable('total_demand', group='households', variable='demand', reduce='sum'),
        Observable('total_expenditure', group='households', variable='expenditure', reduce='sum'),
        Observable('mean_utility', group='households', variable='utility', reduce='mean'),
    )

    def __init__(
        self,
        n_households: int = 1000,
        *,
        demand: str = 'cobb-douglas',
        shares: Sequence[float] = FOOD_SHARES,
        share_deviation: float = 0.02,
        elasticities: Sequence[float] = FOOD_ELASTICITIES,
        elasticity_deviation: float = 0.1,
        minimum: float = 100 / 3,
        change: float = 0.1,
        random_state: int | np.random.Generator | None = 0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.n_households = n_households
        self.demand = demand
        self.shares = shares
        self.share_deviation = share_deviation
        self.elasticities = elasticities
        self.elasticity_deviation = elasticity_deviation
        self.minimum = minimum
        self.change = change
        self.random_state = random_state

    @staticmethod
    def _get_budgets(n_households: int, minimum: float, rng: np.random.Generator) -> Array:
        """Return budgets drawn from an exponential law shifted right by the minimum.

        They are normalized to a mean of 100.
        """
        draws = minimum + rng.exponential(1.0, n_households) * (100.0 - minimum)
        return draws * 100.0 / draws.mean()

    @staticmethod
    def _draw_by_quintile(budgets: Array, means: Sequence[float], deviation: float, rng: np.random.Generator) -> Array:
        """Return normal draws around the mean of the budget quintile of every household."""
        quintiles = np.minimum((np.argsort(np.argsort(budgets)) * 5) // len(budgets), 4)
        return np.asarray(means, dtype=float)[quintiles] + deviation * rng.normal(size=len(budgets))

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of the components built from the model parameters."""
        super()._prepare(context)
        rng = np.random.default_rng(self.random_state)
        budgets = self._get_budgets(self.n_households, self.minimum, rng)
        alphas = np.clip(self._draw_by_quintile(budgets, self.shares, self.share_deviation, rng), 0.0, 1.0)
        slopes = (
            self._draw_by_quintile(budgets, self.elasticities, self.elasticity_deviation, rng)
            if self.demand == 'elasticity'
            else -1.0
        )
        quantities = alphas * budgets
        households = BudgetHouseholdElement(
            'households',
            budget=budgets,
            alpha=alphas,
            elasticity=slopes,
            demand=quantities,
            expenditure=quantities,
            utility=quantities**alphas * (budgets - quantities) ** (1 - alphas),
            change=self.change,
            size=self.n_households,
        )
        demand = HouseholdDemandInteraction('demand', target='households', kind=self.demand)
        self.system_ = System(self.label, elements=[households], interactions=[demand])

Components

The system uses these element and interaction classes, each with its nearest class of the core.

Elements:

  • BudgetHouseholdElement, from Element

Interactions:

  • HouseholdDemandInteraction, from Interaction
class BudgetHouseholdElement(Element):
    """Household with a budget that buys a good at a rising price.

    `HouseholdDemandInteraction` raises the price and sets the demand, the expenditure, and the utility.

    Args:
        label:
            The label of the agent or group.

        demand:
            The demand for the good.

        expenditure:
            The expenditure on the good.

        utility:
            The Cobb-Douglas utility of the good and the composite good bought.

        price:
            The price of the good.

        budget:
            The budget of the household.

        alpha:
            The budget share of the good, the exponent of the Cobb-Douglas utility.

        elasticity:
            The own-price elasticity of the demand.

        change:
            The relative rise of the price every step.

        initial_price:
            The price at the start.

        size:
            The number of members, or `None` for one.

    Examples:
        >>> from skcomplex.systems.economics.markets import BudgetHouseholdElement
        >>> BudgetHouseholdElement('households', budget=[50.0, 150.0], size=2).size
        2
    """

    def __init__(
        self,
        label: str,
        *,
        demand: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
        expenditure: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
        utility: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
        price: Annotated[object, RealSet.open(0, oo)] = 1.0,
        budget: Annotated[object, RealSet.open(0, oo)] = 100.0,
        alpha: Annotated[object, RealSet.closed(0, 1)] = 0.1,
        elasticity: object = -1.0,
        change: Annotated[object, RealSet.open(-1, oo)] = 0.1,
        initial_price: Annotated[object, RealSet.open(0, oo)] = 1.0,
        size: int | None = None,
    ) -> None:
        super().__init__(label, size=size)
        self.demand = demand
        self.expenditure = expenditure
        self.utility = utility
        self.price = price
        self.budget = budget
        self.alpha = alpha
        self.elasticity = elasticity
        self.change = change
        self.initial_price = initial_price

class HouseholdDemandInteraction(Interaction):
    """Demand of households for a good whose price rises by a share every step.

    With the demand `'cobb-douglas'` the household maximizes `A^alpha B^(1 - alpha)` against a composite good `B` of
    price 1, so it buys `A = alpha m / p` and spends the share `alpha` of its budget `m` on the good. With the demand
    `'elasticity'` it spends the budget share `alpha` at the initial price `p0` and its demand changes with its
    own-price elasticity, `A = (alpha m / p0) (p / p0)^elasticity`. The demand, the expenditure, and the utility are at
    the new price.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the group of households.

        kind:
            The demand, `'cobb-douglas'` or `'elasticity'`.

    Raises:
        ValidationError:
            The demand is unknown, raised by `prepare`.

    Examples:
        >>> from skcomplex.systems.economics.markets import HouseholdDemandInteraction
        >>> HouseholdDemandInteraction('demand', target='households', kind='elasticity').kind
        'elasticity'
    """

    law_classes = (UpdateLaw,)

    def __init__(self, label: str, *, target: Role, kind: str = 'cobb-douglas') -> None:
        super().__init__(label)
        self.target = target
        self.kind = kind

    def get_demand(self, s: SimpleNamespace, price: Expression) -> Expression:
        """Return the demand of the household at a price.

        Args:
            s:
                The namespace of the household.

            price:
                The price.

        Returns:
            demand:
                The demand for the good.
        """
        if self.kind == 'cobb-douglas':
            return s.alpha * s.budget / price
        return s.alpha * s.budget / s.initial_price * (price / s.initial_price) ** s.elasticity

    def _check_arguments(self) -> None:
        """Raise an error for an argument the interaction cannot take.

        Raises:
            ValidationError:
                The demand is unknown.
        """
        super()._check_arguments()
        if self.kind not in DEMANDS:
            error_msg = f'The demand of {self.label!r} is {self.kind!r}. Use one of {DEMANDS}.'
            raise ValidationError(error_msg)

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the rise of the price and the demand, expenditure, and utility at the new price as the laws.

        Args:
            context:
                The namespace of the households.
        """
        super()._prepare(context)
        s = context.target
        price = s.price * (1 + s.change)
        demand = self.get_demand(s, price)
        rest = s.budget - price * demand
        self.laws_: list[BaseLaw] = [
            UpdateLaw(s.price, price),
            UpdateLaw(s.demand, demand),
            UpdateLaw(s.expenditure, price * demand),
            UpdateLaw(s.utility, demand**s.alpha * rest ** (1 - s.alpha)),
        ]

Equations

The equations are those that symbolic returns for the system with its default parameters.

households.demand[i]: demand_households(t + 1) == alpha_households*budget_households/((change_households + 1)*price_households(t))
households.expenditure[i]: expenditure_households(t + 1) == alpha_households*budget_households
households.utility[i]: utility_households(t + 1) == (-alpha_households*budget_households + budget_households)^(-alpha_households + 1)*(alpha_households*budget_households/((change_households + 1)*price_households(t)))^alpha_households
households.price[i]: price_households(t + 1) == (change_households + 1)*price_households(t)