Exchange rates in international trade
Hamill and Gilbert's staged adjustment of trade and the exchange rate.
- Class:
ExchangeRatesSystem - Import:
from skcomplex.systems.economics.macroeconomics import ExchangeRatesSystem - Field:
economics/macroeconomics - Topics:
international trade,exchange rate,discrete map - References:
- Hamill and Gilbert 2016
Use this system
The block imports the class and simulates the system with its default parameters and its tuned run settings.
from skcomplex.systems.economics.macroeconomics import ExchangeRatesSystem
trajectory = ExchangeRatesSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
exports |
32.0 |
imports |
34.0 |
home_price |
1.2 |
inflation |
0.1 |
export_elasticity |
-1.0 |
import_elasticity |
-1.0 |
floating |
True |
demand |
52.0 |
government |
50.0 |
world_price |
1.0 |
solver |
'auto' |
backend |
'auto' |
Tags
The system with its default parameters has these capability tags, which solvers and analyses check.
| Tag | Values |
|---|---|
| Time | discrete |
| Space | none |
| Laws | update |
| Randomness | unknown |
| Domains | real |
| Structure | fixed |
Class
The source of the class shows how it builds its components from its model parameters.
class ExchangeRatesSystem(BaseSystem):
"""Hamill and Gilbert's staged adjustment of trade and the exchange rate.
The adjustment follows a rise in home prices. The economy starts in balance at the exchange rate
`E = M * PW / (X * PH)`, in units of World currency per unit of Home currency, with the export and import volumes
and prices of the United Kingdom in 1999 by default. Home prices rise by `inflation` at the first stage. At every
stage a floating rate takes the value that balances the currency market at the current volumes, a fixed rate stays,
and the volumes respond to the prices of the stage before with constant price elasticities. The book follows two
stages, the default.
The system has the economy `home`, the balance of trade at home prices `balance`, the real exchange rate
`real_rate`, and the output `output`.
Args:
exports:
The initial export volume.
imports:
The initial import volume.
home_price:
The home price of home-produced goods before the rise.
inflation:
The relative rise of the home prices.
export_elasticity:
The price elasticity of the exports.
import_elasticity:
The price elasticity of the imports.
floating:
Whether the exchange rate floats, or is fixed as in the Eurozone.
demand:
The private domestic demand, consumption and investment.
government:
The government spending.
world_price:
The world price level.
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.macroeconomics import ExchangeRatesSystem
>>> round(ExchangeRatesSystem().prepare().system_.elements[0].E, 3)
0.885
"""
field = 'economics/macroeconomics'
topics = ('international trade', 'exchange rate', 'discrete map')
references = ('Hamill and Gilbert 2016',)
until = 2
dt = 1
observables = (
Observable('balance', _balance),
Observable('real_rate', _get_real_rate),
Observable('output', _get_output),
)
@staticmethod
def _get_home_price(s: SimpleNamespace) -> Expression:
"""Return the home price after the rise."""
home = s.target
price: Expression = home.home_price * (1 + home.inflation)
return price
@staticmethod
def _exchange_rate(s: SimpleNamespace) -> Expression:
"""Return the rate that balances the currency market when it floats.
It balances the market at the current volumes, and otherwise it is the rate.
"""
home = s.target
balancing = home.M * home.world_price / (home.X * home.home_price * (1 + home.inflation))
rate: Expression = where(home.floating > 0, balancing, home.E)
return rate
@staticmethod
def _get_exports(s: SimpleNamespace) -> Expression:
"""Return the export volume.
It responds to the World price of the exports with a constant elasticity.
"""
home = s.target
volume: Expression = home.exports * (1 + home.export_elasticity * (home.PH * home.E / home.export_price - 1))
return volume
@staticmethod
def _get_imports(s: SimpleNamespace) -> Expression:
"""Return the import volume.
It responds to the home price of the imports with a constant elasticity.
"""
home = s.target
volume: Expression = home.imports * (
1 + home.import_elasticity * (home.world_price / (home.E * home.import_price) - 1)
)
return volume
def __init__(
self,
exports: float = 32.0,
imports: float = 34.0,
*,
home_price: float = 1.2,
inflation: float = 0.1,
export_elasticity: float = -1.0,
import_elasticity: float = -1.0,
floating: bool = True,
demand: float = 52.0,
government: float = 50.0,
world_price: float = 1.0,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.exports = exports
self.imports = imports
self.home_price = home_price
self.inflation = inflation
self.export_elasticity = export_elasticity
self.import_elasticity = import_elasticity
self.floating = floating
self.demand = demand
self.government = government
self.world_price = world_price
@staticmethod
def _get_adjustments() -> list[Interaction]:
"""Return the maps of the home price, the exchange rate, and the trade volumes.
There is one at every stage.
"""
system = ExchangeRatesSystem
return [
Interaction(
'PH_adjustment',
roles={'target': 'home'},
laws=lambda s: [UpdateLaw(s.target.PH, system._get_home_price(s))],
),
Interaction(
'E_adjustment',
roles={'target': 'home'},
laws=lambda s: [UpdateLaw(s.target.E, system._exchange_rate(s))],
),
Interaction(
'X_adjustment',
roles={'target': 'home'},
laws=lambda s: [UpdateLaw(s.target.X, system._get_exports(s))],
),
Interaction(
'M_adjustment',
roles={'target': 'home'},
laws=lambda s: [UpdateLaw(s.target.M, system._get_imports(s))],
),
]
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set the system of the components built from the model parameters."""
super()._prepare(context)
rate = self.imports * self.world_price / (self.exports * self.home_price)
home = TradingEconomyElement(
'home',
E=rate,
X=self.exports,
M=self.imports,
PH=self.home_price,
home_price=self.home_price,
inflation=self.inflation,
world_price=self.world_price,
exports=self.exports,
imports=self.imports,
export_price=self.home_price * rate,
import_price=self.world_price / rate,
export_elasticity=self.export_elasticity,
import_elasticity=self.import_elasticity,
floating=float(self.floating),
import_share=self.imports / (self.demand + self.government + self.exports - self.imports),
demand=self.demand,
government=self.government,
)
self.system_ = System(self.label, elements=[home], interactions=self._get_adjustments())
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
TradingEconomyElement, fromElement
Interactions:
Interaction
class TradingEconomyElement(Element):
"""Open economy that trades with the World at an exchange rate, floating or fixed.
Its states are the exchange rate `E` in World currency per unit of home currency, the export and import volumes
`X` and `M`, and the home price `PH`. Its parameters are the prices, volumes, and elasticities of the balanced
start, the rise `inflation` of home prices, whether the rate floats, and the shares of the output.
Args:
label:
The label of the economy.
E:
The exchange rate.
X:
The export volume.
M:
The import volume.
PH:
The home price of home-produced goods.
home_price:
The home price before the rise.
inflation:
The relative rise of the home prices.
world_price:
The world price level.
exports:
The export volume of the balanced start.
imports:
The import volume of the balanced start.
export_price:
The World price of the exports at the start.
import_price:
The home price of the imports at the start.
export_elasticity:
The price elasticity of the exports.
import_elasticity:
The price elasticity of the imports.
floating:
1 when the exchange rate floats, 0 when it is fixed.
import_share:
The share of the imports in the output.
demand:
The private domestic demand.
government:
The government spending.
Examples:
>>> from skcomplex.systems.economics.macroeconomics import TradingEconomyElement
>>> TradingEconomyElement('home').floating
1.0
"""
def __init__(
self,
label: str,
*,
E: Annotated[object, RealSet.open(0, oo)] = 0.885,
X: Annotated[object, RealSet.closed_open(0, oo)] = 32.0,
M: Annotated[object, RealSet.closed_open(0, oo)] = 34.0,
PH: Annotated[object, RealSet.open(0, oo)] = 1.2,
home_price: Annotated[object, RealSet.open(0, oo)] = 1.2,
inflation: object = 0.1,
world_price: Annotated[object, RealSet.open(0, oo)] = 1.0,
exports: Annotated[object, RealSet.closed_open(0, oo)] = 32.0,
imports: Annotated[object, RealSet.closed_open(0, oo)] = 34.0,
export_price: Annotated[object, RealSet.open(0, oo)] = 1.062,
import_price: Annotated[object, RealSet.open(0, oo)] = 1.13,
export_elasticity: object = -1.0,
import_elasticity: object = -1.0,
floating: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
import_share: Annotated[object, RealSet.closed_open(0, oo)] = 0.34,
demand: Annotated[object, RealSet.closed_open(0, oo)] = 52.0,
government: Annotated[object, RealSet.closed_open(0, oo)] = 50.0,
) -> None:
super().__init__(label)
self.E = E
self.X = X
self.M = M
self.PH = PH
self.home_price = home_price
self.inflation = inflation
self.world_price = world_price
self.exports = exports
self.imports = imports
self.export_price = export_price
self.import_price = import_price
self.export_elasticity = export_elasticity
self.import_elasticity = import_elasticity
self.floating = floating
self.import_share = import_share
self.demand = demand
self.government = government
class Interaction(BaseInteraction):
"""An interaction whose laws run once for the elements its roles bind.
It states the laws that change the values of the elements its roles bind, such as gravity on a ball in
`Interaction('gravity', roles={'target': 'ball'}, laws=lambda s: [RateLaw(s.target.x.diff(s.t, 2), -9.81)])`. When a
role binds a group, the laws run once for every member, as arrays. With `among` and `along`, they run once for every
edge of a network and read `s.source` and `s.target`, the members at its two ends, or once for every hyperedge or
random small group and read `s.member`, `s.others`, and `s.members`. With `within`, they run once for every pair of
members closer than a radius and read `s.first` and `s.second`. A subclass takes its roles, typed `Role`, and its
parameters as arguments of its `__init__` and sets `laws_` in its `_prepare`. It states predation between two
populations, a reaction between two chemicals, and an infection along the contacts of a network.
Read more in the user guide, under Interactions.
Args:
label:
The name of the interaction, unique among the components of its system, such as `'predation'`.
roles:
The element each role binds, by the name of the role, such as `{'target': 'ball'}`, for a rule written
without a class, or `None`.
laws:
The function of the namespace that returns the laws of a rule written without a class, such as
`lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`, the laws themselves when they read no element, or
`None`.
among:
The group whose members sit at the ends of the edges, such as `'people'`, or `None` to bind elements by
their roles only. A subclass annotates it as a role, and a rule written without a class binds it as one.
along:
`True` for the edges of the network the group lives on, the name of a layer of a network with several, such
as `'contacts'`, `'hyperedges'` for its hyperedges, `('hyperedges', k)` for its hyperedges of `k` members,
`RandomPartition(k)` for random groups of `k` members drawn at every step, `'neighborhoods'` for every
member with the members around it, or `None` for no edges. On the edges, the laws read the member of an
element that sits on them as `s.edge`, and on the hyperedges as `s.hyperedge`.
within:
A `RadiusNeighborhood(r)` for laws that run once for every pair of members of the roles `first` and `second`
closer than `r`, which read `s.first` and `s.second` and give the laws of both, such as the repulsion of
walkers of two crowds, or `None` for no pairs. With `among`, both members come from that group. The laws may
give the energy of the pair as `ObjectiveLaw(V)` in place of its forces, and each member then feels the
force `-dV/dx` on its position `x`.
See Also:
BaseInteraction: The base of every interaction.
RandomPartition: Groups the members of a group at random at every step.
TrainingInteraction: Trains the parameters of a nested system.
Examples:
>>> from skcomplex.core.components.interactions import Interaction
>>> from skcomplex.core.components.laws import RateLaw
>>> birth = Interaction('birth', roles={'target': 'fish'}, laws=lambda s: [RateLaw(s.target.n.diff(s.t), 1)])
>>> birth.roles
{'target': 'fish'}
"""
def __init__(
self,
label: str,
*,
roles: Mapping[str, object] | None = None,
laws: Callable[[SimpleNamespace], Sequence[BaseLaw]] | Sequence[BaseLaw] | None = None,
among: str | None = None,
along: bool | str | tuple[str, int] | RandomPartition | None = None,
within: RadiusNeighborhood | None = None,
) -> None:
super().__init__(label)
self.roles = roles
self.laws = laws
self.among = among
self.along = along
self.within = within
def _get_declared(self) -> Mapping[str, _DeclaredVariableSpec]:
"""Return the numeric arguments as parameters, and `roles` and `among` as roles.
With `within`, `among` binds both members of a pair, `first` and `second`.
"""
declared = dict(super()._get_declared())
for name, binding in (self.roles or {}).items():
declared[name] = _DeclaredVariableSpec(binding, RoleSpec())
if self.among is not None and self.within is not None:
for name in PAIR_ROLES:
declared.setdefault(name, _DeclaredVariableSpec(self.among, RoleSpec()))
elif self.among is not None and 'among' not in declared and 'among' not in self._get_specs():
declared['among'] = _DeclaredVariableSpec(self.among, RoleSpec())
return declared
@classmethod
def _get_state_arguments(cls, role: RoleSpec) -> tuple[str, ...]:
"""Return the arguments that name the states a role reads.
The mapping `roles` of bindings names none.
"""
return tuple(name for name in super()._get_state_arguments(role) if name != 'roles')
def _get_binding(self, role: str) -> object:
"""Return what a role binds, from `roles` or from the argument of its name.
Args:
role:
The name of the role.
Returns:
binding:
The label, labels, or entries the role binds, or `None` when it binds nothing.
"""
if self.roles is not None and role in self.roles:
return self.roles[role]
if self.among is not None and self.within is not None and role in PAIR_ROLES:
return self.among
return super()._get_binding(role)
def _check_arguments(self) -> None:
"""Raise an error for roles, laws, or groups the interaction cannot take.
Raises:
ValidationError:
A role of `roles` takes the name of an argument, `laws` is neither a function nor a list of laws, or
`along` names hyperedges of fewer than two members.
"""
clashes = sorted(set(self.roles or {}) & {'label', 'roles', 'laws', 'among', 'along'})
if clashes:
error_msg = f'The role {clashes[0]!r} of {self.label!r} takes the name of an argument. Rename the role.'
raise ValidationError(error_msg)
if self.laws is not None and not callable(self.laws) and not isinstance(self.laws, list | tuple):
error_msg = (
f'The laws of {self.label!r} are {self.laws!r}. Give a function that takes the bound elements as '
'`s` and returns the laws, such as `laws=lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`.'
)
raise ValidationError(error_msg)
if isinstance(self.along, tuple) and not self._is_sized(self.along):
error_msg = (
f'{self.label!r} runs along {self.along!r}. Give the hyperedges of one size as a whole number of 2 or '
"more, such as `along=('hyperedges', 3)`."
)
raise ValidationError(error_msg)
if isinstance(self.along, RandomPartition):
self.along._check()
grouped = isinstance(self.along, RandomPartition) or self.along == NEIGHBORHOODS
if grouped and self.among is None:
error_msg = f'{self.label!r} runs along groups of members. Name their group with `among`.'
raise ValidationError(error_msg)
super()._check_arguments()
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the laws of `laws` for a binding.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
if self.laws is not None:
self.laws_ = list(self.laws(context) if callable(self.laws) else self.laws)
@staticmethod
def _is_sized(along: tuple[object, ...]) -> bool:
"""Return whether `along` names hyperedges of a whole size of at least two."""
if len(along) != MIN_SIZE or along[0] != HYPEREDGES:
return False
size = along[1]
return isinstance(size, int) and not isinstance(size, bool) and size >= MIN_SIZE
def _get_draws(self) -> bool:
"""Return whether the interaction draws, as it does along random groups."""
return super()._get_draws() or isinstance(self.along, RandomPartition)
def _runs_on_edges(self) -> bool:
"""Return whether the interaction runs along edges."""
grouped = self._runs_on_hyperedges() or self._get_grouping() is not None
return self.along is not None and self.along is not False and not grouped
def _runs_on_hyperedges(self) -> bool:
"""Return whether the interaction runs along the hyperedges of a network."""
return self.along == HYPEREDGES or (isinstance(self.along, tuple) and self.along[0] == HYPEREDGES)
def _get_hyperedge_size(self) -> int | None:
"""Return the size `along` gives the hyperedges, or `None` for every size."""
return int(self.along[-1]) if isinstance(self.along, tuple) and self._runs_on_hyperedges() else None
def _get_within(self) -> RadiusNeighborhood | None:
"""Return the neighbourhood of the pairs the laws run for, or `None` for no pairs."""
return self.within
def _get_layer(self) -> str | None:
"""Return the layer `along` names, or `None` for no layer."""
if not isinstance(self.along, str) or self.along == NEIGHBORHOODS or self._runs_on_hyperedges():
return None
return self.along
def _get_grouping(self) -> tuple[str, int, str] | None:
"""Return the kind, size, and reduction of the groups `along` names, or `None`."""
if isinstance(self.along, RandomPartition):
return ('partition', self.along.size, 'sum')
if self.along == NEIGHBORHOODS:
return ('neighborhood', 0, 'sum')
return None
Equations
The equations are those that symbolic returns for the system with its default parameters.
home.E: E_home(t + 1) == where(floating_home > 0, world_price_home*M_home(t)/(home_price_home*(inflation_home + 1)*X_home(t)), E_home(t))
home.X: X_home(t + 1) == (export_elasticity_home*(E_home(t)*PH_home(t)/export_price_home - 1) + 1)*exports_home
home.M: M_home(t + 1) == (import_elasticity_home*(world_price_home/(import_price_home*E_home(t)) - 1) + 1)*imports_home
home.PH: PH_home(t + 1) == home_price_home*(inflation_home + 1)