Traders and exchange rates coupled through arbitrage as lattice electrodynamics
Exchange-rate potentials on links as lattice Maxwell fields.
- Class:
GaugeArbitrageMarketSystem - Import:
from skcomplex.systems.economics.finance import GaugeArbitrageMarketSystem - Field:
economics/finance - Topics:
gauge,arbitrage,exchange rates,lattice,maxwell,cell complex - References:
- Schwichtenberg 2020
Use this system
The block imports the class and simulates the system with its default parameters and its tuned run settings.
from skcomplex.systems.economics.finance import GaugeArbitrageMarketSystem
trajectory = GaugeArbitrageMarketSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
size |
16 |
D |
0.5 |
q |
0.2 |
bump |
1.0 |
seed |
0 |
solver |
'auto' |
backend |
'auto' |
Tags
The system with its default parameters has these capability tags, which solvers and analyses check.
| Tag | Values |
|---|---|
| Time | continuous |
| Space | cell complex |
| Laws | rate |
| Randomness | unknown |
| Domains | real |
| Structure | fixed |
Class
The source of the class shows how it builds its components from its model parameters.
class GaugeArbitrageMarketSystem(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.
Args:
size:
The number of sites along both axes.
D:
The diffusivity of the good.
q:
The charge of the good.
bump:
The height of the random part of the initial density above a density of 1.
seed:
The seed of the initial density.
label:
The label of the system, which names it when it is nested in another one.
solver:
The solver of the problem, or `'auto'` for the one the system chooses.
backend:
The backend that evaluates the compiled functions, or `'auto'` for the one the system chooses.
Examples:
>>> from skcomplex.systems.economics.finance import GaugeArbitrageMarketSystem
>>> [element.label for element in GaugeArbitrageMarketSystem(4).prepare().system_.elements]
['sites', 'links']
"""
field = 'economics/finance'
topics = ('gauge', 'arbitrage', 'exchange rates', 'lattice', 'maxwell', 'cell complex')
references = ('Schwichtenberg 2020',)
until = 20.0
dt = 0.5
@staticmethod
def _get_total_good(t: float, values: Mapping[str, object]) -> float:
"""Return the total of the good."""
del t
return float(np.sum(np.asarray(values['sites.rho'], dtype=float)))
@staticmethod
def _get_gauss_residual(edges: scipy.sparse.csr_array, t: float, values: Mapping[str, object]) -> float:
"""Return the largest absolute difference of the codifferential and the excess.
The codifferential is that of the field, and the excess that of the good.
The excess is that of the good.
"""
del t
density = np.ravel(np.asarray(values['sites.rho'], dtype=float))
electric = np.ravel(np.asarray(values['links.E'], dtype=float))
return float(np.abs(-(edges.T @ electric) - (density - density.mean())).max())
@staticmethod
def _get_market_observables(system: System) -> list[Observable]:
"""Return the total of the good and the Gauss residual against its excess density."""
space = system.elements[0].space.prepare()
return [
Observable('total_good', function=GaugeArbitrageMarketSystem._get_total_good),
Observable(
'gauss_residual',
function=partial(GaugeArbitrageMarketSystem._get_gauss_residual, space.incidences_[0]),
),
]
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
@staticmethod
def _get_potential_rate(namespace: SimpleNamespace) -> Expression:
"""Return the rate of the potential, the field `F_0i` of the link."""
return namespace.target.E
@staticmethod
def _get_field_rate(namespace: SimpleNamespace) -> Expression:
"""Return the rate of the field without the current.
It is minus the codifferential of the exterior derivative.
"""
return -codifferential(exterior_derivative(namespace.target.A))
@staticmethod
def _get_initial_field(edges: scipy.sparse.csr_array, excess: Array) -> Array:
"""Return the electric field of the smallest norm with a given codifferential.
Its codifferential is the excess of the good.
"""
field = scipy.sparse.linalg.lsqr(
-edges.T,
excess,
atol=SOLVER_TOLERANCE,
btol=SOLVER_TOLERANCE,
conlim=0.0,
iter_lim=100 * excess.size,
)[0]
return np.asarray(field, dtype=float)
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set the system of the components built from the model parameters."""
super()._prepare(context)
space = CellComplexSpace(LatticeSpace((self.size, self.size))).prepare()
density = 1.0 + self.bump * np.random.default_rng(self.seed).random(self.size * self.size)
field = self._get_initial_field(space.incidences_[0], density - density.mean())
sites = GoodSiteElement('sites', rho=density, space=space)
links = ExchangeLinkElement('links', E=field, space=space, on='edges')
interactions = [
Interaction(
'potential',
roles={'target': 'links'},
laws=lambda s: [RateLaw(s.target.A.diff(s.t), self._get_potential_rate(s))],
),
Interaction(
'field',
roles={'target': 'links'},
laws=lambda s: [RateLaw(s.target.E.diff(s.t), self._get_field_rate(s))],
),
TraderCurrentInteraction('current', among='sites', D=self.D, q=self.q),
]
self.system_ = System(self.label, elements=[sites, links], interactions=interactions, solver=RK4Solver(dt=0.02))
self.observables_ = tuple(GaugeArbitrageMarketSystem._get_market_observables(self.system_))
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
Interactions:
InteractionTraderCurrentInteraction, fromInteraction
class GoodSiteElement(Element):
"""Site of a lattice with a density `rho` of a good.
Args:
label:
The label of the site or the group on the sites.
rho:
The initial density of the good.
space:
The space whose sites hold the members, or `None` for one site.
Attributes:
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
"""
def __init__(
self,
label: str,
*,
rho: object = 1.0,
space: BaseSpace | None = None,
) -> None:
super().__init__(label, space=space)
self.rho = rho
class ExchangeLinkElement(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.
Args:
label:
The label of the link or the group on the links.
A:
The initial exchange-rate potential.
E:
The initial value of `F_0i` of Schwichtenberg (2020 Eq. 2.22), the rate of change of the potential.
space:
The space whose links hold the members, or `None` for one link.
on:
`'edges'` for one member on every link of the space, or `None` for one per site.
Attributes:
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
"""
visual = VisualSpec('cell', {'state': 'A'})
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
class Interaction(BaseInteraction):
"""An interaction whose laws run once for the elements its roles bind.
It states the laws that change the values of the elements its roles bind, such as gravity on a ball in
`Interaction('gravity', roles={'target': 'ball'}, laws=lambda s: [RateLaw(s.target.x.diff(s.t, 2), -9.81)])`. When a
role binds a group, the laws run once for every member, as arrays. With `among` and `along`, they run once for every
edge of a network and read `s.source` and `s.target`, the members at its two ends, or once for every hyperedge or
random small group and read `s.member`, `s.others`, and `s.members`. With `within`, they run once for every pair of
members closer than a radius and read `s.first` and `s.second`. A subclass takes its roles, typed `Role`, and its
parameters as arguments of its `__init__` and sets `laws_` in its `_prepare`. It states predation between two
populations, a reaction between two chemicals, and an infection along the contacts of a network.
Read more in the user guide, under Interactions.
Args:
label:
The name of the interaction, unique among the components of its system, such as `'predation'`.
roles:
The element each role binds, by the name of the role, such as `{'target': 'ball'}`, for a rule written
without a class, or `None`.
laws:
The function of the namespace that returns the laws of a rule written without a class, such as
`lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`, the laws themselves when they read no element, or
`None`.
among:
The group whose members sit at the ends of the edges, such as `'people'`, or `None` to bind elements by
their roles only. A subclass annotates it as a role, and a rule written without a class binds it as one.
along:
`True` for the edges of the network the group lives on, the name of a layer of a network with several, such
as `'contacts'`, `'hyperedges'` for its hyperedges, `('hyperedges', k)` for its hyperedges of `k` members,
`RandomPartition(k)` for random groups of `k` members drawn at every step, `'neighborhoods'` for every
member with the members around it, or `None` for no edges. On the edges, the laws read the member of an
element that sits on them as `s.edge`, and on the hyperedges as `s.hyperedge`.
within:
A `RadiusNeighborhood(r)` for laws that run once for every pair of members of the roles `first` and `second`
closer than `r`, which read `s.first` and `s.second` and give the laws of both, such as the repulsion of
walkers of two crowds, or `None` for no pairs. With `among`, both members come from that group. The laws may
give the energy of the pair as `ObjectiveLaw(V)` in place of its forces, and each member then feels the
force `-dV/dx` on its position `x`.
See Also:
BaseInteraction: The base of every interaction.
RandomPartition: Groups the members of a group at random at every step.
TrainingInteraction: Trains the parameters of a nested system.
Examples:
>>> from skcomplex.core.components.interactions import Interaction
>>> from skcomplex.core.components.laws import RateLaw
>>> birth = Interaction('birth', roles={'target': 'fish'}, laws=lambda s: [RateLaw(s.target.n.diff(s.t), 1)])
>>> birth.roles
{'target': 'fish'}
"""
def __init__(
self,
label: str,
*,
roles: Mapping[str, object] | None = None,
laws: Callable[[SimpleNamespace], Sequence[BaseLaw]] | Sequence[BaseLaw] | None = None,
among: str | None = None,
along: bool | str | tuple[str, int] | RandomPartition | None = None,
within: RadiusNeighborhood | None = None,
) -> None:
super().__init__(label)
self.roles = roles
self.laws = laws
self.among = among
self.along = along
self.within = within
def _get_declared(self) -> Mapping[str, _DeclaredVariableSpec]:
"""Return the numeric arguments as parameters, and `roles` and `among` as roles.
With `within`, `among` binds both members of a pair, `first` and `second`.
"""
declared = dict(super()._get_declared())
for name, binding in (self.roles or {}).items():
declared[name] = _DeclaredVariableSpec(binding, RoleSpec())
if self.among is not None and self.within is not None:
for name in PAIR_ROLES:
declared.setdefault(name, _DeclaredVariableSpec(self.among, RoleSpec()))
elif self.among is not None and 'among' not in declared and 'among' not in self._get_specs():
declared['among'] = _DeclaredVariableSpec(self.among, RoleSpec())
return declared
@classmethod
def _get_state_arguments(cls, role: RoleSpec) -> tuple[str, ...]:
"""Return the arguments that name the states a role reads.
The mapping `roles` of bindings names none.
"""
return tuple(name for name in super()._get_state_arguments(role) if name != 'roles')
def _get_binding(self, role: str) -> object:
"""Return what a role binds, from `roles` or from the argument of its name.
Args:
role:
The name of the role.
Returns:
binding:
The label, labels, or entries the role binds, or `None` when it binds nothing.
"""
if self.roles is not None and role in self.roles:
return self.roles[role]
if self.among is not None and self.within is not None and role in PAIR_ROLES:
return self.among
return super()._get_binding(role)
def _check_arguments(self) -> None:
"""Raise an error for roles, laws, or groups the interaction cannot take.
Raises:
ValidationError:
A role of `roles` takes the name of an argument, `laws` is neither a function nor a list of laws, or
`along` names hyperedges of fewer than two members.
"""
clashes = sorted(set(self.roles or {}) & {'label', 'roles', 'laws', 'among', 'along'})
if clashes:
error_msg = f'The role {clashes[0]!r} of {self.label!r} takes the name of an argument. Rename the role.'
raise ValidationError(error_msg)
if self.laws is not None and not callable(self.laws) and not isinstance(self.laws, list | tuple):
error_msg = (
f'The laws of {self.label!r} are {self.laws!r}. Give a function that takes the bound elements as '
'`s` and returns the laws, such as `laws=lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`.'
)
raise ValidationError(error_msg)
if isinstance(self.along, tuple) and not self._is_sized(self.along):
error_msg = (
f'{self.label!r} runs along {self.along!r}. Give the hyperedges of one size as a whole number of 2 or '
"more, such as `along=('hyperedges', 3)`."
)
raise ValidationError(error_msg)
if isinstance(self.along, RandomPartition):
self.along._check()
grouped = isinstance(self.along, RandomPartition) or self.along == NEIGHBORHOODS
if grouped and self.among is None:
error_msg = f'{self.label!r} runs along groups of members. Name their group with `among`.'
raise ValidationError(error_msg)
super()._check_arguments()
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the laws of `laws` for a binding.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
if self.laws is not None:
self.laws_ = list(self.laws(context) if callable(self.laws) else self.laws)
@staticmethod
def _is_sized(along: tuple[object, ...]) -> bool:
"""Return whether `along` names hyperedges of a whole size of at least two."""
if len(along) != MIN_SIZE or along[0] != HYPEREDGES:
return False
size = along[1]
return isinstance(size, int) and not isinstance(size, bool) and size >= MIN_SIZE
def _get_draws(self) -> bool:
"""Return whether the interaction draws, as it does along random groups."""
return super()._get_draws() or isinstance(self.along, RandomPartition)
def _runs_on_edges(self) -> bool:
"""Return whether the interaction runs along edges."""
grouped = self._runs_on_hyperedges() or self._get_grouping() is not None
return self.along is not None and self.along is not False and not grouped
def _runs_on_hyperedges(self) -> bool:
"""Return whether the interaction runs along the hyperedges of a network."""
return self.along == HYPEREDGES or (isinstance(self.along, tuple) and self.along[0] == HYPEREDGES)
def _get_hyperedge_size(self) -> int | None:
"""Return the size `along` gives the hyperedges, or `None` for every size."""
return int(self.along[-1]) if isinstance(self.along, tuple) and self._runs_on_hyperedges() else None
def _get_within(self) -> RadiusNeighborhood | None:
"""Return the neighbourhood of the pairs the laws run for, or `None` for no pairs."""
return self.within
def _get_layer(self) -> str | None:
"""Return the layer `along` names, or `None` for no layer."""
if not isinstance(self.along, str) or self.along == NEIGHBORHOODS or self._runs_on_hyperedges():
return None
return self.along
def _get_grouping(self) -> tuple[str, int, str] | None:
"""Return the kind, size, and reduction of the groups `along` names, or `None`."""
if isinstance(self.along, RandomPartition):
return ('partition', self.along.size, 'sum')
if self.along == NEIGHBORHOODS:
return ('neighborhood', 0, 'sum')
return None
class TraderCurrentInteraction(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.
Args:
label:
The label of the interaction, unique among the components of its system.
among:
The path of the group on the sites, whose links the laws run on, reading the potential `A` of the element on
the links.
D:
The diffusivity of the good.
q:
The charge of the good.
along:
The edges the laws run on, `True` for the links of the space of the sites.
Examples:
>>> from skcomplex.systems.economics.finance import TraderCurrentInteraction
>>> TraderCurrentInteraction('current', among='sites', q=0.5).q
0.5
"""
law_classes = (RateLaw,)
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
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the rates of the good at both ends of a link and of its electric field as the laws.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
source, target, edge = context.source, context.target, context.edge
middle = (source.rho + target.rho) / 2
current = -context.D * (target.rho - source.rho - context.q * edge.A * middle)
self.laws_: list[BaseLaw] = [
RateLaw(source.rho, -current),
RateLaw(target.rho, current),
RateLaw(edge.E, -current),
]