Edgeworth and Red Cross barter
Barter of chocolate and cigarettes.
- Class:
BarterSystem - Import:
from skcomplex.systems.economics.markets import BarterSystem - Field:
economics/markets - Topics:
market,agents,barter,Edgeworth box,contract curve - References:
- Hamill and Gilbert 2016 ch. 5
- Radford 1945
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.markets import BarterSystem
trajectory = BarterSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
n_barterers |
2 |
chocolate |
(9.0, 1.0) |
cigarettes |
(2.0, 8.0) |
weights |
(0.6, 0.3) |
quantity |
0.02 |
random_state |
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 | deterministic |
| Domains | real |
| Structure | variable membership |
Class
The source of the class shows how it builds its components from its model parameters.
class BarterSystem(BaseSystem):
"""Barter of chocolate and cigarettes.
It happens in an Edgeworth box of two barterers or among many prisoners. Every step the barterers are paired at
random, and every pair trades small quantities of one good for the other at the geometric mean of their marginal
rates of substitution while both gain, so the totals of both goods are unchanged. Two barterers with the given
endowments and weights of chocolate trade within the Edgeworth box until no trade improves both, which is a point of
the contract curve, where their marginal rates of substitution are equal. More barterers are prisoners of war who
receive random Red Cross parcels and random tastes, and their trades settle on a common price, as Radford (1945)
observed (Hamill and Gilbert 2016 ch. 5).
The system has the group `barterers` and the exchange `exchange`, whose reporters are the price of cigarettes in
chocolate `exchange.price`, its `exchange.dispersion`, and `exchange.volume`.
Args:
n_barterers:
The number of barterers, 2 for the Edgeworth box.
chocolate:
The chocolate of the two barterers of the Edgeworth box, and the range of the parcels of more barterers.
cigarettes:
The cigarettes of the two barterers of the Edgeworth box, and the range of the parcels of more
barterers.
weights:
The weights of chocolate of the two barterers of the Edgeworth box, and the range of the weights of more
barterers.
quantity:
The quantity of the bought good in every trade.
random_state:
The seed or generator of the parcels and the weights of more than two barterers.
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.
Raises:
ValueError:
There are fewer than two barterers.
Examples:
>>> from skcomplex.systems.economics.markets import BarterSystem
>>> BarterSystem().prepare().system_.elements[0].size
2
"""
field = 'economics/markets'
topics = ('market', 'agents', 'barter', 'Edgeworth box', 'contract curve')
references = ('Hamill and Gilbert 2016 ch. 5', 'Radford 1945')
until = 20
observables = (
Observable('utility', _get_utility, group='barterers', reduce='mean'),
*(Observable(good, group='barterers', variable=good, reduce='sum') for good in GOODS),
)
def __init__(
self,
n_barterers: int = 2,
*,
chocolate: tuple[float, float] = (9.0, 1.0),
cigarettes: tuple[float, float] = (2.0, 8.0),
weights: tuple[float, float] = (0.6, 0.3),
quantity: float = 0.02,
random_state: int | np.random.Generator | None = 0,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.n_barterers = n_barterers
self.chocolate = chocolate
self.cigarettes = cigarettes
self.weights = weights
self.quantity = quantity
self.random_state = random_state
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set the system of the components built from the model parameters."""
super()._prepare(context)
if self.n_barterers < EDGEWORTH_BARTERERS:
error_msg = f'Barter needs at least two barterers, but got {self.n_barterers}.'
raise ValueError(error_msg)
rng = np.random.default_rng(self.random_state)
if self.n_barterers == EDGEWORTH_BARTERERS:
holdings: dict[str, list[float] | npt.NDArray[np.float64]] = {
'chocolate': list(self.chocolate),
'cigarettes': list(self.cigarettes),
}
shares = np.asarray(self.weights, dtype=float)
else:
holdings = {
'chocolate': rng.uniform(min(self.chocolate), max(self.chocolate), self.n_barterers),
'cigarettes': rng.uniform(min(self.cigarettes), max(self.cigarettes), self.n_barterers),
}
shares = rng.uniform(min(self.weights), max(self.weights), self.n_barterers)
barterers = BartererElement(
'barterers',
chocolate_weight=shares,
cigarettes_weight=1 - shares,
**holdings,
size=self.n_barterers,
)
self.system_ = System(
self.label,
elements=[barterers],
interactions=[
ExchangeInteraction(
'exchange',
target='barterers',
goods=GOODS,
quantity=self.quantity,
),
],
solver=MesaSolver(phases=[PhaseSpec('trade')]),
)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
BartererElement, fromElement
Interactions:
ExchangeInteraction, fromInteraction
class BartererElement(Element):
"""Barterer who holds chocolate and cigarettes.
It values them with Cobb-Douglas weights.
Args:
label:
The label of the agent or group.
chocolate:
The holding of chocolate.
cigarettes:
The holding of cigarettes.
chocolate_weight:
The Cobb-Douglas weight of chocolate.
cigarettes_weight:
The Cobb-Douglas weight of cigarettes.
size:
The number of members, or `None` for one.
Examples:
>>> from skcomplex.systems.economics.markets import BartererElement
>>> BartererElement('barterers', chocolate=[8.0, 2.0], size=2).size
2
"""
visual = VisualSpec('agents', {'color_by': 'chocolate_weight', 'color_range': (0.0, 1.0)})
def __init__(
self,
label: str,
*,
chocolate: Annotated[object, RealSet.closed_open(0, oo)] = 5.0,
cigarettes: Annotated[object, RealSet.closed_open(0, oo)] = 5.0,
chocolate_weight: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
cigarettes_weight: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
size: int | None = None,
) -> None:
super().__init__(label, size=size)
self.chocolate = chocolate
self.cigarettes = cigarettes
self.chocolate_weight = chocolate_weight
self.cigarettes_weight = cigarettes_weight
class ExchangeInteraction(Interaction):
"""Bilateral barter between paired traders.
Its trades repeat while both traders gain. Every step the exchange pairs the traders, and every
pair barters small quantities of every pair of goods at the geometric mean of their marginal rates of substitution
while both gain. A trader holds every good in the state of its name and its Cobb-Douglas weight in the state
`<good>_weight`. Every trade moves goods between the two traders, so the total of every good stays the same, which
the default run checks as invariants. The exchange reports the mean `price` of the second good in units of the
first, the standard deviation `dispersion` of its logarithm over the trades of the step, and the number of trades
`volume`.
Args:
label:
The label of the exchange.
target:
The path of the group of traders.
goods:
The names of the traded goods.
pairing:
How the exchange pairs the traders, `'neighbor-pairs'` for disjoint pairs of neighbours or `'pairs'` for
disjoint random pairs.
quantity:
The quantity of the bought good in every trade.
phase:
The phase the trades run in.
Examples:
>>> from skcomplex.systems.economics.markets import ExchangeInteraction
>>> ExchangeInteraction('exchange', target='traders').reports
('price', 'dispersion', 'volume')
"""
law_classes = (UpdateLaw,)
reports: ClassVar[tuple[str, ...]] = ('price', 'dispersion', 'volume')
def __init__(
self,
label: str,
*,
target: Role,
goods: tuple[str, ...] = GOODS,
pairing: str = 'pairs',
quantity: float = 0.1,
phase: str = 'trade',
) -> None:
super().__init__(label)
self.target = target
self.goods = goods
self.pairing = pairing
self.quantity = quantity
self.phase = phase
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the barter of every pair of traders and then the report of the trades as rules of the system.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = [
UpdateLaw(context, self.trade, phase=self.phase),
UpdateLaw(context, self.report_trades, phase=self.phase),
]
def trade(self, system: SystemViewProtocol) -> None:
"""Pair the traders and let every pair barter, in random order.
Args:
system:
The system view of the exchange.
"""
traders = system.get_agents('target')
found = list(pairs(traders, traders, system.rng, PAIRINGS[self.pairing]))
for index in system.rng.permutation(len(found)):
first, second = found[int(index)]
if first.alive and second.alive:
self.transfer(first, second, system)
def transfer(self, source: AgentViewProtocol, target: AgentViewProtocol, system: SystemViewProtocol) -> bool:
"""Barter between two traders while both gain.
It keeps the trades of the step for its report.
Args:
source:
The first trader.
target:
The second trader.
system:
The system view of the exchange.
Returns:
traded:
Whether the traders made a trade.
"""
weights = [f'{good}_weight' for good in self.goods]
trades = trade_goods(source, target, self.goods, weights, quantity=self.quantity)
logs = system.storage.setdefault('trades', [])
if isinstance(logs, list):
logs.extend(trades)
return bool(trades)
def report_trades(self, system: SystemViewProtocol) -> None:
"""Report the mean price of the second good in the first, and the trades.
It also reports the dispersion of the price, and the trades are those of the step.
Args:
system:
The system view of the exchange.
"""
trades = system.storage.pop('trades', [])
trades = trades if isinstance(trades, list) else []
logs = [math.log(price) for bought, paid, price in trades if (bought, paid) == (0, 1)]
system.report('price', math.exp(float(np.mean(logs))) if logs else math.nan)
system.report('dispersion', float(np.std(logs)) if len(logs) > 1 else math.nan)
system.report('volume', len(trades))
Equations
The equations are those that symbolic returns for the system with its default parameters.