Skip to content

Stock-flow consistent monetary economy

A stock-flow consistent economy.

  • Class: StockFlowConsistentEconomySystem
  • Import: from skcomplex.systems.economics.macroeconomics import StockFlowConsistentEconomySystem
  • Field: economics/macroeconomics
  • Topics: stocks and flows, stock-flow consistent, money, discrete map
  • References:
    • Godley and Lavoie 2007
    • Caiani et al. 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.macroeconomics import StockFlowConsistentEconomySystem

trajectory = StockFlowConsistentEconomySystem().prepare().simulate()

Parameters

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

Parameter Default
household_deposits 60.0
firm_deposits 20.0
bank_deposits 10.0
loans 50.0
sales 40.0
alpha_income 0.6
alpha_wealth 0.4
wage_share 0.7
interest 0.03
payout 0.5
distribution 0.3
credit 0.1
repayment 0.08
solver 'auto'
backend 'auto'

Tags

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

Tag Values
Time continuous
Space none
Laws rate, update
Randomness unknown
Domains real
Structure fixed

Class

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

class StockFlowConsistentEconomySystem(BaseSystem):
    """A stock-flow consistent economy.

    It is a closed circuit of money between households, firms, and a bank. Money is the deposits of the three sectors,
    tagged as the quantity `money`, and every transaction of a period is a flow, so each payment is one sector's outflow
    and another's inflow. Households consume a share `alpha_income` of their wages and a share `alpha_wealth` of their
    deposits, firms pay the wage share of last period's sales and the interest on their loans, and distribute a share of
    their deposits as profits, and the bank pays out a share of its funds as dividends. Lending creates money and
    repayment destroys it, the only flows with the environment, so the total money changes exactly by lending minus
    repayment, in the spirit of the systems of Godley and Lavoie (2007) and the balance sheets of Caiani et al. (2016).
    Loans approach `credit * sales / repayment` and sales settle where the stocks stop growing. The circuit moves the
    money of a period, and the interactions `loans` and `sales` set the loans and the sales of the firms.

    The system has the deposits `households.deposits`, `firms.deposits`, and `bank.deposits`, the loans `firms.loans`,
    the sales `firms.sales`, the flows `circuit.consumption`, `circuit.wages`, `circuit.interest`, `circuit.dividends`,
    and `circuit.profits` between the sectors, the flows `firms.lending` and `firms.repayments` with the environment,
    and the net money created `__boundary.money`.

    Args:
        household_deposits:
            The initial deposits of the households.

        firm_deposits:
            The initial deposits of the firms.

        bank_deposits:
            The initial own funds of the bank.

        loans:
            The initial loans of the firms.

        sales:
            The sales of the previous period.

        alpha_income:
            The propensity to consume out of wages.

        alpha_wealth:
            The propensity to consume out of deposits.

        wage_share:
            The share of sales paid as wages.

        interest:
            The interest rate on loans per period.

        payout:
            The share of the bank's funds paid out as dividends per period.

        distribution:
            The share of the firms' deposits distributed to households as profits per period.

        credit:
            The new loans per unit of sales.

        repayment:
            The share of loans repaid per period.

        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 Euler rule with a step of one period, so every flow moves
            the money of one period.

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

    Examples:
        >>> from skcomplex.systems.economics.macroeconomics import StockFlowConsistentEconomySystem
        >>> [element.label for element in StockFlowConsistentEconomySystem().prepare().system_.elements]
        ['households', 'firms', 'bank']
    """

    field = 'economics/macroeconomics'
    topics = ('stocks and flows', 'stock-flow consistent', 'money', 'discrete map')
    references = ('Godley and Lavoie 2007', 'Caiani et al. 2016')
    until = 100
    dt = 1

    def __init__(
        self,
        *,
        household_deposits: float = 60.0,
        firm_deposits: float = 20.0,
        bank_deposits: float = 10.0,
        loans: float = 50.0,
        sales: float = 40.0,
        alpha_income: float = 0.6,
        alpha_wealth: float = 0.4,
        wage_share: float = 0.7,
        interest: float = 0.03,
        payout: float = 0.5,
        distribution: float = 0.3,
        credit: float = 0.1,
        repayment: float = 0.08,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.household_deposits = household_deposits
        self.firm_deposits = firm_deposits
        self.bank_deposits = bank_deposits
        self.loans = loans
        self.sales = sales
        self.alpha_income = alpha_income
        self.alpha_wealth = alpha_wealth
        self.wage_share = wage_share
        self.interest = interest
        self.payout = payout
        self.distribution = distribution
        self.credit = credit
        self.repayment = repayment

    @staticmethod
    def _get_next_loans(s: SimpleNamespace) -> list[BaseLaw]:
        """Return the loans of the firms after a period.

        The new loans are added and the repayments taken.
        """
        firms, bank = s.target, s.bank
        return [
            UpdateLaw(
                firms.loans,
                firms.loans + CircuitInteraction._get_lending(firms, bank) - firms.repayment * firms.loans,
            ),
        ]

    @staticmethod
    def _get_next_sales(s: SimpleNamespace) -> list[BaseLaw]:
        """Return the sales of the firms of a period, the consumption of the households."""
        return [UpdateLaw(s.target.sales, CircuitInteraction._get_consumption(s.households, s.target))]

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of the components built from the model parameters."""
        super()._prepare(context)
        self.system_ = System(
            self.label,
            elements=[
                HouseholdsElement(
                    'households',
                    deposits=self.household_deposits,
                    alpha_income=self.alpha_income,
                    alpha_wealth=self.alpha_wealth,
                ),
                FirmsElement(
                    'firms',
                    deposits=self.firm_deposits,
                    loans=self.loans,
                    sales=self.sales,
                    wage_share=self.wage_share,
                    distribution=self.distribution,
                    repayment=self.repayment,
                ),
                MonetaryBankElement(
                    'bank',
                    deposits=self.bank_deposits,
                    interest=self.interest,
                    payout=self.payout,
                    credit=self.credit,
                ),
            ],
            interactions=[
                CircuitInteraction('circuit', households='households', firms='firms', bank='bank'),
                Interaction('loans', roles={'target': 'firms', 'bank': 'bank'}, laws=self._get_next_loans),
                Interaction('sales', roles={'target': 'firms', 'households': 'households'}, laws=self._get_next_sales),
            ],
            solver=EulerSolver(dt=1.0),
        )

Components

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

Elements:

Interactions:

  • CircuitInteraction, from Interaction
  • Interaction
class HouseholdsElement(Element):
    """Households sector, whose deposits are money.

    It consumes out of its wages and its deposits.

    Args:
        label:
            The label of the sector.

        deposits:
            The deposits of the households.

        alpha_income:
            The propensity to consume out of wages.

        alpha_wealth:
            The propensity to consume out of deposits.

    Examples:
        >>> from skcomplex.systems.economics.macroeconomics import HouseholdsElement
        >>> HouseholdsElement('households').deposits
        60.0
    """

    def __init__(
        self,
        label: str,
        *,
        deposits: Annotated[object, RealSet.closed_open(0, oo), Quantity('money')] = 60.0,
        alpha_income: Annotated[float, RealSet.closed_open(0, oo)] = 0.6,
        alpha_wealth: Annotated[float, RealSet.closed_open(0, oo)] = 0.4,
    ) -> None:
        super().__init__(label)
        self.deposits = deposits
        self.alpha_income = alpha_income
        self.alpha_wealth = alpha_wealth

class FirmsElement(Element):
    """Firms sector, with its deposits, its loans, and the sales of the last period.

    It pays wages and profits.

    Args:
        label:
            The label of the sector.

        deposits:
            The deposits of the firms, which are money.

        loans:
            The loans of the firms.

        sales:
            The sales of the last period.

        wage_share:
            The share of sales paid as wages.

        distribution:
            The share of the firms' deposits distributed as profits per period.

        repayment:
            The share of loans repaid per period.

    Examples:
        >>> from skcomplex.systems.economics.macroeconomics import FirmsElement
        >>> FirmsElement('firms').loans
        50.0
    """

    def __init__(
        self,
        label: str,
        *,
        deposits: Annotated[object, RealSet.closed_open(0, oo), Quantity('money')] = 20.0,
        loans: Annotated[object, RealSet.closed_open(0, oo)] = 50.0,
        sales: Annotated[object, RealSet.closed_open(0, oo)] = 40.0,
        wage_share: Annotated[float, RealSet.closed_open(0, oo)] = 0.7,
        distribution: Annotated[float, RealSet.closed_open(0, oo)] = 0.3,
        repayment: Annotated[float, RealSet.closed_open(0, oo)] = 0.08,
    ) -> None:
        super().__init__(label)
        self.deposits = deposits
        self.loans = loans
        self.sales = sales
        self.wage_share = wage_share
        self.distribution = distribution
        self.repayment = repayment

class MonetaryBankElement(Element):
    """Bank of a stock-flow consistent economy, whose own funds are money.

    It lends and charges interest.

    Args:
        label:
            The label of the bank.

        deposits:
            The own funds of the bank.

        interest:
            The interest rate on loans per period.

        payout:
            The share of the bank's funds paid out as dividends per period.

        credit:
            The new loans per unit of sales.

    Examples:
        >>> from skcomplex.systems.economics.macroeconomics import MonetaryBankElement
        >>> MonetaryBankElement('bank').deposits
        10.0
    """

    def __init__(
        self,
        label: str,
        *,
        deposits: Annotated[object, RealSet.closed_open(0, oo), Quantity('money')] = 10.0,
        interest: Annotated[float, RealSet.closed_open(0, oo)] = 0.03,
        payout: Annotated[float, RealSet.closed_open(0, oo)] = 0.5,
        credit: Annotated[float, RealSet.closed_open(0, oo)] = 0.1,
    ) -> None:
        super().__init__(label)
        self.deposits = deposits
        self.interest = interest
        self.payout = payout
        self.credit = credit

class CircuitInteraction(Interaction):
    """Circuit of money between households, firms, and a bank, one period per step.

    The flows of a period between the deposits of the sectors are consumption, wages, interest, dividends, and profits,
    lending from the environment, and repayments to it, each reading the parameters of the sectors. Every flow is
    labelled, so the trajectory records it.

    Args:
        label:
            The label of the circuit.

        households:
            The path of the households.

        firms:
            The path of the firms.

        bank:
            The path of the bank.

    Examples:
        >>> from skcomplex.systems.economics.macroeconomics import CircuitInteraction
        >>> CircuitInteraction('circuit', households='households', firms='firms', bank='bank').bank
        'bank'
    """

    law_classes = (RateLaw,)

    def __init__(self, label: str, *, households: Role, firms: Role, bank: Role) -> None:
        super().__init__(label)
        self.households = households
        self.firms = firms
        self.bank = bank

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the flows of a period between the deposits of the sectors as the laws.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        households, firms, bank = context.households, context.firms, context.bank
        flows = [
            (
                {households.deposits: -1, firms.deposits: +1},
                self._get_consumption(households, firms),
                'consumption',
            ),
            ({firms.deposits: -1, households.deposits: +1}, firms.wage_share * firms.sales, 'wages'),
            ({firms.deposits: -1, bank.deposits: +1}, bank.interest * firms.loans, 'interest'),
            ({bank.deposits: -1, households.deposits: +1}, bank.payout * bank.deposits, 'dividends'),
            ({firms.deposits: -1, households.deposits: +1}, firms.distribution * firms.deposits, 'profits'),
            ({firms.deposits: +1}, self._get_lending(firms, bank), 'lending'),
            ({firms.deposits: -1}, firms.repayment * firms.loans, 'repayments'),
        ]
        self.laws_: list[BaseLaw] = [RateLaw(target, amount, label=flow) for target, amount, flow in flows]

    @staticmethod
    def _get_consumption(households: SimpleNamespace, firms: SimpleNamespace) -> Expression:
        """Return the consumption of a period.

        It is a share of the wages and a share of the deposits of the households.
        """
        return households.alpha_income * firms.wage_share * firms.sales + households.alpha_wealth * households.deposits

    @staticmethod
    def _get_lending(firms: SimpleNamespace, bank: SimpleNamespace) -> Expression:
        """Return the new loans of a period, in proportion to the sales of the firms."""
        return bank.credit * firms.sales

class Interaction(BaseInteraction):
    """An interaction whose laws run once for the elements its roles bind.

    It states the laws that change the values of the elements its roles bind, such as gravity on a ball in
    `Interaction('gravity', roles={'target': 'ball'}, laws=lambda s: [RateLaw(s.target.x.diff(s.t, 2), -9.81)])`. When a
    role binds a group, the laws run once for every member, as arrays. With `among` and `along`, they run once for every
    edge of a network and read `s.source` and `s.target`, the members at its two ends, or once for every hyperedge or
    random small group and read `s.member`, `s.others`, and `s.members`. With `within`, they run once for every pair of
    members closer than a radius and read `s.first` and `s.second`. A subclass takes its roles, typed `Role`, and its
    parameters as arguments of its `__init__` and sets `laws_` in its `_prepare`. It states predation between two
    populations, a reaction between two chemicals, and an infection along the contacts of a network.

    Read more in the user guide, under Interactions.

    Args:
        label:
            The name of the interaction, unique among the components of its system, such as `'predation'`.

        roles:
            The element each role binds, by the name of the role, such as `{'target': 'ball'}`, for a rule written
            without a class, or `None`.

        laws:
            The function of the namespace that returns the laws of a rule written without a class, such as
            `lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`, the laws themselves when they read no element, or
            `None`.

        among:
            The group whose members sit at the ends of the edges, such as `'people'`, or `None` to bind elements by
            their roles only. A subclass annotates it as a role, and a rule written without a class binds it as one.

        along:
            `True` for the edges of the network the group lives on, the name of a layer of a network with several, such
            as `'contacts'`, `'hyperedges'` for its hyperedges, `('hyperedges', k)` for its hyperedges of `k` members,
            `RandomPartition(k)` for random groups of `k` members drawn at every step, `'neighborhoods'` for every
            member with the members around it, or `None` for no edges. On the edges, the laws read the member of an
            element that sits on them as `s.edge`, and on the hyperedges as `s.hyperedge`.

        within:
            A `RadiusNeighborhood(r)` for laws that run once for every pair of members of the roles `first` and `second`
            closer than `r`, which read `s.first` and `s.second` and give the laws of both, such as the repulsion of
            walkers of two crowds, or `None` for no pairs. With `among`, both members come from that group. The laws may
            give the energy of the pair as `ObjectiveLaw(V)` in place of its forces, and each member then feels the
            force `-dV/dx` on its position `x`.

    See Also:
        BaseInteraction: The base of every interaction.
        RandomPartition: Groups the members of a group at random at every step.
        TrainingInteraction: Trains the parameters of a nested system.

    Examples:
        >>> from skcomplex.core.components.interactions import Interaction
        >>> from skcomplex.core.components.laws import RateLaw
        >>> birth = Interaction('birth', roles={'target': 'fish'}, laws=lambda s: [RateLaw(s.target.n.diff(s.t), 1)])
        >>> birth.roles
        {'target': 'fish'}
    """

    def __init__(
        self,
        label: str,
        *,
        roles: Mapping[str, object] | None = None,
        laws: Callable[[SimpleNamespace], Sequence[BaseLaw]] | Sequence[BaseLaw] | None = None,
        among: str | None = None,
        along: bool | str | tuple[str, int] | RandomPartition | None = None,
        within: RadiusNeighborhood | None = None,
    ) -> None:
        super().__init__(label)
        self.roles = roles
        self.laws = laws
        self.among = among
        self.along = along
        self.within = within

    def _get_declared(self) -> Mapping[str, _DeclaredVariableSpec]:
        """Return the numeric arguments as parameters, and `roles` and `among` as roles.

        With `within`, `among` binds both members of a pair, `first` and `second`.
        """
        declared = dict(super()._get_declared())
        for name, binding in (self.roles or {}).items():
            declared[name] = _DeclaredVariableSpec(binding, RoleSpec())
        if self.among is not None and self.within is not None:
            for name in PAIR_ROLES:
                declared.setdefault(name, _DeclaredVariableSpec(self.among, RoleSpec()))
        elif self.among is not None and 'among' not in declared and 'among' not in self._get_specs():
            declared['among'] = _DeclaredVariableSpec(self.among, RoleSpec())
        return declared

    @classmethod
    def _get_state_arguments(cls, role: RoleSpec) -> tuple[str, ...]:
        """Return the arguments that name the states a role reads.

        The mapping `roles` of bindings names none.
        """
        return tuple(name for name in super()._get_state_arguments(role) if name != 'roles')

    def _get_binding(self, role: str) -> object:
        """Return what a role binds, from `roles` or from the argument of its name.

        Args:
            role:
                The name of the role.

        Returns:
            binding:
                The label, labels, or entries the role binds, or `None` when it binds nothing.
        """
        if self.roles is not None and role in self.roles:
            return self.roles[role]
        if self.among is not None and self.within is not None and role in PAIR_ROLES:
            return self.among
        return super()._get_binding(role)

    def _check_arguments(self) -> None:
        """Raise an error for roles, laws, or groups the interaction cannot take.

        Raises:
            ValidationError:
                A role of `roles` takes the name of an argument, `laws` is neither a function nor a list of laws, or
                `along` names hyperedges of fewer than two members.
        """
        clashes = sorted(set(self.roles or {}) & {'label', 'roles', 'laws', 'among', 'along'})
        if clashes:
            error_msg = f'The role {clashes[0]!r} of {self.label!r} takes the name of an argument. Rename the role.'
            raise ValidationError(error_msg)
        if self.laws is not None and not callable(self.laws) and not isinstance(self.laws, list | tuple):
            error_msg = (
                f'The laws of {self.label!r} are {self.laws!r}. Give a function that takes the bound elements as '
                '`s` and returns the laws, such as `laws=lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`.'
            )
            raise ValidationError(error_msg)
        if isinstance(self.along, tuple) and not self._is_sized(self.along):
            error_msg = (
                f'{self.label!r} runs along {self.along!r}. Give the hyperedges of one size as a whole number of 2 or '
                "more, such as `along=('hyperedges', 3)`."
            )
            raise ValidationError(error_msg)
        if isinstance(self.along, RandomPartition):
            self.along._check()
        grouped = isinstance(self.along, RandomPartition) or self.along == NEIGHBORHOODS
        if grouped and self.among is None:
            error_msg = f'{self.label!r} runs along groups of members. Name their group with `among`.'
            raise ValidationError(error_msg)
        super()._check_arguments()

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the laws of `laws` for a binding.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        if self.laws is not None:
            self.laws_ = list(self.laws(context) if callable(self.laws) else self.laws)

    @staticmethod
    def _is_sized(along: tuple[object, ...]) -> bool:
        """Return whether `along` names hyperedges of a whole size of at least two."""
        if len(along) != MIN_SIZE or along[0] != HYPEREDGES:
            return False
        size = along[1]
        return isinstance(size, int) and not isinstance(size, bool) and size >= MIN_SIZE

    def _get_draws(self) -> bool:
        """Return whether the interaction draws, as it does along random groups."""
        return super()._get_draws() or isinstance(self.along, RandomPartition)

    def _runs_on_edges(self) -> bool:
        """Return whether the interaction runs along edges."""
        grouped = self._runs_on_hyperedges() or self._get_grouping() is not None
        return self.along is not None and self.along is not False and not grouped

    def _runs_on_hyperedges(self) -> bool:
        """Return whether the interaction runs along the hyperedges of a network."""
        return self.along == HYPEREDGES or (isinstance(self.along, tuple) and self.along[0] == HYPEREDGES)

    def _get_hyperedge_size(self) -> int | None:
        """Return the size `along` gives the hyperedges, or `None` for every size."""
        return int(self.along[-1]) if isinstance(self.along, tuple) and self._runs_on_hyperedges() else None

    def _get_within(self) -> RadiusNeighborhood | None:
        """Return the neighbourhood of the pairs the laws run for, or `None` for no pairs."""
        return self.within

    def _get_layer(self) -> str | None:
        """Return the layer `along` names, or `None` for no layer."""
        if not isinstance(self.along, str) or self.along == NEIGHBORHOODS or self._runs_on_hyperedges():
            return None
        return self.along

    def _get_grouping(self) -> tuple[str, int, str] | None:
        """Return the kind, size, and reduction of the groups `along` names, or `None`."""
        if isinstance(self.along, RandomPartition):
            return ('partition', self.along.size, 'sum')
        if self.along == NEIGHBORHOODS:
            return ('neighborhood', 0, 'sum')
        return None

Equations

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

households.deposits: diff(deposits_households(t), t) == -alpha_income_households*wage_share_firms*sales_firms(t) + payout_bank*deposits_bank(t) + distribution_firms*deposits_firms(t) - alpha_wealth_households*deposits_households(t) + wage_share_firms*sales_firms(t)
firms.deposits: diff(deposits_firms(t), t) == alpha_income_households*wage_share_firms*sales_firms(t) - distribution_firms*deposits_firms(t) + alpha_wealth_households*deposits_households(t) - interest_bank*loans_firms(t) - repayment_firms*loans_firms(t) + credit_bank*sales_firms(t) - wage_share_firms*sales_firms(t)
firms.loans: diff(loans_firms(t), t) == 0
firms.sales: diff(sales_firms(t), t) == 0
bank.deposits: diff(deposits_bank(t), t) == -payout_bank*deposits_bank(t) + interest_bank*loans_firms(t)