microstructure-sim 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- microbook/__init__.py +30 -0
- microbook/book.py +553 -0
- microbook/order.py +86 -0
- microbook/py.typed +0 -0
- microbook/replay.py +673 -0
- microbook/rl.py +221 -0
- microbook/sim/__init__.py +93 -0
- microbook/sim/agents.py +495 -0
- microbook/sim/analytics.py +199 -0
- microbook/sim/events.py +41 -0
- microbook/sim/execution_metrics.py +217 -0
- microbook/sim/metrics.py +20 -0
- microbook/sim/orderflow.py +70 -0
- microbook/sim/portfolio.py +83 -0
- microbook/sim/scenarios.py +145 -0
- microbook/sim/simulator.py +274 -0
- microbook/sim/strategies_mm.py +190 -0
- microbook/sim/strategy.py +352 -0
- microbook/stylized.py +324 -0
- microbook/types.py +119 -0
- microstructure_sim-1.0.0.dist-info/METADATA +615 -0
- microstructure_sim-1.0.0.dist-info/RECORD +24 -0
- microstructure_sim-1.0.0.dist-info/WHEEL +4 -0
- microstructure_sim-1.0.0.dist-info/licenses/LICENSE +21 -0
microbook/sim/events.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Events the simulator schedules on its heap."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from enum import Enum
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from microbook.order import Order
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class EventType(str, Enum):
|
|
13
|
+
"""Kinds of simulator event."""
|
|
14
|
+
|
|
15
|
+
SUBMIT = "SUBMIT" # submit an order (limit or market)
|
|
16
|
+
CANCEL = "CANCEL" # cancel a resting order by id
|
|
17
|
+
MODIFY = "MODIFY" # amend a resting order (new_price / new_qty)
|
|
18
|
+
SNAPSHOT = "SNAPSHOT" # record book state and call every strategy's on_tick
|
|
19
|
+
TIMER = "TIMER" # wake a single strategy (its on_timer hook)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(order=True)
|
|
23
|
+
class Event:
|
|
24
|
+
"""A scheduled simulator event. Ordered by ``(time, seq)``; ``seq`` is the
|
|
25
|
+
global scheduling sequence, which makes ties deterministic (FIFO)."""
|
|
26
|
+
|
|
27
|
+
time: int
|
|
28
|
+
"""When the event fires."""
|
|
29
|
+
seq: int
|
|
30
|
+
"""Global scheduling sequence number. It breaks ties at equal `time` in FIFO order."""
|
|
31
|
+
etype: EventType = field(compare=False)
|
|
32
|
+
"""Kind of event."""
|
|
33
|
+
|
|
34
|
+
order: Order | None = field(default=None, compare=False)
|
|
35
|
+
"""The order, for `SUBMIT`."""
|
|
36
|
+
order_id: str | None = field(default=None, compare=False)
|
|
37
|
+
"""Target order id, for `CANCEL` and `MODIFY`."""
|
|
38
|
+
modify: dict[str, Any] | None = field(default=None, compare=False)
|
|
39
|
+
"""`new_price` and/or `new_qty`, for `MODIFY`."""
|
|
40
|
+
owner: int | None = field(default=None, compare=False)
|
|
41
|
+
"""Index of the strategy that sent the event; `None` for events scheduled directly."""
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""Per-strategy execution statistics: volumes, prices, slippage and spread capture."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import NamedTuple
|
|
6
|
+
|
|
7
|
+
from microbook import Side
|
|
8
|
+
from microbook.types import Fill
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class FillRecord(NamedTuple):
|
|
12
|
+
"""One fill from a strategy's point of view (kept for post-trade analysis such as markouts)."""
|
|
13
|
+
|
|
14
|
+
time: int | None
|
|
15
|
+
"""Simulation time of the fill; `None` if it was not recorded."""
|
|
16
|
+
side: Side
|
|
17
|
+
"""This strategy's side of the trade."""
|
|
18
|
+
price: float
|
|
19
|
+
"""Execution price."""
|
|
20
|
+
qty: int
|
|
21
|
+
"""Shares traded."""
|
|
22
|
+
is_maker: bool
|
|
23
|
+
"""Whether this strategy's order was resting."""
|
|
24
|
+
mid: float | None
|
|
25
|
+
"""Midprice just before the trade; `None` if the book was one-sided."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ExecutionMetrics:
|
|
29
|
+
"""Per-strategy execution quality metrics.
|
|
30
|
+
|
|
31
|
+
* VWAP of buys and sells, blended average price, total notional
|
|
32
|
+
* slippage vs **arrival** (decision-time) midprice, per direction
|
|
33
|
+
* spread capture per share on maker fills (vs the pre-trade mid)
|
|
34
|
+
* fill ratio (filled / submitted) and participation rate (share of market volume)
|
|
35
|
+
|
|
36
|
+
Each ratio is computed only over the fills that carry the information it
|
|
37
|
+
needs (e.g. slippage only over fills of orders with a known arrival mid),
|
|
38
|
+
so missing data never dilutes a metric.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(self) -> None:
|
|
42
|
+
self.market_volume: int = 0
|
|
43
|
+
self.fills: list[FillRecord] = []
|
|
44
|
+
self.orders_submitted: int = 0
|
|
45
|
+
self.orders_rejected: int = 0
|
|
46
|
+
|
|
47
|
+
self._buy_qty = 0
|
|
48
|
+
self._sell_qty = 0
|
|
49
|
+
self._buy_notional = 0.0
|
|
50
|
+
self._sell_notional = 0.0
|
|
51
|
+
self._maker_qty = 0
|
|
52
|
+
self._taker_qty = 0
|
|
53
|
+
|
|
54
|
+
# spread capture: maker fills with a known mid
|
|
55
|
+
self._maker_spread_total = 0.0
|
|
56
|
+
self._maker_spread_qty = 0
|
|
57
|
+
|
|
58
|
+
# order_id -> (side, submitted_qty, arrival_mid | None)
|
|
59
|
+
self._order_registry: dict[str, tuple[Side, int, float | None]] = {}
|
|
60
|
+
self._submitted_qty = 0
|
|
61
|
+
|
|
62
|
+
# slippage: fills of orders with a known arrival mid, per direction
|
|
63
|
+
self._buy_arr_qty = 0
|
|
64
|
+
self._buy_arr_notional = 0.0 # sum(qty * fill price)
|
|
65
|
+
self._buy_arr_mid_notional = 0.0 # sum(qty * arrival mid)
|
|
66
|
+
self._sell_arr_qty = 0
|
|
67
|
+
self._sell_arr_notional = 0.0
|
|
68
|
+
self._sell_arr_mid_notional = 0.0
|
|
69
|
+
|
|
70
|
+
# ------------------------------------------------------------------ #
|
|
71
|
+
# Recording API #
|
|
72
|
+
# ------------------------------------------------------------------ #
|
|
73
|
+
|
|
74
|
+
def record_order(self, order_id: str, side: Side, qty: int, arrival_mid: float | None) -> None:
|
|
75
|
+
"""Register an order at decision time. ``arrival_mid`` may be ``None``
|
|
76
|
+
(no two-sided market), in which case its fills are excluded from slippage."""
|
|
77
|
+
self._order_registry[order_id] = (side, qty, arrival_mid)
|
|
78
|
+
self._submitted_qty += qty
|
|
79
|
+
self.orders_submitted += 1
|
|
80
|
+
|
|
81
|
+
def record_market_volume(self, fills: list[Fill] | tuple[Fill, ...]) -> None:
|
|
82
|
+
"""Accumulate market-wide traded volume (called for every fill in the market)."""
|
|
83
|
+
for f in fills:
|
|
84
|
+
self.market_volume += f.qty
|
|
85
|
+
|
|
86
|
+
def on_fill(
|
|
87
|
+
self,
|
|
88
|
+
fill: Fill,
|
|
89
|
+
my_side: Side,
|
|
90
|
+
is_maker: bool,
|
|
91
|
+
mid: float | None = None,
|
|
92
|
+
time: int | None = None,
|
|
93
|
+
) -> None:
|
|
94
|
+
"""Record a fill of one of this strategy's orders.
|
|
95
|
+
|
|
96
|
+
``mid`` is the midprice immediately before the trade (used for spread
|
|
97
|
+
capture); ``time`` is the simulation time (used for markouts).
|
|
98
|
+
"""
|
|
99
|
+
qty, px = fill.qty, fill.price
|
|
100
|
+
is_buy = my_side is Side.BUY
|
|
101
|
+
if is_buy:
|
|
102
|
+
self._buy_qty += qty
|
|
103
|
+
self._buy_notional += px * qty
|
|
104
|
+
else:
|
|
105
|
+
self._sell_qty += qty
|
|
106
|
+
self._sell_notional += px * qty
|
|
107
|
+
|
|
108
|
+
if is_maker:
|
|
109
|
+
self._maker_qty += qty
|
|
110
|
+
if mid is not None:
|
|
111
|
+
self._maker_spread_total += ((mid - px) if is_buy else (px - mid)) * qty
|
|
112
|
+
self._maker_spread_qty += qty
|
|
113
|
+
else:
|
|
114
|
+
self._taker_qty += qty
|
|
115
|
+
|
|
116
|
+
rec = self._order_registry.get(fill.maker_order_id if is_maker else fill.taker_order_id)
|
|
117
|
+
if rec is not None and rec[2] is not None:
|
|
118
|
+
arrival = rec[2]
|
|
119
|
+
if is_buy:
|
|
120
|
+
self._buy_arr_qty += qty
|
|
121
|
+
self._buy_arr_notional += px * qty
|
|
122
|
+
self._buy_arr_mid_notional += arrival * qty
|
|
123
|
+
else:
|
|
124
|
+
self._sell_arr_qty += qty
|
|
125
|
+
self._sell_arr_notional += px * qty
|
|
126
|
+
self._sell_arr_mid_notional += arrival * qty
|
|
127
|
+
|
|
128
|
+
self.fills.append(FillRecord(time, my_side, px, qty, is_maker, mid))
|
|
129
|
+
|
|
130
|
+
# ------------------------------------------------------------------ #
|
|
131
|
+
# Computed metrics #
|
|
132
|
+
# ------------------------------------------------------------------ #
|
|
133
|
+
|
|
134
|
+
@property
|
|
135
|
+
def filled_qty(self) -> int:
|
|
136
|
+
"""Shares filled, buys plus sells."""
|
|
137
|
+
return self._buy_qty + self._sell_qty
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def buy_qty(self) -> int:
|
|
141
|
+
"""Shares bought."""
|
|
142
|
+
return self._buy_qty
|
|
143
|
+
|
|
144
|
+
@property
|
|
145
|
+
def sell_qty(self) -> int:
|
|
146
|
+
"""Shares sold."""
|
|
147
|
+
return self._sell_qty
|
|
148
|
+
|
|
149
|
+
@property
|
|
150
|
+
def maker_qty(self) -> int:
|
|
151
|
+
"""Shares filled as the resting order (maker)."""
|
|
152
|
+
return self._maker_qty
|
|
153
|
+
|
|
154
|
+
@property
|
|
155
|
+
def taker_qty(self) -> int:
|
|
156
|
+
"""Shares filled as the incoming order (taker)."""
|
|
157
|
+
return self._taker_qty
|
|
158
|
+
|
|
159
|
+
def buy_vwap(self) -> float | None:
|
|
160
|
+
"""Volume-weighted average buy price, or ``None`` if nothing was bought."""
|
|
161
|
+
return self._buy_notional / self._buy_qty if self._buy_qty else None
|
|
162
|
+
|
|
163
|
+
def sell_vwap(self) -> float | None:
|
|
164
|
+
"""Volume-weighted average sell price, or ``None`` if nothing was sold."""
|
|
165
|
+
return self._sell_notional / self._sell_qty if self._sell_qty else None
|
|
166
|
+
|
|
167
|
+
def avg_price(self) -> float | None:
|
|
168
|
+
"""Volume-weighted average price over all fills, or ``None`` if there were none."""
|
|
169
|
+
total = self.filled_qty
|
|
170
|
+
return (self._buy_notional + self._sell_notional) / total if total else None
|
|
171
|
+
|
|
172
|
+
def total_notional(self) -> float:
|
|
173
|
+
"""Sum of price times quantity over all fills."""
|
|
174
|
+
return self._buy_notional + self._sell_notional
|
|
175
|
+
|
|
176
|
+
def buy_slippage(self) -> float | None:
|
|
177
|
+
"""Buy VWAP minus qty-weighted arrival mid. Positive = paid up (cost)."""
|
|
178
|
+
q = self._buy_arr_qty
|
|
179
|
+
return (self._buy_arr_notional - self._buy_arr_mid_notional) / q if q else None
|
|
180
|
+
|
|
181
|
+
def sell_slippage(self) -> float | None:
|
|
182
|
+
"""Qty-weighted arrival mid minus sell VWAP. Positive = sold below arrival (cost)."""
|
|
183
|
+
q = self._sell_arr_qty
|
|
184
|
+
return (self._sell_arr_mid_notional - self._sell_arr_notional) / q if q else None
|
|
185
|
+
|
|
186
|
+
def spread_capture_per_share(self) -> float | None:
|
|
187
|
+
"""Average distance from the pre-trade mid earned per maker share (positive = earned)."""
|
|
188
|
+
q = self._maker_spread_qty
|
|
189
|
+
return self._maker_spread_total / q if q else None
|
|
190
|
+
|
|
191
|
+
def fill_ratio(self) -> float | None:
|
|
192
|
+
"""Filled quantity / submitted quantity."""
|
|
193
|
+
return self.filled_qty / self._submitted_qty if self._submitted_qty else None
|
|
194
|
+
|
|
195
|
+
def participation_rate(self) -> float | None:
|
|
196
|
+
"""This strategy's share of total market volume."""
|
|
197
|
+
return self.filled_qty / self.market_volume if self.market_volume else None
|
|
198
|
+
|
|
199
|
+
def summary(self) -> dict[str, float | int | None]:
|
|
200
|
+
"""All metrics as a flat dict."""
|
|
201
|
+
return {
|
|
202
|
+
"filled_qty": self.filled_qty,
|
|
203
|
+
"buy_qty": self._buy_qty,
|
|
204
|
+
"sell_qty": self._sell_qty,
|
|
205
|
+
"maker_qty": self._maker_qty,
|
|
206
|
+
"taker_qty": self._taker_qty,
|
|
207
|
+
"total_notional": self.total_notional(),
|
|
208
|
+
"avg_price": self.avg_price(),
|
|
209
|
+
"buy_vwap": self.buy_vwap(),
|
|
210
|
+
"sell_vwap": self.sell_vwap(),
|
|
211
|
+
"buy_slippage_vs_arrival": self.buy_slippage(),
|
|
212
|
+
"sell_slippage_vs_arrival": self.sell_slippage(),
|
|
213
|
+
"spread_capture_per_share": self.spread_capture_per_share(),
|
|
214
|
+
"fill_ratio": self.fill_ratio(),
|
|
215
|
+
"market_volume": self.market_volume,
|
|
216
|
+
"participation_rate": self.participation_rate(),
|
|
217
|
+
}
|
microbook/sim/metrics.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Order-book state metrics."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from microbook import LimitOrderBook
|
|
6
|
+
|
|
7
|
+
__all__ = ["imbalance"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def imbalance(lob: LimitOrderBook, levels: int = 3) -> float | None:
|
|
11
|
+
"""Depth imbalance over the top ``levels``: (bid qty - ask qty) / total, in [-1, 1].
|
|
12
|
+
|
|
13
|
+
Positive means more resting size on the bid (buying pressure); ``None`` when
|
|
14
|
+
both sides are empty.
|
|
15
|
+
"""
|
|
16
|
+
d = lob.depth(levels=levels)
|
|
17
|
+
bids = sum(q for _, q in d["bids"])
|
|
18
|
+
asks = sum(q for _, q in d["asks"])
|
|
19
|
+
total = bids + asks
|
|
20
|
+
return None if total == 0 else (bids - asks) / total
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Pre-generated (open-loop) order flow.
|
|
2
|
+
|
|
3
|
+
[`PoissonOrderFlow`][microbook.sim.PoissonOrderFlow] produces a fixed stream of
|
|
4
|
+
orders around a *constant* reference price. Because it never reacts to the book,
|
|
5
|
+
prices cannot move; it is useful for controlled matching/attribution tests. For a
|
|
6
|
+
market with price discovery and adverse selection use the closed-loop agents
|
|
7
|
+
assembled by [`build_market()`][microbook.sim.build_market].
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import random
|
|
13
|
+
from collections.abc import Iterator
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
|
|
16
|
+
from microbook import Order, Side
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class FlowConfig:
|
|
21
|
+
"""Parameters of [`PoissonOrderFlow`][microbook.sim.PoissonOrderFlow]."""
|
|
22
|
+
|
|
23
|
+
seed: int = 7
|
|
24
|
+
"""Seed of the order stream."""
|
|
25
|
+
intensity_per_100: float = 20.0
|
|
26
|
+
"""Average orders per 100 time units (at most one order per unit)."""
|
|
27
|
+
min_qty: int = 1
|
|
28
|
+
"""Smallest order size (sizes are uniform)."""
|
|
29
|
+
max_qty: int = 10
|
|
30
|
+
"""Largest order size."""
|
|
31
|
+
tick: float = 1.0
|
|
32
|
+
"""Price step between placement levels."""
|
|
33
|
+
max_ticks_away: int = 5
|
|
34
|
+
"""Limit prices are 1 to this many `tick`s from the reference mid."""
|
|
35
|
+
p_market: float = 0.05
|
|
36
|
+
"""Probability that an order is a market order."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class PoissonOrderFlow:
|
|
40
|
+
"""Bernoulli-thinned arrivals on the integer clock (a discrete-time
|
|
41
|
+
approximation of a Poisson process: each unit holds at most one order)."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, cfg: FlowConfig) -> None:
|
|
44
|
+
self.cfg = cfg
|
|
45
|
+
self.rng = random.Random(cfg.seed)
|
|
46
|
+
self._oid = 0
|
|
47
|
+
|
|
48
|
+
def _next_id(self) -> str:
|
|
49
|
+
self._oid += 1
|
|
50
|
+
return f"o{self._oid:06d}"
|
|
51
|
+
|
|
52
|
+
def iter_orders(self, *, start: int, end: int, ref_mid: float) -> Iterator[tuple[int, Order]]:
|
|
53
|
+
"""Yield ``(time, order)`` for each arrival in ``[start, end]``.
|
|
54
|
+
|
|
55
|
+
Limit prices are 1 to ``max_ticks_away`` ticks from ``ref_mid``.
|
|
56
|
+
"""
|
|
57
|
+
p = min(1.0, self.cfg.intensity_per_100 / 100.0)
|
|
58
|
+
rng = self.rng
|
|
59
|
+
for t in range(start, end + 1):
|
|
60
|
+
if rng.random() > p:
|
|
61
|
+
continue
|
|
62
|
+
side = Side.BUY if rng.random() < 0.5 else Side.SELL
|
|
63
|
+
qty = rng.randint(self.cfg.min_qty, self.cfg.max_qty)
|
|
64
|
+
if rng.random() < self.cfg.p_market:
|
|
65
|
+
yield t, Order.market(self._next_id(), side, qty, ts=t)
|
|
66
|
+
continue
|
|
67
|
+
ticks = rng.randint(1, self.cfg.max_ticks_away)
|
|
68
|
+
offset = ticks * self.cfg.tick
|
|
69
|
+
price = ref_mid - offset if side is Side.BUY else ref_mid + offset
|
|
70
|
+
yield t, Order.limit(self._next_id(), side, float(price), qty, ts=t)
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Position, cash and profit and loss of one participant."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
|
|
7
|
+
from microbook import LimitOrderBook, Side
|
|
8
|
+
from microbook.types import Fill
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class Portfolio:
|
|
13
|
+
"""Single-asset position and PnL accounting (average-cost method).
|
|
14
|
+
|
|
15
|
+
Fees are charged per share and are *negative* for rebates, e.g. a typical
|
|
16
|
+
maker/taker schedule is ``maker_fee=-0.002, taker_fee=0.003``.
|
|
17
|
+
|
|
18
|
+
Identity (checked by the test-suite for arbitrary fill sequences)::
|
|
19
|
+
|
|
20
|
+
total_pnl(mark) == cash - initial_cash + position * mark
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
cash: float = 0.0
|
|
24
|
+
"""Cash balance."""
|
|
25
|
+
position: int = 0
|
|
26
|
+
"""Signed position, in shares."""
|
|
27
|
+
avg_cost: float = 0.0
|
|
28
|
+
"""Average entry price of the open position."""
|
|
29
|
+
realized_pnl: float = 0.0
|
|
30
|
+
"""Realized PnL, gross of fees."""
|
|
31
|
+
fees_paid: float = 0.0
|
|
32
|
+
"""Fees paid, net of rebates."""
|
|
33
|
+
maker_fee: float = 0.0
|
|
34
|
+
"""Fee per share on maker fills; negative for a rebate."""
|
|
35
|
+
taker_fee: float = 0.0
|
|
36
|
+
"""Fee per share on taker fills."""
|
|
37
|
+
volume: int = 0
|
|
38
|
+
"""Shares traded."""
|
|
39
|
+
initial_cash: float = field(default=0.0, init=False)
|
|
40
|
+
"""Cash at construction: the baseline of total PnL."""
|
|
41
|
+
|
|
42
|
+
def __post_init__(self) -> None:
|
|
43
|
+
self.initial_cash = self.cash
|
|
44
|
+
|
|
45
|
+
def on_fill(self, fill: Fill, my_order_id: str | None, my_side: Side, *, is_maker: bool = False) -> None:
|
|
46
|
+
"""Apply a fill of one of *my* orders. ``my_side`` is my order's side;
|
|
47
|
+
``is_maker`` selects the maker or taker fee."""
|
|
48
|
+
qty, px = fill.qty, fill.price
|
|
49
|
+
signed = qty if my_side is Side.BUY else -qty
|
|
50
|
+
pos = self.position
|
|
51
|
+
new_pos = pos + signed
|
|
52
|
+
|
|
53
|
+
self.cash -= signed * px
|
|
54
|
+
if pos == 0 or (pos > 0) == (signed > 0):
|
|
55
|
+
# opening or adding: blend the average cost
|
|
56
|
+
self.avg_cost = (self.avg_cost * abs(pos) + px * qty) / abs(new_pos)
|
|
57
|
+
else:
|
|
58
|
+
# reducing, closing or flipping: realize PnL on the closed quantity
|
|
59
|
+
closed = min(qty, abs(pos))
|
|
60
|
+
self.realized_pnl += closed * (px - self.avg_cost) * (1 if pos > 0 else -1)
|
|
61
|
+
if new_pos == 0:
|
|
62
|
+
self.avg_cost = 0.0
|
|
63
|
+
elif (new_pos > 0) != (pos > 0):
|
|
64
|
+
self.avg_cost = px # flipped: the residual was opened at px
|
|
65
|
+
|
|
66
|
+
self.position = new_pos
|
|
67
|
+
fee = (self.maker_fee if is_maker else self.taker_fee) * qty
|
|
68
|
+
self.cash -= fee
|
|
69
|
+
self.fees_paid += fee
|
|
70
|
+
self.volume += qty
|
|
71
|
+
|
|
72
|
+
def unrealized_pnl(self, mark: float) -> float:
|
|
73
|
+
"""PnL of the open position marked at ``mark``, against its average cost."""
|
|
74
|
+
return (mark - self.avg_cost) * self.position
|
|
75
|
+
|
|
76
|
+
def total_pnl(self, mark: float) -> float:
|
|
77
|
+
"""Realized + unrealized PnL, net of fees, marking the position at ``mark``."""
|
|
78
|
+
return self.realized_pnl + self.unrealized_pnl(mark) - self.fees_paid
|
|
79
|
+
|
|
80
|
+
def mark_to_market(self, lob: LimitOrderBook) -> float | None:
|
|
81
|
+
"""Total PnL marked at the book's midprice (``None`` if the book is one-sided)."""
|
|
82
|
+
mid = lob.midprice()
|
|
83
|
+
return None if mid is None else self.total_pnl(mid)
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Ready-made market environments for experiments."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from dataclasses import dataclass, field, replace
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from microbook import LimitOrderBook, STPMode
|
|
10
|
+
from microbook.stylized import MetaorderRecord
|
|
11
|
+
|
|
12
|
+
from .agents import (
|
|
13
|
+
FundamentalValue,
|
|
14
|
+
HawkesConfig,
|
|
15
|
+
InformedConfig,
|
|
16
|
+
InformedTrader,
|
|
17
|
+
MetaorderConfig,
|
|
18
|
+
MetaorderTrader,
|
|
19
|
+
NoiseConfig,
|
|
20
|
+
NoiseTrader,
|
|
21
|
+
)
|
|
22
|
+
from .simulator import MarketSimulator
|
|
23
|
+
from .strategy import Strategy
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class MarketConfig:
|
|
28
|
+
"""A noise + informed-flow market around a latent random-walk fundamental.
|
|
29
|
+
|
|
30
|
+
The defaults are the simple v0.2 market (Poisson flow, fixed-size informed
|
|
31
|
+
trades). [`realistic()`][microbook.sim.MarketConfig.realistic] returns the calibrated preset that reproduces
|
|
32
|
+
the stylized facts of real markets (see ``examples/stylized_facts.py``).
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
seed: int = 0
|
|
36
|
+
"""Seed of the fundamental path and of every background agent's random stream."""
|
|
37
|
+
tick_size: float = 0.01
|
|
38
|
+
"""Tick size of the book."""
|
|
39
|
+
start_price: float = 100.0
|
|
40
|
+
"""Initial fundamental value."""
|
|
41
|
+
fundamental_vol: float = 0.005
|
|
42
|
+
"""Standard deviation of the fundamental's change per step, in price units (on average, with stochastic
|
|
43
|
+
volatility)."""
|
|
44
|
+
jump_rate: float = 0.0
|
|
45
|
+
"""Probability of a fundamental jump per step."""
|
|
46
|
+
jump_size: float = 0.0
|
|
47
|
+
"""Size of each jump, up or down with equal probability, in price units."""
|
|
48
|
+
vol_of_vol: float = 0.0
|
|
49
|
+
"""Volatility of log-volatility. Above 0, the fundamental's volatility is stochastic."""
|
|
50
|
+
vol_persistence: float = 0.999
|
|
51
|
+
"""Per-step persistence of log-volatility (its AR(1) coefficient)."""
|
|
52
|
+
noise: NoiseConfig = field(default_factory=NoiseConfig)
|
|
53
|
+
"""The noise-trader population."""
|
|
54
|
+
informed: InformedConfig | None = field(default_factory=InformedConfig)
|
|
55
|
+
"""The informed trader; `None` for none."""
|
|
56
|
+
metaorders: MetaorderConfig | None = None
|
|
57
|
+
"""Institutional metaorder flow; `None` for none."""
|
|
58
|
+
snapshot_every: int = 10
|
|
59
|
+
"""Time between `SNAPSHOT` events, which sample the book and PnL and call every strategy's `on_tick`."""
|
|
60
|
+
record_snapshots: bool = False
|
|
61
|
+
"""Keep an L2 snapshot for every `SNAPSHOT` (memory-heavy on long runs)."""
|
|
62
|
+
|
|
63
|
+
@classmethod
|
|
64
|
+
def realistic(cls, seed: int = 0, **overrides: Any) -> MarketConfig:
|
|
65
|
+
"""Calibrated market with the stylized facts of real markets.
|
|
66
|
+
|
|
67
|
+
Compared with the defaults it adds stochastic volatility in the
|
|
68
|
+
fundamental, self-exciting (Hawkes) noise market orders, metaorder
|
|
69
|
+
splitting, and arbitrage capital that scales with the mispricing. That
|
|
70
|
+
last change removes the strong short-horizon momentum of the simple
|
|
71
|
+
market (lag-1 autocorrelation of 100-step returns ~0.5 -> ~0).
|
|
72
|
+
|
|
73
|
+
Metaorders are split into many small children (2 shares, one per step),
|
|
74
|
+
so one metaorder spans many trades: that is what gives order signs
|
|
75
|
+
their long memory and lets a metaorder move the price faster than
|
|
76
|
+
arbitrage pulls it back.
|
|
77
|
+
|
|
78
|
+
Calibration on seeds 1-8, 200k steps each (``examples/stylized_facts.py``):
|
|
79
|
+
Hill tail index ~2.7, excess kurtosis ~40 / 4 / 1.6 at 10 / 100 /
|
|
80
|
+
1000-step horizons, |return| autocorrelation decaying over ~1000
|
|
81
|
+
steps, order-sign autocorrelation ~ lag^-0.5, and metaorder impact
|
|
82
|
+
~ 0.5 sigma sqrt(Q/V). Checked on held-out seeds 11-18.
|
|
83
|
+
"""
|
|
84
|
+
base = cls(
|
|
85
|
+
seed=seed,
|
|
86
|
+
vol_of_vol=0.02,
|
|
87
|
+
vol_persistence=0.999,
|
|
88
|
+
noise=replace(NoiseConfig(), market_rate=0.03, cancel_prob=0.03, market_hawkes=HawkesConfig(branching=0.8)),
|
|
89
|
+
informed=InformedConfig(rate=0.3, qty=2, qty_per_tick=20),
|
|
90
|
+
metaorders=MetaorderConfig(rate=0.03, size_alpha=1.4, child_qty=2, child_rate=1.0),
|
|
91
|
+
)
|
|
92
|
+
return replace(base, **overrides)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@dataclass
|
|
96
|
+
class Market:
|
|
97
|
+
"""A built market: the simulator, the fundamental value and the background agents' names."""
|
|
98
|
+
|
|
99
|
+
sim: MarketSimulator
|
|
100
|
+
"""The simulator, holding the background agents and your strategies."""
|
|
101
|
+
fundamental: FundamentalValue
|
|
102
|
+
"""The latent value the agents trade around."""
|
|
103
|
+
background: list[str]
|
|
104
|
+
"""Names of the background agents."""
|
|
105
|
+
|
|
106
|
+
def run(self, until: int) -> MarketSimulator:
|
|
107
|
+
"""Run the simulation up to time ``until`` and return the simulator."""
|
|
108
|
+
self.sim.run(until)
|
|
109
|
+
return self.sim
|
|
110
|
+
|
|
111
|
+
@property
|
|
112
|
+
def metaorders(self) -> list[MetaorderRecord]:
|
|
113
|
+
"""Completed background metaorders (empty unless ``MarketConfig.metaorders`` is set)."""
|
|
114
|
+
out: list[MetaorderRecord] = []
|
|
115
|
+
for s in self.sim.strategies:
|
|
116
|
+
if isinstance(s, MetaorderTrader) and s.name in self.background:
|
|
117
|
+
out.extend(s.completed)
|
|
118
|
+
return out
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def build_market(cfg: MarketConfig, strategies: Sequence[Strategy] = (), *, horizon: int) -> Market:
|
|
122
|
+
"""Assemble a simulator with background agents plus ``strategies``.
|
|
123
|
+
|
|
124
|
+
The fundamental path and the agents' arrival streams depend only on
|
|
125
|
+
``cfg.seed``, so runs with different ``strategies`` see the same exogenous
|
|
126
|
+
flow (common random numbers) and can be compared fairly.
|
|
127
|
+
"""
|
|
128
|
+
fv = FundamentalValue(
|
|
129
|
+
cfg.start_price,
|
|
130
|
+
cfg.fundamental_vol,
|
|
131
|
+
jump_rate=cfg.jump_rate,
|
|
132
|
+
jump_size=cfg.jump_size,
|
|
133
|
+
vol_of_vol=cfg.vol_of_vol,
|
|
134
|
+
vol_persistence=cfg.vol_persistence,
|
|
135
|
+
seed=cfg.seed,
|
|
136
|
+
)
|
|
137
|
+
background: list[Strategy] = [NoiseTrader(cfg.noise, fv, seed=cfg.seed)]
|
|
138
|
+
if cfg.informed is not None:
|
|
139
|
+
background.append(InformedTrader(cfg.informed, fv, seed=cfg.seed))
|
|
140
|
+
if cfg.metaorders is not None:
|
|
141
|
+
background.append(MetaorderTrader(cfg.metaorders, seed=cfg.seed))
|
|
142
|
+
lob = LimitOrderBook(cfg.tick_size, stp=STPMode.CANCEL_RESTING)
|
|
143
|
+
sim = MarketSimulator(lob, [*background, *strategies], record_snapshots=cfg.record_snapshots)
|
|
144
|
+
sim.schedule_snapshots(0, horizon, cfg.snapshot_every)
|
|
145
|
+
return Market(sim, fv, [s.name for s in background])
|