Skip to content

Markets

Markets: prices, competition, retail, inventories, queues, and barter.

The barter is of Cobb-Douglas traders on trade networks.

AdaptiveAuctionInteraction(label, *, rule=None, phase=None, buyers, sellers, step=1.0, unlimited=False)

Bases: PolicyRuleInteraction[SystemView]

Double auction in which every buyer meets a random seller every iteration.

Both adapt their quotes. Every iteration the buyers that still want units, in random order, meet a random seller that still holds units. When the bid reaches the ask, one unit trades at the ask, and afterwards the buyer lowers its bid and the seller raises its ask, to push the price their way. When it does not, the buyer raises its bid and the seller lowers its ask, to create trade, each change a uniform draw between 0 and step. Bids never exceed the values and asks never fall below the costs. With unlimited units, traders are resupplied and keep consuming, so trade goes on forever.

Parameters:

Name Type Description Default
label str

The label of the auction.

required
rule None

Unused, since the auction overrides act.

None
phase str | None

The phase the auction acts in, or None for the default phase.

None
buyers Role

The path of the group of buyers.

required
sellers Role

The path of the group of sellers.

required
step Annotated[float, open(0, oo)]

The change of a quote after a meeting.

1.0
unlimited bool

Whether the units of the traders never run out.

False

Examples:

>>> from skcomplex.systems.economics.markets import AdaptiveAuctionInteraction
>>> AdaptiveAuctionInteraction('auction', buyers='buyers', sellers='sellers').reports
('price', 'volume', 'mean_bid', 'mean_ask')
Source code in src/skcomplex/systems/economics/markets/_adaptive_auction.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def __init__(
    self,
    label: str,
    *,
    rule: None = None,
    phase: str | None = None,
    buyers: Role,
    sellers: Role,
    step: Annotated[float, RealSet.open(0, oo)] = 1.0,
    unlimited: bool = False,
) -> None:
    super().__init__(label, rule=rule, phase=phase)
    self.buyers = buyers
    self.sellers = sellers
    self.step = step
    self.unlimited = unlimited

act(system)

Run the meetings of one iteration.

Parameters:

Name Type Description Default
system SystemView

The system view of the auction.

required
Source code in src/skcomplex/systems/economics/markets/_adaptive_auction.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
def act(self, system: SystemView) -> None:
    """Run the meetings of one iteration.

    Args:
        system:
            The system view of the auction.
    """
    rng, step = system.rng, system.get_parameter('step')
    buyers = sorted(cast(list[AdaptiveTraderView], system.get_agents('buyers')), key=lambda trader: trader.id)
    sellers = sorted(cast(list[AdaptiveTraderView], system.get_agents('sellers')), key=lambda trader: trader.id)
    prices = []
    for buyer in (buyers[index] for index in rng.permutation(len(buyers))):
        stocked = [seller for seller in sellers if seller.units > 0]
        if buyer.units <= 0 or not stocked:
            continue
        seller = stocked[int(rng.integers(len(stocked)))]
        bid_step, ask_step = step * rng.random(), step * rng.random()
        if buyer.quote >= seller.quote:
            prices.append(seller.quote)
            if not self.unlimited:
                buyer.units, seller.units = buyer.units - 1, seller.units - 1
            buyer.quote = max(buyer.quote - bid_step, 0.0)
            seller.quote += ask_step
        else:
            buyer.quote = min(buyer.quote + bid_step, buyer.value)
            seller.quote = max(seller.quote - ask_step, seller.value)
    last = system.get_history('price', 1)
    price = prices[-1] if prices else (float(last[-1]) if len(last) else float('nan'))
    system.report('price', price)
    system.report('volume', float(len(prices)))
    system.report('mean_bid', float(np.mean([buyer.quote for buyer in buyers])))
    system.report('mean_ask', float(np.mean([seller.quote for seller in sellers])))

AdaptiveTraderElement(label, *, value=0.0, quote=0.0, units=5.0, size=None)

Bases: Element

Buyer or seller of a double auction.

It holds its value or cost, its current bid or ask, and its units left.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
value Annotated[object, closed_open(0, oo)]

The value of a unit to a buyer, or its cost to a seller.

0.0
quote Annotated[object, closed_open(0, oo)]

The current bid of a buyer or ask of a seller.

0.0
units Annotated[object, closed_open(0, oo)]

The units a buyer still wants or a seller still holds.

5.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.markets import AdaptiveTraderElement
>>> AdaptiveTraderElement('buyers', value=120.0, size=3).size
3
Source code in src/skcomplex/systems/economics/markets/_adaptive_auction.py
66
67
68
69
70
71
72
73
74
75
76
77
78
def __init__(
    self,
    label: str,
    *,
    value: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    quote: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    units: Annotated[object, RealSet.closed_open(0, oo)] = 5.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.value = value
    self.quote = quote
    self.units = units

AuctionLedgerInteraction(label, *, rule=None, phase=None)

Bases: PolicyRuleInteraction[SystemView]

Ledger that closes every trading period.

It measures its surplus and gives every trader a new unit. The realised surplus is the value of the units bought minus the cost of the units sold, and the allocative efficiency is its ratio to the maximum surplus of the supply and demand schedules.

Parameters:

Name Type Description Default
label str

The label of the ledger.

required
phase str | None

The phase the ledger acts in.

None

Examples:

>>> from skcomplex.systems.economics.markets import AuctionLedgerInteraction
>>> AuctionLedgerInteraction('ledger', phase='close').reports
('surplus', 'efficiency')
Source code in src/skcomplex/systems/economics/common/policy/_policy_rule.py
47
48
49
50
51
52
53
54
55
56
def __init__(
    self,
    label: str,
    *,
    rule: Callable[[SystemT], None] | None = None,
    phase: str | None = None,
) -> None:
    super().__init__(label)
    self.rule = rule
    self.phase = phase

act(system)

Report the surplus and the efficiency of the trading period.

It then opens the next one.

Parameters:

Name Type Description Default
system SystemView

The system view scoped to the ledger.

required
Source code in src/skcomplex/systems/economics/markets/_double_auction.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
def act(self, system: SystemView) -> None:
    """Report the surplus and the efficiency of the trading period.

    It then opens the next one.

    Args:
        system:
            The system view scoped to the ledger.
    """
    buyers = cast(list[ZeroIntelligenceBuyerView], system.get_agents('buyers'))
    sellers = cast(list[ZeroIntelligenceSellerView], system.get_agents('sellers'))
    values = np.array([buyer.value for buyer in buyers])
    costs = np.array([seller.value for seller in sellers])
    bought = np.array([buyer.demand <= 0 for buyer in buyers])
    sold = np.array([seller.supply <= 0 for seller in sellers])
    surplus = float(values[bought].sum() - costs[sold].sum())
    system.report('surplus', surplus)
    system.report('efficiency', surplus / maximum_surplus(values, costs))
    for buyer in buyers:
        buyer.demand = 1.0
    for seller in sellers:
        seller.supply = 1.0

BarterSystem(n_barterers=2, *, chocolate=(9.0, 1.0), cigarettes=(2.0, 8.0), weights=(0.6, 0.3), quantity=0.02, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Barter of chocolate and cigarettes.

It happens in an Edgeworth box of two barterers or among many prisoners. Every step the barterers are paired at random, and every pair trades small quantities of one good for the other at the geometric mean of their marginal rates of substitution while both gain, so the totals of both goods are unchanged. Two barterers with the given endowments and weights of chocolate trade within the Edgeworth box until no trade improves both, which is a point of the contract curve, where their marginal rates of substitution are equal. More barterers are prisoners of war who receive random Red Cross parcels and random tastes, and their trades settle on a common price, as Radford (1945) observed (Hamill and Gilbert 2016 ch. 5).

The system has the group barterers and the exchange exchange, whose reporters are the price of cigarettes in chocolate exchange.price, its exchange.dispersion, and exchange.volume.

Parameters:

Name Type Description Default
n_barterers int

The number of barterers, 2 for the Edgeworth box.

2
chocolate tuple[float, float]

The chocolate of the two barterers of the Edgeworth box, and the range of the parcels of more barterers.

(9.0, 1.0)
cigarettes tuple[float, float]

The cigarettes of the two barterers of the Edgeworth box, and the range of the parcels of more barterers.

(2.0, 8.0)
weights tuple[float, float]

The weights of chocolate of the two barterers of the Edgeworth box, and the range of the weights of more barterers.

(0.6, 0.3)
quantity float

The quantity of the bought good in every trade.

0.02
random_state int | Generator | None

The seed or generator of the parcels and the weights of more than two barterers.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Raises:

Type Description
ValueError

There are fewer than two barterers.

Examples:

>>> from skcomplex.systems.economics.markets import BarterSystem
>>> BarterSystem().prepare().system_.elements[0].size
2
Source code in src/skcomplex/systems/economics/markets/_barter.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def __init__(
    self,
    n_barterers: int = 2,
    *,
    chocolate: tuple[float, float] = (9.0, 1.0),
    cigarettes: tuple[float, float] = (2.0, 8.0),
    weights: tuple[float, float] = (0.6, 0.3),
    quantity: float = 0.02,
    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_barterers = n_barterers
    self.chocolate = chocolate
    self.cigarettes = cigarettes
    self.weights = weights
    self.quantity = quantity
    self.random_state = random_state

BarterTraderElement(label, *, good1=10.0, good2=10.0, mrs=1.0, links=0.0, partners=math.inf, values=None, size=None, space=None)

Bases: Element

Trader with a bundle of two goods and the Cobb-Douglas utility good1 good2.

It records its rate. Its marginal rate of substitution good2 / good1 is the price of the first good, in units of the second, at which it is indifferent to trade. Every step it records the rate of its current bundle.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
good1 Annotated[object, open(0, oo)]

The holding of the first good.

10.0
good2 Annotated[object, open(0, oo)]

The holding of the second good.

10.0
mrs Annotated[object, open(0, oo)]

The marginal rate of substitution of the bundle.

1.0
links Annotated[object, NN]

The number of trading partners the trader can search.

0.0
partners object

The number of partners that can match with the trader in a step, without limit.

inf
values Mapping[str, object] | None

Further values by name, such as the node of every member.

None
size int | None

The number of members, or None for one.

None
space BaseSpace | None

The network whose nodes hold the members, or None for none.

None

Examples:

>>> from skcomplex.systems.economics.markets import BarterTraderElement
>>> BarterTraderElement('traders', size=4).size
4
Source code in src/skcomplex/systems/economics/markets/_barter_networks.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def __init__(
    self,
    label: str,
    *,
    good1: Annotated[object, RealSet.open(0, oo)] = 10.0,
    good2: Annotated[object, RealSet.open(0, oo)] = 10.0,
    mrs: Annotated[object, RealSet.open(0, oo)] = 1.0,
    links: Annotated[object, NN] = 0.0,
    partners: object = math.inf,
    values: Mapping[str, object] | None = None,
    size: int | None = None,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, values=values, size=size, space=space)
    self.good1 = good1
    self.good2 = good2
    self.mrs = mrs
    self.links = links
    self.partners = partners

get_rate_gap(trader, other) staticmethod

Return the gap between the logarithms of the rates of substitution.

The rates are those of a trader and a trading partner. The gap is minus infinity for a trader that is not a partner, so a trader takes a partner whenever it has one.

Parameters:

Name Type Description Default
trader object

The trader that searches.

required
other object

Another trader.

required

Returns:

Name Type Description
gap float

The absolute difference of the logarithms of the two rates.

Source code in src/skcomplex/systems/economics/markets/_barter_networks.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
@staticmethod
def get_rate_gap(trader: object, other: object) -> float:
    """Return the gap between the logarithms of the rates of substitution.

    The rates are those of a trader and a trading partner. The gap is minus infinity for a trader that is not a
    partner, so a trader takes a partner whenever it has one.

    Args:
        trader:
            The trader that searches.

        other:
            Another trader.

    Returns:
        gap:
            The absolute difference of the logarithms of the two rates.
    """
    if not BarterTraderElement.is_partner(trader, other):
        return -math.inf
    if not isinstance(trader, BarterTraderView) or not isinstance(other, BarterTraderView):
        return -math.inf
    return abs(math.log(other.good2 / other.good1) - math.log(trader.good2 / trader.good1))

is_partner(trader, other) staticmethod

Return whether another trader is a trading partner of a trader.

A partner is a neighbour on the trade network.

Parameters:

Name Type Description Default
trader object

The trader that searches.

required
other object

Another trader.

required

Returns:

Name Type Description
partner bool

Whether the other trader is in a node next to the trader's node.

Source code in src/skcomplex/systems/economics/markets/_barter_networks.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
@staticmethod
def is_partner(trader: object, other: object) -> bool:
    """Return whether another trader is a trading partner of a trader.

    A partner is a neighbour on the trade network.

    Args:
        trader:
            The trader that searches.

        other:
            Another trader.

    Returns:
        partner:
            Whether the other trader is in a node next to the trader's node.
    """
    if not isinstance(trader, BarterTraderView) or not isinstance(other, BarterTraderView):
        return False
    return other.id != trader.id and other.location in trader.get_neighbor_cells()

BartererElement(label, *, chocolate=5.0, cigarettes=5.0, chocolate_weight=0.5, cigarettes_weight=0.5, size=None)

Bases: Element

Barterer who holds chocolate and cigarettes.

It values them with Cobb-Douglas weights.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
chocolate Annotated[object, closed_open(0, oo)]

The holding of chocolate.

5.0
cigarettes Annotated[object, closed_open(0, oo)]

The holding of cigarettes.

5.0
chocolate_weight Annotated[object, closed_open(0, oo)]

The Cobb-Douglas weight of chocolate.

0.5
cigarettes_weight Annotated[object, closed_open(0, oo)]

The Cobb-Douglas weight of cigarettes.

0.5
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.markets import BartererElement
>>> BartererElement('barterers', chocolate=[8.0, 2.0], size=2).size
2
Source code in src/skcomplex/systems/economics/markets/_barter.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def __init__(
    self,
    label: str,
    *,
    chocolate: Annotated[object, RealSet.closed_open(0, oo)] = 5.0,
    cigarettes: Annotated[object, RealSet.closed_open(0, oo)] = 5.0,
    chocolate_weight: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
    cigarettes_weight: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.chocolate = chocolate
    self.cigarettes = cigarettes
    self.chocolate_weight = chocolate_weight
    self.cigarettes_weight = cigarettes_weight

BeerGameSystem(inventory=12.0, *, demand=4.0, demand_step=4.0, step_time=5.0, theta=0.36, alpha=0.26, beta=0.34, dispatch_time=1.0, mail_delay=2.0, shipping_delay=2.0, production_delay=3.0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Sterman's beer distribution game.

Its orders swing wider at every echelon upstream. A retailer, a wholesaler, a distributor, and a factory each hold an inventory of beer and a backlog of orders waiting to ship. Each ships its backlog over the dispatch time, limited by its inventory, and the beer reaches the next echelon downstream after the shipping delay. Orders reach the next echelon upstream after the mail delay, and the factory brews its orders over the production delay. Customer demand steps from 4 to 8 cases a week in week 5. Every echelon orders by Sterman's anchoring and adjustment rule, its expected demand plus alpha times the gap between its desired stock S' and its effective inventory, the inventory less the backlog, plus beta times its supply line, the beer it ordered and has not received. The expected demand adapts to incoming orders at the rate theta. The defaults of theta, alpha, and beta are the median estimates of Sterman 1989, and S' is set so the chain starts in equilibrium at 4 cases a week. The game is weekly and its delays are fixed, while this system is a continuous approximation in which third-order delays stand in for the fixed ones. The amplitude of the orders grows from the retailer to the factory, the bullwhip effect.

The system has the stocks <echelon>.inventory, <echelon>.in_transit, <echelon>.backlog, <echelon>.expected, and <echelon>.supply_line of the echelons retailer, wholesaler, distributor, and factory, and the flows <upstream>_to_<downstream>.shipments between the echelons, <downstream>.arrivals at every echelon a link supplies, retailer.sales, and factory.starts and factory.completions. The interactions <echelon>_shipping ship the backlog of every echelon and decay its expectation, the rates <echelon>_backlog and <echelon>_expected add the orders that reach every echelon and adapt its expectation, and the rates <echelon>_supply_line keep its supply line. The observables of the system are the orders <echelon>.orders and the shipments <echelon>.shipments of every echelon, and the orders of the customers customers.orders.

Parameters:

Name Type Description Default
inventory float

The initial inventory of every echelon, in cases.

12.0
demand float

The customer demand, in cases a week.

4.0
demand_step float

The permanent change of the customer demand.

4.0
step_time float

The week of the change of the customer demand.

5.0
theta float

The rate at which the expected demand adapts to incoming orders.

0.36
alpha float

The fraction of the stock gap ordered per week.

0.26
beta float

The weight of the supply line in the stock gap.

0.34
dispatch_time float

The time over which an echelon ships its backlog.

1.0
mail_delay float

The average time an order takes to reach the next echelon upstream.

2.0
shipping_delay float

The average time a shipment takes to reach the next echelon downstream.

2.0
production_delay float

The average time the factory takes to brew its orders.

3.0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.economics.markets import BeerGameSystem
>>> [element.label for element in BeerGameSystem().prepare().system_.elements]
['retailer', 'wholesaler', 'distributor', 'factory']
Source code in src/skcomplex/systems/economics/markets/_supply_chains.py
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
def __init__(
    self,
    inventory: float = 12.0,
    *,
    demand: float = 4.0,
    demand_step: float = 4.0,
    step_time: float = 5.0,
    theta: float = 0.36,
    alpha: float = 0.26,
    beta: float = 0.34,
    dispatch_time: float = 1.0,
    mail_delay: float = 2.0,
    shipping_delay: float = 2.0,
    production_delay: float = 3.0,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.inventory = inventory
    self.demand = demand
    self.demand_step = demand_step
    self.step_time = step_time
    self.theta = theta
    self.alpha = alpha
    self.beta = beta
    self.dispatch_time = dispatch_time
    self.mail_delay = mail_delay
    self.shipping_delay = shipping_delay
    self.production_delay = production_delay

BilateralBarterInteraction(label, *, requesters, providers, rule=RandomSearchSpec(), reserve='reserve', quantity='quantity', cap='cap', transfers=(), phase=None, on_match=None, units=100)

Bases: MatchingInteraction[SystemView]

Barter in which every trader trades with the neighbour it matched.

A greedy matching pairs every trader, in random order, with the neighbour whose marginal rate of substitution differs the most in logarithm, and a neighbour takes any number of partners. The score of a trader that is not a neighbour is minus infinity, and a trader without neighbours trades with no one. Each pair trades single units of the first good at the price (g2 + g2') / (g1 + g1') of their pooled bundles, which lies between their rates, while the trade raises the utility of both. Besides the reporters of a matching, the reporters trades and searches count the units traded and the neighbours searched in a step.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
requesters Role

The path of the group of traders that search for a partner.

required
providers Role

The path of the group of traders that can be found, the same group.

required
rule MatchingRule

The spec of the algorithm that pairs the traders, such as PartnerMatchingSpec('local', value='provider').

RandomSearchSpec()
reserve str | tuple[str, str]

The state with the reserve value of both sides, missing for traders, which then accept any partner.

'reserve'
quantity str | tuple[str, str]

The states of the partners a requester wants and a provider takes, one and without limit for traders.

'quantity'
cap str

The state of a requester with the most value it can give, missing for traders.

'cap'
transfers Sequence[tuple[str, int]]

The states every match moves, none for traders, whose trades move the goods.

()
phase str | None

The phase the barter runs in, or None for the default phase.

None
on_match Callable[[MatchSpec, SystemView], None] | None

A function of every match and the system view, run after the trade, or None.

None
units Annotated[int, NN]

The most units one pair trades in a step.

100

Examples:

>>> from skcomplex.systems.economics.markets import BilateralBarterInteraction
>>> BilateralBarterInteraction('barter', requesters='traders', providers='traders').units
100
Source code in src/skcomplex/systems/economics/markets/_barter_networks.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def __init__(
    self,
    label: str,
    *,
    requesters: Role,
    providers: Role,
    rule: MatchingRule = RandomSearchSpec(),
    reserve: str | tuple[str, str] = 'reserve',
    quantity: str | tuple[str, str] = 'quantity',
    cap: str = 'cap',
    transfers: Sequence[tuple[str, int]] = (),
    phase: str | None = None,
    on_match: Callable[[MatchSpec, SystemView], None] | None = None,
    units: Annotated[int, NN] = 100,
) -> None:
    super().__init__(
        label,
        requesters=requesters,
        providers=providers,
        rule=rule,
        reserve=reserve,
        quantity=quantity,
        cap=cap,
        transfers=transfers,
        phase=phase,
        on_match=on_match,
    )
    self.units = units

match(system)

Pair and trade, and report the units traded and the neighbours searched.

The report comes besides the matching reporters.

Parameters:

Name Type Description Default
system SystemView

The system view of the interaction.

required
Source code in src/skcomplex/systems/economics/markets/_barter_networks.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
def match(self, system: SystemView) -> None:
    """Pair and trade, and report the units traded and the neighbours searched.

    The report comes besides the matching reporters.

    Args:
        system:
            The system view of the interaction.
    """
    system.storage['trades'] = 0.0
    super().match(system)
    system.report('trades', self._get_trades(system))
    traders = cast(list[BarterTraderView], system.get_agents('requesters'))
    system.report('searches', float(sum(trader.links for trader in traders)))

BreweryInteraction(label, *, factory)

Bases: Interaction

Brewery of a supply chain.

It brews the orders of the factory over its production delay. The brewing is a flow starts into the beer in production at the factory and a flow completions on to its inventory.

Parameters:

Name Type Description Default
label str

The label of the brewery.

required
factory Role

The path of the factory.

required

Examples:

>>> from skcomplex.systems.economics.markets import BreweryInteraction
>>> BreweryInteraction('brewery', factory='factory').factory
'factory'
Source code in src/skcomplex/systems/economics/markets/_supply_chains.py
374
375
376
377
378
379
380
381
def __init__(
    self,
    label: str,
    *,
    factory: Role,
) -> None:
    super().__init__(label)
    self.factory = factory

BrockHommesSystem(n_traders=1000, *, intensity=1.0, rate=1.1, strength=1.2, cost=1.0, risk=1.0, noise=0.01, initial=0.1, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Brock and Hommes' asset market.

Traders switch between fundamentalists and trend chasers. Every step the traders score every heuristic by its last realised fitness and choose a heuristic by a logit choice of intensity beta on its last realised fitness, and the market maker clears the deviation of the price from the fundamental at R x_t = sum_h n_h f_h. The fundamental steady state is stable while the share of trend chasers there, 1 / (1 + exp(-beta C)), is below R / g, and beyond the critical intensity beta* = ln(R / (g - R)) / C the price fluctuates persistently around the fundamental.

The system has the group traders, their scores learning and choice choice, and the institution pricing, whose reporters are the deviation of the price pricing.deviation, the share of trend chasers pricing.trend_share, and the fitnesses pricing.fitness_fundamentalist and pricing.fitness_trend.

Parameters:

Name Type Description Default
n_traders int

The number of traders.

1000
intensity float

The intensity of choice beta.

1.0
rate float

The gross return R of the riskless asset.

1.1
strength float

The extrapolation g of the trend chasers.

1.2
cost float

The cost C of the fundamentalist heuristic.

1.0
risk float

The risk aversion times the variance of returns, a sigma^2.

1.0
noise float

The standard deviation of the noise of the price.

0.01
initial float

The initial deviation of the price from its fundamental value.

0.1
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.economics.markets import BrockHommesSystem
>>> BrockHommesSystem(100).prepare().system_.elements[0].size
100
Source code in src/skcomplex/systems/economics/markets/_brock_hommes.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
def __init__(
    self,
    n_traders: int = 1000,
    *,
    intensity: float = 1.0,
    rate: float = 1.1,
    strength: float = 1.2,
    cost: float = 1.0,
    risk: float = 1.0,
    noise: float = 0.01,
    initial: float = 0.1,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.n_traders = n_traders
    self.intensity = intensity
    self.rate = rate
    self.strength = strength
    self.cost = cost
    self.risk = risk
    self.noise = noise
    self.initial = initial

BudgetHouseholdElement(label, *, demand=0.0, expenditure=0.0, utility=0.0, price=1.0, budget=100.0, alpha=0.1, elasticity=-1.0, change=0.1, initial_price=1.0, size=None)

Bases: 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.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
demand Annotated[object, closed_open(0, oo)]

The demand for the good.

0.0
expenditure Annotated[object, closed_open(0, oo)]

The expenditure on the good.

0.0
utility Annotated[object, closed_open(0, oo)]

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

0.0
price Annotated[object, open(0, oo)]

The price of the good.

1.0
budget Annotated[object, open(0, oo)]

The budget of the household.

100.0
alpha Annotated[object, closed(0, 1)]

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

0.1
elasticity object

The own-price elasticity of the demand.

-1.0
change Annotated[object, open(-1, oo)]

The relative rise of the price every step.

0.1
initial_price Annotated[object, open(0, oo)]

The price at the start.

1.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.markets import BudgetHouseholdElement
>>> BudgetHouseholdElement('households', budget=[50.0, 150.0], size=2).size
2
Source code in src/skcomplex/systems/economics/markets/_household_demand.py
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
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

CarDealerSystem(inventory=200.0, *, demand=20.0, demand_step=2.0, step_time=25.0, coverage=10.0, perception_delay=5.0, response_delay=3.0, delivery_delay=5.0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Meadows' car dealership.

Its inventory oscillates after a step in demand because of its delays. The inventory is a stock of cars that deliveries from the factory fill and sales to customers drain. Sales are the customer demand, limited by the cars on the lot. The dealer smooths sales over the perception delay, wants an inventory of coverage days of perceived sales, and orders the perceived sales plus the gap to that inventory divided by the response delay. Orders arrive through a third-order material delay, a continuous stand-in for Meadows' fixed delivery delay. Lengthening the response delay damps the oscillation, while shortening the perception delay makes the dealer react faster to the new demand and slightly enlarges it.

The system has the cars on the lot dealer.inventory, and the flows dealer.deliveries and dealer.sales. The observables of the system are dealer.perceived for the perceived sales, dealer.desired_inventory, and dealer.orders.

Parameters:

Name Type Description Default
inventory float

The initial number of cars on the lot.

200.0
demand float

The customer demand in cars per day.

20.0
demand_step float

The permanent change of the demand.

2.0
step_time float

The day of the change of the demand.

25.0
coverage float

The days of perceived sales the dealer wants on the lot.

10.0
perception_delay float

The time over which the dealer averages sales.

5.0
response_delay float

The time over which the dealer closes the inventory gap.

3.0
delivery_delay float

The average time between an order and its delivery.

5.0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.economics.markets import CarDealerSystem
>>> CarDealerSystem(response_delay=6.0).prepare().system_.elements[0].response_delay
6.0
Source code in src/skcomplex/systems/economics/markets/_inventory.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def __init__(
    self,
    inventory: float = 200.0,
    *,
    demand: float = 20.0,
    demand_step: float = 2.0,
    step_time: float = 25.0,
    coverage: float = 10.0,
    perception_delay: float = 5.0,
    response_delay: float = 3.0,
    delivery_delay: float = 5.0,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.inventory = inventory
    self.demand = demand
    self.demand_step = demand_step
    self.step_time = step_time
    self.coverage = coverage
    self.perception_delay = perception_delay
    self.response_delay = response_delay
    self.delivery_delay = delivery_delay

CarDealershipElement(label, *, inventory=200.0, demand=20.0, demand_step=2.0, step_time=25.0, coverage=10.0, perception_delay=5.0, response_delay=3.0, delivery_delay=5.0)

Bases: Element

Car dealership whose inventory deliveries fill and sales drain.

Its orders close the gap to a desired coverage. Sales are the demand, stepping up at step_time, limited by the inventory. The dealer perceives sales through a first-order smoothing, desires coverage days of perceived sales, and orders the perceived sales plus the gap to the desired inventory over the response delay, never negative. Orders arrive through a third-order delay. The dealership holds the inventory and the parameters, and the flows of deliveries and sales of the system move the cars.

Parameters:

Name Type Description Default
label str

The label of the dealership.

required
inventory Annotated[float, closed_open(0, oo), Quantity(cars)]

The initial number of cars on the lot.

200.0
demand Annotated[float, closed_open(0, oo)]

The customer demand in cars per day.

20.0
demand_step float

The permanent change of the demand.

2.0
step_time Annotated[float, closed_open(0, oo)]

The day of the change of the demand.

25.0
coverage Annotated[float, open(0, oo)]

The days of perceived sales the dealer wants on the lot.

10.0
perception_delay Annotated[float, open(0, oo)]

The time over which the dealer averages sales.

5.0
response_delay Annotated[float, open(0, oo)]

The time over which the dealer closes the inventory gap.

3.0
delivery_delay Annotated[float, open(0, oo)]

The average time between an order and its delivery.

5.0

Examples:

>>> from skcomplex.systems.economics.markets import CarDealershipElement
>>> CarDealershipElement('dealer', inventory=150.0).inventory
150.0
Source code in src/skcomplex/systems/economics/markets/_inventory.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def __init__(
    self,
    label: str,
    *,
    inventory: Annotated[float, RealSet.closed_open(0, oo), Quantity('cars')] = 200.0,
    demand: Annotated[float, RealSet.closed_open(0, oo)] = 20.0,
    demand_step: float = 2.0,
    step_time: Annotated[float, RealSet.closed_open(0, oo)] = 25.0,
    coverage: Annotated[float, RealSet.open(0, oo)] = 10.0,
    perception_delay: Annotated[float, RealSet.open(0, oo)] = 5.0,
    response_delay: Annotated[float, RealSet.open(0, oo)] = 3.0,
    delivery_delay: Annotated[float, RealSet.open(0, oo)] = 5.0,
) -> None:
    super().__init__(label)
    self.inventory = inventory
    self.demand = demand
    self.demand_step = demand_step
    self.step_time = step_time
    self.coverage = coverage
    self.perception_delay = perception_delay
    self.response_delay = response_delay
    self.delivery_delay = delivery_delay

CarElement(label, *, stage=WASH, work=525.0, crew=0, size=None)

Bases: Element

Car at the wash, waiting for or receiving a wash or a valet.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
stage Annotated[object, NN]

0 for the wash and 1 for the valet.

WASH
work object

The person-seconds of work left at the current stage.

525.0
crew Annotated[object, NN]

The number of workers on the car in the current second.

0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.markets import CarElement
>>> CarElement('cars', size=1).size
1
Source code in src/skcomplex/systems/economics/markets/_queues.py
65
66
67
68
69
70
71
72
73
74
75
76
77
def __init__(
    self,
    label: str,
    *,
    stage: Annotated[object, NN] = WASH,
    work: object = 525.0,
    crew: Annotated[object, NN] = 0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.stage = stage
    self.work = work
    self.crew = crew

CarWashOperationInteraction(label, *, cars, till, p_pass=0.33, p_enter=0.005, p_valet=0.5, wash_work=525.0, valet_work=1750.0, wash_price=4.0, valet_price=10.0, balk=3.0)

Bases: Interaction

Arrival of passing cars, completion of washes and valets, and payment.

They happen once every second. A passing car turns in with a probability, unless the wash queue holds balk cars or more. A washed car stays for a valet with a probability, and pays the wash price or the valet price when it leaves.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
cars Role

The path of the group of cars.

required
till Role

The path of the group that holds the till.

required
p_pass Annotated[float, closed_open(0, oo)]

The probability that a car passes in a second.

0.33
p_enter Annotated[float, closed_open(0, oo)]

The probability that a passing car turns in.

0.005
p_valet Annotated[float, closed_open(0, oo)]

The probability that a washed car stays for a valet.

0.5
wash_work Annotated[float, open(0, oo)]

The person-seconds of a wash.

525.0
valet_work Annotated[float, open(0, oo)]

The person-seconds of a valet.

1750.0
wash_price Annotated[float, closed_open(0, oo)]

The price of a wash.

4.0
valet_price Annotated[float, closed_open(0, oo)]

The price of a wash with a valet.

10.0
balk Annotated[float, open(0, oo)]

The length of the wash queue at which drivers no longer turn in.

3.0

Examples:

>>> from skcomplex.systems.economics.markets import CarWashOperationInteraction
>>> CarWashOperationInteraction('wash', cars='cars', till='till', p_enter=0.01).p_enter
0.01
Source code in src/skcomplex/systems/economics/markets/_queues.py
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
def __init__(
    self,
    label: str,
    *,
    cars: Role,
    till: Role,
    p_pass: Annotated[float, RealSet.closed_open(0, oo)] = 0.33,
    p_enter: Annotated[float, RealSet.closed_open(0, oo)] = 0.005,
    p_valet: Annotated[float, RealSet.closed_open(0, oo)] = 0.5,
    wash_work: Annotated[float, RealSet.open(0, oo)] = 525.0,
    valet_work: Annotated[float, RealSet.open(0, oo)] = 1750.0,
    wash_price: Annotated[float, RealSet.closed_open(0, oo)] = 4.0,
    valet_price: Annotated[float, RealSet.closed_open(0, oo)] = 10.0,
    balk: Annotated[float, RealSet.open(0, oo)] = 3.0,
) -> None:
    super().__init__(label)
    self.cars = cars
    self.till = till
    self.p_pass = p_pass
    self.p_enter = p_enter
    self.p_valet = p_valet
    self.wash_work = wash_work
    self.valet_work = valet_work
    self.wash_price = wash_price
    self.valet_price = valet_price
    self.balk = balk

operate(system)

Finish the cars whose work is done and reset the crews.

Then a passing car turns in or drives on.

Parameters:

Name Type Description Default
system SystemView

The system.

required
Source code in src/skcomplex/systems/economics/markets/_queues.py
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
def operate(self, system: SystemView) -> None:
    """Finish the cars whose work is done and reset the crews.

    Then a passing car turns in or drives on.

    Args:
        system:
            The system.
    """
    values = {name: float(system.get_parameter(name)) for name in PARAMETERS}
    till = cast(list[TillView], system.get_agents('till'))[0]
    for car in cast(list[CarView], system.get_agents('cars')):
        car.crew = 0
        if car.work <= 0:
            self._finish(car, till, system, values)
    if system.rng.random() >= values['p_pass'] * values['p_enter']:
        return
    if sum(car.stage == WASH for car in cast(list[CarView], system.get_agents('cars'))) >= values['balk']:
        till.turned_away += 1
        return
    system.create('cars', stage=WASH, work=values['wash_work'])

CarWashSystem(n_workers=4, n_cars=1, *, p_pass=0.33, p_enter=0.005, p_valet=0.5, wash_work=525.0, valet_work=1750.0, wash_price=4.0, valet_price=10.0, balk=3, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Chesney's Clean and Wax hand car wash.

It is a shadow account of the revenue of its workers' labour. Every step is one second. Passing cars turn in with a probability and queue for the wash, washed cars may queue for a valet, and the workers serve the front car of each area, two at a time if they can. The wash opens with cars already queuing. The system has the groups workers, cars, and till.

Parameters:

Name Type Description Default
n_workers int

The number of workers.

4
n_cars int

The number of cars queuing for the wash at the start, at least one.

1
p_pass float

The probability that a car passes in a second.

0.33
p_enter float

The probability that a passing car turns in.

0.005
p_valet float

The probability that a washed car stays for a valet.

0.5
wash_work float

The person-seconds of a wash.

525.0
valet_work float

The person-seconds of a valet.

1750.0
wash_price float

The price of a wash.

4.0
valet_price float

The price of a wash with a valet.

10.0
balk int

The length of the wash queue at which drivers no longer turn in.

3
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.economics.markets import CarWashSystem
>>> CarWashSystem(5).prepare().system_.elements[0].size
5
Source code in src/skcomplex/systems/economics/markets/_queues.py
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
def __init__(
    self,
    n_workers: int = 4,
    n_cars: int = 1,
    *,
    p_pass: float = 0.33,
    p_enter: float = 0.005,
    p_valet: float = 0.5,
    wash_work: float = 525.0,
    valet_work: float = 1750.0,
    wash_price: float = 4.0,
    valet_price: float = 10.0,
    balk: int = 3,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.n_workers = n_workers
    self.n_cars = n_cars
    self.p_pass = p_pass
    self.p_enter = p_enter
    self.p_valet = p_valet
    self.wash_work = wash_work
    self.valet_work = valet_work
    self.wash_price = wash_price
    self.valet_price = valet_price
    self.balk = balk

CobwebInteraction(label, *, target='market', a=10.0, b=2.0, c=1.0, d=1.0)

Bases: Interaction

Cobweb system, where supply reacts to the previous price.

Demand clears the market. Demand is a - b * price and supply is c + d * previous price, so the next price is (a - c - d * price) / b, a map of the state price of the market.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the market.

'market'
a float

The demand intercept.

10.0
b Annotated[float, open(0, oo)]

The demand slope.

2.0
c float

The supply intercept.

1.0
d Annotated[float, open(0, oo)]

The supply slope.

1.0

Examples:

>>> from skcomplex.systems.economics.markets import CobwebInteraction
>>> CobwebInteraction('cobweb', target='wheat', a=10, b=2, c=1, d=1).b
2
Source code in src/skcomplex/systems/economics/markets/_cobweb.py
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def __init__(
    self,
    label: str,
    *,
    target: Role = 'market',
    a: float = 10.0,
    b: Annotated[float, RealSet.open(0, oo)] = 2.0,
    c: float = 1.0,
    d: Annotated[float, RealSet.open(0, oo)] = 1.0,
) -> None:
    super().__init__(label)
    self.target = target
    self.a = a
    self.b = b
    self.c = c
    self.d = d

CobwebSystem(price=1.0, *, a=10.0, b=2.0, c=1.0, d=1.0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

A market whose price converges to or oscillates around equilibrium.

Supply lags the price. The system has the market market.

Parameters:

Name Type Description Default
price float

The initial price.

1.0
a float

The demand intercept.

10.0
b float

The demand slope.

2.0
c float

The supply intercept.

1.0
d float

The supply slope.

1.0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.economics.markets import CobwebSystem
>>> CobwebSystem(price=2.0).prepare().simulate(until=2).get_values('market.price').tolist()
[2.0, 3.5, 2.75]
Source code in src/skcomplex/systems/economics/markets/_cobweb.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
def __init__(
    self,
    price: float = 1.0,
    *,
    a: float = 10.0,
    b: float = 2.0,
    c: float = 1.0,
    d: float = 1.0,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.price = price
    self.a = a
    self.b = b
    self.c = c
    self.d = d

CommodityCycleSystem(inventory=25.0, capacity=100.0, *, demand=100.0, demand_step=10.0, step_time=2.0, desired_coverage=0.25, reference_price=1.0, supply_elasticity=0.1, demand_elasticity=0.25, expectation_time=1.0, construction_delay=3.0, lifetime=15.0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

A commodity market whose price and capacity cycle.

New capacity arrives after a delay. The inventory is a stock of the commodity that production fills and consumption drains. The price is a falling table function of the inventory coverage, the years of demand the inventory holds, relative to the desired coverage. A high price raises the utilization of capacity and lowers consumption with constant elasticities. Producers form an expected price by smoothing the price, and order new capacity at the rate of retirements multiplied by a rising table function of the expected price. Orders become capacity through a third-order delay. After a step in demand the market overshoots, so the price and the capacity oscillate, the commodity cycle of Bala et al. Section 4.11.4. The book was not at hand, so the tables and the parameters are a documented reconstruction of that structure, in years and in units of the reference demand and price. The market starts in equilibrium.

The system has the inventory market.inventory and the capacity market.capacity in years, the flows market.production, market.consumption, market.completions, and market.retirements. The observables of the system are market.coverage, market.price, market.expected_price, and market.capacity_orders.

Parameters:

Name Type Description Default
inventory float

The initial inventory of the commodity.

25.0
capacity float

The initial production capacity per year.

100.0
demand float

The demand per year at the reference price.

100.0
demand_step float

The permanent change of the demand.

10.0
step_time float

The year of the change of the demand.

2.0
desired_coverage float

The years of demand producers want the inventory to hold.

0.25
reference_price float

The price at the desired coverage.

1.0
supply_elasticity float

The elasticity of the utilization of capacity with respect to the price.

0.1
demand_elasticity float

The elasticity of consumption with respect to the price, as a positive number.

0.25
expectation_time float

The time over which producers smooth the price into their expected price.

1.0
construction_delay float

The average time between an order of capacity and its completion.

3.0
lifetime float

The average lifetime of capacity.

15.0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.economics.markets import CommodityCycleSystem
>>> CommodityCycleSystem(construction_delay=5.0).prepare().system_.elements[0].construction_delay
5.0
Source code in src/skcomplex/systems/economics/markets/_commodities.py
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
def __init__(
    self,
    inventory: float = 25.0,
    capacity: float = 100.0,
    *,
    demand: float = 100.0,
    demand_step: float = 10.0,
    step_time: float = 2.0,
    desired_coverage: float = 0.25,
    reference_price: float = 1.0,
    supply_elasticity: float = 0.1,
    demand_elasticity: float = 0.25,
    expectation_time: float = 1.0,
    construction_delay: float = 3.0,
    lifetime: float = 15.0,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.inventory = inventory
    self.capacity = capacity
    self.demand = demand
    self.demand_step = demand_step
    self.step_time = step_time
    self.desired_coverage = desired_coverage
    self.reference_price = reference_price
    self.supply_elasticity = supply_elasticity
    self.demand_elasticity = demand_elasticity
    self.expectation_time = expectation_time
    self.construction_delay = construction_delay
    self.lifetime = lifetime

CommodityMarketElement(label, *, inventory=25.0, capacity=100.0, demand=100.0, demand_step=10.0, step_time=2.0, desired_coverage=0.25, reference_price=1.0, supply_elasticity=0.1, demand_elasticity=0.25, expectation_time=1.0, construction_delay=3.0, lifetime=15.0)

Bases: Element

Commodity market whose inventory production fills and consumption drains.

Its capacity is built after a delay. The price is a falling table function of the coverage of the demand by the inventory relative to the desired coverage. Production is the capacity times the relative price to the supply elasticity, consumption the demand times the relative price to minus the demand elasticity. Capacity is ordered at the rate of retirements times a rising table function of the smoothed price, completed through a third-order delay, and retired over its lifetime. The market holds the stocks and the parameters, and labelled flows of the system move the commodity and the capacity.

Parameters:

Name Type Description Default
label str

The label of the market.

required
inventory Annotated[float, closed_open(0, oo), Quantity(commodity)]

The initial inventory of the commodity.

25.0
capacity Annotated[float, closed_open(0, oo), Quantity(capacity)]

The initial production capacity per year.

100.0
demand Annotated[float, open(0, oo)]

The demand per year at the reference price.

100.0
demand_step float

The permanent change of the demand.

10.0
step_time Annotated[float, closed_open(0, oo)]

The year of the change of the demand.

2.0
desired_coverage Annotated[float, open(0, oo)]

The years of demand producers want the inventory to hold.

0.25
reference_price Annotated[float, open(0, oo)]

The price at the desired coverage.

1.0
supply_elasticity Annotated[float, closed_open(0, oo)]

The elasticity of the utilization of capacity with respect to the price.

0.1
demand_elasticity Annotated[float, closed_open(0, oo)]

The elasticity of consumption with respect to the price, as a positive number.

0.25
expectation_time Annotated[float, open(0, oo)]

The time over which producers smooth the price into their expected price.

1.0
construction_delay Annotated[float, open(0, oo)]

The average time between an order of capacity and its completion.

3.0
lifetime Annotated[float, open(0, oo)]

The average lifetime of capacity.

15.0

Examples:

>>> from skcomplex.systems.economics.markets import CommodityMarketElement
>>> CommodityMarketElement('market', lifetime=20.0).lifetime
20.0
Source code in src/skcomplex/systems/economics/markets/_commodities.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def __init__(
    self,
    label: str,
    *,
    inventory: Annotated[float, RealSet.closed_open(0, oo), Quantity('commodity')] = 25.0,
    capacity: Annotated[float, RealSet.closed_open(0, oo), Quantity('capacity')] = 100.0,
    demand: Annotated[float, RealSet.open(0, oo)] = 100.0,
    demand_step: float = 10.0,
    step_time: Annotated[float, RealSet.closed_open(0, oo)] = 2.0,
    desired_coverage: Annotated[float, RealSet.open(0, oo)] = 0.25,
    reference_price: Annotated[float, RealSet.open(0, oo)] = 1.0,
    supply_elasticity: Annotated[float, RealSet.closed_open(0, oo)] = 0.1,
    demand_elasticity: Annotated[float, RealSet.closed_open(0, oo)] = 0.25,
    expectation_time: Annotated[float, RealSet.open(0, oo)] = 1.0,
    construction_delay: Annotated[float, RealSet.open(0, oo)] = 3.0,
    lifetime: Annotated[float, RealSet.open(0, oo)] = 15.0,
) -> None:
    super().__init__(label)
    self.inventory = inventory
    self.capacity = capacity
    self.demand = demand
    self.demand_step = demand_step
    self.step_time = step_time
    self.desired_coverage = desired_coverage
    self.reference_price = reference_price
    self.supply_elasticity = supply_elasticity
    self.demand_elasticity = demand_elasticity
    self.expectation_time = expectation_time
    self.construction_delay = construction_delay
    self.lifetime = lifetime

ConsumerElement(label, *, fair=0.0, ethics=0.5, budget=2.0, premium=0.3, ethics_weight=2.0, price_weight=5.0, social_weight=2.0, values=None, size=None, space=None)

Bases: Element

Consumer who buys fair-trade or regular food.

It holds an ethical concern, a budget, and the weights of its utility. The utility of fair food is ethics_weight * ethics - price_weight * premium / budget + social_weight * share, where share is the share of neighbours who bought fair food in the last step, and the utility of regular food is zero. A consumer whose budget does not cover the price 1 + premium of fair food buys regular food.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
fair Annotated[object, FiniteEnumeratedSet([0, 1])]

One when the consumer bought fair food in the last step, zero otherwise.

0.0
ethics Annotated[object, closed_open(0, oo)]

The ethical concern of the consumer, between zero and one.

0.5
budget Annotated[object, closed_open(0, oo)]

The money the consumer can spend on one unit of food, regular food costing one.

2.0
premium Annotated[object, closed_open(0, oo)]

The extra price of fair food over regular food.

0.3
ethics_weight Annotated[object, closed_open(0, oo)]

The weight of ethical concern in the utility of fair food.

2.0
price_weight Annotated[object, closed_open(0, oo)]

The weight of the premium relative to the budget.

5.0
social_weight Annotated[object, closed_open(0, oo)]

The weight of the share of neighbours who buy fair food.

2.0
values Mapping[str, object] | None

Further values by name, such as the cell x and y of every member.

None
size int | None

The number of members, or None for one.

None
space BaseSpace | None

The grid whose axes x and y place the members, or None for none.

None

Examples:

>>> from skcomplex.systems.economics.markets import ConsumerElement
>>> ConsumerElement('consumers', ethics=0.5, size=4).size
4
Source code in src/skcomplex/systems/economics/markets/_fair_food.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def __init__(
    self,
    label: str,
    *,
    fair: Annotated[object, FiniteEnumeratedSet([0, 1])] = 0.0,
    ethics: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
    budget: Annotated[object, RealSet.closed_open(0, oo)] = 2.0,
    premium: Annotated[object, RealSet.closed_open(0, oo)] = 0.3,
    ethics_weight: Annotated[object, RealSet.closed_open(0, oo)] = 2.0,
    price_weight: Annotated[object, RealSet.closed_open(0, oo)] = 5.0,
    social_weight: Annotated[object, RealSet.closed_open(0, oo)] = 2.0,
    values: Mapping[str, object] | None = None,
    size: int | None = None,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, values=values, size=size, space=space)
    self.fair = fair
    self.ethics = ethics
    self.budget = budget
    self.premium = premium
    self.ethics_weight = ethics_weight
    self.price_weight = price_weight
    self.social_weight = social_weight

CournotAdjustmentInteraction(label, *, target, a=1500.0, b=10.0, error=0.0)

Bases: Interaction

Simultaneous best responses of two firms to their beliefs.

The beliefs are about the rival's last output. Under the inverse demand P = a - b Q, each firm sets q_i = (a - c_i) / (2 b) - belief_j / 2, where the belief is the rival's last output scaled by a factor drawn uniformly from [1 - error, 1 + error]. It is a rule of the system that sets every output from the outputs of the step before, so both firms respond to them.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of the two firms.

required
a Annotated[float, open(0, oo)]

The intercept of the inverse demand.

1500.0
b Annotated[float, open(0, oo)]

The slope of the inverse demand.

10.0
error Annotated[float, closed_open(0, oo)]

The largest relative error of a firm's belief about the rival's output.

0.0

Examples:

>>> from skcomplex.systems.economics.markets import CournotAdjustmentInteraction
>>> CournotAdjustmentInteraction('market', target='firms', error=0.1).error
0.1
Source code in src/skcomplex/systems/economics/markets/_duopoly.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def __init__(
    self,
    label: str,
    *,
    target: Role,
    a: Annotated[float, RealSet.open(0, oo)] = 1500.0,
    b: Annotated[float, RealSet.open(0, oo)] = 10.0,
    error: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
) -> None:
    super().__init__(label)
    self.target = target
    self.a = a
    self.b = b
    self.error = error

respond(system)

Set the output of every firm to its response to the outputs of the step before.

Parameters:

Name Type Description Default
system SystemView

The system view of the market.

required
Source code in src/skcomplex/systems/economics/markets/_duopoly.py
128
129
130
131
132
133
134
135
136
137
138
def respond(self, system: SystemView) -> None:
    """Set the output of every firm to its response to the outputs of the step before.

    Args:
        system:
            The system view of the market.
    """
    firms = cast(list[DuopolistView], system.get_agents('target'))
    responses = [self._get_response(firm, system) for firm in firms]
    for firm, response in zip(firms, responses, strict=True):
        firm.output = response

CournotBestResponseElement(label, *, q_i=0.0, q_j=0.0, demand=10.0, c_i=1.0, c_j=2.0, lambda_i=0.0, lambda_j=0.0)

Bases: Element

Quantities of two firms of a Cournot game, with the demand and the costs of the firms.

Each firm holds a share of the other. CournotBestResponseInteraction sets the quantities at the best responses.

Parameters:

Name Type Description Default
label str

The label of the element.

required
q_i float

The initial guess of the quantity of the first firm, which the equations replace.

0.0
q_j float

The initial guess of the quantity of the second firm, which the equations replace.

0.0
demand float

The intercept alpha of the inverse demand.

10.0
c_i float

The unit cost of the first firm.

1.0
c_j float

The unit cost of the second firm.

2.0
lambda_i float

The cross holding of the first firm.

0.0
lambda_j float

The cross holding of the second firm.

0.0

Examples:

>>> from skcomplex.systems.economics.markets import CournotBestResponseElement
>>> CournotBestResponseElement('duopoly', demand=8.0).demand
8.0
Source code in src/skcomplex/systems/economics/markets/_oligopoly.py
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
def __init__(
    self,
    label: str,
    *,
    q_i: float = 0.0,
    q_j: float = 0.0,
    demand: float = 10.0,
    c_i: float = 1.0,
    c_j: float = 2.0,
    lambda_i: float = 0.0,
    lambda_j: float = 0.0,
) -> None:
    super().__init__(label)
    self.q_i = q_i
    self.q_j = q_j
    self.demand = demand
    self.c_i = c_i
    self.c_j = c_j
    self.lambda_i = lambda_i
    self.lambda_j = lambda_j

CournotBestResponseInteraction(label, *, target='cournot')

Bases: Interaction

Best responses of the two firms of a Cournot game.

The conditions are alpha - 2 q_i - q_j = c_i / (1 + lambda_i) and its mirror (Forrest 2018 Eq. 21.5), whose solution is q_i = (alpha - 2 c_i / (1 + lambda_i) + c_j / (1 + lambda_j)) / 3 (Eq. 21.6).

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The duopoly whose quantities the conditions set.

'cournot'

Examples:

>>> from skcomplex.systems.economics.markets import CournotBestResponseInteraction
>>> CournotBestResponseInteraction('best_responses').target
'cournot'
Source code in src/skcomplex/systems/economics/markets/_oligopoly.py
117
118
119
def __init__(self, label: str, *, target: Role = 'cournot') -> None:
    super().__init__(label)
    self.target = target

CournotDuopolySystem(outputs=(100.0, 100.0), costs=(0.0, 0.0), *, a=1500.0, b=10.0, error=0.0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Two Cournot duopolists that adjust their output to their beliefs.

The beliefs are about each other. Without errors the outputs converge to the Nash equilibrium, q_i = (a - 2 c_i + c_j) / (3 b), which is 50 units each for the defaults. Errors in the beliefs keep the total output fluctuating around it. The system has the group firms, the total output total, and the price price.

Parameters:

Name Type Description Default
outputs Sequence[float]

The initial outputs of the two firms.

(100.0, 100.0)
costs Sequence[float]

The marginal costs of the two firms.

(0.0, 0.0)
a float

The intercept of the inverse demand.

1500.0
b float

The slope of the inverse demand.

10.0
error float

The largest relative error of a firm's belief about the rival's output.

0.0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.economics.markets import CournotDuopolySystem
>>> CournotDuopolySystem(error=0.01).prepare().system_.interactions[0].error
0.01
Source code in src/skcomplex/systems/economics/markets/_duopoly.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
def __init__(
    self,
    outputs: Sequence[float] = (100.0, 100.0),
    costs: Sequence[float] = (0.0, 0.0),
    *,
    a: float = 1500.0,
    b: float = 10.0,
    error: float = 0.0,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.outputs = outputs
    self.costs = costs
    self.a = a
    self.b = b
    self.error = error

CustomerElement(label, *, s1=0.5, s2=0.5, shop=0.0, freshness=1.0, T=0.1, size=None)

Bases: Element

Customer who remembers how satisfied it was with each of two shops.

The satisfaction is with the products of the shops. The customer visits the shop k of larger satisfaction S_k more often, with the logit utility S_k / T, and holds the freshness of the product it bought last.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
s1 object

The satisfaction with the first shop.

0.5
s2 object

The satisfaction with the second shop.

0.5
shop Annotated[object, FiniteEnumeratedSet([0, 1])]

The index of the shop the customer visits, 0 or 1.

0.0
freshness Annotated[object, closed(0, 1)]

The freshness of the product the customer bought last.

1.0
T Annotated[object, open(0, oo)]

The temperature of the choice, the randomness of the customer.

0.1
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.markets import CustomerElement
>>> CustomerElement('customers', s1=0.5, s2=0.5, size=10).size
10
Source code in src/skcomplex/systems/economics/markets/_perishables.py
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def __init__(
    self,
    label: str,
    *,
    s1: object = 0.5,
    s2: object = 0.5,
    shop: Annotated[object, FiniteEnumeratedSet([0, 1])] = 0.0,
    freshness: Annotated[object, RealSet.closed(0, 1)] = 1.0,
    T: Annotated[object, RealSet.open(0, oo)] = 0.1,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.s1 = s1
    self.s2 = s2
    self.shop = shop
    self.freshness = freshness
    self.T = T

get_destination(agent, system) staticmethod

Return the node of the shop the customer chose.

Parameters:

Name Type Description Default
agent AgentViewProtocol

The customer.

required
system SystemViewProtocol

The system view of the movement.

required

Returns:

Name Type Description
node int | None

The node of the shop, or None to stay for an agent that is not a customer.

Source code in src/skcomplex/systems/economics/markets/_perishables.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
@staticmethod
def get_destination(agent: AgentViewProtocol, system: SystemViewProtocol) -> int | None:
    """Return the node of the shop the customer chose.

    Args:
        agent:
            The customer.

        system:
            The system view of the movement.

    Returns:
        node:
            The node of the shop, or `None` to stay for an agent that is not a customer.
    """
    return int(agent.shop) if isinstance(agent, CustomerView) else None

get_payoff(agent, system, option) staticmethod

Return the freshness of the product the customer bought last.

It is the payoff of the shop it visited.

Parameters:

Name Type Description Default
agent CustomerView

The customer.

required
system SystemView

The system view of the reinforcement.

required
option int

The index of the shop the customer visited.

required

Returns:

Name Type Description
freshness float

The freshness of the product.

Source code in src/skcomplex/systems/economics/markets/_perishables.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
@staticmethod
def get_payoff(agent: CustomerView, system: SystemView, option: int) -> float:
    """Return the freshness of the product the customer bought last.

    It is the payoff of the shop it visited.

    Args:
        agent:
            The customer.

        system:
            The system view of the reinforcement.

        option:
            The index of the shop the customer visited.

    Returns:
        freshness:
            The freshness of the product.
    """
    return agent.freshness

get_preference(agent) staticmethod

Return p_1 - p_2 = tanh((S_1 - S_2) / 2T).

It is how much more likely the customer visits the first shop.

Parameters:

Name Type Description Default
agent CustomerView

The customer.

required

Returns:

Name Type Description
preference float

The difference of the probabilities of visiting the first and the second shop.

Source code in src/skcomplex/systems/economics/markets/_perishables.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
@staticmethod
def get_preference(agent: CustomerView) -> float:
    """Return `p_1 - p_2 = tanh((S_1 - S_2) / 2T)`.

    It is how much more likely the customer visits the first shop.

    Args:
        agent:
            The customer.

    Returns:
        preference:
            The difference of the probabilities of visiting the first and the second shop.
    """
    return float(np.tanh((agent.s1 - agent.s2) / (2 * agent.T)))

get_utility(agent, system, option) staticmethod

Return the utility S_k / T of visiting shop k.

Parameters:

Name Type Description Default
agent CustomerView

The customer.

required
system SystemView

The system view of the choice.

required
option float

The index of the shop.

required

Returns:

Name Type Description
utility float

The satisfaction with the shop divided by the temperature.

Source code in src/skcomplex/systems/economics/markets/_perishables.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
@staticmethod
def get_utility(agent: CustomerView, system: SystemView, option: float) -> float:
    """Return the utility `S_k / T` of visiting shop `k`.

    Args:
        agent:
            The customer.

        system:
            The system view of the choice.

        option:
            The index of the shop.

    Returns:
        utility:
            The satisfaction with the shop divided by the temperature.
    """
    return (agent.s1 if option == 0 else agent.s2) / agent.T

DoubleAuctionSystem(n_buyers=50, n_sellers=50, *, protocol='order_book', rounds=20, constrained=True, ceiling=200.0, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Gode and Sunder's double auction of zero-intelligence traders.

Each step is a trading period. Every buyer values one unit and every seller can produce one unit at a cost, both drawn uniformly below the price ceiling. During a trading period of several rounds, every trader that has not traded yet quotes a random price and the market matches the quotes, continuously in a limit order book or at one uniform price in a call auction. With the budget constraint (ZI-C) no trader accepts a loss, and the market alone reaches nearly the whole competitive surplus. Without it (ZI-U), traders make losing trades and the efficiency drops.

The traders are the zero-intelligence traders of Gode and Sunder (1993). The double auction of Gooding (2019), whose traders adapt their bids and asks, is a different model. The system has the groups buyers and sellers, the market auction, and the realised ledger.surplus and ledger.efficiency of every trading period.

Parameters:

Name Type Description Default
n_buyers int

The number of buyers.

50
n_sellers int

The number of sellers.

50
protocol str

The protocol of the market, 'order_book' or 'call_auction'.

'order_book'
rounds int

The number of quoting rounds of a trading period.

20
constrained bool

Whether traders never quote at a loss.

True
ceiling float

The highest price of the market.

200.0
random_state int | Generator | None

The seed or generator of the values and the costs.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Raises:

Type Description
ValueError

The protocol is unknown.

Examples:

>>> from skcomplex.systems.economics.markets import DoubleAuctionSystem
>>> [group.size for group in DoubleAuctionSystem(10, 8).prepare().system_.elements]
[10, 8]
Source code in src/skcomplex/systems/economics/markets/_double_auction.py
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
def __init__(
    self,
    n_buyers: int = 50,
    n_sellers: int = 50,
    *,
    protocol: str = 'order_book',
    rounds: int = 20,
    constrained: bool = True,
    ceiling: float = 200.0,
    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_buyers = n_buyers
    self.n_sellers = n_sellers
    self.protocol = protocol
    self.rounds = rounds
    self.constrained = constrained
    self.ceiling = ceiling
    self.random_state = random_state

DuopolistElement(label, *, output=50.0, cost=0.0, size=None)

Bases: Element

Firm of a Cournot duopoly.

It is described by its output and its constant marginal cost.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
output Annotated[object, closed_open(0, oo)]

The initial output.

50.0
cost Annotated[object, closed_open(0, oo)]

The marginal cost.

0.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.markets import DuopolistElement
>>> DuopolistElement('firms', output=[100.0, 100.0], size=2).size
2
Source code in src/skcomplex/systems/economics/markets/_duopoly.py
60
61
62
63
64
65
66
67
68
69
70
def __init__(
    self,
    label: str,
    *,
    output: Annotated[object, RealSet.closed_open(0, oo)] = 50.0,
    cost: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.output = output
    self.cost = cost

EchelonElement(label, *, inventory=12.0, in_transit=8.0, backlog=4.0, expected=4.0, supply_line=16.0, desired=13.44, theta=0.36, alpha=0.26, beta=0.34, dispatch_time=1.0, mail_delay=2.0, shipping_delay=2.0)

Bases: Element

Echelon of a supply chain.

It ships its backlog from its inventory and orders by anchoring and adjustment, by the laws of EchelonInteraction. It ships its backlog over the dispatch time, limited by its inventory. Its expected demand adapts to incoming orders at the rate theta, and it orders its expected demand plus alpha times the gap between its desired stock and its effective inventory, the inventory less the backlog, less beta times its supply line, never negative. Its orders reach its supplier after the mail delay, and the beer its supplier ships arrives after the shipping delay.

Parameters:

Name Type Description Default
label str

The label of the echelon.

required
inventory Annotated[float, closed_open(0, oo), Quantity(beer)]

The initial inventory, in cases.

12.0
in_transit Annotated[float, closed_open(0, oo), Quantity(beer)]

The initial beer on its way to the echelon.

8.0
backlog Annotated[float, closed_open(0, oo)]

The initial orders waiting to ship.

4.0
expected Annotated[float, closed_open(0, oo)]

The initial expected demand.

4.0
supply_line Annotated[float, closed_open(0, oo)]

The initial beer ordered and not received.

16.0
desired float

The desired stock S'.

13.44
theta Annotated[float, closed_open(0, oo)]

The rate at which the expected demand adapts to incoming orders.

0.36
alpha Annotated[float, closed_open(0, oo)]

The fraction of the stock gap ordered per week.

0.26
beta Annotated[float, closed_open(0, oo)]

The weight of the supply line in the stock gap.

0.34
dispatch_time Annotated[float, open(0, oo)]

The time over which the echelon ships its backlog.

1.0
mail_delay Annotated[float, open(0, oo)]

The average time an order of the echelon takes to reach its supplier.

2.0
shipping_delay Annotated[float, open(0, oo)]

The average time a shipment takes to reach the echelon from its supplier.

2.0

Examples:

>>> from skcomplex.systems.economics.markets import EchelonElement
>>> EchelonElement('retailer', inventory=10.0).inventory
10.0
Source code in src/skcomplex/systems/economics/markets/_supply_chains.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def __init__(
    self,
    label: str,
    *,
    inventory: Annotated[float, RealSet.closed_open(0, oo), Quantity('beer')] = 12.0,
    in_transit: Annotated[float, RealSet.closed_open(0, oo), Quantity('beer')] = 8.0,
    backlog: Annotated[float, RealSet.closed_open(0, oo)] = 4.0,
    expected: Annotated[float, RealSet.closed_open(0, oo)] = 4.0,
    supply_line: Annotated[float, RealSet.closed_open(0, oo)] = 16.0,
    desired: float = 13.44,
    theta: Annotated[float, RealSet.closed_open(0, oo)] = 0.36,
    alpha: Annotated[float, RealSet.closed_open(0, oo)] = 0.26,
    beta: Annotated[float, RealSet.closed_open(0, oo)] = 0.34,
    dispatch_time: Annotated[float, RealSet.open(0, oo)] = 1.0,
    mail_delay: Annotated[float, RealSet.open(0, oo)] = 2.0,
    shipping_delay: Annotated[float, RealSet.open(0, oo)] = 2.0,
) -> None:
    super().__init__(label)
    self.inventory = inventory
    self.in_transit = in_transit
    self.backlog = backlog
    self.expected = expected
    self.supply_line = supply_line
    self.desired = desired
    self.theta = theta
    self.alpha = alpha
    self.beta = beta
    self.dispatch_time = dispatch_time
    self.mail_delay = mail_delay
    self.shipping_delay = shipping_delay

EchelonInteraction(label, *, target)

Bases: Interaction

Shipping of the backlog of an echelon of a supply chain and the decay of its expected demand.

The echelon ships its backlog over the dispatch time, limited by its inventory, and its expected demand decays at the rate theta, while the orders that reach it raise both.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the echelon.

required

Examples:

>>> from skcomplex.systems.economics.markets import EchelonInteraction
>>> EchelonInteraction('retailer_shipping', target='retailer').target
'retailer'
Source code in src/skcomplex/systems/economics/markets/_supply_chains.py
336
337
338
def __init__(self, label: str, *, target: Role) -> None:
    super().__init__(label)
    self.target = target

EmployerElement(label, *, bid=0.0, demand=0.0, posted=-1.0, vacancy_rate=0.5, low_wage=0.5, high_wage=1.0, size=None)

Bases: Element

Firm that posts a vacancy with a random wage offer in some steps.

At most one worker fills the vacancy.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
bid Annotated[object, closed_open(0, oo)]

The wage offered for the vacancy.

0.0
demand Annotated[object, NN]

The number of open vacancies, one or zero.

0.0
posted object

The step in which the vacancy was posted.

-1.0
vacancy_rate Annotated[object, closed_open(0, oo)]

The probability of posting a vacancy in a step.

0.5
low_wage Annotated[object, closed_open(0, oo)]

The lowest wage offer.

0.5
high_wage Annotated[object, closed_open(0, oo)]

The highest wage offer.

1.0
size int | None

The number of firms, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.markets import EmployerElement
>>> EmployerElement('firms', size=5).size
5
Source code in src/skcomplex/systems/economics/markets/_labour.py
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def __init__(
    self,
    label: str,
    *,
    bid: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    demand: Annotated[object, NN] = 0.0,
    posted: object = -1.0,
    vacancy_rate: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
    low_wage: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
    high_wage: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.bid = bid
    self.demand = demand
    self.posted = posted
    self.vacancy_rate = vacancy_rate
    self.low_wage = low_wage
    self.high_wage = high_wage

ExchangeInteraction(label, *, target, goods=GOODS, pairing='pairs', quantity=0.1, phase='trade')

Bases: Interaction

Bilateral barter between paired traders.

Its trades repeat while both traders gain. Every step the exchange pairs the traders, and every pair barters small quantities of every pair of goods at the geometric mean of their marginal rates of substitution while both gain. A trader holds every good in the state of its name and its Cobb-Douglas weight in the state <good>_weight. Every trade moves goods between the two traders, so the total of every good stays the same, which the default run checks as invariants. The exchange reports the mean price of the second good in units of the first, the standard deviation dispersion of its logarithm over the trades of the step, and the number of trades volume.

Parameters:

Name Type Description Default
label str

The label of the exchange.

required
target Role

The path of the group of traders.

required
goods tuple[str, ...]

The names of the traded goods.

GOODS
pairing str

How the exchange pairs the traders, 'neighbor-pairs' for disjoint pairs of neighbours or 'pairs' for disjoint random pairs.

'pairs'
quantity float

The quantity of the bought good in every trade.

0.1
phase str

The phase the trades run in.

'trade'

Examples:

>>> from skcomplex.systems.economics.markets import ExchangeInteraction
>>> ExchangeInteraction('exchange', target='traders').reports
('price', 'dispersion', 'volume')
Source code in src/skcomplex/systems/economics/common/exchange/_exchange_interaction.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def __init__(
    self,
    label: str,
    *,
    target: Role,
    goods: tuple[str, ...] = GOODS,
    pairing: str = 'pairs',
    quantity: float = 0.1,
    phase: str = 'trade',
) -> None:
    super().__init__(label)
    self.target = target
    self.goods = goods
    self.pairing = pairing
    self.quantity = quantity
    self.phase = phase

report_trades(system)

Report the mean price of the second good in the first, and the trades.

It also reports the dispersion of the price, and the trades are those of the step.

Parameters:

Name Type Description Default
system SystemViewProtocol

The system view of the exchange.

required
Source code in src/skcomplex/systems/economics/common/exchange/_exchange_interaction.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
def report_trades(self, system: SystemViewProtocol) -> None:
    """Report the mean price of the second good in the first, and the trades.

    It also reports the dispersion of the price, and the trades are those of the step.

    Args:
        system:
            The system view of the exchange.
    """
    trades = system.storage.pop('trades', [])
    trades = trades if isinstance(trades, list) else []
    logs = [math.log(price) for bought, paid, price in trades if (bought, paid) == (0, 1)]
    system.report('price', math.exp(float(np.mean(logs))) if logs else math.nan)
    system.report('dispersion', float(np.std(logs)) if len(logs) > 1 else math.nan)
    system.report('volume', len(trades))

trade(system)

Pair the traders and let every pair barter, in random order.

Parameters:

Name Type Description Default
system SystemViewProtocol

The system view of the exchange.

required
Source code in src/skcomplex/systems/economics/common/exchange/_exchange_interaction.py
100
101
102
103
104
105
106
107
108
109
110
111
112
def trade(self, system: SystemViewProtocol) -> None:
    """Pair the traders and let every pair barter, in random order.

    Args:
        system:
            The system view of the exchange.
    """
    traders = system.get_agents('target')
    found = list(pairs(traders, traders, system.rng, PAIRINGS[self.pairing]))
    for index in system.rng.permutation(len(found)):
        first, second = found[int(index)]
        if first.alive and second.alive:
            self.transfer(first, second, system)

transfer(source, target, system)

Barter between two traders while both gain.

It keeps the trades of the step for its report.

Parameters:

Name Type Description Default
source AgentViewProtocol

The first trader.

required
target AgentViewProtocol

The second trader.

required
system SystemViewProtocol

The system view of the exchange.

required

Returns:

Name Type Description
traded bool

Whether the traders made a trade.

Source code in src/skcomplex/systems/economics/common/exchange/_exchange_interaction.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def transfer(self, source: AgentViewProtocol, target: AgentViewProtocol, system: SystemViewProtocol) -> bool:
    """Barter between two traders while both gain.

    It keeps the trades of the step for its report.

    Args:
        source:
            The first trader.

        target:
            The second trader.

        system:
            The system view of the exchange.

    Returns:
        traded:
            Whether the traders made a trade.
    """
    weights = [f'{good}_weight' for good in self.goods]
    trades = trade_goods(source, target, self.goods, weights, quantity=self.quantity)
    logs = system.storage.setdefault('trades', [])
    if isinstance(logs, list):
        logs.extend(trades)
    return bool(trades)

FactoryElement(label, *, inventory=12.0, in_transit=8.0, backlog=4.0, expected=4.0, supply_line=16.0, desired=13.44, theta=0.36, alpha=0.26, beta=0.34, dispatch_time=1.0, mail_delay=2.0, shipping_delay=2.0, production_delay=3.0)

Bases: EchelonElement

Factory of a supply chain.

It is an echelon whose orders a brewery brews over the production delay.

Parameters:

Name Type Description Default
label str

The label of the factory.

required
inventory Annotated[float, closed_open(0, oo), Quantity(beer)]

The initial inventory, in cases.

12.0
in_transit Annotated[float, closed_open(0, oo), Quantity(beer)]

The initial beer on its way to the echelon.

8.0
backlog Annotated[float, closed_open(0, oo)]

The initial orders waiting to ship.

4.0
expected Annotated[float, closed_open(0, oo)]

The initial expected demand.

4.0
supply_line Annotated[float, closed_open(0, oo)]

The initial beer ordered and not received.

16.0
desired float

The desired stock S'.

13.44
theta Annotated[float, closed_open(0, oo)]

The rate at which the expected demand adapts to incoming orders.

0.36
alpha Annotated[float, closed_open(0, oo)]

The fraction of the stock gap ordered per week.

0.26
beta Annotated[float, closed_open(0, oo)]

The weight of the supply line in the stock gap.

0.34
dispatch_time Annotated[float, open(0, oo)]

The time over which the echelon ships its backlog.

1.0
mail_delay Annotated[float, open(0, oo)]

The average time an order of the echelon takes to reach its supplier.

2.0
shipping_delay Annotated[float, open(0, oo)]

The average time a shipment takes to reach the echelon from its supplier.

2.0
production_delay Annotated[float, open(0, oo)]

The average time the brewery takes to brew an order, through a third-order delay.

3.0

Examples:

>>> from skcomplex.systems.economics.markets import FactoryElement
>>> FactoryElement('factory').production_delay
3.0
Source code in src/skcomplex/systems/economics/markets/_supply_chains.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
def __init__(
    self,
    label: str,
    *,
    inventory: Annotated[float, RealSet.closed_open(0, oo), Quantity('beer')] = 12.0,
    in_transit: Annotated[float, RealSet.closed_open(0, oo), Quantity('beer')] = 8.0,
    backlog: Annotated[float, RealSet.closed_open(0, oo)] = 4.0,
    expected: Annotated[float, RealSet.closed_open(0, oo)] = 4.0,
    supply_line: Annotated[float, RealSet.closed_open(0, oo)] = 16.0,
    desired: float = 13.44,
    theta: Annotated[float, RealSet.closed_open(0, oo)] = 0.36,
    alpha: Annotated[float, RealSet.closed_open(0, oo)] = 0.26,
    beta: Annotated[float, RealSet.closed_open(0, oo)] = 0.34,
    dispatch_time: Annotated[float, RealSet.open(0, oo)] = 1.0,
    mail_delay: Annotated[float, RealSet.open(0, oo)] = 2.0,
    shipping_delay: Annotated[float, RealSet.open(0, oo)] = 2.0,
    production_delay: Annotated[float, RealSet.open(0, oo)] = 3.0,
) -> None:
    super().__init__(
        label,
        inventory=inventory,
        in_transit=in_transit,
        backlog=backlog,
        expected=expected,
        supply_line=supply_line,
        desired=desired,
        theta=theta,
        alpha=alpha,
        beta=beta,
        dispatch_time=dispatch_time,
        mail_delay=mail_delay,
        shipping_delay=shipping_delay,
    )
    self.production_delay = production_delay

FairFoodMarketInteraction(label, *, rule=None, phase=None, shops, farms, pressure=0.001)

Bases: PolicyRuleInteraction[SystemView]

Tomato market and the Fair Food Program.

Buyers and farms join the programme by the four rules of Chesney. Every period, in the order of the code of Chesney (2021, Section 7.6), every buyer outside the programme joins it at level 1 with the probability pressure (Rule 1). Every buyer at level 1, in random order, moves to level 2 when the member farms grow at least what the buyers at level 2 need plus its own need (Rule 2). The buyers then fill their needs in random order from the farms in random order, any farm at level 0, member farms first at level 1, and only member farms at level 2 (Rule 3). Finally every farm outside the programme joins it when it grows more than the buyers outside the programme need (Rule 4). Levels only rise.

Parameters:

Name Type Description Default
label str

The label of the market.

required
rule None

Unused, since the market overrides act.

None
phase str | None

The phase the market acts in, or None for the default phase.

None
shops Role

The path of the group of buyers.

required
farms Role

The path of the group of farms.

required
pressure Annotated[float, closed(0, 1)]

The probability per period that a buyer outside the programme joins it at level 1.

0.001

Examples:

>>> from skcomplex.systems.economics.markets import FairFoodMarketInteraction
>>> FairFoodMarketInteraction('market', shops='shops', farms='farms').reports[:2]
('committed_shops', 'member_shops')
Source code in src/skcomplex/systems/economics/markets/_fair_food_program.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def __init__(
    self,
    label: str,
    *,
    rule: None = None,
    phase: str | None = None,
    shops: Role,
    farms: Role,
    pressure: Annotated[float, RealSet.closed(0, 1)] = 0.001,
) -> None:
    super().__init__(label, rule=rule, phase=phase)
    self.shops = shops
    self.farms = farms
    self.pressure = pressure

act(system)

Run the four rules of one period.

Parameters:

Name Type Description Default
system SystemView

The system view of the market.

required
Source code in src/skcomplex/systems/economics/markets/_fair_food_program.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
def act(self, system: SystemView) -> None:
    """Run the four rules of one period.

    Args:
        system:
            The system view of the market.
    """
    rng = system.rng
    shops = sorted(cast(list[ProgramMemberView], system.get_agents('shops')), key=lambda shop: shop.id)
    farms = sorted(cast(list[ProgramMemberView], system.get_agents('farms')), key=lambda farm: farm.id)
    need = np.array([shop.acres for shop in shops])
    shop_level = np.array([shop.level for shop in shops])
    acres = np.array([farm.acres for farm in farms])
    farm_level = np.array([farm.level for farm in farms])
    joining = (shop_level == OUTSIDE) & (rng.random(len(shops)) < system.get_parameter('pressure'))
    shop_level = np.where(joining, float(COMMITTED), shop_level)
    for shop in rng.permutation(len(shops)):
        member_acres = acres[farm_level == 1].sum()
        if shop_level[shop] == COMMITTED and member_acres >= need[shop_level == MEMBER].sum() + need[shop]:
            shop_level[shop] = float(MEMBER)
    left, bought = acres.copy(), np.zeros(len(shops))
    for shop in rng.permutation(len(shops)):
        order = rng.permutation(len(farms))
        members, others = order[farm_level[order] == 1], order[farm_level[order] == 0]
        if shop_level[shop] == OUTSIDE:
            bought[shop] = self._buy(need[shop], order, left)
        elif shop_level[shop] == COMMITTED:
            bought[shop] = self._buy(need[shop], members, left)
            bought[shop] += self._buy(need[shop] - bought[shop], others, left)
        else:
            bought[shop] = self._buy(need[shop], members, left)
    for farm in range(len(farms)):
        if farm_level[farm] == 0 and acres[farm] > need[shop_level == OUTSIDE].sum():
            farm_level[farm] = 1.0
    for view, level, amount in zip(shops, shop_level, bought, strict=True):
        view.level, view.traded = float(level), float(amount)
    for grower, level, rest, grown in zip(farms, farm_level, left, acres, strict=True):
        grower.level, grower.traded = float(level), float(grown - rest)
    system.report('committed_shops', float(np.sum(shop_level == COMMITTED)))
    system.report('member_shops', float(np.sum(shop_level == MEMBER)))
    system.report('member_farms', float(np.sum(farm_level == 1)))
    system.report('unfulfilled', float((need - bought).sum()))
    system.report('unsold', float(left.sum()))

FairFoodProgramSystem(n_shops=30, n_farms=20, *, acres=1000.0, pressure=0.001, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Chesney's Fair Food Program.

Pressure on tomato buyers draws farms into fair wages. The Coalition of Immokalee Workers presses tomato buyers to join the Fair Food Program, whose member farms pay pickers a penny more per pound. Buyers join at level 1, buying from member farms first, then move to level 2, buying only from member farms, once the member farms grow enough, and farms join when the buyers outside the programme need less than they grow. Buyers and farms have random sizes that share the acres of farmland, and the buyers need as much as the farms grow. This is the model of Chesney (2021, Sections 7.2 to 7.6), with the floor and ceiling of its NetLogo code, whose sell_me subtracts the last tomatoes of a farm from the buyer instead of adding them, which this system corrects. Farms hold out until most buyers have joined, then join in a cascade, a tipping point that comes later the more unequal the agents.

The system has the groups shops and farms and the market market, whose reporters are the buyers at level 1 market.committed_shops and level 2 market.member_shops, the member farms market.member_farms, the unfulfilled needs market.unfulfilled, and the unsold tomatoes market.unsold.

Parameters:

Name Type Description Default
n_shops int

The number of buyers.

30
n_farms int

The number of farms.

20
acres float

The acres of farmland, which the buyers need and the farms grow.

1000.0
pressure float

The probability per period that a buyer outside the programme joins it at level 1.

0.001
random_state int | Generator | None

The seed or generator of the sizes of the buyers and farms.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.economics.markets import FairFoodProgramSystem
>>> [group.size for group in FairFoodProgramSystem(5, 3).prepare().system_.elements]
[5, 3]
Source code in src/skcomplex/systems/economics/markets/_fair_food_program.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def __init__(
    self,
    n_shops: int = 30,
    n_farms: int = 20,
    *,
    acres: float = 1000.0,
    pressure: float = 0.001,
    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_shops = n_shops
    self.n_farms = n_farms
    self.acres = acres
    self.pressure = pressure
    self.random_state = random_state

FairFoodSystem(width=20, height=20, *, premium=0.3, ethics_weight=2.0, price_weight=5.0, social_weight=2.0, intensity=1.0, low_budget=1.0, high_budget=3.0, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The choice between fair-trade and regular food of consumers.

The consumers influence their neighbours. Every consumer, of uniform ethical concern and budget, sits on a cell of a grid and every step buys fair or regular food, all at once from the choices of their neighbours in the last step. The share of fair food rises with the weight of ethics and falls with the premium, and social influence raises it.

The choice is the binary logit choice with social interactions of Brock and Durlauf (2001), with a private utility of ethics and price and a social utility of the share of neighbours who buy fair food. Neither Ajani's Choice nor the Fair Food Program of Chesney (2021) is this model. The system has the group consumers, their logit choice shopping, and the share of fair food fair_share.

Parameters:

Name Type Description Default
width int

The number of columns of the grid.

20
height int

The number of rows of the grid.

20
premium float

The extra price of fair food over regular food, which costs one.

0.3
ethics_weight float

The weight of ethical concern in the utility of fair food.

2.0
price_weight float

The weight of the premium relative to the budget.

5.0
social_weight float

The weight of the share of neighbours who buy fair food.

2.0
intensity float

The intensity of the logit choice.

1.0
low_budget float

The lowest budget.

1.0
high_budget float

The highest budget.

3.0
random_state int | Generator | None

The seed or generator of the ethics and the budgets.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.economics.markets import FairFoodSystem
>>> FairFoodSystem(5, 4).prepare().system_.elements[0].size
20
Source code in src/skcomplex/systems/economics/markets/_fair_food.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
def __init__(
    self,
    width: int = 20,
    height: int = 20,
    *,
    premium: float = 0.3,
    ethics_weight: float = 2.0,
    price_weight: float = 5.0,
    social_weight: float = 2.0,
    intensity: float = 1.0,
    low_budget: float = 1.0,
    high_budget: float = 3.0,
    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.width = width
    self.height = height
    self.premium = premium
    self.ethics_weight = ethics_weight
    self.price_weight = price_weight
    self.social_weight = social_weight
    self.intensity = intensity
    self.low_budget = low_budget
    self.high_budget = high_budget
    self.random_state = random_state

ForagerElement(label, *, sugar=10.0, vision=1.0, metabolism=1.0, values=None, size=None, space=None)

Bases: Element

Agent that moves to the richest free cell in sight and harvests its sugar.

It burns its metabolism, and may starve. In its own activation, a forager sees vision cells along each of the four lattice directions and moves to the free cell with the most sugar, the nearest among equals, or stays when no cell in sight beats its own, by a MovementInteraction of the best step with a vision. Transfers then harvest the sugar of its cell and burn its metabolism, and a BirthDeathInteraction removes it when its wealth falls below zero.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
sugar object

The wealth of the forager.

10.0
vision Annotated[object, NN]

The number of cells the forager sees in every direction.

1.0
metabolism Annotated[object, closed_open(0, oo)]

The sugar the forager burns in a step.

1.0
values Mapping[str, object] | None

Further values by name, such as the cell x and y of every member.

None
size int | None

The number of members, or None for one.

None
space BaseSpace | None

The grid whose axes x and y place the members, or None for none.

None

Examples:

>>> from skcomplex.systems.economics.markets import ForagerElement
>>> ForagerElement('foragers', vision=2.0, size=3).size
3
Source code in src/skcomplex/systems/economics/markets/_sugarscape.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def __init__(
    self,
    label: str,
    *,
    sugar: object = 10.0,
    vision: Annotated[object, NN] = 1.0,
    metabolism: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
    values: Mapping[str, object] | None = None,
    size: int | None = None,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, values=values, size=size, space=space)
    self.sugar = sugar
    self.vision = vision
    self.metabolism = metabolism

GoodingDoubleAuctionSystem(n_buyers=100, n_sellers=100, *, value=120.0, cost=20.0, spread=0.1, units=5.0, step=1.0, unlimited=False, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Gooding's double auction.

Its buyers and sellers move their quotes towards trade and then apart. Buyers value a unit near value and sellers can supply it near cost, each differing by up to spread of it. As in the experiments the model replicates, buyers start bidding near the sellers' cost and sellers start asking near the buyers' value, and both move their quotes towards one another until they trade, after which each tries to push the price its way (Gooding 2019, Section 11.3 and the appendix). In the short run, with sellers of a few units and buyers that are satiated after a few, the price settles near the competitive price halfway between value and cost, 70 at the defaults. With unlimited supply and demand, the long-run price wanders between the cost and the value and the equilibrium disappears. The source describes the rules in prose, so the meetings and the fixed steps of the quotes are a reconstruction of them.

The system has the groups buyers and sellers and the auction auction, whose reporters are the last traded price auction.price, the units traded auction.volume, and the mean quotes auction.mean_bid and auction.mean_ask.

Parameters:

Name Type Description Default
n_buyers int

The number of buyers.

100
n_sellers int

The number of sellers.

100
value float

The mean value of a unit to the buyers.

120.0
cost float

The mean cost of a unit to the sellers.

20.0
spread float

The largest relative difference of a trader's value or cost from the mean.

0.1
units float

The units every seller holds and every buyer wants.

5.0
step float

The change of a quote after a meeting.

1.0
unlimited bool

Whether the units of the traders never run out.

False
random_state int | Generator | None

The seed or generator of the values and costs.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.economics.markets import GoodingDoubleAuctionSystem
>>> [group.size for group in GoodingDoubleAuctionSystem(4, 3).prepare().system_.elements]
[4, 3]
Source code in src/skcomplex/systems/economics/markets/_adaptive_auction.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
def __init__(
    self,
    n_buyers: int = 100,
    n_sellers: int = 100,
    *,
    value: float = 120.0,
    cost: float = 20.0,
    spread: float = 0.1,
    units: float = 5.0,
    step: float = 1.0,
    unlimited: bool = False,
    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_buyers = n_buyers
    self.n_sellers = n_sellers
    self.value = value
    self.cost = cost
    self.spread = spread
    self.units = units
    self.step = step
    self.unlimited = unlimited
    self.random_state = random_state

GoodsTraderElement(label, *, sugar=10.0, spice=10.0, salt=0.0, sugar_weight=0.5, spice_weight=0.5, salt_weight=0.0, values=None, size=None, space=None)

Bases: Element

Trader who holds goods and values them with Cobb-Douglas weights.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
sugar Annotated[object, closed_open(0, oo)]

The holding of sugar.

10.0
spice Annotated[object, closed_open(0, oo)]

The holding of spice.

10.0
salt Annotated[object, closed_open(0, oo)]

The holding of salt.

0.0
sugar_weight Annotated[object, closed_open(0, oo)]

The Cobb-Douglas weight of sugar.

0.5
spice_weight Annotated[object, closed_open(0, oo)]

The Cobb-Douglas weight of spice.

0.5
salt_weight Annotated[object, closed_open(0, oo)]

The Cobb-Douglas weight of salt, zero when salt is not traded.

0.0
values Mapping[str, object] | None

Further values by name, such as the cell x and y of every member.

None
size int | None

The number of members, or None for one.

None
space BaseSpace | None

The grid whose axes x and y place the members, or None for none.

None

Examples:

>>> from skcomplex.systems.economics.markets import GoodsTraderElement
>>> GoodsTraderElement('traders', sugar=5.0, size=4).size
4
Source code in src/skcomplex/systems/economics/markets/_goods_traders.py
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
def __init__(
    self,
    label: str,
    *,
    sugar: Annotated[object, RealSet.closed_open(0, oo)] = 10.0,
    spice: Annotated[object, RealSet.closed_open(0, oo)] = 10.0,
    salt: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    sugar_weight: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
    spice_weight: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
    salt_weight: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    values: Mapping[str, object] | None = None,
    size: int | None = None,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, values=values, size=size, space=space)
    self.sugar = sugar
    self.spice = spice
    self.salt = salt
    self.sugar_weight = sugar_weight
    self.spice_weight = spice_weight
    self.salt_weight = salt_weight

GoodsTradersSystem(n_traders=200, *, goods=3, width=20, height=20, quantity=0.1, mobility=0.5, low=1.0, high=20.0, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Traders who wander a grid and barter two or three goods with their neighbours.

Every trader holds random amounts of the goods and values them with random Cobb-Douglas weights. Every step the traders wander to a random neighbouring cell, then every trader is paired with a neighbour, and the pairs barter while both gain, at the geometric mean of their marginal rates of substitution. Trades only move goods between the traders, so the total of every good is unchanged, while the mean utility rises and the prices of different trades converge, so the dispersion of the logarithm of the price falls.

The trade rule is the bilateral barter of sugar and spice of Epstein and Axtell (1996), and salt extends it to a third good. The Toy Trader of Gooding (2019), with money, posted prices, and imitation of price rules, is a different model. The system has the group traders, their random walk wander, and the exchange exchange, whose reporters are exchange.price, exchange.dispersion, and exchange.volume.

Parameters:

Name Type Description Default
n_traders int

The number of traders.

200
goods int

The number of goods, 2 for sugar and spice or 3 with salt.

3
width int

The number of columns of the grid.

20
height int

The number of rows of the grid.

20
quantity float

The quantity of the bought good in every trade.

0.1
mobility float

The probability that a trader moves in a step.

0.5
low float

The smallest initial holding of a good.

1.0
high float

The largest initial holding of a good.

20.0
random_state int | Generator | None

The seed or generator of the cells, holdings, and weights.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Raises:

Type Description
ValueError

The number of goods is not 2 or 3.

Examples:

>>> from skcomplex.systems.economics.markets import GoodsTradersSystem
>>> GoodsTradersSystem(20, goods=2).prepare().system_.elements[0].size
20
Source code in src/skcomplex/systems/economics/markets/_goods_traders.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
def __init__(
    self,
    n_traders: int = 200,
    *,
    goods: int = 3,
    width: int = 20,
    height: int = 20,
    quantity: float = 0.1,
    mobility: float = 0.5,
    low: float = 1.0,
    high: float = 20.0,
    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_traders = n_traders
    self.goods = goods
    self.width = width
    self.height = height
    self.quantity = quantity
    self.mobility = mobility
    self.low = low
    self.high = high
    self.random_state = random_state

HeuristicPricingInteraction(label, *, rule=None, phase=None, traders, rate=1.1, strength=1.2, cost=1.0, risk=1.0, noise=0.01, initial=0.1)

Bases: PolicyRuleInteraction[SystemView]

Market maker that clears the risky asset.

It clears at the price where the mean forecast of the traders is met. The deviation x of the price from its fundamental value clears at R x_t = sum_h n_h f_h + eps_t, where n_h is the share of traders using heuristic h. The fundamentalists forecast the fundamental, f = 0, and the trend chasers extrapolate the last deviation, f = g x_{t-1}, both as heuristics.fundamental with a reversion of 0 and g. The realised fitness of a heuristic is the profit of its last forecast, (x_t - R x_{t-1}) (f_h(t - 1) - R x_{t-1}) / (a sigma^2), minus its cost.

Parameters:

Name Type Description Default
label str

The label of the institution.

required
rule Callable[[SystemView], None] | None

Unused, since the institution overrides act.

None
phase str | None

The phase the institution clears in.

None
traders Role

The path of the group of traders.

required
rate Annotated[float, open(0, oo)]

The gross return R of the riskless asset.

1.1
strength float

The extrapolation g of the trend chasers.

1.2
cost Annotated[float, closed_open(0, oo)]

The cost of the fundamentalist heuristic.

1.0
risk Annotated[float, open(0, oo)]

The risk aversion times the variance of returns, a sigma^2.

1.0
noise Annotated[float, closed_open(0, oo)]

The standard deviation of the noise of the price.

0.01
initial float

The initial deviation of the price from its fundamental value.

0.1

Examples:

>>> from skcomplex.systems.economics.markets import HeuristicPricingInteraction
>>> HeuristicPricingInteraction('pricing', traders='traders').reports
('deviation', 'trend_share', 'fitness_fundamentalist', 'fitness_trend')
Source code in src/skcomplex/systems/economics/markets/_brock_hommes.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def __init__(
    self,
    label: str,
    *,
    rule: Callable[[SystemView], None] | None = None,
    phase: str | None = None,
    traders: Role,
    rate: Annotated[float, RealSet.open(0, oo)] = 1.1,
    strength: float = 1.2,
    cost: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
    risk: Annotated[float, RealSet.open(0, oo)] = 1.0,
    noise: Annotated[float, RealSet.closed_open(0, oo)] = 0.01,
    initial: float = 0.1,
) -> None:
    super().__init__(label, rule=rule, phase=phase)
    self.traders = traders
    self.rate = rate
    self.strength = strength
    self.cost = cost
    self.risk = risk
    self.noise = noise
    self.initial = initial

act(system)

Clear the price from the forecasts of the traders' heuristics.

It also reports the fitnesses.

Parameters:

Name Type Description Default
system SystemView

The system view of the institution.

required
Source code in src/skcomplex/systems/economics/markets/_brock_hommes.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
def act(self, system: SystemView) -> None:
    """Clear the price from the forecasts of the traders' heuristics.

    It also reports the fitnesses.

    Args:
        system:
            The system view of the institution.
    """
    rate, strength = system.get_parameter('rate'), system.get_parameter('strength')
    state = system.storage.get('market')
    if not isinstance(state, _MarketStateSpec):
        state = _MarketStateSpec((system.get_parameter('initial'),))
    history = list(state.history)
    forecasts = np.array(
        [heuristics.fundamental(history), heuristics.fundamental(history, fundamental=0.0, reversion=strength)],
    )
    traders = cast(list[HeuristicTraderView], system.get_agents('traders'))
    share = float(np.mean([trader.predictor for trader in traders])) if traders else 0.0
    price = float(forecasts @ [1 - share, share] + system.rng.normal(0.0, system.get_parameter('noise'))) / rate
    previous = state.forecasts
    excess = price - rate * history[-1]
    if previous is None:
        fitness = np.zeros(len(PREDICTORS))
    else:
        fitness = excess * (previous - rate * history[-1]) / system.get_parameter('risk')
    fitness -= [system.get_parameter('cost'), 0.0]
    system.storage['market'] = _MarketStateSpec((history[-1], price), forecasts)
    system.report('deviation', price)
    system.report('trend_share', share)
    for name, value in zip(PREDICTORS, fitness, strict=True):
        system.report(f'fitness_{name}', value)

HeuristicTraderElement(label, *, predictor=0.0, fundamentalist_fitness=0.0, trend_fitness=0.0, size=None)

Bases: Element

Trader who holds the index of the forecasting heuristic in use.

The index is 0 for the fundamentalist and 1 for the trend. The trader scores every heuristic by its last realised fitness, fundamentalist_fitness and trend_fitness, which a reinforcement of rate 1 sets every step and a logit choice reads.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
predictor Annotated[object, NN]

The index of the heuristic in use.

0.0
fundamentalist_fitness object

The last realised fitness of the fundamentalist heuristic.

0.0
trend_fitness object

The last realised fitness of the trend heuristic.

0.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.markets import HeuristicTraderElement
>>> HeuristicTraderElement('traders', predictor=1.0, size=10).size
10
Source code in src/skcomplex/systems/economics/markets/_brock_hommes.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def __init__(
    self,
    label: str,
    *,
    predictor: Annotated[object, NN] = 0.0,
    fundamentalist_fitness: object = 0.0,
    trend_fitness: object = 0.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.predictor = predictor
    self.fundamentalist_fitness = fundamentalist_fitness
    self.trend_fitness = trend_fitness

get_fitness(agent, system, option) staticmethod

Return the score of a heuristic of a trader, its last realised fitness.

Parameters:

Name Type Description Default
agent HeuristicTraderView

The trader.

required
system SystemView

The system view of the choice.

required
option float

The index of the heuristic.

required

Returns:

Name Type Description
fitness float

The last realised fitness of the heuristic.

Source code in src/skcomplex/systems/economics/markets/_brock_hommes.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
@staticmethod
def get_fitness(agent: HeuristicTraderView, system: SystemView, option: float) -> float:
    """Return the score of a heuristic of a trader, its last realised fitness.

    Args:
        agent:
            The trader.

        system:
            The system view of the choice.

        option:
            The index of the heuristic.

    Returns:
        fitness:
            The last realised fitness of the heuristic.
    """
    return float(getattr(agent, f'{PREDICTORS[int(option)]}_fitness'))

get_realised_fitness(agent, system, index) staticmethod

Return the fitness of a heuristic that the market maker reported last.

It is zero before the first report.

Parameters:

Name Type Description Default
agent HeuristicTraderView

The trader.

required
system SystemView

The system view of the reinforcement.

required
index int

The index of the heuristic.

required

Returns:

Name Type Description
fitness float

The last reported fitness of the heuristic.

Source code in src/skcomplex/systems/economics/markets/_brock_hommes.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
@staticmethod
def get_realised_fitness(agent: HeuristicTraderView, system: SystemView, index: int) -> float:
    """Return the fitness of a heuristic that the market maker reported last.

    It is zero before the first report.

    Args:
        agent:
            The trader.

        system:
            The system view of the reinforcement.

        index:
            The index of the heuristic.

    Returns:
        fitness:
            The last reported fitness of the heuristic.
    """
    reported = system.get_history(f'{PRICING}.fitness_{PREDICTORS[index]}', 1)
    return float(reported[-1]) if len(reported) else 0.0

HouseholdDemandInteraction(label, *, target, kind='cobb-douglas')

Bases: 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.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of households.

required
kind str

The demand, 'cobb-douglas' or 'elasticity'.

'cobb-douglas'

Raises:

Type Description
ValidationError

The demand is unknown, raised by prepare.

Examples:

>>> from skcomplex.systems.economics.markets import HouseholdDemandInteraction
>>> HouseholdDemandInteraction('demand', target='households', kind='elasticity').kind
'elasticity'
Source code in src/skcomplex/systems/economics/markets/_household_demand.py
135
136
137
138
def __init__(self, label: str, *, target: Role, kind: str = 'cobb-douglas') -> None:
    super().__init__(label)
    self.target = target
    self.kind = kind

get_demand(s, price)

Return the demand of the household at a price.

Parameters:

Name Type Description Default
s SimpleNamespace

The namespace of the household.

required
price Expression

The price.

required

Returns:

Name Type Description
demand Expression

The demand for the good.

Source code in src/skcomplex/systems/economics/markets/_household_demand.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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

HouseholdDemandSystem(n_households=1000, *, demand='cobb-douglas', shares=FOOD_SHARES, share_deviation=0.02, elasticities=FOOD_ELASTICITIES, elasticity_deviation=0.1, minimum=100 / 3, change=0.1, random_state=0, label='system', solver='auto', backend='auto')

Bases: 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.

Parameters:

Name Type Description Default
n_households int

The number of households.

1000
demand str

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

'cobb-douglas'
shares Sequence[float]

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

FOOD_SHARES
share_deviation float

The standard deviation of the budget shares within a quintile.

0.02
elasticities Sequence[float]

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

FOOD_ELASTICITIES
elasticity_deviation float

The standard deviation of the elasticities within a quintile.

0.1
minimum float

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

100 / 3
change float

The relative rise of the price every step.

0.1
random_state int | Generator | None

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

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.economics.markets import HouseholdDemandSystem
>>> HouseholdDemandSystem(10).prepare().system_.elements[0].size
10
Source code in src/skcomplex/systems/economics/markets/_household_demand.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
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

IndifferenceInteraction(label, *, target='prices')

Bases: Interaction

Equilibrium distribution of prices that makes a firm indifferent among its prices.

A firm that charges P has the expected profit P (alpha + beta (1 - F)^(m - 1)). In equilibrium every price gives the profit alpha of selling to the loyal share at the highest price 1, which F(P) = 1 - (alpha (1 - P) / (beta P))^(1 / (m - 1)) solves (Forrest 2018 Lemma 20.1). The condition holds at every price of the group it binds.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The prices whose distribution the condition sets.

'prices'

Examples:

>>> from skcomplex.systems.economics.markets import IndifferenceInteraction
>>> IndifferenceInteraction('indifference').target
'prices'
Source code in src/skcomplex/systems/economics/markets/_oligopoly.py
228
229
230
def __init__(self, label: str, *, target: Role = 'prices') -> None:
    super().__init__(label)
    self.target = target

JobOffersInteraction(label, *, firms, workers, phase='offers')

Bases: Interaction

Phase of offers of the labour market, before the firms meet the workers.

Every firm withdraws its last vacancy and posts a new one at the vacancy rate, with a wage offer drawn uniformly from low_wage to high_wage and the step of posting. Every worker unemployed at the start of the step searches, with a reservation wage reservation (1 - decline)^d that falls with the duration d of its search. Every employed worker then loses its job at the separation rate, a worker without a job earns no wage, and the duration of a search grows while the worker searches.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
firms Role

The path of the group of firms.

required
workers Role

The path of the group of workers.

required
phase str | None

The phase the offers run in.

'offers'

Examples:

>>> from skcomplex.systems.economics.markets import JobOffersInteraction
>>> JobOffersInteraction('offers', firms='firms', workers='workers').phase
'offers'
Source code in src/skcomplex/systems/economics/markets/_labour.py
234
235
236
237
238
def __init__(self, label: str, *, firms: Role, workers: Role, phase: str | None = 'offers') -> None:
    super().__init__(label)
    self.firms = firms
    self.workers = workers
    self.phase = phase

offer(system)

Post the vacancies of the firms, then set the search, the separations, and the spells of the workers.

Every step of the phase runs for every firm or worker before the next one.

Parameters:

Name Type Description Default
system SystemView

The system view of the offers.

required
Source code in src/skcomplex/systems/economics/markets/_labour.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
def offer(self, system: SystemView) -> None:
    """Post the vacancies of the firms, then set the search, the separations, and the spells of the workers.

    Every step of the phase runs for every firm or worker before the next one.

    Args:
        system:
            The system view of the offers.
    """
    firms = cast(list[EmployerView], system.get_agents('firms'))
    for firm in firms:
        firm.demand = float(system.rng.random() < firm.vacancy_rate)
    for firm in firms:
        firm.bid = float(system.rng.uniform(firm.low_wage, firm.high_wage)) if firm.demand else firm.bid
    for firm in firms:
        firm.posted = float(system.time if firm.demand else firm.posted)
    workers = cast(list[JobseekerView], system.get_agents('workers'))
    for worker in workers:
        worker.supply = float(worker.employer < 0)
    for worker in workers:
        worker.ask = worker.reservation * (1 - worker.decline) ** worker.duration if worker.supply else worker.ask
    for worker in workers:
        if worker.employer >= 0 and system.rng.random() < worker.separation:
            worker.employer = -1.0
    for worker in workers:
        worker.wage = 0.0 if worker.employer < 0 else worker.wage
    for worker in workers:
        searching = worker.duration + 1 if worker.supply else 0.0 if worker.employer < 0 else worker.duration
        worker.duration = float(searching)

JobseekerElement(label, *, ask=1.0, supply=1.0, employer=-1, wage=0.0, duration=0.0, hired=-1.0, offer=-1.0, separation=0.05, reservation=1.0, decline=0.1, size=None)

Bases: Element

Worker who loses its job at the separation rate.

While unemployed, it lowers its reservation wage. A worker who loses its job searches from the next step. An unemployed worker asks the reservation wage w_0 (1 - decline)^d, where d is the number of steps of search, and is hired by the matching market.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
ask Annotated[object, closed_open(0, oo)]

The reservation wage.

1.0
supply Annotated[object, NN]

One while the worker searches in the current step, zero otherwise.

1.0
employer Annotated[object, Member(firms)]

The index of the employer among the firms, or -1 for an unemployed worker.

-1
wage Annotated[object, closed_open(0, oo)]

The wage of the current job.

0.0
duration Annotated[object, NN]

The number of steps of the current spell of search.

0.0
hired object

The step of the last hire.

-1.0
offer object

The step in which the offer of the last hire was posted.

-1.0
separation Annotated[object, closed_open(0, oo)]

The probability that a job is destroyed in a step.

0.05
reservation Annotated[object, closed_open(0, oo)]

The reservation wage at the start of a search.

1.0
decline Annotated[object, closed_open(0, oo)]

The relative fall of the reservation wage per step of search.

0.1
size int | None

The number of workers, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.markets import JobseekerElement
>>> JobseekerElement('workers', size=5).size
5
Source code in src/skcomplex/systems/economics/markets/_labour.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def __init__(
    self,
    label: str,
    *,
    ask: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
    supply: Annotated[object, NN] = 1.0,
    employer: Annotated[object, Member('firms')] = -1,
    wage: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    duration: Annotated[object, NN] = 0.0,
    hired: object = -1.0,
    offer: object = -1.0,
    separation: Annotated[object, RealSet.closed_open(0, oo)] = 0.05,
    reservation: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
    decline: Annotated[object, RealSet.closed_open(0, oo)] = 0.1,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.ask = ask
    self.supply = supply
    self.employer = employer
    self.wage = wage
    self.duration = duration
    self.hired = hired
    self.offer = offer
    self.separation = separation
    self.reservation = reservation
    self.decline = decline

LabourMarketSystem(n_workers=200, n_firms=40, *, separation=0.05, vacancy_rate=0.3, reservation=1.0, decline=0.1, low_wage=0.5, high_wage=1.0, unemployment=0.5, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Hamill and Gilbert's labour market.

Firms post wage offers and unemployed workers search. In the phase of offers, jobs are destroyed at the separation rate s, every firm posts a vacancy with a uniform wage offer at the vacancy rate, and unemployed workers set reservation wages that fall with the duration of their search. In the phase of matching, a deferred-acceptance market pairs vacancies with workers whose reservation wage they cover, every worker getting the best offer of a stable matching. The unemployment rate settles at the flow-balance value s / (s + f), with f the share of searching workers hired in a step.

The system has the groups firms and workers, the market labour with the reporters labour.value (the mean wage of the hires) and labour.volume (the hires), and the catalog observables of the unemployment rate unemployment and of the searching workers searching.

Parameters:

Name Type Description Default
n_workers int

The number of workers.

200
n_firms int

The number of firms, each with at most one vacancy per step.

40
separation float

The probability s that a job is destroyed in a step.

0.05
vacancy_rate float

The probability that a firm posts a vacancy in a step.

0.3
reservation float

The reservation wage at the start of a search.

1.0
decline float

The relative fall of the reservation wage per step of search.

0.1
low_wage float

The lowest wage offer.

0.5
high_wage float

The highest wage offer.

1.0
unemployment float

The initial share of unemployed workers.

0.5
random_state int | Generator | None

The seed or generator of the initial employment.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.economics.markets import LabourMarketSystem
>>> [group.size for group in LabourMarketSystem(20, 5).prepare().system_.elements]
[5, 20]
Source code in src/skcomplex/systems/economics/markets/_labour.py
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
def __init__(
    self,
    n_workers: int = 200,
    n_firms: int = 40,
    *,
    separation: float = 0.05,
    vacancy_rate: float = 0.3,
    reservation: float = 1.0,
    decline: float = 0.1,
    low_wage: float = 0.5,
    high_wage: float = 1.0,
    unemployment: float = 0.5,
    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_workers = n_workers
    self.n_firms = n_firms
    self.separation = separation
    self.vacancy_rate = vacancy_rate
    self.reservation = reservation
    self.decline = decline
    self.low_wage = low_wage
    self.high_wage = high_wage
    self.unemployment = unemployment
    self.random_state = random_state

MarketElement(label, *, price=1.0)

Bases: Element

Market of one good described by its price.

Parameters:

Name Type Description Default
label str

The label of the market.

required
price float

The initial price.

1.0

Examples:

>>> from skcomplex.systems.economics.markets import MarketElement
>>> MarketElement('wheat', price=2.0).price
2.0
Source code in src/skcomplex/systems/economics/markets/_cobweb.py
39
40
41
42
43
44
45
46
def __init__(
    self,
    label: str,
    *,
    price: float = 1.0,
) -> None:
    super().__init__(label)
    self.price = price

OligopolyEquilibriaSystem(n_firms=2, *, alpha=0.25, n_prices=21, demand=10.0, c_i=1.0, c_j=2.0, lambda_i=0.0, lambda_j=0.0, dynamics='static', label='system', solver='auto', backend='auto')

Bases: BaseSystem

The equilibria of a Cournot duopoly and of a pricing game.

The pricing game has firms with loyal customers and switchers. The static system solves the Cournot best responses (Forrest 2018 Eqs. 21.5-21.6) and, on a grid of prices, the symmetric mixed equilibrium of m firms of loyal share alpha and switchers beta = 1 - m alpha, whose price distribution makes a firm indifferent among its prices, at the profit alpha (Lemma 20.1). With dynamics='fictitious-play', two firms learn to price on the grid instead: every round each plays a best response to the prices of its rival so far, and the prices they charge are distributed near the mixed equilibrium.

The static system, with the states cournot.q_i, cournot.q_j, prices.price, and prices.distribution and the observables lowest_profit and highest_profit, or the learning system, with the group firms and the observables lower_price and higher_price. The catalog lists the observables, so a run passes them in observables.

Parameters:

Name Type Description Default
n_firms int

The number of firms of the pricing game, two under fictitious play.

2
alpha float

The loyal share of every firm.

0.25
n_prices int

The number of prices of the grid from alpha / (alpha + beta) to 1.

21
demand float

The intercept of the inverse demand of the Cournot duopoly.

10.0
c_i float

The unit cost of the first Cournot firm.

1.0
c_j float

The unit cost of the second Cournot firm.

2.0
lambda_i float

The cross holding of the first Cournot firm.

0.0
lambda_j float

The cross holding of the second Cournot firm.

0.0
dynamics str

'static' for the equilibria, or 'fictitious-play' for the learning of two pricing firms.

'static'
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Raises:

Type Description
ValidationError

The dynamics are unknown, or fictitious play has other than two firms.

Examples:

>>> from skcomplex.systems.economics.markets import OligopolyEquilibriaSystem
>>> trajectory = OligopolyEquilibriaSystem().prepare().simulate(until=1.0)
>>> round(float(trajectory.get_values('cournot.q_i')[0]), 6)
3.333333
Source code in src/skcomplex/systems/economics/markets/_oligopoly.py
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
def __init__(
    self,
    n_firms: int = 2,
    *,
    alpha: float = 0.25,
    n_prices: int = 21,
    demand: float = 10.0,
    c_i: float = 1.0,
    c_j: float = 2.0,
    lambda_i: float = 0.0,
    lambda_j: float = 0.0,
    dynamics: str = 'static',
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.n_firms = n_firms
    self.alpha = alpha
    self.n_prices = n_prices
    self.demand = demand
    self.c_i = c_i
    self.c_j = c_j
    self.lambda_i = lambda_i
    self.lambda_j = lambda_j
    self.dynamics = dynamics

PerishableGoodsDuopolySystem(customers=200, *, stock=0.5, T=0.1, alpha=0.9, tau_a=1.0, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Customers who choose between two shops of perishable goods.

They prefer the one that sold fresher goods. Each shop holds stock products per customer, and every sale replaces a product with a fresh one, so the shop with more customers sells fresher goods and attracts more customers. With the control parameter R = 2 stock / tau_a, the symmetric state m = p_1 - p_2 = 0 loses its stability below the temperature T_c = R / (1 + R)^2, and one shop takes most customers. The transition is continuous for R > sqrt(3) - 1 and discontinuous below. One unit of time is N visits by customers drawn with replacement. A visited customer chooses a shop with the probability 1 / (1 + exp(-(S_1 - S_2) / T)) for the first one, moves to it, buys a random product of age tau, of freshness h = exp(-tau / tau_a), which the shop replaces with a fresh one, and updates its satisfaction with that shop alone to alpha S + (1 - alpha) h. The shops are the two nodes of a network on which their products stand.

The system has the groups customers and products, and the asymmetry m of the probabilities of visiting the two shops.

Parameters:

Name Type Description Default
customers int

The number of customers N.

200
stock float

The number of products of each shop per customer.

0.5
T float

The temperature of the choice, the randomness of the customers.

0.1
alpha float

The memory of the satisfaction, between 0 and 1.

0.9
tau_a float

The time over which the products age.

1.0
random_state int | Generator | None

The seed or generator of the initial satisfactions, which scatter by 0.01 around 0.5.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.economics.markets import PerishableGoodsDuopolySystem
>>> PerishableGoodsDuopolySystem(20).prepare().system_.elements[0].size
20
Source code in src/skcomplex/systems/economics/markets/_perishables.py
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
def __init__(
    self,
    customers: int = 200,
    *,
    stock: float = 0.5,
    T: float = 0.1,
    alpha: float = 0.9,
    tau_a: float = 1.0,
    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.customers = customers
    self.stock = stock
    self.T = T
    self.alpha = alpha
    self.tau_a = tau_a
    self.random_state = random_state

PriceAdjustmentInteraction(label, *, target, state, signal, step=0.1, stepping='multiplicative', lower=None, upper=None, phase=None, schedule=None)

Bases: Interaction

Price adjustment of a state of discrete time by the sign of a signal, kept within bounds.

Economics names it a price adjustment by trial and error, as a shop that raises its price while demand exceeds its supply and lowers it otherwise. With the stepping 'multiplicative' the next value of the state x is x (1 + step sign(signal)), and with the stepping 'additive' it is x + step sign(signal), so the state rises while the signal is positive, falls while it is negative, and stays while it is zero, by trial and error rather than by the size of the signal. The next value is then limited to [lower, upper].

Without a schedule it sets an update law, and the signal, the step, and the bounds are numbers or functions of the namespace, where namespace.target holds the states and parameters of the target. With a schedule it sets one rule that walks the agents of the target in that order, and they are numbers or functions f(agent, system) that return numbers. Under the schedule 'synchronous' every agent steps from the values at the start of the rule, under 'sequential' or 'random-sequential' one after the other, in their order or in a new random order, and under 'member' each in its own activation.

Parameters:

Name Type Description Default
label str

The label of the interaction, unique among the components of its system.

required
target Role

The path of the element or group whose state steps.

required
state str

The name of the state of the target.

required
signal Callable[..., object]

The function of the signal whose sign sets the direction of the step.

required
step float | Callable[..., object]

The size of the step, relative with the stepping 'multiplicative', a number or a function.

0.1
stepping str

'multiplicative' or 'additive'.

'multiplicative'
lower float | Callable[..., object] | None

The lowest next value, a number or a function, or None for none.

None
upper float | Callable[..., object] | None

The highest next value, a number or a function, or None for none.

None
phase str | None

The phase of the step the rule of a schedule runs in, or None for the default phase.

None
schedule str | None

The order in which a rule walks the agents, 'synchronous', 'sequential', 'random-sequential', or 'member', or None for an update law of the state of the target.

None

Raises:

Type Description
ValidationError

The stepping or the schedule is unknown, or the signal is not callable, raised by prepare.

Examples:

>>> from skcomplex.core.components.elements import Element
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.economics.markets import PriceAdjustmentInteraction
>>> search = PriceAdjustmentInteraction(
...     'search', target='quote', state='x', signal=lambda s: 2 - s.target.x, step=0.5, upper=2.0
... )
>>> system = System(elements=[Element('quote', values={'x': 1.0})], interactions=[search])
>>> system.prepare().simulate(until=3).get_values('quote.x').tolist()
[1.0, 1.5, 2.0, 2.0]
Source code in src/skcomplex/systems/economics/markets/_shops.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def __init__(
    self,
    label: str,
    *,
    target: Role,
    state: str,
    signal: Callable[..., object],
    step: float | Callable[..., object] = 0.1,
    stepping: str = 'multiplicative',
    lower: float | Callable[..., object] | None = None,
    upper: float | Callable[..., object] | None = None,
    phase: str | None = None,
    schedule: str | None = None,
) -> None:
    super().__init__(label)
    self.target = target
    self.state = state
    self.signal = signal
    self.step = step
    self.stepping = stepping
    self.lower = lower
    self.upper = upper
    self.phase = phase
    self.schedule = schedule

step_agents(system)

Step the state of every agent by the schedule.

Parameters:

Name Type Description Default
system SystemViewProtocol

The system view of the adjustment.

required
Source code in src/skcomplex/systems/economics/markets/_shops.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def step_agents(self, system: SystemViewProtocol) -> None:
    """Step the state of every agent by the schedule.

    Args:
        system:
            The system view of the adjustment.
    """
    agents = list(system.get_agents('target'))
    if self.schedule == 'synchronous':
        values = [self._get_agent_next(agent, system) for agent in agents]
        for agent, value in zip(agents, values, strict=True):
            setattr(agent, self.state, value)
        return
    order = system.rng.permutation(len(agents)) if self.schedule == 'random-sequential' else range(len(agents))
    for index in order:
        self._step_member(agents[int(index)], system)

PricePointElement(label, *, distribution=0.5, price=1.0, alpha=0.25, beta=0.5, n_firms=2.0, size=None)

Bases: Element

Distribution of prices at one price of a pricing game.

IndifferenceInteraction sets it at the equilibrium. A firm that charges P sells to its loyal share alpha, and to the switchers beta when it undercuts all its m - 1 rivals, each with the probability 1 - F(P).

Parameters:

Name Type Description Default
label str

The label of the point or the group.

required
distribution object

The initial guess of F(P), which the equations replace.

0.5
price Annotated[object, open_closed(0, 1)]

The price P.

1.0
alpha Annotated[object, open(0, oo)]

The loyal share of every firm.

0.25
beta Annotated[object, open(0, oo)]

The share of switchers.

0.5
n_firms Annotated[object, closed_open(2, oo)]

The number of firms m.

2.0
size int | None

The number of prices, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.markets import PricePointElement
>>> PricePointElement('point', price=0.5).price
0.5
Source code in src/skcomplex/systems/economics/markets/_oligopoly.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def __init__(
    self,
    label: str,
    *,
    distribution: object = 0.5,
    price: Annotated[object, RealSet.open_closed(0, 1)] = 1.0,
    alpha: Annotated[object, RealSet.open(0, oo)] = 0.25,
    beta: Annotated[object, RealSet.open(0, oo)] = 0.5,
    n_firms: Annotated[object, RealSet.closed_open(2, oo)] = 2.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.distribution = distribution
    self.price = price
    self.alpha = alpha
    self.beta = beta
    self.n_firms = n_firms

get_profit(member) staticmethod

Return the expected profit of a firm at the price of a member.

It serves the observables of a run.

Parameters:

Name Type Description Default
member SimpleNamespace

The namespace of the states and parameters of the member.

required

Returns:

Name Type Description
profit Expression

The expected profit P (alpha + beta (1 - F)^(m - 1)).

Source code in src/skcomplex/systems/economics/markets/_oligopoly.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
@staticmethod
def get_profit(member: SimpleNamespace) -> Expression:
    """Return the expected profit of a firm at the price of a member.

    It serves the observables of a run.

    Args:
        member:
            The namespace of the states and parameters of the member.

    Returns:
        profit:
            The expected profit `P (alpha + beta (1 - F)^(m - 1))`.
    """
    return member.price * (member.alpha + member.beta * (1 - member.distribution) ** (member.n_firms - 1))

PricingFirmElement(label, price=1.0, scores=0.0, size=None)

Bases: Element

Firm that charges one price of a grid.

It counts what every price would have earned.

Parameters:

Name Type Description Default
label str

The label of the firm or the group.

required
price object

The price the firm charges.

1.0
scores ArrayLike

The sum of the payoffs of every price of the grid against the prices of the rival so far.

0.0
size int | None

The number of firms, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.markets import PricingFirmElement
>>> PricingFirmElement('firms', size=2).size
2
Source code in src/skcomplex/systems/economics/markets/_oligopoly.py
349
350
351
352
353
354
355
356
357
358
def __init__(
    self,
    label: str,
    price: object = 1.0,
    scores: npt.ArrayLike = 0.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.price = price
    self.scores = scores

PricingGameSpec(prices, alpha, beta) dataclass

Bases: BaseSpec

Grid of prices of two firms, each with a loyal share.

The firms share the switchers who pay the lower price.

Parameters:

Name Type Description Default
prices Array

The prices the firms choose among, increasing.

required
alpha float

The loyal share of every firm.

required
beta float

The share of switchers.

required

Examples:

>>> import numpy as np
>>> from skcomplex.systems.economics.markets import PricingGameSpec
>>> PricingGameSpec(np.array([0.5, 1.0]), 0.25, 0.5).beta
0.5

get_payoff(agent, system, k)

Return what the price of index k earns against the rival's price.

The rival's price is the one charged in this step.

Parameters:

Name Type Description Default
agent PricingFirmView

The firm.

required
system SystemView

The system view, which holds the rival.

required
k int

The index of the price.

required

Returns:

Name Type Description
payoff float

The profit of the price.

Source code in src/skcomplex/systems/economics/markets/_oligopoly.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
def get_payoff(self, agent: PricingFirmView, system: SystemView, k: int) -> float:
    """Return what the price of index `k` earns against the rival's price.

    The rival's price is the one charged in this step.

    Args:
        agent:
            The firm.

        system:
            The system view, which holds the rival.

        k:
            The index of the price.

    Returns:
        payoff:
            The profit of the price.
    """
    rival = cast(PricingFirmView, next(item for item in system.get_agents(agent.group) if item.id != agent.id))
    price, against = float(self.prices[k]), float(rival.price)
    share = 1.0 if price < against else 0.5 if price == against else 0.0
    return price * (self.alpha + self.beta * share)

get_utility(agent, system, option)

Return what a price has earned so far against the prices of the rival.

It is its score.

Parameters:

Name Type Description Default
agent PricingFirmView

The firm.

required
system SystemView

The system view, which the score does not read.

required
option float

The price.

required

Returns:

Name Type Description
utility float

The score of the price.

Source code in src/skcomplex/systems/economics/markets/_oligopoly.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
def get_utility(self, agent: PricingFirmView, system: SystemView, option: float) -> float:
    """Return what a price has earned so far against the prices of the rival.

    It is its score.

    Args:
        agent:
            The firm.

        system:
            The system view, which the score does not read.

        option:
            The price.

    Returns:
        utility:
            The score of the price.
    """
    return float(agent.scores[int(np.searchsorted(self.prices, option))])

ProduceMarketSystem(n_shoppers=50, n_stalls=9, *, n_items_stocked=6, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Hamill and Gilbert's produce market.

Shoppers with lists of produce visit stalls at random. There are twelve kinds of fruit and vegetables. Every stall sells a random selection of them at its own markup of 1 to 30 percent on the wholesale prices, and every shopper wants between one and eight of them. The system has the groups stalls and shoppers, the mean number of items left on the lists items_left, and the mean money spent spent.

Parameters:

Name Type Description Default
n_shoppers int

The number of shoppers.

50
n_stalls int

The number of stalls.

9
n_items_stocked int

The number of kinds of produce that every stall sells.

6
random_state int | Generator | None

The seed or generator of the stocks, the markups, and the shopping lists.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.economics.markets import ProduceMarketSystem
>>> [group.size for group in ProduceMarketSystem(10, 3).prepare().system_.elements]
[3, 10]
Source code in src/skcomplex/systems/economics/markets/_produce.py
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
def __init__(
    self,
    n_shoppers: int = 50,
    n_stalls: int = 9,
    *,
    n_items_stocked: int = 6,
    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_shoppers = n_shoppers
    self.n_stalls = n_stalls
    self.n_items_stocked = n_items_stocked
    self.random_state = random_state

ProductElement(label, *, shelved=0.0, tau_a=1.0, values=None, size=None, space=None)

Bases: Element

Product on the shelf of a shop, which ages from the time it was shelved.

Its freshness is exp(-age / tau_a).

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
shelved object

The time at which the product was put on the shelf.

0.0
tau_a Annotated[object, open(0, oo)]

The time over which the product ages.

1.0
values Mapping[str, object] | None

Further values by name, such as the node of the shop of every member.

None
size int | None

The number of members, or None for one.

None
space BaseSpace | None

The network whose nodes are the shops, or None for none.

None

Examples:

>>> from skcomplex.systems.economics.markets import ProductElement
>>> ProductElement('products', values={'node': [0, 0, 1, 1]}, size=4).size
4
Source code in src/skcomplex/systems/economics/markets/_perishables.py
218
219
220
221
222
223
224
225
226
227
228
229
230
def __init__(
    self,
    label: str,
    *,
    shelved: object = 0.0,
    tau_a: Annotated[object, RealSet.open(0, oo)] = 1.0,
    values: Mapping[str, object] | None = None,
    size: int | None = None,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, values=values, size=size, space=space)
    self.shelved = shelved
    self.tau_a = tau_a

ProgramMemberElement(label, *, acres=0.0, level=0.0, traded=0.0, size=None)

Bases: Element

Tomato buyer or farm with its acres of tomatoes.

It holds its level in the Fair Food Program and what it traded. A buyer needs acres of tomatoes every period and has the level 0 outside the programme, 1 when it buys from member farms first, and 2 when it buys only from member farms. A farm grows acres of tomatoes and has the level 0 outside the programme and 1 inside. traded is what a buyer bought or a farm sold in the period.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
acres Annotated[object, closed_open(0, oo)]

The tomatoes a buyer needs or a farm grows every period, in acres.

0.0
level Annotated[object, NN]

The level of involvement in the programme.

0.0
traded Annotated[object, closed_open(0, oo)]

The tomatoes bought or sold in the period.

0.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.markets import ProgramMemberElement
>>> ProgramMemberElement('farms', acres=10.0, size=3).size
3
Source code in src/skcomplex/systems/economics/markets/_fair_food_program.py
72
73
74
75
76
77
78
79
80
81
82
83
84
def __init__(
    self,
    label: str,
    *,
    acres: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    level: Annotated[object, NN] = 0.0,
    traded: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.acres = acres
    self.level = level
    self.traded = traded

QuotingInteraction(label, *, buyers, sellers, phase='trade')

Bases: Interaction

Quotes of the zero-intelligence traders in every round.

Every buyer bids a price drawn uniformly from 0 to its value and every seller asks a price drawn uniformly from its cost to the price ceiling. Without the budget constraint, the bid goes up to the ceiling and the ask starts from 0.

Parameters:

Name Type Description Default
label str

The label of the quotes.

required
buyers Role

The path of the group of buyers.

required
sellers Role

The path of the group of sellers.

required
phase str | None

The phase the traders quote in.

'trade'

Examples:

>>> from skcomplex.systems.economics.markets import QuotingInteraction
>>> QuotingInteraction('quotes', buyers='buyers', sellers='sellers').phase
'trade'
Source code in src/skcomplex/systems/economics/markets/_double_auction.py
234
235
236
237
238
def __init__(self, label: str, *, buyers: Role, sellers: Role, phase: str | None = 'trade') -> None:
    super().__init__(label)
    self.buyers = buyers
    self.sellers = sellers
    self.phase = phase

quote(system)

Draw the bid of every buyer and then the ask of every seller.

Parameters:

Name Type Description Default
system SystemView

The system view of the quotes.

required
Source code in src/skcomplex/systems/economics/markets/_double_auction.py
250
251
252
253
254
255
256
257
258
259
260
261
def quote(self, system: SystemView) -> None:
    """Draw the bid of every buyer and then the ask of every seller.

    Args:
        system:
            The system view of the quotes.
    """
    for buyer in cast(list[ZeroIntelligenceBuyerView], system.get_agents('buyers')):
        buyer.bid = float(system.rng.uniform(0.0, buyer.value if buyer.constrained else buyer.ceiling))
    for seller in cast(list[ZeroIntelligenceSellerView], system.get_agents('sellers')):
        bottom = seller.value if seller.constrained else 0.0
        seller.ask = float(system.rng.uniform(bottom, max(bottom, seller.ceiling)))

ResidentElement(label, *, bid=20.0, demand=1.0, money=1000.0, travel=1.0, distance_cost=1.0, online=0.0, values=None, size=None, space=None)

Bases: Element

Shopper who wants one unit a step.

It shops in person, paying for travel, or online, where distance is free.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
bid Annotated[object, closed_open(0, oo)]

The highest price the shopper pays.

20.0
demand Annotated[object, closed_open(0, oo)]

The units still wanted in the step.

1.0
money object

The money of the shopper.

1000.0
travel Annotated[object, closed_open(0, oo)]

The travel cost per cell of the current step, zero online.

1.0
distance_cost Annotated[object, closed_open(0, oo)]

The travel cost per cell of shopping in person.

1.0
online Annotated[object, closed_open(0, oo)]

The probability of shopping online in a step.

0.0
values Mapping[str, object] | None

Further values by name, such as the cell x and y of every member.

None
size int | None

The number of members, or None for one.

None
space BaseSpace | None

The grid whose axes x and y place the members, or None for none.

None

Examples:

>>> from skcomplex.systems.economics.markets import ResidentElement
>>> ResidentElement('shoppers', online=1.0, size=3).size
3
Source code in src/skcomplex/systems/economics/markets/_shops.py
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
def __init__(
    self,
    label: str,
    *,
    bid: Annotated[object, RealSet.closed_open(0, oo)] = 20.0,
    demand: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
    money: object = 1000.0,
    travel: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
    distance_cost: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
    online: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    values: Mapping[str, object] | None = None,
    size: int | None = None,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, values=values, size=size, space=space)
    self.bid = bid
    self.demand = demand
    self.money = money
    self.travel = travel
    self.distance_cost = distance_cost
    self.online = online

get_preference(shopper, shop) staticmethod

Return the preference of a shopper for a shop.

It is the opposite of the delivered price. The delivered price is the shop's ask plus the shopper's travel cost per cell times the distance to the shop.

Parameters:

Name Type Description Default
shopper object

The shopper.

required
shop object

The shop.

required

Returns:

Name Type Description
preference float

The opposite of the delivered price, higher for a preferred shop.

Source code in src/skcomplex/systems/economics/markets/_shops.py
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
@staticmethod
def get_preference(shopper: object, shop: object) -> float:
    """Return the preference of a shopper for a shop.

    It is the opposite of the delivered price. The delivered price is the shop's ask plus the shopper's travel cost
    per cell times the distance to the shop.

    Args:
        shopper:
            The shopper.

        shop:
            The shop.

    Returns:
        preference:
            The opposite of the delivered price, higher for a preferred shop.
    """
    if not isinstance(shopper, ResidentView) or not isinstance(shop, StoreView):
        return -math.inf
    return -(shop.ask + shopper.travel * shopper.get_distance_to(shop))

RetailDemandInteraction(label, *, retailer)

Bases: Interaction

Customers of a supply chain, who take the shipments of the retailer.

The sales are a flow out of the inventory of the retailer.

Parameters:

Name Type Description Default
label str

The label of the customers.

required
retailer Role

The path of the retailer.

required

Examples:

>>> from skcomplex.systems.economics.markets import RetailDemandInteraction
>>> RetailDemandInteraction('customers', retailer='retailer').retailer
'retailer'
Source code in src/skcomplex/systems/economics/markets/_supply_chains.py
438
439
440
441
442
443
444
445
def __init__(
    self,
    label: str,
    *,
    retailer: Role,
) -> None:
    super().__init__(label)
    self.retailer = retailer

RetailerElement(label, *, inventory=12.0, in_transit=8.0, backlog=4.0, expected=4.0, supply_line=16.0, desired=13.44, theta=0.36, alpha=0.26, beta=0.34, dispatch_time=1.0, mail_delay=2.0, shipping_delay=2.0, demand=4.0, demand_step=4.0, step_time=5.0)

Bases: EchelonElement

Retailer of a supply chain.

It is an echelon whose customers order their demand, which steps once.

Parameters:

Name Type Description Default
label str

The label of the retailer.

required
inventory Annotated[float, closed_open(0, oo), Quantity(beer)]

The initial inventory, in cases.

12.0
in_transit Annotated[float, closed_open(0, oo), Quantity(beer)]

The initial beer on its way to the echelon.

8.0
backlog Annotated[float, closed_open(0, oo)]

The initial orders waiting to ship.

4.0
expected Annotated[float, closed_open(0, oo)]

The initial expected demand.

4.0
supply_line Annotated[float, closed_open(0, oo)]

The initial beer ordered and not received.

16.0
desired float

The desired stock S'.

13.44
theta Annotated[float, closed_open(0, oo)]

The rate at which the expected demand adapts to incoming orders.

0.36
alpha Annotated[float, closed_open(0, oo)]

The fraction of the stock gap ordered per week.

0.26
beta Annotated[float, closed_open(0, oo)]

The weight of the supply line in the stock gap.

0.34
dispatch_time Annotated[float, open(0, oo)]

The time over which the echelon ships its backlog.

1.0
mail_delay Annotated[float, open(0, oo)]

The average time an order of the echelon takes to reach its supplier.

2.0
shipping_delay Annotated[float, open(0, oo)]

The average time a shipment takes to reach the echelon from its supplier.

2.0
demand Annotated[float, closed_open(0, oo)]

The customer demand, in cases a week.

4.0
demand_step float

The permanent change of the demand.

4.0
step_time Annotated[float, closed_open(0, oo)]

The week of the change of the demand.

5.0

Examples:

>>> from skcomplex.systems.economics.markets import RetailerElement
>>> RetailerElement('retailer').demand
4.0
Source code in src/skcomplex/systems/economics/markets/_supply_chains.py
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
def __init__(
    self,
    label: str,
    *,
    inventory: Annotated[float, RealSet.closed_open(0, oo), Quantity('beer')] = 12.0,
    in_transit: Annotated[float, RealSet.closed_open(0, oo), Quantity('beer')] = 8.0,
    backlog: Annotated[float, RealSet.closed_open(0, oo)] = 4.0,
    expected: Annotated[float, RealSet.closed_open(0, oo)] = 4.0,
    supply_line: Annotated[float, RealSet.closed_open(0, oo)] = 16.0,
    desired: float = 13.44,
    theta: Annotated[float, RealSet.closed_open(0, oo)] = 0.36,
    alpha: Annotated[float, RealSet.closed_open(0, oo)] = 0.26,
    beta: Annotated[float, RealSet.closed_open(0, oo)] = 0.34,
    dispatch_time: Annotated[float, RealSet.open(0, oo)] = 1.0,
    mail_delay: Annotated[float, RealSet.open(0, oo)] = 2.0,
    shipping_delay: Annotated[float, RealSet.open(0, oo)] = 2.0,
    demand: Annotated[float, RealSet.closed_open(0, oo)] = 4.0,
    demand_step: float = 4.0,
    step_time: Annotated[float, RealSet.closed_open(0, oo)] = 5.0,
) -> None:
    super().__init__(
        label,
        inventory=inventory,
        in_transit=in_transit,
        backlog=backlog,
        expected=expected,
        supply_line=supply_line,
        desired=desired,
        theta=theta,
        alpha=alpha,
        beta=beta,
        dispatch_time=dispatch_time,
        mail_delay=mail_delay,
        shipping_delay=shipping_delay,
    )
    self.demand = demand
    self.demand_step = demand_step
    self.step_time = step_time

RiccatiPricesSystem(price=1.0, *, k=1.0, beta=10.0, lam=1.0, delta=1.0, alpha=2.0, gamma=-0.1, label='system', solver='auto', backend='auto')

Bases: DynamicalSystem

A price that moves with excess demand.

Demand is linear and supply is quadratic and saturating. The price follows the Riccati equation dP/dt = k (D - S) with demand D = beta - lam P and supply S = delta + alpha P + gamma P^2. When (lam + alpha)^2 > 4 gamma (delta - beta) there are two equilibrium prices, and prices below the larger one converge to the smaller one. Otherwise the price blows up in finite time. The system has the price market.P.

Parameters:

Name Type Description Default
price float

The initial price.

1.0
k float

The speed of the price adjustment.

1.0
beta float

The demand at price zero.

10.0
lam float

The slope of the demand.

1.0
delta float

The supply at price zero.

1.0
alpha float

The linear intensity of the supply.

2.0
gamma float

The quadratic intensity of the supply, negative for saturation.

-0.1
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.economics.markets import RiccatiPricesSystem
>>> RiccatiPricesSystem(gamma=-0.2).prepare().system_.elements[0].values['gamma']
-0.2
Source code in src/skcomplex/systems/economics/markets/_prices.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def __init__(
    self,
    price: float = 1.0,
    *,
    k: float = 1.0,
    beta: float = 10.0,
    lam: float = 1.0,
    delta: float = 1.0,
    alpha: float = 2.0,
    gamma: float = -0.1,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label=label, solver=solver, backend=backend)
    self.price = price
    self.k = k
    self.beta = beta
    self.lam = lam
    self.delta = delta
    self.alpha = alpha
    self.gamma = gamma

ShopperElement(label, *, wanted=0, visited=0, missed=0, spent=0.0, values=None, size=None, space=None)

Bases: Element

Shopper with a shopping list, who visits stalls by ShoppingInteraction.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
wanted Annotated[object, NN]

The bit mask of the items on the shopping list.

0
visited Annotated[object, NN]

The bit mask of the stalls already visited.

0
missed Annotated[object, NN]

The bit mask of the items given up.

0
spent Annotated[object, closed_open(0, oo)]

The money spent.

0.0
values Mapping[str, object] | None

Further values by name, or None for none.

None
size int | None

The number of shoppers, or None for one.

None
space BaseSpace | None

The space of the shoppers, or None for none.

None

Examples:

>>> from skcomplex.systems.economics.markets import ShopperElement
>>> ShopperElement('shoppers', wanted=3, size=5).size
5
Source code in src/skcomplex/systems/economics/markets/_produce.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def __init__(
    self,
    label: str,
    *,
    wanted: Annotated[object, NN] = 0,
    visited: Annotated[object, NN] = 0,
    missed: Annotated[object, NN] = 0,
    spent: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    values: Mapping[str, object] | None = None,
    size: int | None = None,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, values=values, size=size, space=space)
    self.wanted = wanted
    self.visited = visited
    self.missed = missed
    self.spent = spent

ShoppingInteraction(label, *, target, stalls)

Bases: Interaction

Shopping of every shopper, who visits one stall a step and buys what it wants there.

A shopper only visits stalls it has not visited yet, and gives up the items that it has not found once it has visited every stall.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of shoppers.

required
stalls Role

The path of the group of stalls.

required

Examples:

>>> from skcomplex.systems.economics.markets import ShoppingInteraction
>>> ShoppingInteraction('shopping', target='shoppers', stalls='stalls').stalls
'stalls'
Source code in src/skcomplex/systems/economics/markets/_produce.py
136
137
138
139
def __init__(self, label: str, *, target: Role, stalls: Role) -> None:
    super().__init__(label)
    self.target = target
    self.stalls = stalls

shop(agent, system)

Visit a random stall not visited yet and buy every wanted item that it sells.

Parameters:

Name Type Description Default
agent ShopperView

The shopper.

required
system SystemView

The system.

required
Source code in src/skcomplex/systems/economics/markets/_produce.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
def shop(self, agent: ShopperView, system: SystemView) -> None:
    """Visit a random stall not visited yet and buy every wanted item that it sells.

    Args:
        agent:
            The shopper.

        system:
            The system.
    """
    wanted, visited = int(agent.wanted), int(agent.visited)
    if not wanted:
        return
    unvisited = [
        stall for stall in cast(list[StallView], system.get_agents('stalls')) if not visited >> int(stall.stall) & 1
    ]
    if not unvisited:
        agent.missed, agent.wanted = wanted, 0
        return
    stall = unvisited[int(system.rng.integers(len(unvisited)))]
    bought = wanted & int(stall.stock)
    agent.visited = visited | 1 << int(stall.stall)
    agent.spent += (1 + stall.markup) * sum(WHOLESALE_PRICES[item] for item in _items_of(bought))
    agent.wanted = wanted & ~bought

ShopsSystem(n_shops=16, *, width=20, height=20, online=0.0, distance_cost=1.0, capacity=1000.0, fixed_cost=20.0, value=20.0, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Shops on a grid that compete for the shoppers on every cell.

The shoppers buy in person or in a digital market. Every step every shopper wants one unit and shops online with probability online, and in person otherwise, when it pays a travel cost for the distance to the shop. The shoppers choose in random order the shops they prefer by price plus travel cost, within the shops' capacities, a greedy matching that pays the shop's ask for a unit. Shops search for the price of the largest profit by trial and error, pay a fixed cost every step, and close when their money runs out. Distance gives every shop a local market, so many shops survive with high prices. In the digital market the cheapest shop takes every shopper, the others undercut it, prices fall toward the unit cost, and most shops close (Hamill and Gilbert 2016 sec. 6.3-6.4).

The system has the groups shoppers and shops and the market shopping, whose reporters are the shopping.value, shopping.volume, and shopping.unmatched of the purchases.

Parameters:

Name Type Description Default
n_shops int

The initial number of shops.

16
width int

The number of columns of the grid, with one shopper per cell.

20
height int

The number of rows of the grid.

20
online float

The probability that a shopper shops online in a step.

0.0
distance_cost float

The travel cost per cell of shopping in person.

1.0
capacity float

The units every shop can sell in a step.

1000.0
fixed_cost float

The cost of running a shop for a step.

20.0
value float

The highest price a shopper pays.

20.0
random_state int | Generator | None

The seed or generator of the cells and initial prices of the shops.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.economics.markets import ShopsSystem
>>> [group.size for group in ShopsSystem(4, width=5, height=5).prepare().system_.elements]
[25, 4]
Source code in src/skcomplex/systems/economics/markets/_shops.py
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
def __init__(
    self,
    n_shops: int = 16,
    *,
    width: int = 20,
    height: int = 20,
    online: float = 0.0,
    distance_cost: float = 1.0,
    capacity: float = 1000.0,
    fixed_cost: float = 20.0,
    value: float = 20.0,
    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_shops = n_shops
    self.width = width
    self.height = height
    self.online = online
    self.distance_cost = distance_cost
    self.capacity = capacity
    self.fixed_cost = fixed_cost
    self.value = value
    self.random_state = random_state

StallElement(label, *, stall=0, stock=0, markup=0.1, values=None, size=None, space=None)

Bases: Element

Market stall that sells some kinds of produce.

It sells at the wholesale price plus its markup.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
stall Annotated[object, NN]

The index of the stall.

0
stock Annotated[object, NN]

The bit mask of the kinds of produce that the stall sells.

0
markup Annotated[object, closed_open(0, oo)]

The relative markup on the wholesale prices.

0.1
values Mapping[str, object] | None

Further values by name, or None for none.

None
size int | None

The number of stalls, or None for one.

None
space BaseSpace | None

The space of the stalls, or None for none.

None

Examples:

>>> from skcomplex.systems.economics.markets import StallElement
>>> StallElement('stalls', stall=[0, 1, 2], size=3).size
3
Source code in src/skcomplex/systems/economics/markets/_produce.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def __init__(
    self,
    label: str,
    *,
    stall: Annotated[object, NN] = 0,
    stock: Annotated[object, NN] = 0,
    markup: Annotated[object, RealSet.closed_open(0, oo)] = 0.1,
    values: Mapping[str, object] | None = None,
    size: int | None = None,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, values=values, size=size, space=space)
    self.stall = stall
    self.stock = stock
    self.markup = markup

StoreElement(label, *, price=10.0, ask=10.0, supply=0.0, sales=0.0, money=100.0, profit=0.0, direction=1.0, capacity=1000.0, unit_cost=1.0, fixed_cost=20.0, adjustment=0.05, values=None, size=None, space=None)

Bases: Element

Shop that offers its capacity at its price.

It searches for the price of the largest profit, and may close. The shop searches for its price by trial and error: it moves the price by adjustment in the same direction as long as its profit grows, and turns back when the profit falls, never below the unit cost. It pays the unit cost of every unit sold and the fixed cost every step, and closes when its money runs out.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
price Annotated[object, closed_open(0, oo)]

The price of a unit.

10.0
ask Annotated[object, closed_open(0, oo)]

The price offered in the current step.

10.0
supply Annotated[object, closed_open(0, oo)]

The units still offered in the step.

0.0
sales Annotated[object, closed_open(0, oo)]

The units sold in the last step.

0.0
money object

The money of the shop.

100.0
profit object

The profit of the last step.

0.0
direction object

The direction of the last change of the price, 1 up or -1 down.

1.0
capacity Annotated[object, open(0, oo)]

The units the shop can sell in a step.

1000.0
unit_cost Annotated[object, closed_open(0, oo)]

The cost of a unit sold.

1.0
fixed_cost Annotated[object, closed_open(0, oo)]

The cost of running the shop for a step.

20.0
adjustment Annotated[object, closed_open(0, oo)]

The relative change of the price in a step.

0.05
values Mapping[str, object] | None

Further values by name, such as the cell x and y of every member.

None
size int | None

The number of members, or None for one.

None
space BaseSpace | None

The grid whose axes x and y place the members, or None for none.

None

Examples:

>>> from skcomplex.systems.economics.markets import StoreElement
>>> StoreElement('shops', price=10.0, size=4).size
4
Source code in src/skcomplex/systems/economics/markets/_shops.py
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
def __init__(
    self,
    label: str,
    *,
    price: Annotated[object, RealSet.closed_open(0, oo)] = 10.0,
    ask: Annotated[object, RealSet.closed_open(0, oo)] = 10.0,
    supply: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    sales: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    money: object = 100.0,
    profit: object = 0.0,
    direction: object = 1.0,
    capacity: Annotated[object, RealSet.open(0, oo)] = 1000.0,
    unit_cost: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
    fixed_cost: Annotated[object, RealSet.closed_open(0, oo)] = 20.0,
    adjustment: Annotated[object, RealSet.closed_open(0, oo)] = 0.05,
    values: Mapping[str, object] | None = None,
    size: int | None = None,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, values=values, size=size, space=space)
    self.price = price
    self.ask = ask
    self.supply = supply
    self.sales = sales
    self.money = money
    self.profit = profit
    self.direction = direction
    self.capacity = capacity
    self.unit_cost = unit_cost
    self.fixed_cost = fixed_cost
    self.adjustment = adjustment

get_profit(agent) staticmethod

Return the profit of the step, the margin on the units sold less the fixed cost.

Parameters:

Name Type Description Default
agent StoreView

The shop.

required

Returns:

Name Type Description
profit float

The profit of the step.

Source code in src/skcomplex/systems/economics/markets/_shops.py
446
447
448
449
450
451
452
453
454
455
456
457
458
@staticmethod
def get_profit(agent: StoreView) -> float:
    """Return the profit of the step, the margin on the units sold less the fixed cost.

    Args:
        agent:
            The shop.

    Returns:
        profit:
            The profit of the step.
    """
    return agent.sales * (agent.ask - agent.unit_cost) - agent.fixed_cost

record_sale(match, system) staticmethod

Count the units of a purchase in the sales of the shop.

Parameters:

Name Type Description Default
match MatchSpec

The purchase of a shopper, the requester, from a shop, the provider.

required
system SystemView

The system view of the market.

required
Source code in src/skcomplex/systems/economics/markets/_shops.py
460
461
462
463
464
465
466
467
468
469
470
471
472
473
@staticmethod
def record_sale(match: MatchSpec, system: SystemView) -> None:
    """Count the units of a purchase in the sales of the shop.

    Args:
        match:
            The purchase of a shopper, the requester, from a shop, the provider.

        system:
            The system view of the market.
    """
    shop = match.provider
    if isinstance(shop, StoreView):
        shop.sales += match.quantity

SugarPatchElement(label, *, sugar=0.0, capacity=0.0, growback=1.0, values=None, size=None, space=None)

Bases: Element

Cell of the landscape whose sugar grows back up to its capacity.

The sugar grows back by a fixed amount a step. The growback is a RegrowthInteraction of the group of patches.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
sugar Annotated[object, closed_open(0, oo)]

The sugar on the patch.

0.0
capacity Annotated[object, closed_open(0, oo)]

The most sugar the patch holds.

0.0
growback Annotated[object, closed_open(0, oo)]

The sugar that grows back in a step.

1.0
values Mapping[str, object] | None

Further values by name, such as the cell x and y of every member.

None
size int | None

The number of members, or None for one.

None
space BaseSpace | None

The grid whose axes x and y place the members, or None for none.

None

Examples:

>>> from skcomplex.systems.economics.markets import SugarPatchElement
>>> SugarPatchElement('patches', capacity=2.0, size=4).size
4
Source code in src/skcomplex/systems/economics/markets/_sugarscape.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def __init__(
    self,
    label: str,
    *,
    sugar: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    capacity: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    growback: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
    values: Mapping[str, object] | None = None,
    size: int | None = None,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, values=values, size=size, space=space)
    self.sugar = sugar
    self.capacity = capacity
    self.growback = growback

SugarscapeSystem(width=50, height=50, *, n_foragers=400, max_vision=6, max_metabolism=4.0, low_sugar=5.0, high_sugar=25.0, growback=1.0, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The Sugarscape of Epstein and Axtell.

Foragers of random vision and metabolism live on two sugar peaks. Every step the foragers, in random order, move to the richest free cell in sight, harvest it, and burn their metabolism, and those whose wealth falls below zero die. Then the sugar grows back. Foragers of poor vision or high metabolism starve, so the population falls to the carrying capacity of the landscape, and the wealth of the survivors becomes skewed, with a Gini coefficient that rises from its initial value. The system has the groups patches and foragers, whose catalog observables are the population population and the Gini coefficient of wealth gini.

Parameters:

Name Type Description Default
width int

The number of columns.

50
height int

The number of rows.

50
n_foragers int

The initial number of foragers.

400
max_vision int

The largest vision, every forager seeing from 1 to max_vision cells.

6
max_metabolism float

The largest metabolism, every forager burning from 1 to max_metabolism sugar a step.

4.0
low_sugar float

The lowest initial wealth.

5.0
high_sugar float

The highest initial wealth.

25.0
growback float

The sugar that grows back on every patch in a step.

1.0
random_state int | Generator | None

The seed or generator of the foragers' cells, visions, metabolisms, and wealth.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.economics.markets import SugarscapeSystem
>>> [group.size for group in SugarscapeSystem(10, 10, n_foragers=20).prepare().system_.elements]
[100, 20]
Source code in src/skcomplex/systems/economics/markets/_sugarscape.py
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
def __init__(
    self,
    width: int = 50,
    height: int = 50,
    *,
    n_foragers: int = 400,
    max_vision: int = 6,
    max_metabolism: float = 4.0,
    low_sugar: float = 5.0,
    high_sugar: float = 25.0,
    growback: float = 1.0,
    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.width = width
    self.height = height
    self.n_foragers = n_foragers
    self.max_vision = max_vision
    self.max_metabolism = max_metabolism
    self.low_sugar = low_sugar
    self.high_sugar = high_sugar
    self.growback = growback
    self.random_state = random_state

SupplyLinkInteraction(label, *, downstream, upstream)

Bases: Interaction

Link of a supply chain.

It ships beer from the upstream echelon to the downstream echelon. The shipments flow from the inventory of the upstream echelon to the beer in transit to the downstream echelon, and the arrivals, after a third-order delay of the shipping delay of the downstream echelon, flow on to its inventory.

Parameters:

Name Type Description Default
label str

The label of the link.

required
downstream Role

The path of the echelon that orders.

required
upstream Role

The path of the echelon that ships.

required

Examples:

>>> from skcomplex.systems.economics.markets import SupplyLinkInteraction
>>> SupplyLinkInteraction('link', downstream='retailer', upstream='wholesaler').upstream
'wholesaler'
Source code in src/skcomplex/systems/economics/markets/_supply_chains.py
484
485
486
487
488
489
490
491
492
493
def __init__(
    self,
    label: str,
    *,
    downstream: Role,
    upstream: Role,
) -> None:
    super().__init__(label)
    self.downstream = downstream
    self.upstream = upstream

TillElement(label, *, revenue=0.0, washes=0, valets=0, turned_away=0, size=None)

Bases: Element

Till of the car wash.

It counts the revenue and the cars served and turned away.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
revenue Annotated[object, closed_open(0, oo)]

The money taken.

0.0
washes Annotated[object, NN]

The number of cars that left after a wash only.

0
valets Annotated[object, NN]

The number of cars that left after a valet.

0
turned_away Annotated[object, NN]

The number of drivers who did not turn in because of the queue.

0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.markets import TillElement
>>> TillElement('till', size=1).size
1
Source code in src/skcomplex/systems/economics/markets/_queues.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def __init__(
    self,
    label: str,
    *,
    revenue: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    washes: Annotated[object, NN] = 0,
    valets: Annotated[object, NN] = 0,
    turned_away: Annotated[object, NN] = 0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.revenue = revenue
    self.washes = washes
    self.valets = valets
    self.turned_away = turned_away

ToyMarketInteraction(label, *, rule=None, phase=None, traders, sight=1.0, mutation=0.0, imitation=0.1, elite=0.05, size=51.0, n_goods=1, fitness='none')

Bases: PolicyRuleInteraction[SystemView]

Market of the Toy Trader.

Every trader buys the cheapest good it can see, sellers price by inventory, and all move. Every iteration the traders, in random order, try to buy one unit of every good from the trader with the lowest price within the radius sight, picking at random among equal prices, and buy it when they can pay. After a sale the seller lowers its price by its factor price_down when its stock is above the target and raises it by price_up when it is below, never below 0.5. Then every trader moves one unit in a random direction on the torus. Toys are priced by the trader's own factors, which mutate with the probability mutation by the difference of two uniform draws on [0, 0.01), and crayons and blackboards by the factors 1.0101 and 0.99. With a fitness test, a trader of the poorest half copies with the probability imitation the toy price of a random trader of the richest elite share and, each with probability one half, its factors plus a uniform mutation on [-0.01, 0.01].

Parameters:

Name Type Description Default
label str

The label of the market.

required
rule None

Unused, since the market overrides act.

None
phase str | None

The phase the market acts in, or None for the default phase.

None
traders Role

The path of the group of traders.

required
sight Annotated[float, open(0, oo)]

The radius within which a trader sees prices, its market sight.

1.0
mutation Annotated[float, closed(0, 1)]

The probability per iteration that a factor of the toy price mutates.

0.0
imitation Annotated[float, closed(0, 1)]

The probability per iteration that a poor trader imitates a rich one.

0.1
elite Annotated[float, open(0, 1)]

The share of the richest traders that poor traders imitate.

0.05
size Annotated[float, open(0, oo)]

The side of the torus.

51.0
n_goods int

The goods traded, 1 for toys only or 3 for toys, crayons, and blackboards.

1
fitness str

The fitness test of imitation, 'none', 'money', or 'assets'.

'none'

Raises:

Type Description
ValidationError

The fitness test or the number of goods is unknown, raised by prepare.

Examples:

>>> from skcomplex.systems.economics.markets import ToyMarketInteraction
>>> ToyMarketInteraction('market', traders='traders').reports[:2]
('average_price', 'trades')
Source code in src/skcomplex/systems/economics/markets/_toy_trader.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def __init__(
    self,
    label: str,
    *,
    rule: None = None,
    phase: str | None = None,
    traders: Role,
    sight: Annotated[float, RealSet.open(0, oo)] = 1.0,
    mutation: Annotated[float, RealSet.closed(0, 1)] = 0.0,
    imitation: Annotated[float, RealSet.closed(0, 1)] = 0.1,
    elite: Annotated[float, RealSet.open(0, 1)] = 0.05,
    size: Annotated[float, RealSet.open(0, oo)] = 51.0,
    n_goods: int = 1,
    fitness: str = 'none',
) -> None:
    super().__init__(label, rule=rule, phase=phase)
    self.traders = traders
    self.sight = sight
    self.mutation = mutation
    self.imitation = imitation
    self.elite = elite
    self.size = size
    self.n_goods = n_goods
    self.fitness = fitness

act(system)

Run one iteration: trade, evolve the pricing rules, and move.

Parameters:

Name Type Description Default
system SystemView

The system view of the market.

required
Source code in src/skcomplex/systems/economics/markets/_toy_trader.py
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
def act(self, system: SystemView) -> None:
    """Run one iteration: trade, evolve the pricing rules, and move.

    Args:
        system:
            The system view of the market.
    """
    traders = sorted(cast(list[ToyTraderView], system.get_agents('traders')), key=lambda trader: trader.id)
    prices_of = ('toy_price', 'crayon_price', 'blackboard_price')
    state = {
        'places': np.array([[trader.x, trader.y] for trader in traders]),
        'money': np.array([trader.money for trader in traders]),
        'stocks': np.array([[getattr(trader, good) for good in GOODS] for trader in traders]),
        'prices': np.array([[getattr(trader, name) for name in prices_of] for trader in traders]),
        'up': np.array([trader.price_up for trader in traders]),
        'down': np.array([trader.price_down for trader in traders]),
    }
    sold = self._trade(system, state)
    last = system.get_history('average_price', 1)
    fallback = float(last[-1]) if len(last) else float(state['prices'][:, 0].mean())
    average = float(np.mean(sold)) if sold else fallback
    self._evolve(system, state, average)
    angles = system.rng.uniform(0, 2 * np.pi, len(traders))
    steps = np.column_stack((np.cos(angles), np.sin(angles)))
    state['places'] = (state['places'] + steps) % system.get_parameter('size')
    for index, trader in enumerate(traders):
        trader.x, trader.y = (float(value) for value in state['places'][index])
        trader.money = float(state['money'][index])
        for good, name, value in zip(GOODS, prices_of, state['prices'][index], strict=True):
            setattr(trader, good, float(state['stocks'][index, GOODS.index(good)]))
            setattr(trader, name, float(value))
        trader.price_up, trader.price_down = float(state['up'][index]), float(state['down'][index])
    system.report('average_price', average)
    system.report('trades', float(len(sold)))
    system.report('money_gini', self._get_gini(state['money']))
    system.report('asset_gini', self._get_gini(state['money'] + state['stocks'][:, 0] * average))

ToyTraderElement(label, *, x=0.0, y=0.0, money=100.0, toys=5.0, crayons=0.0, blackboards=0.0, toy_price=10.0, crayon_price=10.0, blackboard_price=10.0, price_up=PRICE_UP, price_down=PRICE_DOWN, size=None)

Bases: Element

Trader on a torus with money, toys, crayons, and blackboards.

It holds its selling prices and its pricing rule.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
x object

The horizontal place of the trader.

0.0
y object

The vertical place of the trader.

0.0
money Annotated[object, closed_open(0, oo)]

The money of the trader.

100.0
toys Annotated[object, closed_open(0, oo)]

The toys of the trader.

5.0
crayons Annotated[object, closed_open(0, oo)]

The crayons of the trader.

0.0
blackboards Annotated[object, closed_open(0, oo)]

The blackboards of the trader.

0.0
toy_price Annotated[object, open(0, oo)]

The price the trader sells a toy at.

10.0
crayon_price Annotated[object, open(0, oo)]

The price the trader sells a crayon at.

10.0
blackboard_price Annotated[object, open(0, oo)]

The price the trader sells a blackboard at.

10.0
price_up Annotated[object, closed_open(1, oo)]

The factor that raises the toy price when the toys run short.

PRICE_UP
price_down Annotated[object, closed(0, 1)]

The factor that lowers the toy price when the toys pile up.

PRICE_DOWN
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.markets import ToyTraderElement
>>> ToyTraderElement('traders', size=3).size
3
Source code in src/skcomplex/systems/economics/markets/_toy_trader.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
def __init__(
    self,
    label: str,
    *,
    x: object = 0.0,
    y: object = 0.0,
    money: Annotated[object, RealSet.closed_open(0, oo)] = 100.0,
    toys: Annotated[object, RealSet.closed_open(0, oo)] = 5.0,
    crayons: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    blackboards: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    toy_price: Annotated[object, RealSet.open(0, oo)] = 10.0,
    crayon_price: Annotated[object, RealSet.open(0, oo)] = 10.0,
    blackboard_price: Annotated[object, RealSet.open(0, oo)] = 10.0,
    price_up: Annotated[object, RealSet.closed_open(1, oo)] = PRICE_UP,
    price_down: Annotated[object, RealSet.closed(0, 1)] = PRICE_DOWN,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.x = x
    self.y = y
    self.money = money
    self.toys = toys
    self.crayons = crayons
    self.blackboards = blackboards
    self.toy_price = toy_price
    self.crayon_price = crayon_price
    self.blackboard_price = blackboard_price
    self.price_up = price_up
    self.price_down = price_down

ToyTraderSystem(n_traders=400, *, sight=1.0, mutation=0.0, imitation=0.1, fitness='none', n_goods=1, size=51.0, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Gooding's Toy Trader.

Traders with money and toys buy the cheapest toy they can see. Four hundred traders on a 51 by 51 torus start with 100 money, 5 toys, and a toy price of 10. Every iteration every trader buys one toy from the cheapest trader within its market sight, if it can pay, and moves one unit in a random direction. A seller keeps its stock at 3 toys by lowering its price by the factor 0.99 above it and raising it by 1.0101 below it (Gooding 2019, Section 8.2 and the appendix). Money and toys are conserved and supply exceeds the demand for stocks, yet the price depends on the market sight: it falls when traders see only their neighbours and rises when they see everyone, so supply and demand alone do not set it (Section 10.1). Mutating pricing factors make the traders heterogeneous and raise prices and inequality, and the imitation of the richest 5 percent by the poorest half under a fitness test of money or of assets evolves the price patterns of speculation and asset markets (Sections 10.2 and 11). With n_goods=3 the traders also trade crayons and blackboards, starting with 30 and 15, which keep the fixed factors and the target stocks of 10 to 15 and 5 to 8 of the Three-Goods Trader (Section 11.1).

The system has the group traders and the market market, whose reporters are the average price of the toys traded market.average_price, the toys traded market.trades, and the Gini coefficients of money market.money_gini and of assets market.asset_gini.

Parameters:

Name Type Description Default
n_traders int

The number of traders.

400
sight float

The radius within which a trader sees prices.

1.0
mutation float

The probability per iteration that a factor of the toy price mutates, such as 1 / 5000.

0.0
imitation float

The probability per iteration that a poor trader imitates a rich one under a fitness test.

0.1
fitness str

The fitness test of imitation, 'none', 'money', or 'assets'.

'none'
n_goods int

The goods traded, 1 for toys only or 3 for toys, crayons, and blackboards.

1
size float

The side of the torus.

51.0
random_state int | Generator | None

The seed or generator of the places of the traders.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Examples:

>>> from skcomplex.systems.economics.markets import ToyTraderSystem
>>> ToyTraderSystem(10).prepare().system_.elements[0].size
10
Source code in src/skcomplex/systems/economics/markets/_toy_trader.py
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
def __init__(
    self,
    n_traders: int = 400,
    *,
    sight: float = 1.0,
    mutation: float = 0.0,
    imitation: float = 0.1,
    fitness: str = 'none',
    n_goods: int = 1,
    size: float = 51.0,
    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_traders = n_traders
    self.sight = sight
    self.mutation = mutation
    self.imitation = imitation
    self.fitness = fitness
    self.n_goods = n_goods
    self.size = size
    self.random_state = random_state

WasherElement(label, *, size=None)

Bases: Element

Worker of the car wash, whose work WashingInteraction sets.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.markets import WasherElement
>>> WasherElement('workers', size=4).size
4
Source code in src/skcomplex/systems/economics/markets/_queues.py
96
97
def __init__(self, label: str, *, size: int | None = None) -> None:
    super().__init__(label, size=size)

WashingInteraction(label, *, target, cars)

Bases: Interaction

Work of the workers of the car wash on the front car of the wash or of the valet.

A worker joins the front car while it has fewer than two workers. A worker who finds both areas staffed helps at a random one of them. One second of work removes one person-second from the car.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of workers.

required
cars Role

The path of the group of cars.

required

Examples:

>>> from skcomplex.systems.economics.markets import WashingInteraction
>>> WashingInteraction('washing', target='workers', cars='cars').cars
'cars'
Source code in src/skcomplex/systems/economics/markets/_queues.py
125
126
127
128
def __init__(self, label: str, *, target: Role, cars: Role) -> None:
    super().__init__(label)
    self.target = target
    self.cars = cars

work(agent, system)

Work one second on the front car of an area.

Parameters:

Name Type Description Default
agent AgentViewProtocol

The worker.

required
system SystemView

The system.

required
Source code in src/skcomplex/systems/economics/markets/_queues.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def work(self, agent: AgentViewProtocol, system: SystemView) -> None:
    """Work one second on the front car of an area.

    Args:
        agent:
            The worker.

        system:
            The system.
    """
    cars = cast(list[CarView], system.get_agents('cars'))
    fronts = [
        car
        for car in (WashingInteraction._get_front(cars, WASH), WashingInteraction._get_front(cars, VALET))
        if car is not None
    ]
    if not fronts:
        return
    short = [car for car in fronts if car.crew < CREW_SIZE]
    car = short[0] if short else fronts[int(system.rng.integers(len(fronts)))]
    car.crew += 1
    car.work -= 1.0

WilhiteTradeNetworksSystem(n_agents=500, *, topology='small_world', n_groups=10, shortcuts=5, endowment=100.0, units=100, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Wilhite's bilateral barter of two goods among traders on a trade network.

The network is one of four. Traders start with random bundles of two goods and the utility good1 good2. Every step, each trader searches its neighbours and trades with the one whose marginal rate of substitution differs the most, single units at a price between their rates, while both gain. Trade drives the rates of every connected set of traders towards one price. On the complete network every trader searches every other, so it needs the most searches, and traders crowd onto the most extreme partners, so prices converge slowly. Isolated groups settle on different prices. Groups chained by shared end traders, or a small world with some long links, bring the prices together with far fewer searches.

The system has the group traders on the network, the reporters barter.trades and barter.searches, and the observables dispersion, the spread of the logarithms of the rates, and utility, the mean utility.

Parameters:

Name Type Description Default
n_agents int

The number of traders.

500
topology str

'complete', 'isolated' groups, groups 'linked' in a ring by shared end traders, or 'small_world', the linked groups with random long links.

'small_world'
n_groups int

The number of groups of the isolated, linked, and small-world networks.

10
shortcuts int

The number of random long links between groups of the small world.

5
endowment float

The largest initial holding of each good, drawn uniformly from 1 to it.

100.0
units int

The most units one pair trades in a step.

100
random_state int | Generator | None

The seed or generator of the bundles and the long links.

0
label str

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

'system'
solver BaseSolver | str

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

'auto'
backend BaseBackend | str

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

'auto'

Raises:

Type Description
ValueError

The topology is unknown.

Examples:

>>> from skcomplex.systems.economics.markets import WilhiteTradeNetworksSystem
>>> system = WilhiteTradeNetworksSystem(40, topology='isolated', n_groups=4).prepare().system_
>>> system.elements[0].size
40
Source code in src/skcomplex/systems/economics/markets/_barter_networks.py
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
def __init__(
    self,
    n_agents: int = 500,
    *,
    topology: str = 'small_world',
    n_groups: int = 10,
    shortcuts: int = 5,
    endowment: float = 100.0,
    units: int = 100,
    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_agents = n_agents
    self.topology = topology
    self.n_groups = n_groups
    self.shortcuts = shortcuts
    self.endowment = endowment
    self.units = units
    self.random_state = random_state

ZeroIntelligenceBuyerElement(label, *, value=100.0, bid=0.0, demand=1.0, profit=0.0, ceiling=200.0, constrained=1.0, size=None)

Bases: Element

Buyer of one unit per trading period who bids a random price.

Under the budget constraint, the bid is below its value. In every round of a trading period, a buyer that has not bought yet bids a price drawn uniformly from 0 to its value, or to the price ceiling without the constraint, the zero-intelligence traders of Gode and Sunder (1993).

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
value Annotated[object, closed_open(0, oo)]

The value of the unit to the buyer, its redemption value.

100.0
bid Annotated[object, closed_open(0, oo)]

The current bid.

0.0
demand Annotated[object, closed_open(0, oo)]

The number of units still wanted in the trading period.

1.0
profit object

The accumulated surplus of the buyer's trades.

0.0
ceiling Annotated[object, open(0, oo)]

The highest price of the market.

200.0
constrained Annotated[object, closed_open(0, oo)]

One when the buyer never bids above its value, zero otherwise.

1.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.markets import ZeroIntelligenceBuyerElement
>>> ZeroIntelligenceBuyerElement('buyers', value=100.0, size=5).size
5
Source code in src/skcomplex/systems/economics/markets/_double_auction.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def __init__(
    self,
    label: str,
    *,
    value: Annotated[object, RealSet.closed_open(0, oo)] = 100.0,
    bid: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    demand: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
    profit: object = 0.0,
    ceiling: Annotated[object, RealSet.open(0, oo)] = 200.0,
    constrained: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.value = value
    self.bid = bid
    self.demand = demand
    self.profit = profit
    self.ceiling = ceiling
    self.constrained = constrained

ZeroIntelligenceSellerElement(label, *, value=100.0, ask=200.0, supply=1.0, profit=0.0, ceiling=200.0, constrained=1.0, size=None)

Bases: Element

Seller of one unit per trading period who asks a random price.

Under the budget constraint, the ask is above its cost. In every round of a trading period, a seller that has not sold yet asks a price drawn uniformly from its cost, or from 0 without the constraint, to the price ceiling.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
value Annotated[object, closed_open(0, oo)]

The cost of the unit to the seller.

100.0
ask Annotated[object, closed_open(0, oo)]

The current ask.

200.0
supply Annotated[object, closed_open(0, oo)]

The number of units still offered in the trading period.

1.0
profit object

The accumulated surplus of the seller's trades.

0.0
ceiling Annotated[object, open(0, oo)]

The highest price of the market.

200.0
constrained Annotated[object, closed_open(0, oo)]

One when the seller never asks below its cost, zero otherwise.

1.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.markets import ZeroIntelligenceSellerElement
>>> ZeroIntelligenceSellerElement('sellers', value=50.0, size=5).size
5
Source code in src/skcomplex/systems/economics/markets/_double_auction.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def __init__(
    self,
    label: str,
    *,
    value: Annotated[object, RealSet.closed_open(0, oo)] = 100.0,
    ask: Annotated[object, RealSet.closed_open(0, oo)] = 200.0,
    supply: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
    profit: object = 0.0,
    ceiling: Annotated[object, RealSet.open(0, oo)] = 200.0,
    constrained: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.value = value
    self.ask = ask
    self.supply = supply
    self.profit = profit
    self.ceiling = ceiling
    self.constrained = constrained

cobb_douglas(agent, goods, weights)

Return the logarithm of the Cobb-Douglas utility of an agent.

It is sum_i a_i log x_i.

Parameters:

Name Type Description Default
agent object

The agent, with a state for the holding of every good and for the weight of every good.

required
goods Sequence[str]

The names of the states that hold the goods.

required
weights Sequence[str]

The names of the states that hold the weights of the goods, in the order of goods.

required

Returns:

Name Type Description
utility float

The logarithm of the utility, minus infinity when a weighted good runs out.

Examples:

>>> from types import SimpleNamespace
>>> from skcomplex.systems.economics.markets import cobb_douglas
>>> agent = SimpleNamespace(x=4.0, y=1.0, a=0.5, b=0.5)
>>> round(cobb_douglas(agent, ('x', 'y'), ('a', 'b')), 6)
0.693147
Source code in src/skcomplex/systems/economics/common/exchange/_exchange.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def cobb_douglas(agent: object, goods: Sequence[str], weights: Sequence[str]) -> float:
    """Return the logarithm of the Cobb-Douglas utility of an agent.

    It is `sum_i a_i log x_i`.

    Args:
        agent:
            The agent, with a state for the holding of every good and for the weight of every good.

        goods:
            The names of the states that hold the goods.

        weights:
            The names of the states that hold the weights of the goods, in the order of `goods`.

    Returns:
        utility:
            The logarithm of the utility, minus infinity when a weighted good runs out.

    Examples:
        >>> from types import SimpleNamespace
        >>> from skcomplex.systems.economics.markets import cobb_douglas
        >>> agent = SimpleNamespace(x=4.0, y=1.0, a=0.5, b=0.5)
        >>> round(cobb_douglas(agent, ('x', 'y'), ('a', 'b')), 6)
        0.693147
    """
    total = 0.0
    for good, weight in zip(goods, weights, strict=True):
        share, holding = float(getattr(agent, weight)), float(getattr(agent, good))
        if share == 0:
            continue
        if holding <= 0:
            return -math.inf
        total += share * math.log(holding)
    return total

contract_curve(chocolate, first_weight, second_weight, total_chocolate, total_cigarettes)

Return the cigarettes of the first of two barterers on the contract curve.

They are given its chocolate. On the contract curve of two Cobb-Douglas barterers the marginal rates of substitution are equal, a y / ((1 - a) x) = b (Y - y) / ((1 - b) (X - x)), where a and b are the weights of chocolate, x and y the chocolate and cigarettes of the first barterer, and X and Y the totals.

Parameters:

Name Type Description Default
chocolate ArrayLike

The chocolate of the first barterer.

required
first_weight float

The weight of chocolate of the first barterer.

required
second_weight float

The weight of chocolate of the second barterer.

required
total_chocolate float

The total chocolate of both.

required
total_cigarettes float

The total cigarettes of both.

required

Returns:

Name Type Description
cigarettes NDArray[float64]

The cigarettes of the first barterer on the contract curve.

Examples:

>>> from skcomplex.systems.economics.markets import contract_curve
>>> float(contract_curve(5.0, 0.5, 0.5, 10.0, 10.0))
5.0
Source code in src/skcomplex/systems/economics/markets/_barter.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def contract_curve(
    chocolate: npt.ArrayLike,
    first_weight: float,
    second_weight: float,
    total_chocolate: float,
    total_cigarettes: float,
) -> npt.NDArray[np.float64]:
    """Return the cigarettes of the first of two barterers on the contract curve.

    They are given its chocolate. On the contract curve of two Cobb-Douglas barterers the marginal rates of substitution
    are equal, `a y / ((1 - a) x) = b (Y - y) / ((1 - b) (X - x))`, where `a` and `b` are the weights of chocolate, `x`
    and `y` the chocolate and cigarettes of the first barterer, and `X` and `Y` the totals.

    Args:
        chocolate:
            The chocolate of the first barterer.

        first_weight:
            The weight of chocolate of the first barterer.

        second_weight:
            The weight of chocolate of the second barterer.

        total_chocolate:
            The total chocolate of both.

        total_cigarettes:
            The total cigarettes of both.

    Returns:
        cigarettes:
            The cigarettes of the first barterer on the contract curve.

    Examples:
        >>> from skcomplex.systems.economics.markets import contract_curve
        >>> float(contract_curve(5.0, 0.5, 0.5, 10.0, 10.0))
        5.0
    """
    x = np.asarray(chocolate, dtype=float)
    a, b = first_weight, second_weight
    return b * (1 - a) * x * total_cigarettes / (a * (1 - b) * (total_chocolate - x) + b * (1 - a) * x)

hire(trade, system)

Record the employer, the wage, and the steps of the hire on the hired worker.

The steps are those of the hire and of its offer. The hired worker keeps its search flag supply until the next step, which the market lowered when it cleared, so the observable searching counts every worker who searched in the step.

Parameters:

Name Type Description Default
trade MatchSpec

The match of a firm, the requester of labour, with a worker, its provider.

required
system SystemView

The system view of the market.

required
Source code in src/skcomplex/systems/economics/markets/_labour.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
def hire(trade: MatchSpec, system: SystemView) -> None:
    """Record the employer, the wage, and the steps of the hire on the hired worker.

    The steps are those of the hire and of its offer. The hired worker keeps its search flag `supply` until the next
    step, which the market lowered when it cleared, so the observable `searching` counts every worker who searched in
    the step.

    Args:
        trade:
            The match of a firm, the requester of labour, with a worker, its provider.

        system:
            The system view of the market.
    """
    worker, firm = trade.provider, trade.requester
    if not isinstance(worker, JobseekerView) or not isinstance(firm, EmployerView):
        return
    worker.employer, worker.wage, worker.duration = float(firm.id), trade.value, 0.0
    worker.supply += trade.quantity
    worker.hired, worker.offer = system.time, firm.posted

marginal_rate(agent, good, numeraire, weights)

Return the marginal rate of substitution of a good for a numeraire.

It is the units of numeraire one unit is worth.

Parameters:

Name Type Description Default
agent object

The agent.

required
good str

The name of the state that holds the good.

required
numeraire str

The name of the state that holds the numeraire.

required
weights tuple[str, str]

The names of the states that hold the weights of the good and of the numeraire.

required

Returns:

Name Type Description
rate float

The ratio of the marginal utilities, (a_good / x_good) / (a_numeraire / x_numeraire).

Examples:

>>> from types import SimpleNamespace
>>> from skcomplex.systems.economics.markets import marginal_rate
>>> agent = SimpleNamespace(x=2.0, y=6.0, a=0.5, b=0.5)
>>> marginal_rate(agent, 'x', 'y', ('a', 'b'))
3.0
Source code in src/skcomplex/systems/economics/common/exchange/_exchange.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def marginal_rate(agent: object, good: str, numeraire: str, weights: tuple[str, str]) -> float:
    """Return the marginal rate of substitution of a good for a numeraire.

    It is the units of numeraire one unit is worth.

    Args:
        agent:
            The agent.

        good:
            The name of the state that holds the good.

        numeraire:
            The name of the state that holds the numeraire.

        weights:
            The names of the states that hold the weights of the good and of the numeraire.

    Returns:
        rate:
            The ratio of the marginal utilities, `(a_good / x_good) / (a_numeraire / x_numeraire)`.

    Examples:
        >>> from types import SimpleNamespace
        >>> from skcomplex.systems.economics.markets import marginal_rate
        >>> agent = SimpleNamespace(x=2.0, y=6.0, a=0.5, b=0.5)
        >>> marginal_rate(agent, 'x', 'y', ('a', 'b'))
        3.0
    """
    good_weight, numeraire_weight = (float(getattr(agent, name)) for name in weights)
    return (good_weight / float(getattr(agent, good))) / (numeraire_weight / float(getattr(agent, numeraire)))

maximum_surplus(values, costs)

Return the largest total surplus of single units.

It is the competitive surplus of the supply and demand schedules.

Parameters:

Name Type Description Default
values ndarray

The value of a unit to every buyer.

required
costs ndarray

The cost of a unit to every seller.

required

Returns:

Name Type Description
surplus float

The sum of the positive differences between the highest values and the lowest costs.

Examples:

>>> import numpy as np
>>> from skcomplex.systems.economics.markets import maximum_surplus
>>> maximum_surplus(np.array([10.0, 6.0, 2.0]), np.array([1.0, 4.0, 8.0]))
11.0
Source code in src/skcomplex/systems/economics/markets/_double_auction.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def maximum_surplus(values: np.ndarray, costs: np.ndarray) -> float:
    """Return the largest total surplus of single units.

    It is the competitive surplus of the supply and demand schedules.

    Args:
        values:
            The value of a unit to every buyer.

        costs:
            The cost of a unit to every seller.

    Returns:
        surplus:
            The sum of the positive differences between the highest values and the lowest costs.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.systems.economics.markets import maximum_surplus
        >>> maximum_surplus(np.array([10.0, 6.0, 2.0]), np.array([1.0, 4.0, 8.0]))
        11.0
    """
    demand, supply = np.sort(values)[::-1], np.sort(costs)
    size = min(len(demand), len(supply))
    return float(np.maximum(demand[:size] - supply[:size], 0).sum())

trade_goods(first, second, goods, weights, *, quantity=0.1, limit=1000)

Barter small quantities of goods between two agents while both gain.

It returns the trades. For every pair of goods in turn, the agent that values the first good more in units of the second buys quantity of it from the other at the geometric mean of their marginal rates of substitution, as in the Sugarscape trade of Epstein and Axtell (1996). A trade happens only when it raises the Cobb-Douglas utility of both agents, and every trade is two transfers, so the total of every good is unchanged. The agents trade until a round over all pairs of goods makes no trade, or until limit trades.

Parameters:

Name Type Description Default
first object

The first agent, with a state for the holding and for the weight of every good.

required
second object

The second agent.

required
goods Sequence[str]

The names of the states that hold the goods.

required
weights Sequence[str]

The names of the states that hold the weights of the goods, in the order of goods.

required
quantity float

The quantity of the bought good in every trade.

0.1
limit int

The largest number of trades.

1000

Returns:

Name Type Description
trades list[tuple[int, int, float]]

The index of the bought good, the index of the good paid with, and the price of every trade.

Examples:

>>> from types import SimpleNamespace
>>> from skcomplex.systems.economics.markets import trade_goods
>>> first = SimpleNamespace(x=9.0, y=1.0, a=0.5, b=0.5)
>>> second = SimpleNamespace(x=1.0, y=9.0, a=0.5, b=0.5)
>>> trades = trade_goods(first, second, ('x', 'y'), ('a', 'b'), quantity=0.5)
>>> first.x + second.x, len(trades) > 0
(10.0, True)
Source code in src/skcomplex/systems/economics/common/exchange/_exchange.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def trade_goods(
    first: object,
    second: object,
    goods: Sequence[str],
    weights: Sequence[str],
    *,
    quantity: float = 0.1,
    limit: int = 1000,
) -> list[tuple[int, int, float]]:
    """Barter small quantities of goods between two agents while both gain.

    It returns the trades. For every pair of goods in turn, the agent that values the first good more in units of the
    second buys `quantity` of it from the other at the geometric mean of their marginal rates of substitution, as in the
    Sugarscape trade of Epstein and Axtell (1996). A trade happens only when it raises the Cobb-Douglas utility of both
    agents, and every trade is two transfers, so the total of every good is unchanged. The agents trade until a round
    over all pairs of goods makes no trade, or until `limit` trades.

    Args:
        first:
            The first agent, with a state for the holding and for the weight of every good.

        second:
            The second agent.

        goods:
            The names of the states that hold the goods.

        weights:
            The names of the states that hold the weights of the goods, in the order of `goods`.

        quantity:
            The quantity of the bought good in every trade.

        limit:
            The largest number of trades.

    Returns:
        trades:
            The index of the bought good, the index of the good paid with, and the price of every trade.

    Examples:
        >>> from types import SimpleNamespace
        >>> from skcomplex.systems.economics.markets import trade_goods
        >>> first = SimpleNamespace(x=9.0, y=1.0, a=0.5, b=0.5)
        >>> second = SimpleNamespace(x=1.0, y=9.0, a=0.5, b=0.5)
        >>> trades = trade_goods(first, second, ('x', 'y'), ('a', 'b'), quantity=0.5)
        >>> first.x + second.x, len(trades) > 0
        (10.0, True)
    """
    trades: list[tuple[int, int, float]] = []
    pairs = list(itertools.combinations(range(len(goods)), 2))
    while len(trades) < limit:
        traded = False
        for pair in pairs:
            price = _trade_once(first, second, pair, goods=goods, weights=weights, quantity=quantity)
            if price is not None:
                trades.append((pair[0], pair[1], price))
                traded = True
        if not traded:
            break
    return trades