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,352 @@
1
+ """Strategy interface and the baseline strategies.
2
+
3
+ A strategy never touches the book directly. Its hooks receive a read-only view
4
+ of the book and return [`Action`][microbook.sim.Action] objects; the simulator delivers order
5
+ messages after the strategy's ``latency`` and attributes the resulting fills
6
+ back to it.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass, field
12
+ from typing import Any
13
+
14
+ from microbook import ExecutionReport, LimitOrderBook, Order, OrderStatus, Side
15
+ from microbook.types import Fill
16
+
17
+ from .events import EventType
18
+ from .portfolio import Portfolio
19
+
20
+
21
+ @dataclass
22
+ class Action:
23
+ """A request from a strategy: an order message or a timer."""
24
+
25
+ time: int
26
+ """Decision time. An order message reaches the book `latency` later; a timer fires at this time."""
27
+ etype: EventType
28
+ """`SUBMIT`, `CANCEL`, `MODIFY` or `TIMER`."""
29
+ kwargs: dict[str, Any] = field(default_factory=dict)
30
+ """Event fields of the message (`order`, `order_id` or `modify`), filled in by the constructors."""
31
+
32
+ @classmethod
33
+ def submit(cls, order: Order, time: int) -> Action:
34
+ """Send ``order`` to the book at ``time`` (plus the strategy's latency)."""
35
+ return cls(time, EventType.SUBMIT, {"order": order})
36
+
37
+ @classmethod
38
+ def cancel(cls, order_id: str, time: int) -> Action:
39
+ """Cancel the resting order ``order_id``."""
40
+ return cls(time, EventType.CANCEL, {"order_id": order_id})
41
+
42
+ @classmethod
43
+ def modify(cls, order_id: str, time: int, *, new_price: float | None = None, new_qty: int | None = None) -> Action:
44
+ """Change a resting order's price and/or quantity.
45
+
46
+ See [`LimitOrderBook.modify()`][microbook.LimitOrderBook.modify].
47
+ """
48
+ mod: dict[str, Any] = {}
49
+ if new_price is not None:
50
+ mod["new_price"] = new_price
51
+ if new_qty is not None:
52
+ mod["new_qty"] = new_qty
53
+ return cls(time, EventType.MODIFY, {"order_id": order_id, "modify": mod})
54
+
55
+ @classmethod
56
+ def reduce(cls, order_id: str, time: int, qty: int) -> Action:
57
+ """Partial cancel of ``qty`` shares, resolved when the message reaches the book
58
+ (see [`LimitOrderBook.reduce()`][microbook.LimitOrderBook.reduce]); keeps queue priority."""
59
+ return cls(time, EventType.MODIFY, {"order_id": order_id, "modify": {"reduce_by": qty}})
60
+
61
+ @classmethod
62
+ def timer(cls, time: int) -> Action:
63
+ """Wake this strategy's [`Strategy.on_timer()`][microbook.sim.Strategy.on_timer] at ``time``."""
64
+ return cls(time, EventType.TIMER)
65
+
66
+
67
+ class Strategy:
68
+ """Base strategy. Override any of the hooks; each returns a list of actions.
69
+
70
+ =================== ==========================================================
71
+ ``on_start`` once, when the simulation starts
72
+ ``on_tick`` on every ``SNAPSHOT`` event
73
+ ``on_timer`` on a ``TIMER`` this strategy scheduled (``Action.timer``)
74
+ ``on_fill`` for each fill of one of this strategy's orders
75
+ ``on_report`` for each execution report of a message this strategy sent
76
+ =================== ==========================================================
77
+
78
+ ``latency`` delays every order message (submit/cancel/modify) by that many
79
+ time units between the decision and its arrival at the book.
80
+
81
+ Timers must be in the future unless a subclass sets ``same_time_timers``:
82
+ then a timer at the current time is allowed and fires after everything
83
+ already queued for that time (the strategy must make progress each time,
84
+ or the run never ends).
85
+ """
86
+
87
+ same_time_timers: bool = False
88
+ """Allow timers at the current time; they fire after everything already queued for that time."""
89
+
90
+ def __init__(self, name: str, portfolio: Portfolio | None = None, *, latency: int = 0) -> None:
91
+ if latency < 0:
92
+ raise ValueError("latency must be >= 0")
93
+ self.name = name
94
+ self.portfolio = portfolio if portfolio is not None else Portfolio()
95
+ self.latency = latency
96
+ # Ids of orders scheduled *outside* the strategy (e.g. ``sim.schedule``)
97
+ # that should still be attributed to it. Orders a strategy sends via
98
+ # actions are attributed automatically.
99
+ self.my_order_ids: set[str] = set()
100
+ self._oid_seq = 0
101
+
102
+ def next_order_id(self, tag: str = "o") -> str:
103
+ """A fresh order id, unique within this strategy."""
104
+ self._oid_seq += 1
105
+ return f"{self.name}:{tag}{self._oid_seq}"
106
+
107
+ # --- hooks -------------------------------------------------------------
108
+
109
+ def on_start(self, now: int, lob: LimitOrderBook) -> list[Action]:
110
+ """Called once when the simulation starts."""
111
+ return []
112
+
113
+ def on_tick(self, now: int, lob: LimitOrderBook) -> list[Action]:
114
+ """Called on every ``SNAPSHOT`` event."""
115
+ return []
116
+
117
+ def on_timer(self, now: int, lob: LimitOrderBook) -> list[Action]:
118
+ """Called on a timer this strategy scheduled with [`Action.timer()`][microbook.sim.Action.timer]."""
119
+ return []
120
+
121
+ def on_fill(self, now: int, fill: Fill, side: Side, is_maker: bool, lob: LimitOrderBook) -> list[Action]:
122
+ """Called for each fill of one of this strategy's orders.
123
+
124
+ Runs before [`on_report()`][microbook.sim.Strategy.on_report] for the same message.
125
+
126
+ ``side`` is this strategy's side of the trade and ``is_maker`` whether its order was resting.
127
+ """
128
+ return []
129
+
130
+ def on_report(self, now: int, report: ExecutionReport) -> list[Action]:
131
+ """Called with the execution report of each message this strategy sent."""
132
+ return []
133
+
134
+ def __repr__(self) -> str:
135
+ return f"{type(self).__name__}(name={self.name!r})"
136
+
137
+
138
+ class TwoSidedQuoter(Strategy):
139
+ """Base class for market makers that keep at most one bid and one ask.
140
+
141
+ Subclasses implement [`compute_quotes()`][microbook.sim.TwoSidedQuoter.compute_quotes]. Quote management rules:
142
+
143
+ * prices are rounded *passively* onto the book's grid (bids down, asks up);
144
+ * quotes never cross the opposite touch: they are slid to one tick behind
145
+ it and sent post-only, so a maker never pays to take liquidity;
146
+ * an existing quote whose price is unchanged is left alone, preserving its
147
+ queue priority; otherwise it is cancelled and replaced.
148
+ """
149
+
150
+ def __init__(
151
+ self,
152
+ name: str,
153
+ *,
154
+ tick_interval: int,
155
+ latency: int = 0,
156
+ portfolio: Portfolio | None = None,
157
+ ) -> None:
158
+ super().__init__(name, portfolio, latency=latency)
159
+ if tick_interval <= 0:
160
+ raise ValueError("tick_interval must be positive")
161
+ self.tick_interval = tick_interval
162
+ self._last_quote_t = -(10**18)
163
+ # side -> (order_id, price, sent_at) of the latest quote sent
164
+ self._quotes: dict[Side, tuple[str, float, int] | None] = {Side.BUY: None, Side.SELL: None}
165
+
166
+ def compute_quotes(self, now: int, lob: LimitOrderBook) -> tuple[float | None, float | None, int, int] | None:
167
+ """Return ``(bid_px, ask_px, bid_qty, ask_qty)``; a ``None`` price pulls that
168
+ side. Return ``None`` to leave all quotes untouched this tick."""
169
+ raise NotImplementedError
170
+
171
+ def on_tick(self, now: int, lob: LimitOrderBook) -> list[Action]:
172
+ """Requote at most once every ``tick_interval``.
173
+
174
+ Quotes come from [`compute_quotes()`][microbook.sim.TwoSidedQuoter.compute_quotes].
175
+ """
176
+ if now - self._last_quote_t < self.tick_interval:
177
+ return []
178
+ quotes = self.compute_quotes(now, lob)
179
+ if quotes is None:
180
+ return []
181
+ self._last_quote_t = now
182
+ bid_px, ask_px, bid_qty, ask_qty = quotes
183
+ return self.requote(now, lob, bid_px, ask_px, bid_qty, ask_qty)
184
+
185
+ def on_report(self, now: int, report: ExecutionReport) -> list[Action]:
186
+ """Forget a quote the book rejected, so the next requote replaces it."""
187
+ if report.status is OrderStatus.REJECTED:
188
+ for side, q in self._quotes.items():
189
+ if q is not None and q[0] == report.order_id:
190
+ self._quotes[side] = None
191
+ return []
192
+
193
+ def requote(
194
+ self,
195
+ now: int,
196
+ lob: LimitOrderBook,
197
+ bid_px: float | None,
198
+ ask_px: float | None,
199
+ bid_qty: int,
200
+ ask_qty: int,
201
+ ) -> list[Action]:
202
+ """Actions that move the quotes to ``bid_px`` / ``ask_px`` (``None`` pulls that side).
203
+
204
+ Prices are rounded passively and kept off the opposite touch; an unchanged quote
205
+ keeps its queue position.
206
+ """
207
+ tick = lob.tick_size
208
+ bb, ba = lob.best_bid(), lob.best_ask()
209
+ if bid_px is not None:
210
+ bid_px = lob.round_price(bid_px, Side.BUY)
211
+ if ba is not None and bid_px >= ba:
212
+ bid_px = lob.price_of(lob.to_ticks(ba) - 1)
213
+ if ask_px is not None:
214
+ ask_px = lob.round_price(ask_px, Side.SELL)
215
+ if bb is not None and ask_px <= bb:
216
+ ask_px = lob.price_of(lob.to_ticks(bb) + 1)
217
+ if bid_px is not None and ask_px is not None and bid_px >= ask_px:
218
+ ask_px = lob.price_of(lob.to_ticks(bid_px) + 1)
219
+ if bid_px is not None and bid_px < tick:
220
+ bid_px = None
221
+
222
+ actions: list[Action] = []
223
+ self._update_side(now, lob, Side.BUY, bid_px, bid_qty, actions)
224
+ self._update_side(now, lob, Side.SELL, ask_px, ask_qty, actions)
225
+ return actions
226
+
227
+ def cancel_all(self, now: int) -> list[Action]:
228
+ """Cancel both quotes."""
229
+ actions = []
230
+ for side, q in self._quotes.items():
231
+ if q is not None:
232
+ actions.append(Action.cancel(q[0], now))
233
+ self._quotes[side] = None
234
+ return actions
235
+
236
+ def _update_side(
237
+ self, now: int, lob: LimitOrderBook, side: Side, px: float | None, qty: int, actions: list[Action]
238
+ ) -> None:
239
+ cur = self._quotes[side]
240
+ if cur is not None:
241
+ oid, cur_px, sent_at = cur
242
+ alive = oid in lob or sent_at + self.latency >= now # resting, or still in flight
243
+ if alive and px is not None and cur_px == px:
244
+ return # unchanged: keep queue priority
245
+ if alive:
246
+ actions.append(Action.cancel(oid, now))
247
+ self._quotes[side] = None
248
+ if px is None or qty <= 0:
249
+ return
250
+ oid = self.next_order_id("b" if side is Side.BUY else "a")
251
+ actions.append(Action.submit(Order.limit(oid, side, px, qty, ts=now, post_only=True), now))
252
+ self._quotes[side] = (oid, px, now)
253
+
254
+
255
+ class MarketMaker(TwoSidedQuoter):
256
+ """Baseline symmetric market maker.
257
+
258
+ Quotes ``mid +/- half_spread_ticks`` and, when carrying inventory, shifts
259
+ both quotes by ``inventory_skew_ticks`` against the position (long -> lower,
260
+ to attract buyers; short -> higher). ``tick_size`` is the quoting unit and
261
+ defaults to the book's tick.
262
+ """
263
+
264
+ def __init__(
265
+ self,
266
+ name: str = "mm",
267
+ *,
268
+ tick_size: float | None = None,
269
+ half_spread_ticks: int = 1,
270
+ size: int = 5,
271
+ tick_interval: int = 10,
272
+ inventory_skew_ticks: int = 2,
273
+ latency: int = 0,
274
+ ) -> None:
275
+ super().__init__(name, tick_interval=tick_interval, latency=latency)
276
+ self.tick_size = tick_size
277
+ self.half_spread_ticks = half_spread_ticks
278
+ self.size = size
279
+ self.inventory_skew_ticks = inventory_skew_ticks
280
+
281
+ def compute_quotes(self, now: int, lob: LimitOrderBook) -> tuple[float | None, float | None, int, int] | None:
282
+ """Mid plus or minus the half-spread, shifted against any inventory."""
283
+ mid = lob.midprice()
284
+ if mid is None:
285
+ return None
286
+ q = self.tick_size or lob.tick_size
287
+ inv = self.portfolio.position
288
+ skew = -self.inventory_skew_ticks if inv > 0 else self.inventory_skew_ticks if inv < 0 else 0
289
+ bid = mid + (skew - self.half_spread_ticks) * q
290
+ ask = mid + (skew + self.half_spread_ticks) * q
291
+ return bid, ask, self.size, self.size
292
+
293
+
294
+ class TWAPExecutor(Strategy):
295
+ """Time-weighted execution of ``total_qty`` between ``start`` and ``end``.
296
+
297
+ Sends a market-order slice every ``tick_interval`` (driven by SNAPSHOT
298
+ ticks). Slices are sized so the remainder is spread evenly over the slices
299
+ left; the final slice sends everything outstanding. Quantity that a market
300
+ order could not fill (thin book) is returned to the schedule. It waits for
301
+ a two-sided market so every slice has a well-defined arrival price.
302
+ """
303
+
304
+ def __init__(
305
+ self,
306
+ side: Side,
307
+ total_qty: int,
308
+ start: int,
309
+ end: int,
310
+ *,
311
+ tick_interval: int = 10,
312
+ name: str = "twap",
313
+ latency: int = 0,
314
+ ) -> None:
315
+ super().__init__(name=name, latency=latency)
316
+ if total_qty <= 0:
317
+ raise ValueError("total_qty must be positive")
318
+ if end < start:
319
+ raise ValueError("end must be >= start")
320
+ self.side = side
321
+ self.total_qty = total_qty
322
+ self.start = start
323
+ self.end = end
324
+ self.tick_interval = tick_interval
325
+ self._sent = 0 # sent and not (yet) known to be unfilled
326
+ self._last_t = -(10**18)
327
+
328
+ @property
329
+ def remaining(self) -> int:
330
+ """Shares not yet sent, or sent but returned unfilled."""
331
+ return self.total_qty - self._sent
332
+
333
+ def on_tick(self, now: int, lob: LimitOrderBook) -> list[Action]:
334
+ """Send the next market-order slice when one is due."""
335
+ if now < self.start or now > self.end:
336
+ return []
337
+ if now - self._last_t < self.tick_interval:
338
+ return []
339
+ if self.remaining <= 0 or lob.midprice() is None:
340
+ return []
341
+
342
+ slices_left = max(1, (self.end - now) // self.tick_interval + 1)
343
+ qty = self.remaining if slices_left == 1 else max(1, self.remaining // slices_left)
344
+
345
+ self._sent += qty
346
+ self._last_t = now
347
+ return [Action.submit(Order.market(self.next_order_id(), self.side, qty, ts=now), now)]
348
+
349
+ def on_report(self, now: int, report: ExecutionReport) -> list[Action]:
350
+ """Return the unfilled part of a market order to the schedule."""
351
+ self._sent -= report.canceled_qty # unfilled market remainder goes back on the schedule
352
+ return []
microbook/stylized.py ADDED
@@ -0,0 +1,324 @@
1
+ """Stylized facts of market data: the statistical signatures every realistic
2
+ market model must reproduce (Cont 2001; Bouchaud, Bonart, Donier & Gould 2018).
3
+
4
+ All functions are pure and work on plain sequences, so they apply equally to
5
+ simulator output (``SimResult.mid_path`` / ``SimResult.fills``) and to replayed
6
+ historical data.
7
+
8
+ ========================= ==================================== ==================
9
+ Fact Statistic here Typical equities
10
+ ========================= ==================================== ==================
11
+ Fat tails excess kurtosis, Hill tail index kurtosis >> 0, alpha ~ 3
12
+ Aggregational Gaussianity kurtosis falls as the horizon grows -
13
+ No return autocorrelation ACF(r) at lag >= 1 ~ 0 (negative at tick scale)
14
+ Volatility clustering ACF(|r|) at lags 1..100 > 0, slow decay
15
+ Long memory of order sign ACF(sign) ~ lag^-gamma gamma ~ 0.5
16
+ Square-root impact I(Q) ~ sigma * (Q / V)^delta delta ~ 0.5
17
+ ========================= ==================================== ==================
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import math
23
+ import statistics
24
+ from bisect import bisect_right
25
+ from collections.abc import Iterable, Sequence
26
+ from dataclasses import dataclass
27
+ from typing import NamedTuple
28
+
29
+ from .types import Fill
30
+
31
+ __all__ = [
32
+ "MetaorderRecord",
33
+ "StylizedFacts",
34
+ "acf",
35
+ "aggressor_signs",
36
+ "bin_impacts",
37
+ "excess_kurtosis",
38
+ "hill_tail_index",
39
+ "impact_curve",
40
+ "log_lags",
41
+ "metaorder_impacts",
42
+ "power_law_fit",
43
+ "sample_returns",
44
+ "stylized_facts",
45
+ ]
46
+
47
+
48
+ def _time_of(entry: tuple[int, float]) -> int:
49
+ return entry[0]
50
+
51
+
52
+ def _value_at(path: Sequence[tuple[int, float]], t: int) -> float | None:
53
+ i = bisect_right(path, t, key=_time_of) - 1
54
+ if i < 0:
55
+ return None
56
+ v = path[i][1]
57
+ return None if math.isnan(v) else v
58
+
59
+
60
+ def sample_returns(mid_path: Sequence[tuple[int, float]], dt: int, *, start: int = 0, end: int) -> list[float]:
61
+ """Log returns of a step-function mid path sampled every ``dt`` time units.
62
+
63
+ Intervals where the mid is undefined at either end are skipped.
64
+ """
65
+ if dt <= 0:
66
+ raise ValueError("dt must be positive")
67
+ out: list[float] = []
68
+ prev = _value_at(mid_path, start)
69
+ for t in range(start + dt, end + 1, dt):
70
+ cur = _value_at(mid_path, t)
71
+ if prev is not None and cur is not None and prev > 0 and cur > 0:
72
+ out.append(math.log(cur / prev))
73
+ prev = cur
74
+ return out
75
+
76
+
77
+ def acf(xs: Sequence[float], lags: Iterable[int]) -> list[float]:
78
+ """Sample autocorrelation at each lag (biased estimator, like most references)."""
79
+ n = len(xs)
80
+ if n < 2:
81
+ raise ValueError("need at least two observations")
82
+ mu = statistics.fmean(xs)
83
+ d = [x - mu for x in xs]
84
+ var = math.fsum(x * x for x in d)
85
+ if var == 0:
86
+ return [math.nan for _ in lags]
87
+ out = []
88
+ for lag in lags:
89
+ if not 0 < lag < n:
90
+ raise ValueError(f"lag {lag} out of range for {n} observations")
91
+ out.append(math.fsum(d[i] * d[i + lag] for i in range(n - lag)) / var)
92
+ return out
93
+
94
+
95
+ def log_lags(max_lag: int, n: int = 20) -> list[int]:
96
+ """About ``n`` distinct integer lags, logarithmically spaced over ``[1, max_lag]``."""
97
+ if max_lag < 1:
98
+ raise ValueError("max_lag must be >= 1")
99
+ pts = {round(math.exp(i * math.log(max_lag) / max(n - 1, 1))) for i in range(n)}
100
+ return sorted(p for p in pts if p >= 1)
101
+
102
+
103
+ def excess_kurtosis(xs: Sequence[float]) -> float:
104
+ """Fourth standardized moment minus 3 (0 for a Gaussian)."""
105
+ if len(xs) < 4:
106
+ return math.nan
107
+ mu = statistics.fmean(xs)
108
+ m2 = statistics.fmean((x - mu) ** 2 for x in xs)
109
+ if m2 == 0:
110
+ return math.nan
111
+ m4 = statistics.fmean((x - mu) ** 4 for x in xs)
112
+ return m4 / (m2 * m2) - 3.0
113
+
114
+
115
+ def hill_tail_index(xs: Sequence[float], tail: float = 0.05) -> float:
116
+ """Hill estimator of the tail exponent ``alpha`` of ``|x|``: ``P(|X| > x) ~ x^-alpha``.
117
+
118
+ Uses the largest ``tail`` fraction of observations. Smaller ``alpha`` means
119
+ fatter tails (a Gaussian has none: the estimate grows with sample size).
120
+ """
121
+ if not 0 < tail < 1:
122
+ raise ValueError("tail must be in (0, 1)")
123
+ a = sorted((abs(x) for x in xs if x != 0), reverse=True)
124
+ k = int(len(a) * tail)
125
+ if k < 2:
126
+ return math.nan
127
+ ref = a[k]
128
+ total = math.fsum(math.log(a[i] / ref) for i in range(k))
129
+ return k / total if total > 0 else math.nan # all tail values tied: no tail to measure
130
+
131
+
132
+ def aggressor_signs(fills: Iterable[Fill]) -> list[int]:
133
+ """One sign per aggressive order (+1 buy, -1 sell), in time order.
134
+
135
+ Consecutive fills of the same taker order (a sweep through several makers)
136
+ count as one trade, as in the empirical literature.
137
+ """
138
+ out: list[int] = []
139
+ last_taker: str | None = None
140
+ for f in fills:
141
+ if f.aggressor_side is None or f.taker_order_id == last_taker:
142
+ continue
143
+ last_taker = f.taker_order_id
144
+ out.append(f.aggressor_side.sign)
145
+ return out
146
+
147
+
148
+ def power_law_fit(xs: Sequence[float], ys: Sequence[float]) -> tuple[float, float]:
149
+ """Least-squares fit of ``y = c * x^-gamma`` on log-log axes, ignoring ``y <= 0``.
150
+
151
+ Returns ``(gamma, r_squared)``.
152
+ """
153
+ pts = [(math.log(x), math.log(y)) for x, y in zip(xs, ys, strict=True) if x > 0 and y > 0 and not math.isnan(y)]
154
+ if len(pts) < 3:
155
+ return math.nan, math.nan
156
+ lx = [p[0] for p in pts]
157
+ ly = [p[1] for p in pts]
158
+ mx, my = statistics.fmean(lx), statistics.fmean(ly)
159
+ sxx = math.fsum((x - mx) ** 2 for x in lx)
160
+ sxy = math.fsum((x - mx) * (y - my) for x, y in pts)
161
+ slope = sxy / sxx
162
+ ss_tot = math.fsum((y - my) ** 2 for y in ly)
163
+ ss_res = math.fsum((y - (my + slope * (x - mx))) ** 2 for x, y in pts)
164
+ r2 = 1 - ss_res / ss_tot if ss_tot > 0 else math.nan
165
+ return -slope, r2
166
+
167
+
168
+ class MetaorderRecord(NamedTuple):
169
+ """A large order executed as a sequence of child orders."""
170
+
171
+ side: int
172
+ """+1 for a buy metaorder, -1 for a sell."""
173
+ qty: int
174
+ """Total size, in shares."""
175
+ start: int
176
+ """Time the metaorder started."""
177
+ end: int
178
+ """Time of its last child order."""
179
+
180
+
181
+ def metaorder_impacts(
182
+ metaorders: Iterable[MetaorderRecord],
183
+ mid_path: Sequence[tuple[int, float]],
184
+ *,
185
+ daily_volume: float,
186
+ sigma: float,
187
+ ) -> list[tuple[float, float]]:
188
+ """``(Q / daily_volume, impact / sigma)`` for each metaorder with a defined mid.
189
+
190
+ The impact of one metaorder is ``side * log(mid(end) / mid(start))``: the
191
+ price move in its direction during execution. ``sigma`` is the return
192
+ volatility over the same reference "day" as ``daily_volume``.
193
+ """
194
+ pts: list[tuple[float, float]] = []
195
+ for m in metaorders:
196
+ a, b = _value_at(mid_path, m.start), _value_at(mid_path, m.end)
197
+ if a is None or b is None or m.qty <= 0:
198
+ continue
199
+ pts.append((m.qty / daily_volume, m.side * math.log(b / a) / sigma))
200
+ return pts
201
+
202
+
203
+ def bin_impacts(
204
+ points: Sequence[tuple[float, float]], n_bins: int = 8
205
+ ) -> tuple[list[tuple[float, float, int]], float, float]:
206
+ """Group ``(size, impact)`` points into log-spaced size bins and fit ``impact ~ size^delta``.
207
+
208
+ Returns ``(bins, delta, r_squared)`` with bins ``(mean size, mean impact, count)``.
209
+ Bins whose mean impact is not positive cannot enter the log-log fit.
210
+ """
211
+ if len(points) < n_bins:
212
+ return [], math.nan, math.nan
213
+ lo, hi = min(p[0] for p in points), max(p[0] for p in points)
214
+ if lo == hi:
215
+ return [(lo, statistics.fmean(p[1] for p in points), len(points))], math.nan, math.nan
216
+ edges = [math.exp(math.log(lo) + i * (math.log(hi) - math.log(lo)) / n_bins) for i in range(n_bins + 1)]
217
+ groups: list[list[tuple[float, float]]] = [[] for _ in range(n_bins)]
218
+ for q, i_ in points:
219
+ # clamp both ends: exp(log(x)) can land a hair either side of x
220
+ groups[min(max(bisect_right(edges, q) - 1, 0), n_bins - 1)].append((q, i_))
221
+ bins = [(statistics.fmean(p[0] for p in g), statistics.fmean(p[1] for p in g), len(g)) for g in groups if g]
222
+ gamma, r2 = power_law_fit([b[0] for b in bins], [b[1] for b in bins])
223
+ return bins, -gamma, r2
224
+
225
+
226
+ def impact_curve(
227
+ metaorders: Iterable[MetaorderRecord],
228
+ mid_path: Sequence[tuple[int, float]],
229
+ *,
230
+ daily_volume: float,
231
+ sigma: float,
232
+ n_bins: int = 8,
233
+ ) -> tuple[list[tuple[float, float, int]], float, float]:
234
+ """Average metaorder impact against size, and the fitted impact exponent.
235
+
236
+ Combines [`metaorder_impacts()`][microbook.stylized.metaorder_impacts] and
237
+ [`bin_impacts()`][microbook.stylized.bin_impacts]. The square-root law predicts
238
+ ``impact / sigma ~ Y * (Q / V)^0.5`` with ``Y`` of order one.
239
+ """
240
+ pts = metaorder_impacts(metaorders, mid_path, daily_volume=daily_volume, sigma=sigma)
241
+ return bin_impacts(pts, n_bins)
242
+
243
+
244
+ @dataclass(frozen=True)
245
+ class StylizedFacts:
246
+ """Summary statistics of one run (or one replayed day)."""
247
+
248
+ dt_short: int
249
+ """Short return horizon, in time steps."""
250
+ dt_long: int
251
+ """Long return horizon, in time steps."""
252
+ n_returns: int
253
+ """Number of `dt_short` returns."""
254
+ kurtosis_short: float
255
+ """Excess kurtosis of `dt_short` returns."""
256
+ kurtosis_long: float
257
+ """Excess kurtosis of `dt_long` returns."""
258
+ hill_alpha: float
259
+ """Hill estimate of the tail index of `dt_short` returns."""
260
+ return_acf_1: float
261
+ """Lag-1 autocorrelation of `dt_short` returns."""
262
+ abs_return_acf: dict[int, float]
263
+ """Autocorrelation of absolute `dt_short` returns (volatility clustering), by lag in units of `dt_short`."""
264
+ n_trades: int
265
+ """Number of trades (aggressive orders) with a known side."""
266
+ sign_acf: dict[int, float]
267
+ """Autocorrelation of trade signs, by lag in trades."""
268
+ sign_gamma: float
269
+ """Fitted exponent γ in ACF(sign) ∝ lag^−γ."""
270
+ sign_gamma_r2: float
271
+ """R² of that fit, on log-log axes."""
272
+
273
+ def rows(self) -> dict[str, float]:
274
+ """Flat ``{statistic: value}`` dict, convenient for tables."""
275
+ out = {
276
+ f"kurtosis (dt={self.dt_short})": self.kurtosis_short,
277
+ f"kurtosis (dt={self.dt_long})": self.kurtosis_long,
278
+ "Hill tail alpha": self.hill_alpha,
279
+ "ACF r lag 1": self.return_acf_1,
280
+ }
281
+ out.update({f"ACF |r| lag {k}": v for k, v in self.abs_return_acf.items()})
282
+ out.update({f"ACF sign lag {k}": v for k, v in self.sign_acf.items()})
283
+ out["sign ACF gamma"] = self.sign_gamma
284
+ return out
285
+
286
+
287
+ def stylized_facts(
288
+ mid_path: Sequence[tuple[int, float]],
289
+ fills: Sequence[Fill],
290
+ *,
291
+ end: int,
292
+ start: int = 0,
293
+ dt_short: int = 10,
294
+ dt_long: int = 1_000,
295
+ vol_lags: Sequence[int] = (1, 10, 100),
296
+ sign_lags: Sequence[int] = (1, 10, 100, 1_000),
297
+ ) -> StylizedFacts:
298
+ """Compute the standard stylized facts from a mid path and a fill stream."""
299
+ r = sample_returns(mid_path, dt_short, start=start, end=end)
300
+ r_long = sample_returns(mid_path, dt_long, start=start, end=end)
301
+ absr = [abs(x) for x in r]
302
+ max_vol_lag = len(r) - 1
303
+ vlags = [k for k in vol_lags if k < max_vol_lag]
304
+
305
+ signs = aggressor_signs(fills)
306
+ slags = [k for k in sign_lags if k < len(signs) - 1]
307
+ fit_lags = log_lags(min(max(slags, default=1), max(len(signs) // 10, 1)), 16)
308
+ sign_vals = acf(signs, fit_lags) if len(signs) > 20 else []
309
+ gamma, r2 = power_law_fit(fit_lags, sign_vals) if sign_vals else (math.nan, math.nan)
310
+
311
+ return StylizedFacts(
312
+ dt_short=dt_short,
313
+ dt_long=dt_long,
314
+ n_returns=len(r),
315
+ kurtosis_short=excess_kurtosis(r),
316
+ kurtosis_long=excess_kurtosis(r_long),
317
+ hill_alpha=hill_tail_index(r),
318
+ return_acf_1=acf(r, [1])[0] if len(r) > 2 else math.nan,
319
+ abs_return_acf=dict(zip(vlags, acf(absr, vlags), strict=True)) if vlags else {},
320
+ n_trades=len(signs),
321
+ sign_acf=dict(zip(slags, acf(signs, slags), strict=True)) if slags else {},
322
+ sign_gamma=gamma,
323
+ sign_gamma_r2=r2,
324
+ )