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.
@@ -0,0 +1,495 @@
1
+ """Closed-loop background market participants.
2
+
3
+ Together these produce a market with genuine price discovery:
4
+
5
+ * [`FundamentalValue`][microbook.sim.FundamentalValue] — a latent "true" price (Gaussian random walk with
6
+ optional Poisson jumps). No book participant observes it except informed traders.
7
+ * [`NoiseTrader`][microbook.sim.NoiseTrader] — a zero-intelligence population in the spirit of
8
+ Smith, Farmer, Gillemot & Krishnamurthy (2003): Poisson limit-order arrivals
9
+ placed relative to the *current* opposite touch, Poisson market orders, and
10
+ proportional random cancellation. It supplies most of the liquidity and
11
+ random-walks the price on its own.
12
+ * [`InformedTrader`][microbook.sim.InformedTrader] — trades with immediate-or-cancel orders when the
13
+ book is mispriced relative to the fundamental by more than a threshold. It
14
+ drags the book toward the fundamental and is the source of **adverse
15
+ selection** for liquidity providers.
16
+ * [`MetaorderTrader`][microbook.sim.MetaorderTrader] — uninformed institutions splitting large orders
17
+ (Pareto-distributed sizes) into child market orders. Order splitting is the
18
+ mechanism behind the long memory of trade signs (Lillo, Mike & Farmer 2005)
19
+ and produces the metaorders used to measure price impact.
20
+ * [`HawkesProcess`][microbook.sim.HawkesProcess] — optional self-exciting arrivals for the noise
21
+ traders' market orders, which cluster activity and hence volatility.
22
+
23
+ Every agent draws from private RNG streams seeded from a run seed, and arrival
24
+ streams are separated from state-dependent draws, so different strategies can
25
+ be compared against *identical* exogenous order arrivals (common random numbers).
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import math
31
+ import random
32
+ from dataclasses import dataclass
33
+
34
+ from microbook import LimitOrderBook, Order, Side, TimeInForce
35
+ from microbook.stylized import MetaorderRecord
36
+ from microbook.types import Fill
37
+
38
+ from .strategy import Action, Strategy
39
+
40
+
41
+ def _poisson(rng: random.Random, lam: float) -> int:
42
+ """Poisson(lam) sample (Knuth's method; fine for the small rates used here)."""
43
+ if lam <= 0:
44
+ return 0
45
+ if lam > 30: # normal approximation keeps large rates O(1)
46
+ return max(0, round(rng.gauss(lam, math.sqrt(lam))))
47
+ limit = math.exp(-lam)
48
+ k, p = 0, rng.random()
49
+ while p > limit:
50
+ k += 1
51
+ p *= rng.random()
52
+ return k
53
+
54
+
55
+ class FundamentalValue:
56
+ """Latent value process on the integer clock.
57
+
58
+ ``V[t] = V[t-1] + sigma[t] * Z + J``, where ``Z ~ N(0, 1)`` and
59
+ ``J = +/-jump_size`` with probability ``jump_rate`` per step.
60
+
61
+ With ``vol_of_vol > 0`` the volatility is stochastic: ``log sigma`` follows
62
+ a mean-reverting AR(1) around ``log vol_per_step`` with per-step
63
+ persistence ``vol_persistence``, normalized so the *average variance*
64
+ stays ``vol_per_step ** 2``. This produces volatility clustering and fat
65
+ tails at every horizon, as news arrival does in real markets.
66
+
67
+ The path is generated lazily but deterministically: the value at ``t``
68
+ does not depend on query order.
69
+ """
70
+
71
+ def __init__(
72
+ self,
73
+ start: float,
74
+ vol_per_step: float,
75
+ *,
76
+ jump_rate: float = 0.0,
77
+ jump_size: float = 0.0,
78
+ vol_of_vol: float = 0.0,
79
+ vol_persistence: float = 0.999,
80
+ seed: int = 0,
81
+ ) -> None:
82
+ if start <= 0 or vol_per_step < 0 or not 0 <= jump_rate <= 1:
83
+ raise ValueError("invalid fundamental parameters")
84
+ if vol_of_vol < 0 or not 0 <= vol_persistence < 1:
85
+ raise ValueError("invalid stochastic-volatility parameters")
86
+ self.vol = vol_per_step
87
+ self.jump_rate = jump_rate
88
+ self.jump_size = jump_size
89
+ self.vol_of_vol = vol_of_vol
90
+ self.vol_persistence = vol_persistence
91
+ self._rng = random.Random(f"{seed}/fundamental")
92
+ self._path = [float(start)]
93
+ # stationary sd of log-vol; shift the mean so E[sigma^2] = vol^2
94
+ self._h_sd = vol_of_vol / math.sqrt(1 - vol_persistence**2) if vol_of_vol else 0.0
95
+ self._h_mean = math.log(vol_per_step) - self._h_sd**2 if vol_per_step > 0 else 0.0
96
+ self._h = self._h_mean + self._h_sd * self._rng.gauss(0.0, 1.0) if vol_of_vol else self._h_mean
97
+
98
+ def at(self, t: int) -> float:
99
+ """Fundamental value at time ``t``, generated on first request and then fixed."""
100
+ if t < 0:
101
+ raise ValueError("t must be >= 0")
102
+ path, rng = self._path, self._rng
103
+ while len(path) <= t:
104
+ if self.vol_of_vol:
105
+ self._h = (
106
+ self._h_mean
107
+ + self.vol_persistence * (self._h - self._h_mean)
108
+ + self.vol_of_vol * rng.gauss(0.0, 1.0)
109
+ )
110
+ sigma = math.exp(self._h)
111
+ else:
112
+ sigma = self.vol
113
+ v = path[-1] + rng.gauss(0.0, sigma)
114
+ if self.jump_rate and rng.random() < self.jump_rate:
115
+ v += self.jump_size if rng.random() < 0.5 else -self.jump_size
116
+ path.append(max(v, 1e-9))
117
+ return path[t]
118
+
119
+
120
+ @dataclass(frozen=True)
121
+ class HawkesConfig:
122
+ """Self-excitation of noise market orders.
123
+
124
+ ``branching`` is the expected number of extra orders each order triggers
125
+ (must be < 1). The kernel is an equal-weight mixture of exponentials with
126
+ the given ``timescales`` (in steps), a standard approximation of the slowly
127
+ decaying kernels estimated on real data. The *mean* arrival rate is kept
128
+ equal to ``NoiseConfig.market_rate``, so turning excitation on changes how
129
+ activity clusters, not how much there is.
130
+ """
131
+
132
+ branching: float = 0.8
133
+ """Expected number of extra orders each order triggers; must be in [0, 1)."""
134
+ timescales: tuple[float, ...] = (10.0, 100.0, 1_000.0)
135
+ """Decay times of the kernel's exponential components, in steps."""
136
+
137
+
138
+ class HawkesProcess:
139
+ """Discrete-time Hawkes process: counts per step ``N_t ~ Poisson(lambda_t)`` with
140
+ ``lambda_t = mu + sum_k sum_{s<t} a_k * d_k^(t-s) * N_s``.
141
+
142
+ Each kernel component ``k`` has decay ``d_k = exp(-1/tau_k)`` and weight
143
+ ``a_k = (branching / K) * (1 - d_k) / d_k`` so that the total expected
144
+ offspring per event equals ``branching``.
145
+ """
146
+
147
+ def __init__(self, mean_rate: float, cfg: HawkesConfig, rng: random.Random) -> None:
148
+ if not 0 <= cfg.branching < 1:
149
+ raise ValueError("branching ratio must be in [0, 1)")
150
+ if not cfg.timescales or min(cfg.timescales) <= 0:
151
+ raise ValueError("timescales must be positive")
152
+ self.mu = mean_rate * (1 - cfg.branching)
153
+ self._rng = rng
154
+ self._d = [math.exp(-1.0 / tau) for tau in cfg.timescales]
155
+ w = cfg.branching / len(cfg.timescales)
156
+ self._a = [w * (1 - d) / d for d in self._d]
157
+ self._e = [0.0] * len(self._d)
158
+
159
+ @property
160
+ def intensity(self) -> float:
161
+ """Expected number of arrivals in the next step."""
162
+ return self.mu + sum(self._e)
163
+
164
+ def step(self) -> int:
165
+ """Draw this step's number of arrivals and update the self-excitation."""
166
+ n = _poisson(self._rng, self.intensity)
167
+ self._e = [(e + a * n) * d for e, a, d in zip(self._e, self._a, self._d, strict=True)]
168
+ return n
169
+
170
+
171
+ @dataclass
172
+ class NoiseConfig:
173
+ """Parameters of the [`NoiseTrader`][microbook.sim.NoiseTrader] population."""
174
+
175
+ limit_rate: float = 2.0
176
+ """Expected limit orders per time step."""
177
+ market_rate: float = 0.15
178
+ """Expected market orders per time step (the mean rate when `market_hawkes` is set)."""
179
+ cancel_prob: float = 0.02
180
+ """Per-step probability that each resting noise order is cancelled."""
181
+ min_qty: int = 1
182
+ """Smallest order size."""
183
+ max_qty: int = 10
184
+ """Largest order size."""
185
+ mean_offset_ticks: float = 4.0
186
+ """Mean distance of a limit price from the opposite touch, in ticks (1 + a geometric draw)."""
187
+ initial_levels: int = 10
188
+ """Price levels per side in the initial book, around the fundamental."""
189
+ initial_qty: int = 15
190
+ """Size of each initial order."""
191
+ market_hawkes: HawkesConfig | None = None
192
+ """Self-exciting market orders; `None` gives Poisson arrivals at `market_rate`."""
193
+
194
+
195
+ class _Pool:
196
+ """Live order ids with O(1) add, remove and uniform random pick."""
197
+
198
+ __slots__ = ("ids", "pos")
199
+
200
+ def __init__(self) -> None:
201
+ self.ids: list[str] = []
202
+ self.pos: dict[str, int] = {}
203
+
204
+ def __len__(self) -> int:
205
+ return len(self.ids)
206
+
207
+ def __contains__(self, oid: object) -> bool:
208
+ return oid in self.pos
209
+
210
+ def add(self, oid: str) -> None:
211
+ self.pos[oid] = len(self.ids)
212
+ self.ids.append(oid)
213
+
214
+ def drop(self, oid: str) -> None:
215
+ i = self.pos.pop(oid)
216
+ last = self.ids.pop()
217
+ if last != oid:
218
+ self.ids[i] = last
219
+ self.pos[last] = i
220
+
221
+ def cancel_some(self, rng: random.Random, prob: float, now: int, out: list[Action]) -> None:
222
+ """Cancel each live order independently with probability ``prob``.
223
+
224
+ An order picked here may still be in flight; the cancel is sent anyway
225
+ and arrives after it (FIFO), so nothing is ever orphaned.
226
+ """
227
+ n = min(len(self.ids), _poisson(rng, prob * len(self.ids)))
228
+ for _ in range(n):
229
+ oid = self.ids[int(rng.random() * len(self.ids))]
230
+ self.drop(oid)
231
+ out.append(Action.cancel(oid, now))
232
+
233
+
234
+ class NoiseTrader(Strategy):
235
+ """Zero-intelligence liquidity population (see module docstring).
236
+
237
+ Its orders represent many anonymous traders, so each carries a unique
238
+ ``owner`` and the population never triggers self-trade prevention against
239
+ itself. ``portfolio`` holds the *aggregate* position of the population.
240
+ """
241
+
242
+ def __init__(
243
+ self,
244
+ cfg: NoiseConfig,
245
+ fundamental: FundamentalValue,
246
+ *,
247
+ name: str = "noise",
248
+ seed: int = 0,
249
+ ) -> None:
250
+ super().__init__(name)
251
+ self.cfg = cfg
252
+ self.fundamental = fundamental
253
+ self._flow = random.Random(f"{seed}/{name}/flow") # state-independent draws
254
+ self._cancel = random.Random(f"{seed}/{name}/cancel") # state-dependent draws
255
+ self._hawkes = (
256
+ HawkesProcess(cfg.market_rate, cfg.market_hawkes, random.Random(f"{seed}/{name}/hawkes"))
257
+ if cfg.market_hawkes is not None
258
+ else None
259
+ )
260
+ self._live = _Pool() # resting (or in-flight) order ids
261
+ self._last_mid: float | None = None
262
+ p = 1.0 / max(cfg.mean_offset_ticks, 1.0) # geometric success prob, mean 1/p
263
+ self._log_q = math.log(1.0 - p) if p < 1.0 else None
264
+
265
+ # --- helpers ------------------------------------------------------------
266
+
267
+ def _offset(self) -> int:
268
+ """Ticks behind the opposite touch: 1 + Geometric, mean ~ ``mean_offset_ticks``."""
269
+ if self._log_q is None:
270
+ return 1
271
+ u = 1.0 - self._flow.random() # (0, 1]
272
+ return 1 + int(math.log(u) / self._log_q)
273
+
274
+ def _limit(self, oid: str, side: Side, px: float, qty: int, now: int) -> Action:
275
+ self._live.add(oid)
276
+ return Action.submit(Order.limit(oid, side, px, qty, ts=now, owner=f"{self.name}/{oid}"), now)
277
+
278
+ # --- hooks ----------------------------------------------------------------
279
+
280
+ def on_start(self, now: int, lob: LimitOrderBook) -> list[Action]:
281
+ """Build the initial book: ``initial_levels`` levels per side around the fundamental."""
282
+ v = self.fundamental.at(now)
283
+ center = lob.to_ticks(lob.round_price(v, Side.BUY))
284
+ actions: list[Action] = []
285
+ for k in range(1, self.cfg.initial_levels + 1):
286
+ actions.append(
287
+ self._limit(self.next_order_id("b"), Side.BUY, lob.price_of(center - k + 1), self.cfg.initial_qty, now)
288
+ )
289
+ actions.append(
290
+ self._limit(self.next_order_id("a"), Side.SELL, lob.price_of(center + k), self.cfg.initial_qty, now)
291
+ )
292
+ actions.append(Action.timer(now + 1))
293
+ return actions
294
+
295
+ def on_timer(self, now: int, lob: LimitOrderBook) -> list[Action]:
296
+ """One step of noise flow: new limit orders, market orders and random cancellations."""
297
+ cfg, rng = self.cfg, self._flow
298
+ actions: list[Action] = []
299
+
300
+ bb, ba = lob.best_bid(), lob.best_ask()
301
+ mid = lob.midprice()
302
+ if mid is not None:
303
+ self._last_mid = mid
304
+ ref = self._last_mid if self._last_mid is not None else self.fundamental.at(now)
305
+ ref_t = lob.to_ticks(lob.round_price(ref, Side.BUY))
306
+ bb_t = lob.to_ticks(bb) if bb is not None else ref_t
307
+ ba_t = lob.to_ticks(ba) if ba is not None else ref_t + 1
308
+
309
+ for _ in range(_poisson(rng, cfg.limit_rate)):
310
+ side = Side.BUY if rng.random() < 0.5 else Side.SELL
311
+ qty = rng.randint(cfg.min_qty, cfg.max_qty)
312
+ off = self._offset()
313
+ tick = ba_t - off if side is Side.BUY else bb_t + off
314
+ if tick >= 1:
315
+ actions.append(self._limit(self.next_order_id(), side, lob.price_of(tick), qty, now))
316
+
317
+ n_market = self._hawkes.step() if self._hawkes is not None else _poisson(rng, cfg.market_rate)
318
+ for _ in range(n_market):
319
+ side = Side.BUY if rng.random() < 0.5 else Side.SELL
320
+ qty = rng.randint(cfg.min_qty, cfg.max_qty)
321
+ oid = self.next_order_id("m")
322
+ actions.append(Action.submit(Order.market(oid, side, qty, ts=now, owner=f"{self.name}/{oid}"), now))
323
+
324
+ self._live.cancel_some(self._cancel, cfg.cancel_prob, now, actions)
325
+
326
+ actions.append(Action.timer(now + 1))
327
+ return actions
328
+
329
+ def on_fill(self, now: int, fill: Fill, side: Side, is_maker: bool, lob: LimitOrderBook) -> list[Action]:
330
+ """Stop tracking resting orders that have been filled completely."""
331
+ oid = fill.maker_order_id
332
+ if is_maker and oid in self._live and oid not in lob:
333
+ self._live.drop(oid) # fully filled
334
+ return []
335
+
336
+
337
+ @dataclass
338
+ class InformedConfig:
339
+ """Parameters of [`InformedTrader`][microbook.sim.InformedTrader]."""
340
+
341
+ rate: float = 0.4
342
+ """Expected arrivals per time step."""
343
+ qty: int = 5
344
+ """Base order size."""
345
+ threshold_ticks: float = 1.0
346
+ """Minimum mispricing against the fundamental before trading, in ticks. The trader also keeps this edge on its
347
+ limit price."""
348
+ qty_per_tick: float = 0.0
349
+ """Extra shares per tick of mispricing beyond the threshold (0 = fixed size). Arbitrage capital that scales
350
+ with the opportunity closes large gaps fast."""
351
+ max_qty: int = 1_000
352
+ """Cap on the order size."""
353
+
354
+
355
+ class InformedTrader(Strategy):
356
+ """Trades on the gap between the book and the fundamental value.
357
+
358
+ On each arrival it buys with an IOC limit at ``V - threshold`` if the
359
+ best ask is below that, or sells at ``V + threshold`` if the best bid is
360
+ above it. It never pays more than the fundamental minus its required edge.
361
+ The size is ``qty`` plus ``qty_per_tick`` per tick of mispricing beyond the
362
+ threshold (capped at ``max_qty``).
363
+ """
364
+
365
+ def __init__(
366
+ self,
367
+ cfg: InformedConfig,
368
+ fundamental: FundamentalValue,
369
+ *,
370
+ name: str = "informed",
371
+ seed: int = 0,
372
+ ) -> None:
373
+ super().__init__(name)
374
+ self.cfg = cfg
375
+ self.fundamental = fundamental
376
+ self._rng = random.Random(f"{seed}/{name}/flow")
377
+
378
+ def on_start(self, now: int, lob: LimitOrderBook) -> list[Action]:
379
+ """Start the arrival clock (one wake-up per step)."""
380
+ return [Action.timer(now + 1)]
381
+
382
+ def on_timer(self, now: int, lob: LimitOrderBook) -> list[Action]:
383
+ """On an arrival, trade if the book is mispriced by more than the threshold."""
384
+ actions = [Action.timer(now + 1)]
385
+ if _poisson(self._rng, self.cfg.rate) == 0:
386
+ return actions
387
+ cfg = self.cfg
388
+ v = self.fundamental.at(now)
389
+ edge = cfg.threshold_ticks * lob.tick_size
390
+ bb, ba = lob.best_bid(), lob.best_ask()
391
+ if ba is not None and ba < v - edge:
392
+ side, px = Side.BUY, lob.round_price(v - edge, Side.BUY)
393
+ gap = lob.to_ticks(px) - lob.to_ticks(ba) # ticks of edge beyond the threshold
394
+ elif bb is not None and bb > v + edge:
395
+ side, px = Side.SELL, lob.round_price(v + edge, Side.SELL)
396
+ gap = lob.to_ticks(bb) - lob.to_ticks(px)
397
+ else:
398
+ return actions
399
+ qty = min(cfg.max_qty, cfg.qty + int(cfg.qty_per_tick * gap))
400
+ o = Order.limit(self.next_order_id(), side, px, qty, ts=now, tif=TimeInForce.IOC)
401
+ actions.append(Action.submit(o, now))
402
+ return actions
403
+
404
+
405
+ @dataclass
406
+ class MetaorderConfig:
407
+ """Uninformed institutions splitting large orders into child market orders.
408
+
409
+ Metaorders arrive as a Poisson process. Total sizes follow a Pareto law
410
+ ``P(Q > q) ~ q^-size_alpha`` truncated to ``[min_size, max_size]``; with
411
+ ``1 < size_alpha < 2`` the trade-sign autocorrelation decays as
412
+ ``lag^-(size_alpha - 1)`` (Lillo, Mike & Farmer 2005). Each active metaorder
413
+ sends a child market order of ``child_qty`` shares with probability
414
+ ``child_rate`` per step until it is done.
415
+ """
416
+
417
+ rate: float = 0.01
418
+ """Expected new metaorders per step."""
419
+ size_alpha: float = 1.5
420
+ """Pareto tail exponent of metaorder sizes. Values in (1, 2) give long memory in order signs."""
421
+ min_size: int = 10
422
+ """Smallest metaorder, in shares."""
423
+ max_size: int = 10_000
424
+ """Largest metaorder, in shares."""
425
+ child_qty: int = 5
426
+ """Shares per child market order."""
427
+ child_rate: float = 0.1
428
+ """Probability per step that an active metaorder sends a child order, in (0, 1]."""
429
+
430
+
431
+ @dataclass
432
+ class _Meta:
433
+ side: Side
434
+ qty: int
435
+ remaining: int
436
+ start: int
437
+ owner: str
438
+
439
+
440
+ class MetaorderTrader(Strategy):
441
+ """Background population executing metaorders (see [`MetaorderConfig`][microbook.sim.MetaorderConfig]).
442
+
443
+ Completed metaorders are logged in ``completed`` as
444
+ [`MetaorderRecord`][microbook.stylized.MetaorderRecord] (side, size, start, end), the
445
+ data needed to measure price impact. All draws are state-independent, so
446
+ the flow is identical across strategy variants (common random numbers).
447
+ """
448
+
449
+ def __init__(self, cfg: MetaorderConfig, *, name: str = "meta", seed: int = 0) -> None:
450
+ super().__init__(name)
451
+ if not (cfg.size_alpha > 0 and 0 < cfg.min_size <= cfg.max_size and cfg.child_qty > 0):
452
+ raise ValueError("invalid metaorder parameters")
453
+ if not 0 < cfg.child_rate <= 1:
454
+ raise ValueError("child_rate must be in (0, 1]")
455
+ self.cfg = cfg
456
+ self._rng = random.Random(f"{seed}/{name}/flow")
457
+ self.active: list[_Meta] = []
458
+ self.completed: list[MetaorderRecord] = []
459
+ self._n = 0
460
+
461
+ def draw_size(self) -> int:
462
+ """Inverse-CDF sample of the truncated Pareto size distribution."""
463
+ c = self.cfg
464
+ tail = (c.min_size / c.max_size) ** c.size_alpha
465
+ u = self._rng.random()
466
+ return min(c.max_size, int(c.min_size * (1 - u * (1 - tail)) ** (-1 / c.size_alpha)))
467
+
468
+ def on_start(self, now: int, lob: LimitOrderBook) -> list[Action]:
469
+ """Start the arrival clock (one wake-up per step)."""
470
+ return [Action.timer(now + 1)]
471
+
472
+ def on_timer(self, now: int, lob: LimitOrderBook) -> list[Action]:
473
+ """Start new metaorders, then send one child order for each active metaorder with probability ``child_rate``."""
474
+ rng, cfg = self._rng, self.cfg
475
+ for _ in range(_poisson(rng, cfg.rate)):
476
+ side = Side.BUY if rng.random() < 0.5 else Side.SELL
477
+ q = self.draw_size()
478
+ self._n += 1
479
+ self.active.append(_Meta(side, q, q, now, f"{self.name}/{self._n}"))
480
+
481
+ actions: list[Action] = []
482
+ still: list[_Meta] = []
483
+ for m in self.active:
484
+ if m.start < now and rng.random() < cfg.child_rate:
485
+ qty = min(m.remaining, cfg.child_qty)
486
+ m.remaining -= qty
487
+ oid = self.next_order_id()
488
+ actions.append(Action.submit(Order.market(oid, m.side, qty, ts=now, owner=m.owner), now))
489
+ if m.remaining == 0:
490
+ self.completed.append(MetaorderRecord(m.side.sign, m.qty, m.start, now))
491
+ continue
492
+ still.append(m)
493
+ self.active = still
494
+ actions.append(Action.timer(now + 1))
495
+ return actions
@@ -0,0 +1,199 @@
1
+ """Post-trade analytics: book time series, markouts, PnL and inventory statistics."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import statistics
7
+ import warnings
8
+ from bisect import bisect_right
9
+ from collections.abc import Iterable, Sequence
10
+ from dataclasses import dataclass, field
11
+ from itertools import pairwise
12
+ from typing import TYPE_CHECKING, Any
13
+
14
+ from microbook import LimitOrderBook
15
+
16
+ from .execution_metrics import FillRecord
17
+ from .metrics import imbalance
18
+
19
+ if TYPE_CHECKING:
20
+ from .simulator import MarketSimulator
21
+
22
+
23
+ @dataclass
24
+ class TimeSeries:
25
+ """Book state sampled on every SNAPSHOT: midprice, spread and top-3 imbalance."""
26
+
27
+ t: list[int] = field(default_factory=list)
28
+ """Sample times."""
29
+ mid: list[float] = field(default_factory=list)
30
+ """Midprice; NaN while the book is one-sided."""
31
+ spread: list[float] = field(default_factory=list)
32
+ """Best ask minus best bid; NaN while the book is one-sided."""
33
+ imbalance: list[float] = field(default_factory=list)
34
+ """Top-3 depth imbalance in [-1, 1]; NaN for an empty book."""
35
+
36
+ def record(self, now: int, lob: LimitOrderBook) -> None:
37
+ """Append the current mid, spread and top-3 imbalance (NaN where undefined)."""
38
+ self.t.append(now)
39
+ m = lob.midprice()
40
+ self.mid.append(m if m is not None else math.nan)
41
+ s = lob.spread()
42
+ self.spread.append(s if s is not None else math.nan)
43
+ im = imbalance(lob, levels=3)
44
+ self.imbalance.append(im if im is not None else math.nan)
45
+
46
+ def as_dict(self) -> dict[str, list[Any]]:
47
+ """The recorded series as lists keyed by field name."""
48
+ return {"t": self.t, "mid": self.mid, "spread": self.spread, "imbalance": self.imbalance}
49
+
50
+ @property
51
+ def spr(self) -> list[float]:
52
+ """Deprecated alias of [`spread`][microbook.sim.TimeSeries.spread] (removed in 2.0)."""
53
+ warnings.warn("TimeSeries.spr is deprecated; use TimeSeries.spread", DeprecationWarning, stacklevel=2)
54
+ return self.spread
55
+
56
+ @property
57
+ def imb(self) -> list[float]:
58
+ """Deprecated alias of [`imbalance`][microbook.sim.TimeSeries.imbalance] (removed in 2.0)."""
59
+ warnings.warn("TimeSeries.imb is deprecated; use TimeSeries.imbalance", DeprecationWarning, stacklevel=2)
60
+ return self.imbalance
61
+
62
+
63
+ def _time_of(entry: tuple[int, float]) -> int:
64
+ return entry[0]
65
+
66
+
67
+ def mid_at(mid_path: Sequence[tuple[int, float]], t: int) -> float | None:
68
+ """Value of a step-function mid path (``SimResult.mid_path``) at the end of time ``t``."""
69
+ i = bisect_right(mid_path, t, key=_time_of) - 1
70
+ if i < 0:
71
+ return None
72
+ m = mid_path[i][1]
73
+ return None if math.isnan(m) else m
74
+
75
+
76
+ def markouts(
77
+ fills: Iterable[FillRecord],
78
+ mid_path: Sequence[tuple[int, float]],
79
+ horizons: Sequence[int] = (1, 10, 100),
80
+ *,
81
+ end_time: int | None = None,
82
+ ) -> dict[int, float | None]:
83
+ """Volume-weighted markout per share at each horizon, from the trader's side.
84
+
85
+ For a fill at price ``p`` and time ``t`` the markout at horizon ``h`` is
86
+ ``side * (mid(t + h) - p)``: positive means the trade was profitable when
87
+ marked ``h`` time units later. For a market maker, the decay of markouts
88
+ with horizon measures **adverse selection**: spread captured at ``h = 0``
89
+ that is given back as the price moves against the fill.
90
+
91
+ Fills whose horizon would extend past ``end_time`` are excluded.
92
+ """
93
+ out: dict[int, float | None] = {}
94
+ fills = list(fills)
95
+ for h in horizons:
96
+ num = 0.0
97
+ qty = 0
98
+ for f in fills:
99
+ if f.time is None or (end_time is not None and f.time + h > end_time):
100
+ continue
101
+ m = mid_at(mid_path, f.time + h)
102
+ if m is None:
103
+ continue
104
+ num += f.side.sign * (m - f.price) * f.qty
105
+ qty += f.qty
106
+ out[h] = num / qty if qty else None
107
+ return out
108
+
109
+
110
+ def max_drawdown(series: Sequence[float]) -> float:
111
+ """Largest peak-to-trough decline (a non-negative number). NaNs are skipped."""
112
+ peak = -math.inf
113
+ mdd = 0.0
114
+ for x in series:
115
+ if math.isnan(x):
116
+ continue
117
+ peak = max(peak, x)
118
+ mdd = max(mdd, peak - x)
119
+ return mdd
120
+
121
+
122
+ def pnl_stats(pnl: Sequence[float]) -> dict[str, float]:
123
+ """Summary of a cumulative PnL path sampled at regular intervals.
124
+
125
+ ``sharpe`` is mean/stdev of per-sample PnL increments scaled by
126
+ sqrt(number of increments): a dimensionless signal-to-noise ratio for the
127
+ whole run (not annualized).
128
+ """
129
+ xs = [x for x in pnl if not math.isnan(x)]
130
+ if not xs:
131
+ return {"final": math.nan, "max_drawdown": math.nan, "pnl_vol": math.nan, "sharpe": math.nan}
132
+ incs = [b - a for a, b in pairwise(xs)]
133
+ vol = statistics.pstdev(incs) if len(incs) > 1 else 0.0
134
+ mean = statistics.fmean(incs) if incs else 0.0
135
+ sharpe = mean / vol * math.sqrt(len(incs)) if vol > 0 else math.nan
136
+ return {"final": xs[-1], "max_drawdown": max_drawdown(xs), "pnl_vol": vol, "sharpe": sharpe}
137
+
138
+
139
+ def inventory_stats(inventory: Sequence[int]) -> dict[str, float]:
140
+ """Mean and maximum absolute inventory, and the final inventory."""
141
+ if not inventory:
142
+ return {"mean_abs_inventory": math.nan, "max_abs_inventory": math.nan, "final_inventory": math.nan}
143
+ return {
144
+ "mean_abs_inventory": statistics.fmean(abs(q) for q in inventory),
145
+ "max_abs_inventory": float(max(abs(q) for q in inventory)),
146
+ "final_inventory": float(inventory[-1]),
147
+ }
148
+
149
+
150
+ def strategy_report(
151
+ sim: MarketSimulator,
152
+ names: Iterable[str] | None = None,
153
+ *,
154
+ horizons: Sequence[int] = (1, 10, 100),
155
+ ) -> dict[str, dict[str, Any]]:
156
+ """One flat dict per strategy combining PnL, inventory, execution and markout metrics."""
157
+ res = sim.result
158
+ end = sim.now
159
+ out: dict[str, dict[str, Any]] = {}
160
+ for name in names if names is not None else [s.name for s in sim.strategies]:
161
+ strat = sim.strategy(name)
162
+ m = sim.exec_metrics[name]
163
+ row: dict[str, Any] = {}
164
+ row.update(pnl_stats(res.pnl_series.get(name, [])))
165
+ row.update(inventory_stats(res.inventory_series.get(name, [])))
166
+ row["fees"] = strat.portfolio.fees_paid
167
+ row["volume"] = m.filled_qty
168
+ row["maker_share"] = m.maker_qty / m.filled_qty if m.filled_qty else math.nan
169
+ row["spread_capture"] = m.spread_capture_per_share()
170
+ for h, v in markouts(m.fills, res.mid_path, horizons, end_time=end).items():
171
+ row[f"markout_{h}"] = v
172
+ row["fill_ratio"] = m.fill_ratio()
173
+ row["participation"] = m.participation_rate()
174
+ out[name] = row
175
+ return out
176
+
177
+
178
+ def format_table(rows: dict[str, dict[str, Any]], columns: Sequence[str] | None = None, *, precision: int = 4) -> str:
179
+ """Render ``{row_name: {col: value}}`` as a fixed-width text table."""
180
+ if not rows:
181
+ return ""
182
+ cols = list(columns) if columns is not None else list(next(iter(rows.values())).keys())
183
+
184
+ def fmt(v: Any) -> str:
185
+ if v is None:
186
+ return "-"
187
+ if isinstance(v, float):
188
+ return "nan" if math.isnan(v) else f"{v:.{precision}f}"
189
+ return str(v)
190
+
191
+ body = [[name, *(fmt(r.get(c)) for c in cols)] for name, r in rows.items()]
192
+ header = ["", *cols]
193
+ widths = [max(len(row[i]) for row in [header, *body]) for i in range(len(header))]
194
+
195
+ def render(cells: list[str]) -> str:
196
+ # first column (row names) left-aligned, values right-aligned
197
+ return " ".join(c.rjust(w) if i else c.ljust(w) for i, (c, w) in enumerate(zip(cells, widths, strict=True)))
198
+
199
+ return "\n".join([render(header), " ".join("-" * w for w in widths), *(render(row) for row in body)])