Skip to content

Finance

Finance: asset prices, growth processes, wealth, systemic risk, and arbitrage.

AccountingInteraction(label, *, target, phase='account')

Bases: Interaction

Accounts of the traders of the order book after every step of trade.

Every trader values its money and shares at the last price, and its gain is the change of this wealth in the step.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of traders.

required
phase str | None

The phase the accounts run in.

'account'

Examples:

>>> from skcomplex.systems.economics.finance import AccountingInteraction
>>> AccountingInteraction('accounts', target='traders').phase
'account'
Source code in src/skcomplex/systems/economics/finance/_order_book.py
279
280
281
282
def __init__(self, label: str, *, target: Role, phase: str | None = 'account') -> None:
    super().__init__(label)
    self.target = target
    self.phase = phase

account(system)

Set the gain of every trader, and then its wealth at the last price.

Parameters:

Name Type Description Default
system SystemView

The system view of the accounts.

required
Source code in src/skcomplex/systems/economics/finance/_order_book.py
294
295
296
297
298
299
300
301
302
303
304
305
def account(self, system: SystemView) -> None:
    """Set the gain of every trader, and then its wealth at the last price.

    Args:
        system:
            The system view of the accounts.
    """
    traders = cast(list[StockTraderView], system.get_agents('target'))
    for trader in traders:
        trader.gain = self.get_gain(trader, system)
    for trader in traders:
        trader.wealth = self.get_wealth(trader, system)

get_gain(agent, system) staticmethod

Return the change of the wealth valued at the last price.

It is zero before the first valuation.

Parameters:

Name Type Description Default
agent StockTraderView

The trader.

required
system SystemView

The system view of the accounting.

required

Returns:

Name Type Description
gain float

The change of the wealth in the step.

Source code in src/skcomplex/systems/economics/finance/_order_book.py
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
@staticmethod
def get_gain(agent: StockTraderView, system: SystemView) -> float:
    """Return the change of the wealth valued at the last price.

    It is zero before the first valuation.

    Args:
        agent:
            The trader.

        system:
            The system view of the accounting.

    Returns:
        gain:
            The change of the wealth in the step.
    """
    return AccountingInteraction.get_wealth(agent, system) - agent.wealth if agent.wealth else 0.0

get_wealth(agent, system) staticmethod

Return the money plus the shares valued at the last price.

Parameters:

Name Type Description Default
agent StockTraderView

The trader.

required
system SystemView

The system view of the accounting.

required

Returns:

Name Type Description
wealth float

The wealth of the trader.

Source code in src/skcomplex/systems/economics/finance/_order_book.py
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
@staticmethod
def get_wealth(agent: StockTraderView, system: SystemView) -> float:
    """Return the money plus the shares valued at the last price.

    Args:
        agent:
            The trader.

        system:
            The system view of the accounting.

    Returns:
        wealth:
            The wealth of the trader.
    """
    price, _ = LimitOrderInteraction.get_prices(agent, system)
    return agent.money + agent.shares * price

ArbitrageDensityElement(label, *, rho=0.0, D=0.5, A_x=0.0, E=0.5, A_t=0.0, space=None)

Bases: Element

Density of a good carried by random-walk traders.

It is minimally coupled to an exchange rate connection.

Parameters:

Name Type Description Default
label str

The label of the density.

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

The density of the good.

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

The diffusion constant of the traders.

0.5
A_x object

The initial spatial component of the exchange rate connection.

0.0
E object

The arbitrage field strength, the growth rate of the spatial component.

0.5
A_t object

The temporal component of the exchange rate connection.

0.0
space BaseSpace | None

The line whose sites hold the density, or None for one site.

None

Examples:

>>> from skcomplex.systems.economics.finance import ArbitrageDensityElement
>>> ArbitrageDensityElement('market', E=1.0).E
1.0
Source code in src/skcomplex/systems/economics/finance/_arbitrage.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def __init__(
    self,
    label: str,
    *,
    rho: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    D: Annotated[object, RealSet.open(0, oo)] = 0.5,
    A_x: object = 0.0,
    E: object = 0.5,
    A_t: object = 0.0,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, space=space)
    self.rho = rho
    self.D = D
    self.A_x = A_x
    self.E = E
    self.A_t = A_t

ArbitrageTradersSystem(n_sites=200, *, length=20.0, D=0.5, A_x=0.0, E=0.5, A_t=0.0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Schwichtenberg's diffusion of a good by random-walk traders.

It is minimally coupled to exchange rates. The density of the good follows (d_t - A_t) rho = D (d_x - A_x(t))^2 rho on a periodic line, with the exchange rate connection A_x(t) = A_x + E t. The arbitrage opportunity is the field strength F_tx = E. Without it, the traders diffuse the good symmetrically, and with it, they drift at the velocity 2 D A_x(t). The system has the density of the good market.rho.

Parameters:

Name Type Description Default
n_sites int

The number of sites of the line.

200
length float

The length of the line.

20.0
D float

The diffusion constant of the traders.

0.5
A_x float

The initial spatial component of the exchange rate connection.

0.0
E float

The arbitrage field strength, the growth rate of the spatial component.

0.5
A_t float

The temporal component of the exchange rate connection.

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.finance import ArbitrageTradersSystem
>>> ArbitrageTradersSystem(50).prepare().system_.elements[0].E
0.5
Source code in src/skcomplex/systems/economics/finance/_arbitrage.py
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
def __init__(
    self,
    n_sites: int = 200,
    *,
    length: float = 20.0,
    D: float = 0.5,
    A_x: float = 0.0,
    E: float = 0.5,
    A_t: float = 0.0,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.n_sites = n_sites
    self.length = length
    self.D = D
    self.A_x = A_x
    self.E = E
    self.A_t = A_t

AssetElement(label, *, price=1.0)

Bases: Element

Traded asset described by its price.

Parameters:

Name Type Description Default
label str

The label of the asset.

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

The initial price.

1.0

Examples:

>>> from skcomplex.systems.economics.finance import AssetElement
>>> AssetElement('stock', price=100.0).price
100.0
Source code in src/skcomplex/systems/economics/common/assets/_asset.py
30
31
32
33
34
35
36
37
def __init__(
    self,
    label: str,
    *,
    price: Annotated[float, RealSet.open(0, oo)] = 1.0,
) -> None:
    super().__init__(label)
    self.price = price

BalanceSheetElement(label, *, external=0.0, equity=0.0, payment=0.0, status=SOLVENT, size=None)

Bases: Element

Bank of an interbank network.

It holds its external assets, its equity, its payments, and its state of default. The bank is a passive agent that the contagion of the system updates, a solvency cascade through its equity or a clearing of payments through its payment.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

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

The external assets.

0.0
equity object

The equity, the assets minus the liabilities.

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

The payment the bank makes on its interbank liabilities.

0.0
status Annotated[object, NN]

0 for solvent, 1 for defaulting in this step, and 2 for defaulted.

SOLVENT
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.finance import BalanceSheetElement
>>> BalanceSheetElement('banks', equity=4.0, size=3).size
3
Source code in src/skcomplex/systems/economics/common/banking/_balance_sheet.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def __init__(
    self,
    label: str,
    *,
    external: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    equity: object = 0.0,
    payment: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    status: Annotated[object, NN] = SOLVENT,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.external = external
    self.equity = equity
    self.payment = payment
    self.status = status

BookInteraction(label, *, requesters, providers, rule=RandomSearchSpec(), reserve=('bid', 'ask'), quantity=('demand', 'supply'), cap='money', transfers=(('money', -1), ('shares', 1)), phase='trade', on_match=None, opening=100.0)

Bases: MatchingInteraction[SystemView]

Limit order book that matches the orders of the traders.

It reports the last traded price. The book is a matching of the traders with themselves, which binds the requesters' limit to their bid and the providers' to their ask, and every trade is two transfers, money from buyer to seller and shares from seller to buyer, so the total money and the total shares stay the same, which the default run checks as invariants. The book reports the last traded price, the previous price when nothing trades, and the traded volume.

Parameters:

Name Type Description Default
label str

The label of the book.

required
requesters Role

The path of the group of buying traders.

required
providers Role

The path of the group of selling traders.

required
rule MatchingRule

The spec of the algorithm that matches the orders, such as ContinuousMatchingSpec().

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

The states with the limit prices of the buyers and of the sellers.

('bid', 'ask')
quantity str | tuple[str, str]

The states with the quantities the buyers want and the sellers offer.

('demand', 'supply')
cap str

The state of a buyer with the money it can spend.

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

The states every trade moves, money paid by the buyer and shares delivered to it.

(('money', -1), ('shares', 1))
phase str | None

The phase the book clears in.

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

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

None
opening float

The price before the first trade.

100.0

Examples:

>>> from skcomplex.systems.economics.finance import BookInteraction
>>> BookInteraction('book', requesters='traders', providers='traders').reports
('price', 'volume')
Source code in src/skcomplex/systems/economics/finance/_order_book.py
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
def __init__(
    self,
    label: str,
    *,
    requesters: Role,
    providers: Role,
    rule: MatchingRule = RandomSearchSpec(),
    reserve: str | tuple[str, str] = ('bid', 'ask'),
    quantity: str | tuple[str, str] = ('demand', 'supply'),
    cap: str = 'money',
    transfers: Sequence[tuple[str, int]] = (('money', -1), ('shares', 1)),
    phase: str | None = 'trade',
    on_match: Callable[[MatchSpec, SystemView], None] | None = None,
    opening: float = 100.0,
) -> 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.opening = opening

BouchaudMezardWealthSystem(n_agents=20, *, graph=None, J=1.0, sigma=0.5, wealth=1.0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Bouchaud and Mezard's wealth dynamics.

Returns are random and multiplicative, with exchange between neighbours. Agent i follows the Stratonovich equation dW_i = sigma W_i dB_i + (J / c) sum_j (W_j - W_i) dt over its neighbours j on a network of mean degree c. Without a graph, the agents are the members of a group and every agent exchanges with every other, c = N - 1, the complete graph at a cost linear in the number of agents. A given graph keeps the agents on a field over its edges. Exchange conserves the total wealth, and on the complete graph the relative wealth W_i / <W> approaches a stationary distribution with the Pareto tail P(W_i / <W> > w) ~ w^-mu of exponent mu = 1 + 2 J / sigma^2.

The system has the wealth agents.W and the mean wealth mean_wealth.

Parameters:

Name Type Description Default
n_agents int

The number of agents, used when no graph is given.

20
graph object

The NetworkX graph of the exchanges, or None for exchange with every other of n_agents agents.

None
J float

The exchange rate between agents.

1.0
sigma float

The volatility of the returns.

0.5
wealth float | Sequence[float]

The initial wealth of every agent, or one value per agent.

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.finance import BouchaudMezardWealthSystem
>>> BouchaudMezardWealthSystem(10).prepare().system_.elements[0].J
1.0
Source code in src/skcomplex/systems/economics/finance/_wealth.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def __init__(
    self,
    n_agents: int = 20,
    *,
    graph: object = None,
    J: float = 1.0,
    sigma: float = 0.5,
    wealth: float | Sequence[float] = 1.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.graph = graph
    self.J = J
    self.sigma = sigma
    self.wealth = wealth

CorrelatedGeometricBrownianMotionSystem(prices=(100.0, 100.0), *, mu=(0.05, 0.08), sigma=(0.2, 0.3), rho=0.7, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Two assets whose prices follow geometric Brownian motions.

Correlated Wiener processes drive the motions. A WienerProcessSpec of dimension 2 with the covariance [[1, rho], [rho, 1]] drives the two prices, so their log returns over a short time have the correlation rho. The system has the assets first and second, whose motions share the Wiener processes market.

Parameters:

Name Type Description Default
prices tuple[float, float]

The initial prices of the two assets.

(100.0, 100.0)
mu tuple[float, float]

The drifts of the two assets.

(0.05, 0.08)
sigma tuple[float, float]

The volatilities of the two assets.

(0.2, 0.3)
rho float

The correlation of the two Wiener processes, from -1 to 1.

0.7
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.finance import CorrelatedGeometricBrownianMotionSystem
>>> CorrelatedGeometricBrownianMotionSystem(rho=0.5).prepare().system_.interactions[1].process.covariance
[[1.0, 0.5], [0.5, 1.0]]
Source code in src/skcomplex/systems/economics/finance/_correlated_assets.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def __init__(
    self,
    prices: tuple[float, float] = (100.0, 100.0),
    *,
    mu: tuple[float, float] = (0.05, 0.08),
    sigma: tuple[float, float] = (0.2, 0.3),
    rho: float = 0.7,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.prices = prices
    self.mu = mu
    self.sigma = sigma
    self.rho = rho

CovariantDiffusionInteraction(label, *, target='market')

Bases: Interaction

Diffusion of a density by random-walk traders, minimally coupled to an exchange rate connection.

The density follows (d_t - A_t) rho = D (d_x - A_x(t))^2 rho, with the connection A_x(t) = A_x + E t, so it diffuses at the rate D, drifts at the velocity 2 D A_x(t), and grows at the rate D A_x(t)^2 + A_t.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The density of the good, with the diffusion constant and the connection among its values.

'market'

Examples:

>>> from skcomplex.systems.economics.finance import CovariantDiffusionInteraction
>>> CovariantDiffusionInteraction('transport').target
'market'
Source code in src/skcomplex/systems/economics/finance/_arbitrage.py
102
103
104
def __init__(self, label: str, *, target: Role = 'market') -> None:
    super().__init__(label)
    self.target = target

DebtRankCascadeInteraction(label, *, banks, impact=())

Bases: Interaction

Synchronous spread of distress over the distressed banks j.

The distress follows h_i = min(1, h_i + sum_j W_ji h_j). A bank whose distress becomes positive turns distressed, and a distressed bank turns inactive after one step, so every bank passes its distress on once.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
banks Role

The path of the group of banks.

required
impact Sequence[Sequence[float]]

The impact matrix, impact[i][j] the relative loss of j when i defaults.

()

Examples:

>>> from skcomplex.systems.economics.finance import DebtRankCascadeInteraction
>>> DebtRankCascadeInteraction('cascade', banks='banks', impact=[[0.0, 0.5], [0.0, 0.0]]).impact
[[0.0, 0.5], [0.0, 0.0]]
Source code in src/skcomplex/systems/economics/finance/_contagion.py
106
107
108
109
110
111
112
113
114
115
def __init__(
    self,
    label: str,
    *,
    banks: Role,
    impact: Sequence[Sequence[float]] = (),
) -> None:
    super().__init__(label)
    self.banks = banks
    self.impact = impact

spread(system)

Advance the distress and the states of every bank by one step.

Parameters:

Name Type Description Default
system SystemView

The system.

required
Source code in src/skcomplex/systems/economics/finance/_contagion.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def spread(self, system: SystemView) -> None:
    """Advance the distress and the states of every bank by one step.

    Args:
        system:
            The system.
    """
    banks = sorted(cast(list[InterbankView], system.get_agents('banks')), key=lambda bank: bank.id)
    h = np.array([bank.h for bank in banks])
    status = np.array([bank.status for bank in banks])
    distressed = status == DISTRESSED
    new_h = np.minimum(1.0, h + np.asarray(self.impact, dtype=float).T @ (h * distressed))
    hit = (status == UNDISTRESSED) & (new_h > 0)
    new_status = np.where(distressed, INACTIVE, np.where(hit, DISTRESSED, status))
    for bank, level, code in zip(banks, new_h, new_status, strict=True):
        bank.h, bank.status = float(level), float(code)

DebtrankSystem(liabilities=None, capital=None, *, distressed=(0,), psi=1.0, n_banks=10, density=0.3, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The DebtRank cascade of distress from a set of banks.

The distress spreads through their interbank loans. liabilities[i][j] is the loan from bank j to bank i, which j loses when i defaults, and the impact of i on j is min(1, liabilities[i][j] / capital[j]). The banks in distressed start with distress psi. The DebtRank is the final value at risk minus the initial one. The system has the group banks and the distress weighted by economic value value_at_risk.

Parameters:

Name Type Description Default
liabilities Sequence[Sequence[float]] | None

The interbank liabilities, or None for a random network of n_banks banks.

None
capital Sequence[float] | None

The capital of every bank, or None for random capitals.

None
distressed Sequence[int]

The indices of the banks distressed at the start.

(0,)
psi float

The initial distress of those banks, where 1 is default.

1.0
n_banks int

The number of banks of a random network.

10
density float

The probability of a loan between two banks of a random network.

0.3
random_state int | Generator | None

The seed or generator of a random network.

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.finance import DebtrankSystem
>>> DebtrankSystem([[0.0, 5.0], [0.0, 0.0]], [10.0, 10.0]).prepare().system_.elements[0].size
2
Source code in src/skcomplex/systems/economics/finance/_contagion.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
def __init__(
    self,
    liabilities: Sequence[Sequence[float]] | None = None,
    capital: Sequence[float] | None = None,
    *,
    distressed: Sequence[int] = (0,),
    psi: float = 1.0,
    n_banks: int = 10,
    density: float = 0.3,
    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.liabilities = liabilities
    self.capital = capital
    self.distressed = distressed
    self.psi = psi
    self.n_banks = n_banks
    self.density = density
    self.random_state = random_state

DefaultCascadeInteraction(label, *, rule=None, phase=None, banks, liabilities=(), threshold=0.0, recovery=0.0)

Bases: PolicyRuleInteraction[SystemView]

Synchronous cascade of defaults.

The creditors of a defaulting bank write off their claims on it. Every step the banks that defaulted in the last step pass their losses on: every creditor j of a defaulting bank i loses (1 - recovery) L_ij of its equity, and a solvent bank whose equity falls below the threshold defaults.

Parameters:

Name Type Description Default
label str

The label of the cascade.

required
rule None

Unused, since the cascade overrides act.

None
phase str | None

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

None
banks Role

The path of the group of banks.

required
liabilities Sequence[Sequence[float]]

The interbank liabilities, liabilities[i][j] owed by bank i to bank j.

()
threshold float

The equity below which a bank defaults.

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

The share of a claim on a defaulted bank that its creditor recovers.

0.0

Examples:

>>> from skcomplex.systems.economics.finance import DefaultCascadeInteraction
>>> DefaultCascadeInteraction('cascade', banks='banks').reports
('defaults', 'losses')
Source code in src/skcomplex/systems/economics/finance/_solvency.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def __init__(
    self,
    label: str,
    *,
    rule: None = None,
    phase: str | None = None,
    banks: Role,
    liabilities: Sequence[Sequence[float]] = (),
    threshold: float = 0.0,
    recovery: Annotated[float, RealSet.closed(0, 1)] = 0.0,
) -> None:
    super().__init__(label, rule=rule, phase=phase)
    self.banks = banks
    self.liabilities = liabilities
    self.threshold = threshold
    self.recovery = recovery

act(system)

Pass on the losses of the defaulting banks.

Then default the banks below the threshold.

Parameters:

Name Type Description Default
system SystemView

The system view of the cascade.

required
Source code in src/skcomplex/systems/economics/finance/_solvency.py
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def act(self, system: SystemView) -> None:
    """Pass on the losses of the defaulting banks.

    Then default the banks below the threshold.

    Args:
        system:
            The system view of the cascade.
    """
    banks = sorted(cast(list[BalanceSheetView], system.get_agents('banks')), key=lambda bank: bank.id)
    status = np.array([bank.status for bank in banks])
    equity = np.array([bank.equity for bank in banks])
    defaulting = status == DEFAULTING
    losses = (1 - system.get_parameter('recovery')) * np.asarray(self.liabilities, dtype=float).T @ defaulting
    equity = equity - losses
    hit = (status == SOLVENT) & (equity < system.get_parameter('threshold'))
    status = np.where(defaulting, DEFAULTED, np.where(hit, DEFAULTING, status))
    for bank, value, code in zip(banks, equity, status, strict=True):
        bank.equity, bank.status = float(value), float(code)
    system.report('defaults', float(np.sum(status != SOLVENT)))
    system.report('losses', float(losses.sum()))

DefaultCascadeSystem(liabilities=None, equity=None, *, shocked=(0,), shock=1.0, threshold=0.0, recovery=0.0, n_banks=250, degree=4.0, interbank_share=0.2, capital_ratio=0.04, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

A cascade of defaults through interbank exposures.

It starts from a shock to the external assets of some banks. Banks are linked by contracts, liabilities[i][j] the amount bank i owes bank j. A bank whose equity falls below the threshold h defaults, and its creditors write off their claims on it, losing (1 - R) L_ij of their equity at the next step, which may default them in turn. This is the cascade of Thurner et al. (2018, Section 5.5.3.2), and with h = 0 and the recovery rate R = 0 it is the contagion on default of Gai and Kapadia (2010) as Bardoscia et al. (2021, Section 3.1) review it. The shocked banks lose the share shock of their external assets at the start. Without a given network, every bank has assets of 100, a fifth of them interbank claims split evenly over a random number of debtors of mean degree, and capital of 4 percent, the network of Gai and Kapadia, whose cascades are large in a window of intermediate degrees and rare for sparse or dense networks.

The system has the group banks and the cascade cascade, whose reporters are the number of defaulted banks cascade.defaults and the losses written off in the step cascade.losses.

Parameters:

Name Type Description Default
liabilities Sequence[Sequence[float]] | None

The interbank liabilities, or None for the random network of Gai and Kapadia.

None
equity Sequence[float] | None

The equity of every bank before the shock, or None for the capital of the random network.

None
shocked Sequence[int]

The indices of the banks whose external assets the shock hits.

(0,)
shock float

The share of their external assets the shocked banks lose.

1.0
threshold float

The equity below which a bank defaults.

0.0
recovery float

The share of a claim on a defaulted bank that its creditor recovers.

0.0
n_banks int

The number of banks of the random network.

250
degree float

The mean number of debtors of a bank of the random network.

4.0
interbank_share float

The share of the assets of a bank of the random network that are interbank claims.

0.2
capital_ratio float

The capital of a bank of the random network as a share of its assets.

0.04
random_state int | Generator | None

The seed or generator of the random network.

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.finance import DefaultCascadeSystem
>>> DefaultCascadeSystem([[0.0, 5.0], [0.0, 0.0]], [1.0, 2.0]).prepare().system_.elements[0].size
2
Source code in src/skcomplex/systems/economics/finance/_solvency.py
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
264
265
266
267
268
def __init__(
    self,
    liabilities: Sequence[Sequence[float]] | None = None,
    equity: Sequence[float] | None = None,
    *,
    shocked: Sequence[int] = (0,),
    shock: float = 1.0,
    threshold: float = 0.0,
    recovery: float = 0.0,
    n_banks: int = 250,
    degree: float = 4.0,
    interbank_share: float = 0.2,
    capital_ratio: float = 0.04,
    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.liabilities = liabilities
    self.equity = equity
    self.shocked = shocked
    self.shock = shock
    self.threshold = threshold
    self.recovery = recovery
    self.n_banks = n_banks
    self.degree = degree
    self.interbank_share = interbank_share
    self.capital_ratio = capital_ratio
    self.random_state = random_state

EisenbergNoeClearingSystem(liabilities=None, external=None, *, n_banks=50, density=0.1, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The clearing of interbank payments of Eisenberg and Noe.

It is a fixed point of proportional payments. Bank i owes L_ij to bank j, p_bar_i in all, and holds external assets e_i. A clearing vector pays p_i = min(p_bar_i, e_i + sum_j Pi_ji p_j), every bank paying in full or all it has, its debtors paying in proportion Pi_ij = L_ij / p_bar_i, the liquidity contagion of Bardoscia et al. (2021, Section 3.1). Every step is one round of the iteration from full payments, which falls monotonically to the greatest clearing vector, the solution of the linear programme max sum_i p_i with p <= p_bar and p <= e + Pi^T p. Without a given network the liabilities are random and the external assets are small for a few banks.

The system has the group banks of the payments banks.payment, and the clearing clearing, whose reporters are the total unpaid liabilities clearing.shortfall and the number of defaulting banks clearing.defaults.

Parameters:

Name Type Description Default
liabilities Sequence[Sequence[float]] | None

The interbank liabilities, or None for a random network.

None
external Sequence[float] | None

The external assets of every bank, or None for random ones.

None
n_banks int

The number of banks of a random network.

50
density float

The probability of a liability between two banks of a random network.

0.1
random_state int | Generator | None

The seed or generator of a random network.

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.finance import EisenbergNoeClearingSystem
>>> system = EisenbergNoeClearingSystem([[0.0, 2.0], [1.0, 0.0]], [0.5, 1.0]).prepare().system_
>>> system.elements[0].size
2
Source code in src/skcomplex/systems/economics/finance/_solvency.py
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def __init__(
    self,
    liabilities: Sequence[Sequence[float]] | None = None,
    external: Sequence[float] | None = None,
    *,
    n_banks: int = 50,
    density: 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.liabilities = liabilities
    self.external = external
    self.n_banks = n_banks
    self.density = density
    self.random_state = random_state

ExchangeLinkElement(label, *, A=0.0, E=0.0, space=None, on=None)

Bases: Element

Link of a lattice with an exchange-rate potential A and its rate E.

The rate E is the rate of change of the potential.

Parameters:

Name Type Description Default
label str

The label of the link or the group on the links.

required
A object

The initial exchange-rate potential.

0.0
E object

The initial value of F_0i of Schwichtenberg (2020 Eq. 2.22), the rate of change of the potential.

0.0
space BaseSpace | None

The space whose links hold the members, or None for one link.

None
on str | None

'edges' for one member on every link of the space, or None for one per site.

None

Attributes:

Name Type Description
default_visual_

How the link is drawn by default, the visual of its class.

Examples:

>>> from skcomplex.systems.economics.finance import ExchangeLinkElement
>>> ExchangeLinkElement('link', A=0.5).A
0.5
Source code in src/skcomplex/systems/economics/finance/_gauge_arbitrage.py
101
102
103
104
105
106
107
108
109
110
111
112
def __init__(
    self,
    label: str,
    *,
    A: object = 0.0,
    E: object = 0.0,
    space: BaseSpace | None = None,
    on: str | None = None,
) -> None:
    super().__init__(label, space=space, on=on)
    self.A = A
    self.E = E

FireSaleInteraction(label, *, rule=None, phase=None, banks, assets, holdings=(), liabilities=(), alpha=1.0, leverage=20.0, selling='threshold')

Bases: PolicyRuleInteraction[SystemView]

Banks that sell common assets on losses, and the market impact.

The market impact lowers the prices of what they sell. Every step the banks value their holdings at the current prices. Under the rule 'threshold' a bank whose losses exhaust its equity defaults and liquidates its whole portfolio, and otherwise stays passive. Under 'leverage' a bank sells the same share of every holding to bring its assets back to leverage times its equity, and liquidates everything when its equity is gone. The proceeds become cash, and the price of every asset falls to p0 exp(-alpha x), where x is the share of the asset liquidated so far and p0 its price after the shock.

Parameters:

Name Type Description Default
label str

The label of the fire sales.

required
rule None

Unused, since the fire sales override act.

None
phase str | None

The phase the fire sales act in, or None for the default phase.

None
banks Role

The path of the group of banks.

required
assets Role

The path of the group of assets.

required
holdings tuple[tuple[float, ...], ...]

The initial holdings, holdings[i][a] the units of asset a that bank i holds.

()
liabilities tuple[float, ...]

The liabilities of every bank.

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

The market impact.

1.0
leverage Annotated[float, open(1, oo)]

The target ratio of assets to equity of the rule 'leverage'.

20.0
selling str

The rule of the banks, 'threshold' or 'leverage'.

'threshold'

Raises:

Type Description
ValidationError

The rule is unknown, raised by prepare.

Examples:

>>> from skcomplex.systems.economics.finance import FireSaleInteraction
>>> FireSaleInteraction('sales', banks='banks', assets='assets').reports
('defaults', 'sold')
Source code in src/skcomplex/systems/economics/finance/_fire_sales.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
def __init__(
    self,
    label: str,
    *,
    rule: None = None,
    phase: str | None = None,
    banks: Role,
    assets: Role,
    holdings: tuple[tuple[float, ...], ...] = (),
    liabilities: tuple[float, ...] = (),
    alpha: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
    leverage: Annotated[float, RealSet.open(1, oo)] = 20.0,
    selling: str = 'threshold',
) -> None:
    super().__init__(label, rule=rule, phase=phase)
    self.banks = banks
    self.assets = assets
    self.holdings = holdings
    self.liabilities = liabilities
    self.alpha = alpha
    self.leverage = leverage
    self.selling = selling

act(system)

Value the portfolios, sell, and move the prices by the market impact.

Parameters:

Name Type Description Default
system SystemView

The system view of the fire sales.

required
Source code in src/skcomplex/systems/economics/finance/_fire_sales.py
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def act(self, system: SystemView) -> None:
    """Value the portfolios, sell, and move the prices by the market impact.

    Args:
        system:
            The system view of the fire sales.
    """
    banks = sorted(cast(list[BalanceSheetView], system.get_agents('banks')), key=lambda bank: bank.id)
    assets = sorted(cast(list[MarketAssetView], system.get_agents('assets')), key=lambda asset: asset.id)
    initial = np.asarray(self.holdings, dtype=float)
    holdings = np.asarray(system.storage.get('holdings', initial))
    prices = np.array([asset.price for asset in assets])
    base = np.asarray(system.storage.get('base', prices))
    liquidated = np.array([asset.liquidated for asset in assets])
    cash = np.array([bank.external for bank in banks])
    status = np.array([bank.status for bank in banks])
    values = holdings @ prices + cash
    equity = values - np.asarray(self.liabilities, dtype=float)
    failed = equity <= 0
    if self.selling == 'leverage':
        excess = values - system.get_parameter('leverage') * equity
        excess = np.where(excess > 1e-9 * values, excess, 0.0)
        risky = holdings @ prices
        share = np.divide(excess, risky, out=np.zeros_like(excess), where=risky > 0)
        share = np.where(failed, 1.0, np.minimum(share, 1.0))
    else:
        share = np.where(failed & (status == SOLVENT), 1.0, 0.0)
    sold = holdings * share[:, None]
    cash = cash + sold @ prices
    holdings = holdings - sold
    totals = initial.sum(axis=0)
    liquidated = np.minimum(
        1.0,
        liquidated + np.divide(sold.sum(axis=0), totals, out=np.zeros_like(totals), where=totals > 0),
    )
    prices = base * np.exp(-system.get_parameter('alpha') * liquidated)
    status = np.where(failed, DEFAULTED, status)
    equity = holdings @ prices + cash - np.asarray(self.liabilities, dtype=float)
    system.storage.update(holdings=holdings, base=base)
    for bank, value, money, code in zip(banks, equity, cash, status, strict=True):
        bank.equity, bank.external, bank.status = float(value), float(money), float(code)
    for asset, price, share_sold in zip(assets, prices, liquidated, strict=True):
        asset.price, asset.liquidated = float(price), float(share_sold)
    system.report('defaults', float(np.sum(status == DEFAULTED)))
    system.report('sold', float((sold @ prices).sum()))

GaugeArbitrageMarketSystem(size=16, *, D=0.5, q=0.2, bump=1.0, seed=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Exchange-rate potentials on links as lattice Maxwell fields.

Traders who move a good on sites source them.

The potentials follow A_t = E and E_t = -codifferential(dA) - J, and the good follows rho_t = -codifferential(J) with the current J = -D (d rho - q A rho) along its covariant gradient, after Schwichtenberg (2020 §2.1 and §2.2.1). Here E is F_0i of the book, so codifferential(E) equals the excess of the good over its mean, as in its Gauss law, Eq. 2.37, with a uniform background of the mean density that keeps the periodic lattice neutral. The system departs from the book in two places. The book writes Eq. 2.39 with no metric, which gives A_tt = +codifferential(dA) - J, where every mode with a curl grows, so the system takes the sign of a wave. And Eq. 2.56 applies the covariant derivative twice, which does not conserve the good, so the system applies it once inside the divergence of the current. The book gives no values of D and q and sets mu_0 by no number, so D, q, and mu_0 = 1 are choices of this system.

Parameters:

Name Type Description Default
size int

The number of sites along both axes.

16
D float

The diffusivity of the good.

0.5
q float

The charge of the good.

0.2
bump float

The height of the random part of the initial density above a density of 1.

1.0
seed int

The seed of the initial density.

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.finance import GaugeArbitrageMarketSystem
>>> [element.label for element in GaugeArbitrageMarketSystem(4).prepare().system_.elements]
['sites', 'links']
Source code in src/skcomplex/systems/economics/finance/_gauge_arbitrage.py
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
def __init__(
    self,
    size: int = 16,
    *,
    D: float = 0.5,
    q: float = 0.2,
    bump: float = 1.0,
    seed: int = 0,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.size = size
    self.D = D
    self.q = q
    self.bump = bump
    self.seed = seed

GeometricBrownianMotionInteraction(label, *, target, mu=0.05, sigma=0.2, process=None, index=None)

Bases: Interaction

Geometric Brownian motion of the price of an asset.

It follows dS = mu * S * dt + sigma * S * dW. The Wiener process dW is independent by default, or process index of a WienerProcessSpec that correlates it with the motions of other assets.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the asset.

required
mu float

The drift.

0.05
sigma Annotated[float, closed_open(0, oo)]

The volatility.

0.2
process WienerProcessSpec | None

The Wiener processes, one of which drives the price, or None for an independent process.

None
index int | None

The process of process that drives the price, or None without processes.

None

Examples:

>>> from skcomplex.systems.economics.finance import GeometricBrownianMotionInteraction
>>> from skcomplex.core.components.interactions import WienerProcessSpec
>>> GeometricBrownianMotionInteraction('gbm', target='stock', sigma=0.3).sigma
0.3
>>> market = WienerProcessSpec('market', dimension=2)
>>> GeometricBrownianMotionInteraction('gbm', target='stock', process=market, index=1).index
1
Source code in src/skcomplex/systems/economics/common/assets/_geometric_brownian_motion.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def __init__(
    self,
    label: str,
    *,
    target: Role,
    mu: float = 0.05,
    sigma: Annotated[float, RealSet.closed_open(0, oo)] = 0.2,
    process: WienerProcessSpec | None = None,
    index: int | None = None,
) -> None:
    super().__init__(label)
    self.target = target
    self.mu = mu
    self.sigma = sigma
    self.process = process
    self.index = index

GeometricBrownianMotionSystem(price=100.0, *, mu=0.05, sigma=0.2, label='system', solver='auto', backend='auto')

Bases: BaseSystem

An asset whose price follows geometric Brownian motion.

The system has the asset asset.

Parameters:

Name Type Description Default
price float

The initial price.

100.0
mu float

The drift.

0.05
sigma float

The volatility.

0.2
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.finance import GeometricBrownianMotionSystem
>>> GeometricBrownianMotionSystem(sigma=0.3).prepare().system_.interactions[0].sigma
0.3
Source code in src/skcomplex/systems/economics/finance/_assets.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def __init__(
    self,
    price: float = 100.0,
    *,
    mu: float = 0.05,
    sigma: float = 0.2,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.price = price
    self.mu = mu
    self.sigma = sigma

GibratFirmElement(label, *, x=100.0, previous=100.0, mu=1.02, sigma=0.05, size=None)

Bases: Element

Firm whose size is multiplied every step by a normal growth factor.

The factor is independent, x = lambda x.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
x object

The initial size.

100.0
previous object

The size before the last step.

100.0
mu object

The mean of the growth factor.

1.02
sigma Annotated[object, closed_open(0, oo)]

The standard deviation of the growth factor.

0.05
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.finance import GibratFirmElement
>>> GibratFirmElement('firms', mu=1.0, size=10).size
10
Source code in src/skcomplex/systems/economics/finance/_growth_processes.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
def __init__(
    self,
    label: str,
    *,
    x: object = 100.0,
    previous: object = 100.0,
    mu: object = 1.02,
    sigma: Annotated[object, RealSet.closed_open(0, oo)] = 0.05,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.x = x
    self.previous = previous
    self.mu = mu
    self.sigma = sigma

GibratGrowthInteraction(label, *, target='firms')

Bases: Interaction

Growth of the sizes of firms by independent normal factors, x = lambda x.

Every step every firm first keeps its size as previous, and then multiplies it by a factor drawn from a normal distribution of mean mu and deviation sigma, both values of the firm.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The firms, with their sizes x and previous and their mu and sigma.

'firms'

Examples:

>>> from skcomplex.systems.economics.finance import GibratGrowthInteraction
>>> GibratGrowthInteraction('growth').target
'firms'
Source code in src/skcomplex/systems/economics/finance/_growth_processes.py
175
176
177
def __init__(self, label: str, *, target: Role = 'firms') -> None:
    super().__init__(label)
    self.target = target

GibratProcessSystem(n_firms=200, *, x=100.0, mu=1.02, sigma=0.05, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Firms that grow by Gibrat's law of proportionate effect.

The law makes their sizes lognormal. The system has the group firms, the mean size mean_size, and the largest size max_size.

Parameters:

Name Type Description Default
n_firms int

The number of firms.

200
x float

The initial size of every firm.

100.0
mu float

The mean of the growth factor.

1.02
sigma float

The standard deviation of the growth factor.

0.05
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.finance import GibratProcessSystem
>>> GibratProcessSystem(10).prepare().system_.elements[0].size
10
Source code in src/skcomplex/systems/economics/finance/_growth_processes.py
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
def __init__(
    self,
    n_firms: int = 200,
    *,
    x: float = 100.0,
    mu: float = 1.02,
    sigma: float = 0.05,
    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.x = x
    self.mu = mu
    self.sigma = sigma

GoodSiteElement(label, *, rho=1.0, space=None)

Bases: Element

Site of a lattice with a density rho of a good.

Parameters:

Name Type Description Default
label str

The label of the site or the group on the sites.

required
rho object

The initial density of the good.

1.0
space BaseSpace | None

The space whose sites hold the members, or None for one site.

None

Attributes:

Name Type Description
default_visual_

How the site is drawn by default, the visual of its class.

Examples:

>>> from skcomplex.systems.economics.finance import GoodSiteElement
>>> GoodSiteElement('site', rho=2.0).rho
2.0
Source code in src/skcomplex/systems/economics/finance/_gauge_arbitrage.py
57
58
59
60
61
62
63
64
65
def __init__(
    self,
    label: str,
    *,
    rho: object = 1.0,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, space=space)
    self.rho = rho

GuruMarketInteraction(label, *, rule=None, phase=None, traders, tau=100.0, beta_step=1.5, opening=10.0)

Bases: PolicyRuleInteraction[SystemView]

Order-driven market of noise traders who imitate the expectation of a guru.

The network is rewired every day. Every step is a trading day. First every trader picks a random trader j and moves its link from the trader k it follows to j with probability 1 / (1 + exp(-beta (f_j - f_k))), where the fitness f is the wealth relative to the richest trader (Eqs. 3.4 and 3.5 of Caiani et al. 2016). The guru is the trader of the largest in-degree of the day before, and the intensity of choice beta grows by beta_step every day the guru survives and returns to 1 when it is replaced. Every trader draws its expected return sigma_i eps (Eq. 3.3) and adopts the one of the trader it follows, except the guru.

Then tau intraday operations run, each by a trader drawn at random. With the expected price p_ref exp(sqrt(tau) r) (Eq. 3.1), a trader expecting a rise bids U(p (1 - gamma1), p_hat) for a random share of its free cash, and a trader expecting a fall asks U(p_hat, p (1 + gamma2)) for a random share of its free stocks (Eq. 3.2 and Table 3.1). An order that crosses the book is a market order that trades with the best quotes by price and time priority, and what is left rests as a limit order, whose cash or stocks stay tied in the book until it trades or expires at the end of the day. The price is the last traded price, the mid quote when an operation trades nothing, and the previous price when the book is empty.

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
tau Annotated[float, open(0, oo)]

The intraday operations of a day.

100.0
beta_step Annotated[float, closed_open(0, oo)]

The growth of the intensity of choice every day the guru survives.

1.5
opening Annotated[float, open(0, oo)]

The price before the first day.

10.0

Examples:

>>> from skcomplex.systems.economics.finance import GuruMarketInteraction
>>> GuruMarketInteraction('market', traders='traders').reports[:2]
('price', 'log_return')
Source code in src/skcomplex/systems/economics/finance/_guru_order_book.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def __init__(
    self,
    label: str,
    *,
    rule: None = None,
    phase: str | None = None,
    traders: Role,
    tau: Annotated[float, RealSet.open(0, oo)] = 100.0,
    beta_step: Annotated[float, RealSet.closed_open(0, oo)] = 1.5,
    opening: Annotated[float, RealSet.open(0, oo)] = 10.0,
) -> None:
    super().__init__(label, rule=rule, phase=phase)
    self.traders = traders
    self.tau = tau
    self.beta_step = beta_step
    self.opening = opening

act(system)

Rewire the network, form the expectations, and run the trading day.

Parameters:

Name Type Description Default
system SystemView

The system view of the market.

required
Source code in src/skcomplex/systems/economics/finance/_guru_order_book.py
306
307
308
309
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
346
347
def act(self, system: SystemView) -> None:
    """Rewire the network, form the expectations, and run the trading day.

    Args:
        system:
            The system view of the market.
    """
    traders = sorted(cast(list[GuruTraderView], system.get_agents('traders')), key=lambda trader: trader.id)
    rng, store = system.rng, system.storage
    price = self._get_stored(system, 'price', system.get_parameter('opening'))
    beta = self._get_stored(system, 'beta', 1.0)
    cash = np.array([trader.cash for trader in traders])
    stocks = np.array([trader.stocks for trader in traders])
    follows = np.array([int(trader.follows) for trader in traders])
    sigma = np.array([trader.sigma for trader in traders])
    guru = int(np.argmax(np.bincount(follows, minlength=len(traders))))
    beta = beta + system.get_parameter('beta_step') if guru == self._get_stored(system, 'guru', -1.0) else 1.0
    wealth = cash + price * stocks
    follows = self._rewire(follows, wealth / wealth.max(), beta, rng)
    own = sigma * rng.normal(size=len(traders))
    expectation = own[follows]
    expectation[guru] = own[guru]
    holdings = {
        'cash': cash,
        'stocks': stocks,
        'tied_cash': np.zeros_like(cash),
        'tied_stocks': np.zeros_like(cash),
    }
    closing, volume = self._trade_day(system, holdings, expectation, price)
    followers = np.bincount(follows.astype(int), minlength=len(traders))
    store.update(price=closing, beta=beta, guru=guru)
    for index, trader in enumerate(traders):
        trader.cash, trader.stocks = float(cash[index]), float(stocks[index])
        trader.wealth = float(cash[index] + closing * stocks[index])
        trader.expectation, trader.follows = float(expectation[index]), float(follows[index])
        trader.followers = float(followers[index])
    system.report('price', closing)
    system.report('log_return', math.log(closing / price))
    system.report('volume', volume)
    system.report('guru', float(guru))
    system.report('beta', beta)
    system.report('guru_followers', float(followers.max()))

GuruOrderBookSystem(n_traders=100, *, tau=100, beta_step=1.5, sigma=0.01, cash=1000.0, stocks=100.0, opening=10.0, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The order-driven market of Grilli and Tedeschi.

Its noise traders imitate gurus they choose by wealth. Noise traders expect random returns of their own volatility, but every day each adopts the expectation of the trader it follows on a directed communication network. Every day each trader moves its link to a random trader with a logit probability of the difference of their wealths, whose intensity grows every day the guru, the most followed trader, keeps its place, so followers concentrate on successful traders and their expectations synchronize. The traders then place market and limit orders around a geometric Brownian forecast in an order book with price and time priority, within the day. This is the model of Caiani et al. (2016, Chapter 3, Sections 3.2 and 3.4). Imitation produces coordination periods in which most traders follow one guru, and the returns get fat tails and volatility clusters. The source leaves two choices open: the volatilities are uniform on (0, sigma), and the intensity of choice grows by beta_step every day the guru survives. The cash and the stocks of the traders are conserved, which the default run checks as invariants.

The system has the group traders and the market market, whose reporters are market.price, market.log_return, market.volume, market.guru, market.beta, and market.guru_followers. The observables of the system are the totals total_cash and total_stocks.

Parameters:

Name Type Description Default
n_traders int

The number of traders.

100
tau int

The intraday operations of a day.

100
beta_step float

The growth of the intensity of choice every day the guru survives.

1.5
sigma float

The largest volatility of the expected returns of a trader.

0.01
cash float

The initial cash of every trader.

1000.0
stocks float

The initial stocks of every trader.

100.0
opening float

The price before the first day.

10.0
random_state int | Generator | None

The seed or generator of the volatilities and the initial 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'

Examples:

>>> from skcomplex.systems.economics.finance import GuruOrderBookSystem
>>> GuruOrderBookSystem(10).prepare().system_.elements[0].size
10
Source code in src/skcomplex/systems/economics/finance/_guru_order_book.py
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
def __init__(
    self,
    n_traders: int = 100,
    *,
    tau: int = 100,
    beta_step: float = 1.5,
    sigma: float = 0.01,
    cash: float = 1000.0,
    stocks: float = 100.0,
    opening: float = 10.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.tau = tau
    self.beta_step = beta_step
    self.sigma = sigma
    self.cash = cash
    self.stocks = stocks
    self.opening = opening
    self.random_state = random_state

GuruTraderElement(label, *, cash=1000.0, stocks=100.0, wealth=2000.0, expectation=0.0, follows=0.0, sigma=0.01, followers=0.0, size=None)

Bases: Element

Noise trader of an order-driven market.

It follows the expectation of the trader it is linked to. The trader holds cash and stocks, has one outgoing link to the trader whose expected return it adopts, and expects returns of its own volatility sigma. The market of the system rewires its link and runs its orders.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

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

The cash of the trader, including the cash held by its limit orders.

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

The stocks of the trader, including the stocks held by its limit orders.

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

The cash plus the stocks at the price of the day.

2000.0
expectation object

The expected return of the day after imitation.

0.0
follows Annotated[object, NN]

The index of the trader whose expectation the trader adopts.

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

The volatility of the expected returns of the trader.

0.01
followers Annotated[object, NN]

The number of traders that follow the trader, its in-degree.

0.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.finance import GuruTraderElement
>>> GuruTraderElement('traders', size=3).size
3
Source code in src/skcomplex/systems/economics/finance/_guru_order_book.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def __init__(
    self,
    label: str,
    *,
    cash: Annotated[object, RealSet.closed_open(0, oo)] = 1000.0,
    stocks: Annotated[object, RealSet.closed_open(0, oo)] = 100.0,
    wealth: Annotated[object, RealSet.closed_open(0, oo)] = 2000.0,
    expectation: object = 0.0,
    follows: Annotated[object, NN] = 0.0,
    sigma: Annotated[object, RealSet.closed_open(0, oo)] = 0.01,
    followers: Annotated[object, NN] = 0.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.cash = cash
    self.stocks = stocks
    self.wealth = wealth
    self.expectation = expectation
    self.follows = follows
    self.sigma = sigma
    self.followers = followers

InterbankElement(label, *, h=0.0, status=float(UNDISTRESSED), value=0.0, size=None)

Bases: Element

Bank of the DebtRank cascade.

It holds its level of distress, its state, and its economic value.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

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

The level of distress, between 0 and 1, where 1 is default.

0.0
status Annotated[object, NN]

0 for undistressed, 1 for distressed, and 2 for inactive.

float(UNDISTRESSED)
value Annotated[object, closed_open(0, oo)]

The economic value, the bank's share of all interbank lending.

0.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.finance import InterbankElement
>>> InterbankElement('banks', h=[1.0, 0.0, 0.0], size=3).size
3
Source code in src/skcomplex/systems/economics/finance/_contagion.py
67
68
69
70
71
72
73
74
75
76
77
78
79
def __init__(
    self,
    label: str,
    *,
    h: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    status: Annotated[object, NN] = float(UNDISTRESSED),
    value: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.h = h
    self.status = status
    self.value = value

KestenFirmElement(label, *, x=100.0, lambda_low=0.48, lambda_high=1.48, b_low=0.0, b_high=1.0, size=None)

Bases: Element

Firm whose size follows Kesten's process, x = lambda x + b.

The lambda and b are uniform random.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

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

The initial size.

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

The lower bound of the multiplicative factor.

0.48
lambda_high Annotated[object, closed_open(0, oo)]

The upper bound of the multiplicative factor.

1.48
b_low Annotated[object, closed_open(0, oo)]

The lower bound of the additive term.

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

The upper bound of the additive term.

1.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.finance import KestenFirmElement
>>> KestenFirmElement('firms', b_high=2.0, size=10).size
10
Source code in src/skcomplex/systems/economics/finance/_growth_processes.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
def __init__(
    self,
    label: str,
    *,
    x: Annotated[object, RealSet.closed_open(0, oo)] = 100.0,
    lambda_low: Annotated[object, RealSet.closed_open(0, oo)] = 0.48,
    lambda_high: Annotated[object, RealSet.closed_open(0, oo)] = 1.48,
    b_low: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    b_high: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.x = x
    self.lambda_low = lambda_low
    self.lambda_high = lambda_high
    self.b_low = b_low
    self.b_high = b_high

KestenGrowthInteraction(label, *, target='firms')

Bases: Interaction

Growth of the sizes of firms by Kesten's process, x = lambda x + b.

Every step every firm multiplies its size by a factor drawn uniformly between lambda_low and lambda_high and adds a term drawn uniformly between b_low and b_high, all values of the firm.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The firms, with their sizes x and the bounds of their factors and terms.

'firms'

Examples:

>>> from skcomplex.systems.economics.finance import KestenGrowthInteraction
>>> KestenGrowthInteraction('growth').target
'firms'
Source code in src/skcomplex/systems/economics/finance/_growth_processes.py
224
225
226
def __init__(self, label: str, *, target: Role = 'firms') -> None:
    super().__init__(label)
    self.target = target

KestenProcessSystem(n_firms=200, *, x=100.0, lambda_low=0.48, lambda_high=1.48, b_low=0.0, b_high=1.0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Firms whose sizes follow Kesten's process.

It is a random multiplicative factor plus a random positive term. When the factor shrinks sizes on average, the additive term reinjects them, and the stationary distribution has a power-law tail. The system has the group firms, the mean size mean_size, and the largest size max_size.

Parameters:

Name Type Description Default
n_firms int

The number of firms.

200
x float

The initial size of every firm.

100.0
lambda_low float

The lower bound of the multiplicative factor.

0.48
lambda_high float

The upper bound of the multiplicative factor.

1.48
b_low float

The lower bound of the additive term.

0.0
b_high float

The upper bound of the additive term.

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.finance import KestenProcessSystem
>>> KestenProcessSystem(10).prepare().system_.elements[0].size
10
Source code in src/skcomplex/systems/economics/finance/_growth_processes.py
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
def __init__(
    self,
    n_firms: int = 200,
    *,
    x: float = 100.0,
    lambda_low: float = 0.48,
    lambda_high: float = 1.48,
    b_low: float = 0.0,
    b_high: float = 1.0,
    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.x = x
    self.lambda_low = lambda_low
    self.lambda_high = lambda_high
    self.b_low = b_low
    self.b_high = b_high

KirmanExchangeRateSystem(x=0.1, k=15, *, n_traders=30, r=0.01, v=0.5, g=1.0, sigma=0.01, epsilon=0.005, delta=0.01, label='system', solver='auto', backend='auto')

Bases: DynamicalSystem

Kirman's foreign exchange market.

Its traders switch between fundamentalism and chartism like ants. Fundamentalists expect the exchange rate to revert to its fundamental value, s_t-1 + v (s* - s_t-1), and chartists expect the last change to go on, s_t-1 + g (s_t-1 - s_t-2). With the mean-variance demand of both and the share n_t of fundamentalists, the market clears at the deviation of Eq. 1.36 of Caiani et al. (2016, Section 1.3.2), (1 + r) x_t = [1 - v n_t + g (1 - n_t)] x_t-1 - g (1 - n_t) x_t-2, written there with s_t-2 for x_t-2, a shock of the supply of foreign exchange added. The share follows the recruitment chain of Kirman's ants, which the source refers to and Kirman (1993) gives: when spontaneous changes are rarer than recruitment, epsilon < (1 - delta) / (N - 1), the traders spend long periods mostly of one kind and switch suddenly. A market of fundamentalists is stable with the eigenvalue (1 - v) / (1 + r) (Eq. 1.37), and a market of chartists oscillates, stable only while g <= 1 + r (Eq. 1.38), so the volatility of the rate comes and goes with the chartists. One trader meets another every step, so the defaults take a small market of 30 traders, whose regimes switch within a few thousand steps.

The system has the deviation market.x and the number of fundamentalists market.k. The observable of the system is the share of fundamentalists market.fundamentalists.

Parameters:

Name Type Description Default
x float

The initial deviation of the exchange rate from its fundamental value, also its value one step earlier.

0.1
k int

The initial number of fundamentalists.

15
n_traders int

The number of traders.

30
r float

The interest rate of the domestic currency.

0.01
v float

The share of the deviation that fundamentalists expect to close.

0.5
g float

The share of the last change that chartists expect to repeat.

1.0
sigma float

The standard deviation of the shocks of the deviation.

0.01
epsilon float

The probability of a spontaneous change of strategy.

0.005
delta float

One minus the probability that a trader recruits the trader it meets.

0.01
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.finance import KirmanExchangeRateSystem
>>> KirmanExchangeRateSystem(g=1.2).prepare().system_.elements[0].values['g']
1.2
Source code in src/skcomplex/systems/economics/finance/_switching_exchange.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def __init__(
    self,
    x: float = 0.1,
    k: int = 15,
    *,
    n_traders: int = 30,
    r: float = 0.01,
    v: float = 0.5,
    g: float = 1.0,
    sigma: float = 0.01,
    epsilon: float = 0.005,
    delta: float = 0.01,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label=label, solver=solver, backend=backend)
    self.x = x
    self.k = k
    self.n_traders = n_traders
    self.r = r
    self.v = v
    self.g = g
    self.sigma = sigma
    self.epsilon = epsilon
    self.delta = delta

LimitOrderInteraction(label, *, target, phase='quote')

Bases: Interaction

Limit orders of the traders of the order book.

Every trader forecasts the price and quotes a limit order for one share. A fundamentalist expects the price to close the share reversion of its gap to the fundamental value, and a chartist expects the last change of the price to repeat by the share extrapolation, both with a relative normal noise of standard deviation noise.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of traders.

required
phase str | None

The phase the traders quote in.

'quote'

Examples:

>>> from skcomplex.systems.economics.finance import LimitOrderInteraction
>>> LimitOrderInteraction('quotes', target='traders').phase
'quote'
Source code in src/skcomplex/systems/economics/finance/_order_book.py
193
194
195
196
def __init__(self, label: str, *, target: Role, phase: str | None = 'quote') -> None:
    super().__init__(label)
    self.target = target
    self.phase = phase

get_prices(agent, system) staticmethod

Return the last two prices of the book, the fundamental value before the first.

Parameters:

Name Type Description Default
agent StockTraderView

The trader.

required
system SystemView

The system view of the rule.

required

Returns:

Name Type Description
prices tuple[float, float]

The last price and the one before it.

Source code in src/skcomplex/systems/economics/finance/_order_book.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
@staticmethod
def get_prices(agent: StockTraderView, system: SystemView) -> tuple[float, float]:
    """Return the last two prices of the book, the fundamental value before the first.

    Args:
        agent:
            The trader.

        system:
            The system view of the rule.

    Returns:
        prices:
            The last price and the one before it.
    """
    history = system.get_history('book.price', 2)
    prices = [value for value in history if math.isfinite(value)] or [agent.fundamental]
    return prices[-1], prices[0]

quote(agent, system)

Forecast the price and quote a limit order for one share.

Parameters:

Name Type Description Default
agent StockTraderView

The trader.

required
system SystemView

The system.

required
Source code in src/skcomplex/systems/economics/finance/_order_book.py
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 quote(self, agent: StockTraderView, system: SystemView) -> None:
    """Forecast the price and quote a limit order for one share.

    Args:
        agent:
            The trader.

        system:
            The system.
    """
    price, previous = self.get_prices(agent, system)
    if agent.strategy:
        expected = heuristics.trend([previous, price], strength=agent.extrapolation)
    else:
        reversion = 1 - agent.reversion
        expected = heuristics.fundamental(
            [price],
            fundamental=agent.fundamental,
            reversion=reversion,
        )
    expected = max(LOWEST_PRICE, expected * (1 + agent.noise * system.rng.normal()))
    buying = expected > price
    new_bid, new_ask = (expected, 0.0) if buying else (0.0, expected)
    agent.bid = new_bid
    agent.ask = new_ask
    agent.demand = float(buying and agent.money >= expected)
    agent.supply = float(not buying and agent.shares >= 1)

MarketAssetElement(label, *, price=1.0, liquidated=0.0, size=None)

Bases: Element

Asset held by banks, whose price falls with the share of it liquidated.

The price is p = exp(-alpha x).

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 the asset, 1 before any sale.

1.0
liquidated Annotated[object, closed(0, 1)]

The share of the asset sold so far.

0.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.economics.finance import MarketAssetElement
>>> MarketAssetElement('assets', size=4).size
4
Source code in src/skcomplex/systems/economics/finance/_fire_sales.py
62
63
64
65
66
67
68
69
70
71
72
def __init__(
    self,
    label: str,
    *,
    price: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
    liquidated: Annotated[object, RealSet.closed(0, 1)] = 0.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.price = price
    self.liquidated = liquidated

MultiplicativeProcessSystem(n_firms=200, *, x=100.0, mu=1.02, sigma=0.05, c=0.9, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Levy and Solomon's multiplicative process.

Its floor at a fraction of the mean makes a power-law tail. Every size is multiplied by a normal growth factor and then raised to c times the mean size of the step before if it fell below it. With c = 0 the process is Gibrat's. The system has the group firms, the mean size mean_size, and the largest size max_size.

Parameters:

Name Type Description Default
n_firms int

The number of firms.

200
x float

The initial size of every firm.

100.0
mu float

The mean of the growth factor.

1.02
sigma float

The standard deviation of the growth factor.

0.05
c float

The fraction of the previous mean size below which no size falls.

0.9
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.finance import MultiplicativeProcessSystem
>>> MultiplicativeProcessSystem(c=0.5).prepare().system_.interactions[-1].c
0.5
Source code in src/skcomplex/systems/economics/finance/_growth_processes.py
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
def __init__(
    self,
    n_firms: int = 200,
    *,
    x: float = 100.0,
    mu: float = 1.02,
    sigma: float = 0.05,
    c: float = 0.9,
    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.x = x
    self.mu = mu
    self.sigma = sigma
    self.c = c

NetworkSaverElement(label, *, W=1.0, J=1.0, sigma=0.5, degree=1.0, size=None, space=None)

Bases: Element

Saver of Bouchaud and Mezard, whose wealth earns random returns.

The wealth flows to and from its exchange partners.

Parameters:

Name Type Description Default
label str

The label of the saver.

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

The wealth.

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

The exchange rate with the partners.

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

The volatility of the returns.

0.5
degree Annotated[object, open(0, oo)]

The mean number of exchange partners c, which divides the exchange rate, N - 1 for exchange with every other saver.

1.0
size int | None

The number of savers, or None for one or one per node of the space.

None
space BaseSpace | None

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

None

Examples:

>>> from skcomplex.systems.economics.finance import NetworkSaverElement
>>> NetworkSaverElement('saver', W=2.0).W
2.0
Source code in src/skcomplex/systems/economics/finance/_wealth.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def __init__(
    self,
    label: str,
    *,
    W: Annotated[object, RealSet.open(0, oo)] = 1.0,
    J: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
    sigma: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
    degree: Annotated[object, RealSet.open(0, oo)] = 1.0,
    size: int | None = None,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, size=size, space=space)
    self.W = W
    self.J = J
    self.sigma = sigma
    self.degree = degree

OrderBookSystem(width=20, height=20, *, chartists=0.3, fundamental=100.0, reversion=0.2, extrapolation=1.0, noise=0.02, imitation=0.1, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

A stock market of fundamentalists and chartists on a grid.

They trade in a limit order book and imitate. Every step every trader forecasts the price, as a fundamentalist who expects it to revert to the fundamental value or as a chartist who expects the last change to go on, and quotes a limit order for one share at its forecast. The order book matches the orders with price-time priority, and every trade moves money and a share between the two traders. Then traders copy the strategy of a neighbour whose wealth grew more. Fundamentalists hold the price near the fundamental value, chartists amplify its swings, and imitation lets the share of chartists wander, so the returns come in bursts with fat tails.

The two strategies are the fundamentalists and chartists of Lux and Marchesi (1999), and imitating a wealthier neighbour on the grid stands in for their switching between strategies. The order book is the order-driven market of Caiani et al. (2016, section 3.2.1). The traders of Caiani's chapter 3, noise traders who follow gurus of an evolving network, are a different model. The system has the group traders and the book book, whose reporters are book.price and book.volume, and the imitation imitation of the strategies of more successful neighbours.

Parameters:

Name Type Description Default
width int

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

20
height int

The number of rows of the grid.

20
chartists float

The initial share of chartists.

0.3
fundamental float

The fundamental value of the share.

100.0
reversion float

The share of the gap to the fundamental value a fundamentalist expects to close.

0.2
extrapolation float

The share of the last change of the price a chartist expects to repeat.

1.0
noise float

The standard deviation of the relative noise of a forecast.

0.02
imitation float

The probability that a trader looks at a neighbour in a step.

0.1
random_state int | Generator | None

The seed or generator of the initial strategies.

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.finance import OrderBookSystem
>>> OrderBookSystem(5, 5).prepare().system_.elements[0].size
25
Source code in src/skcomplex/systems/economics/finance/_order_book.py
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
def __init__(
    self,
    width: int = 20,
    height: int = 20,
    *,
    chartists: float = 0.3,
    fundamental: float = 100.0,
    reversion: float = 0.2,
    extrapolation: float = 1.0,
    noise: float = 0.02,
    imitation: 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.width = width
    self.height = height
    self.chartists = chartists
    self.fundamental = fundamental
    self.reversion = reversion
    self.extrapolation = extrapolation
    self.noise = noise
    self.imitation = imitation
    self.random_state = random_state

OverlappingPortfolioFireSalesSystem(n_banks=100, n_assets=100, *, diversification=10, leverage=20.0, alpha=1.0, shocked=0, shock=0.2, selling='threshold', random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Banks with overlapping portfolios whose fire sales spread their losses.

The fire sales of common assets spread the losses to one another. Every bank invests equal amounts in diversification assets drawn at random, a bipartite network of banks and assets, with assets leverage times its equity. A shock lowers the price of one asset, and banks react to their losses: under the linear threshold rule a bank stays passive until its losses exhaust its equity and then liquidates its whole portfolio, and under leverage targeting it sells a share of every holding to restore its leverage. Sales lower prices through the market impact p = p0 exp(-alpha x) of the share x of an asset liquidated, which hits every bank holding the asset, so losses travel between banks that share no contract, the indirect contagion of Bardoscia et al. (2021, Section 3.2) after Caccioli et al. (2014). Larger impact and leverage make the cascades larger, and leverage targeting sells more for small shocks.

The system has the groups banks, of the equity banks.equity and the cash banks.external, and assets, of the prices assets.price, and the fire sales sales, whose reporters are the number of defaulted banks sales.defaults and the value sold in the step sales.sold.

Parameters:

Name Type Description Default
n_banks int

The number of banks.

100
n_assets int

The number of assets.

100
diversification int

The number of assets in every portfolio.

10
leverage float

The ratio of assets to equity of every bank, and the target of leverage targeting.

20.0
alpha float

The market impact.

1.0
shocked int

The index of the asset the shock hits.

0
shock float

The share of its price the shocked asset loses.

0.2
selling str

The rule of the banks, 'threshold' or 'leverage'.

'threshold'
random_state int | Generator | None

The seed or generator of the portfolios.

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.finance import OverlappingPortfolioFireSalesSystem
>>> system = OverlappingPortfolioFireSalesSystem(10, 5, diversification=2).prepare().system_
>>> [group.size for group in system.elements]
[10, 5]
Source code in src/skcomplex/systems/economics/finance/_fire_sales.py
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
def __init__(
    self,
    n_banks: int = 100,
    n_assets: int = 100,
    *,
    diversification: int = 10,
    leverage: float = 20.0,
    alpha: float = 1.0,
    shocked: int = 0,
    shock: float = 0.2,
    selling: str = 'threshold',
    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_banks = n_banks
    self.n_assets = n_assets
    self.diversification = diversification
    self.leverage = leverage
    self.alpha = alpha
    self.shocked = shocked
    self.shock = shock
    self.selling = selling
    self.random_state = random_state

PaymentClearingInteraction(label, *, rule=None, phase=None, banks, liabilities=())

Bases: PolicyRuleInteraction[SystemView]

Clearing of interbank payments of Eisenberg and Noe.

It iterates p <- min(p_bar, e + Pi^T p). Every step every bank pays the smaller of what it owes, p_bar_i = sum_j L_ij, and what it has, its external assets plus the payments it receives, which its debtors make in proportion to their liabilities, Pi_ij = L_ij / p_bar_i. From full payments the iteration falls to the greatest clearing vector, and a bank that pays less than it owes defaults.

Parameters:

Name Type Description Default
label str

The label of the clearing.

required
rule None

Unused, since the clearing overrides act.

None
phase str | None

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

None
banks Role

The path of the group of banks.

required
liabilities Sequence[Sequence[float]]

The interbank liabilities, liabilities[i][j] owed by bank i to bank j.

()

Examples:

>>> from skcomplex.systems.economics.finance import PaymentClearingInteraction
>>> PaymentClearingInteraction('clearing', banks='banks').reports
('shortfall', 'defaults')
Source code in src/skcomplex/systems/economics/finance/_solvency.py
134
135
136
137
138
139
140
141
142
143
144
145
def __init__(
    self,
    label: str,
    *,
    rule: None = None,
    phase: str | None = None,
    banks: Role,
    liabilities: Sequence[Sequence[float]] = (),
) -> None:
    super().__init__(label, rule=rule, phase=phase)
    self.banks = banks
    self.liabilities = liabilities

act(system)

Make one round of payments and record the shortfall and the defaults.

Parameters:

Name Type Description Default
system SystemView

The system view of the clearing.

required
Source code in src/skcomplex/systems/economics/finance/_solvency.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def act(self, system: SystemView) -> None:
    """Make one round of payments and record the shortfall and the defaults.

    Args:
        system:
            The system view of the clearing.
    """
    banks = sorted(cast(list[BalanceSheetView], system.get_agents('banks')), key=lambda bank: bank.id)
    matrix = np.asarray(self.liabilities, dtype=float)
    owed = matrix.sum(axis=1)
    shares = np.divide(matrix, owed[:, None], out=np.zeros_like(matrix), where=owed[:, None] > 0)
    payments = np.array([bank.payment for bank in banks])
    external = np.array([bank.external for bank in banks])
    payments = np.minimum(owed, external + shares.T @ payments)
    equity = external + shares.T @ payments - payments
    defaulted = payments < owed * (1 - 1e-12)
    for bank, paid, value, flag in zip(banks, payments, equity, defaulted, strict=True):
        bank.payment, bank.equity, bank.status = float(paid), float(value), float(DEFAULTED * flag)
    system.report('shortfall', float(np.sum(owed - payments)))
    system.report('defaults', float(defaulted.sum()))

ReflectingFloorInteraction(label, *, target, c=0.9, phase=None)

Bases: Interaction

Lower bound on the sizes of a group at a fraction of their mean.

The mean is taken before the step, x = max(x, c <x_{t-1}>). It is a rule of the system that raises every size below the floor to the floor, the mean of the values previous of the group times c.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of firms.

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

The fraction of the previous mean size below which no size falls.

0.9
phase str | None

The phase of the step the floor acts in, or None for the default phase.

None

Examples:

>>> from skcomplex.systems.economics.finance import ReflectingFloorInteraction
>>> ReflectingFloorInteraction('floor', target='firms', c=0.5).c
0.5
Source code in src/skcomplex/systems/economics/finance/_growth_processes.py
276
277
278
279
280
281
282
283
284
285
286
287
def __init__(
    self,
    label: str,
    *,
    target: Role,
    c: Annotated[float, RealSet.closed_open(0, oo)] = 0.9,
    phase: str | None = None,
) -> None:
    super().__init__(label)
    self.target = target
    self.c = c
    self.phase = phase

StockTraderElement(label, *, strategy=0.0, money=1000.0, shares=10.0, bid=0.0, ask=0.0, demand=0.0, supply=0.0, wealth=0.0, gain=0.0, fundamental=100.0, reversion=0.2, extrapolation=1.0, noise=0.02, values=None, size=None, space=None)

Bases: Element

Trader who forecasts the price, quotes a limit order, and imitates.

It forecasts as a fundamentalist or a chartist. A fundamentalist expects the price p to revert to the fundamental value F, p + reversion (F - p), and a chartist expects the last change to go on, p + extrapolation (p - p'), both with a relative noise. The trader bids its expectation for one share when it is above the price and it can pay, and asks its expectation for one share when it is below and it holds one. After trading, an ImitationInteraction of rule 'better' lets a trader whose wealth grew less than that of a random neighbour copy the neighbour's strategy.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

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

0 for a fundamentalist, 1 for a chartist.

0.0
money object

The money of the trader.

1000.0
shares object

The shares of the trader.

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

The limit price of a buy order.

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

The limit price of a sell order.

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

The shares wanted in the step.

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

The shares offered in the step.

0.0
wealth object

The money plus the shares at the last price.

0.0
gain object

The change of the wealth in the last step.

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

The fundamental value of the share.

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

The share of the gap to the fundamental value a fundamentalist expects to close.

0.2
extrapolation Annotated[object, closed_open(0, oo)]

The share of the last change of the price a chartist expects to repeat.

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

The standard deviation of the relative noise of a forecast.

0.02
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.finance import StockTraderElement
>>> StockTraderElement('traders', strategy=1.0, size=4).size
4
Source code in src/skcomplex/systems/economics/finance/_order_book.py
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
def __init__(
    self,
    label: str,
    *,
    strategy: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    money: object = 1000.0,
    shares: object = 10.0,
    bid: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    ask: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    demand: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    supply: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
    wealth: object = 0.0,
    gain: object = 0.0,
    fundamental: Annotated[object, RealSet.open(0, oo)] = 100.0,
    reversion: Annotated[object, RealSet.closed_open(0, oo)] = 0.2,
    extrapolation: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
    noise: Annotated[object, RealSet.closed_open(0, oo)] = 0.02,
    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.strategy = strategy
    self.money = money
    self.shares = shares
    self.bid = bid
    self.ask = ask
    self.demand = demand
    self.supply = supply
    self.wealth = wealth
    self.gain = gain
    self.fundamental = fundamental
    self.reversion = reversion
    self.extrapolation = extrapolation
    self.noise = noise

TraderCurrentInteraction(label, *, among, D=0.5, q=0.2, along=True)

Bases: Interaction

Trader current along the links, down the covariant gradient.

The current is J = -D (rho_t - rho_s - q A (rho_s + rho_t) / 2). The covariant derivative is D_mu = d_mu - A_mu of Schwichtenberg (2020 Eq. 2.55), with the charge q of its Eq. 4.24, and the current is minus the diffusion constant times this derivative of the good, as in Eq. 2.56. The current moves the good from the source of a link to its target (footnote 18 of §2.1), and it is the source of the field of the link with the sign of the Ampere-Maxwell law of Eq. 2.39, E' = ... - J, so the Gauss law holds as the good moves. These signs give the potential a mass, A'' = ... - D q rho A, for a positive density and charge, so the fields stay bounded.

Parameters:

Name Type Description Default
label str

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

required
among Role

The path of the group on the sites, whose links the laws run on, reading the potential A of the element on the links.

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

The diffusivity of the good.

0.5
q float

The charge of the good.

0.2
along bool | str

The edges the laws run on, True for the links of the space of the sites.

True

Examples:

>>> from skcomplex.systems.economics.finance import TraderCurrentInteraction
>>> TraderCurrentInteraction('current', among='sites', q=0.5).q
0.5
Source code in src/skcomplex/systems/economics/finance/_gauge_arbitrage.py
150
151
152
153
154
155
156
157
158
159
160
161
def __init__(
    self,
    label: str,
    *,
    among: Role,
    D: Annotated[float, RealSet.closed_open(0, oo)] = 0.5,
    q: float = 0.2,
    along: bool | str = True,
) -> None:
    super().__init__(label, among=among, along=along)
    self.D = D
    self.q = q