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/rl.py ADDED
@@ -0,0 +1,221 @@
1
+ """Market making as a reinforcement-learning problem (a Gymnasium environment).
2
+
3
+ Install the optional dependency with ``pip install "microstructure-sim[rl]"``.
4
+
5
+ [`MarketMakingEnv`][microbook.rl.MarketMakingEnv] puts one learning agent into the closed-loop market of
6
+ [`build_market()`][microbook.sim.build_market]. Every ``decision_interval`` time steps the
7
+ agent chooses where to quote; the market then runs until the next decision.
8
+
9
+ Action
10
+ ``MultiDiscrete([max_offset + 1, max_offset + 1])``: for the bid and the
11
+ ask, how many ticks behind the most aggressive passive price to quote
12
+ (0 = as close to the mid as the grid allows without crossing). Quotes are
13
+ post-only, unchanged quotes keep their queue position, and the side that
14
+ would push ``|inventory|`` past ``inv_limit`` is not quoted.
15
+
16
+ Observation (``float32``, shape ``(6,)``)
17
+ ====== ==================================================================
18
+ 0 inventory / ``inv_limit``
19
+ 1 spread, in ticks
20
+ 2 depth imbalance of the top 3 levels, in [-1, 1]
21
+ 3 mid change over the last interval, in ticks
22
+ 4 mean absolute mid change per interval over the last 20, in ticks
23
+ 5 fraction of the episode remaining
24
+ ====== ==================================================================
25
+
26
+ Reward
27
+ The change in mark-to-mid PnL over the interval minus
28
+ ``inventory_penalty * inventory**2``, divided by the tick size (so a reward
29
+ of 1 is one tick on one share). The episode ends after ``horizon`` steps.
30
+
31
+ Each ``reset`` draws a fresh market seed from the environment's RNG, so
32
+ ``reset(seed=s)`` makes a whole episode reproducible.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ from collections import deque
38
+ from dataclasses import replace
39
+ from typing import Any
40
+
41
+ try:
42
+ import gymnasium as gym
43
+ import numpy as np
44
+ import numpy.typing as npt
45
+ from gymnasium import spaces
46
+ except ImportError as exc: # pragma: no cover
47
+ raise ImportError('microbook.rl needs gymnasium: pip install "microstructure-sim[rl]"') from exc
48
+
49
+ from .book import LimitOrderBook
50
+ from .sim.metrics import imbalance
51
+ from .sim.scenarios import Market, MarketConfig, build_market
52
+ from .sim.strategy import Action, TwoSidedQuoter
53
+
54
+ __all__ = ["MarketMakingEnv"]
55
+
56
+ Obs = npt.NDArray[np.float32]
57
+ Act = npt.NDArray[np.int64]
58
+
59
+
60
+ class _AgentQuoter(TwoSidedQuoter):
61
+ """Quotes the offsets the environment last chose, once per decision."""
62
+
63
+ def __init__(self, *, size: int, inv_limit: int, latency: int, interval: int, first_decision: int) -> None:
64
+ super().__init__("agent", tick_interval=1, latency=latency)
65
+ self.size = size
66
+ self.inv_limit = inv_limit
67
+ self.interval = interval
68
+ self.first_decision = first_decision
69
+ self.offsets: tuple[int, int] | None = None
70
+
71
+ def on_start(self, now: int, lob: LimitOrderBook) -> list[Action]:
72
+ # one step after each decision time, so the environment sets the offsets first
73
+ return [Action.timer(self.first_decision + 1)]
74
+
75
+ def on_tick(self, now: int, lob: LimitOrderBook) -> list[Action]:
76
+ return [] # decisions are driven by on_timer
77
+
78
+ def on_timer(self, now: int, lob: LimitOrderBook) -> list[Action]:
79
+ actions = [Action.timer(now + self.interval)]
80
+ mid = lob.midprice()
81
+ if self.offsets is None or mid is None:
82
+ return actions
83
+ tick = lob.tick_size
84
+ inv = self.portfolio.position
85
+ b, a = self.offsets
86
+ bid = mid - (b + 0.5) * tick if inv < self.inv_limit else None
87
+ ask = mid + (a + 0.5) * tick if inv > -self.inv_limit else None
88
+ return actions + self.requote(now, lob, bid, ask, self.size, self.size)
89
+
90
+
91
+ class MarketMakingEnv(gym.Env[Obs, Act]):
92
+ """Gymnasium environment: quote in the closed-loop market (see module docstring)."""
93
+
94
+ metadata: dict[str, Any] = {"render_modes": ["ansi"]} # noqa: RUF012 (gymnasium declares it per instance)
95
+ """Gymnasium metadata: the supported render modes."""
96
+
97
+ def __init__(
98
+ self,
99
+ market: MarketConfig | None = None,
100
+ *,
101
+ horizon: int = 5_000,
102
+ decision_interval: int = 10,
103
+ warmup: int = 200,
104
+ max_offset: int = 5,
105
+ size: int = 5,
106
+ inv_limit: int = 50,
107
+ inventory_penalty: float = 0.0,
108
+ latency: int = 0,
109
+ render_mode: str | None = None,
110
+ ) -> None:
111
+ if horizon <= 0 or decision_interval <= 0 or warmup < 0 or max_offset < 0:
112
+ raise ValueError("horizon and decision_interval must be positive; warmup and max_offset >= 0")
113
+ if size <= 0 or inv_limit <= 0 or inventory_penalty < 0 or latency < 0:
114
+ raise ValueError("size and inv_limit must be positive; inventory_penalty and latency >= 0")
115
+ if render_mode is not None and render_mode not in self.metadata["render_modes"]:
116
+ raise ValueError(f"unsupported render_mode {render_mode!r}")
117
+ self.market_config = market if market is not None else MarketConfig()
118
+ self.horizon = horizon
119
+ self.decision_interval = decision_interval
120
+ self.warmup = warmup
121
+ self.size = size
122
+ self.inv_limit = inv_limit
123
+ self.inventory_penalty = inventory_penalty
124
+ self.latency = latency
125
+ self.render_mode = render_mode
126
+
127
+ self.action_space = spaces.MultiDiscrete([max_offset + 1, max_offset + 1])
128
+ # generous finite bounds; observations are clipped to them
129
+ self._obs_low = np.array([-2.0, 0.0, -1.0, -100.0, 0.0, 0.0], dtype=np.float32)
130
+ self._obs_high = np.array([2.0, 100.0, 1.0, 100.0, 100.0, 1.0], dtype=np.float32)
131
+ self.observation_space = spaces.Box(self._obs_low, self._obs_high, dtype=np.float32)
132
+
133
+ self.market: Market | None = None
134
+ self._agent: _AgentQuoter | None = None
135
+ self._t = 0
136
+ self._last_mid = 0.0
137
+ self._last_pnl = 0.0
138
+ self._last_move = 0.0
139
+ self._moves: deque[float] = deque(maxlen=20)
140
+
141
+ # --- gymnasium API --------------------------------------------------------
142
+
143
+ def reset(self, *, seed: int | None = None, options: dict[str, Any] | None = None) -> tuple[Obs, dict[str, Any]]:
144
+ """Start an episode in a fresh market; returns the first observation and an info dict."""
145
+ super().reset(seed=seed)
146
+ cfg = replace(self.market_config, seed=int(self.np_random.integers(2**31)))
147
+ self._agent = _AgentQuoter(
148
+ size=self.size,
149
+ inv_limit=self.inv_limit,
150
+ latency=self.latency,
151
+ interval=self.decision_interval,
152
+ first_decision=self.warmup,
153
+ )
154
+ self.market = build_market(cfg, [self._agent], horizon=self.warmup + self.horizon)
155
+ self.market.run(self.warmup)
156
+ self._t = self.warmup
157
+ self._last_mid = self._mid(cfg.start_price)
158
+ self._last_pnl = 0.0
159
+ self._last_move = 0.0
160
+ self._moves.clear()
161
+ return self._obs(), self._info()
162
+
163
+ def step(self, action: Act) -> tuple[Obs, float, bool, bool, dict[str, Any]]:
164
+ """Quote at the chosen offsets for one decision interval.
165
+
166
+ Returns ``(observation, reward, terminated, truncated, info)``.
167
+ """
168
+ if self.market is None or self._agent is None:
169
+ raise RuntimeError("call reset() before step()")
170
+ lob = self.market.sim.lob
171
+ self._agent.offsets = (int(action[0]), int(action[1]))
172
+ self._t += self.decision_interval
173
+ self.market.run(self._t)
174
+
175
+ mid = self._mid(self._last_mid)
176
+ self._last_move = (mid - self._last_mid) / lob.tick_size
177
+ self._moves.append(abs(self._last_move))
178
+ self._last_mid = mid
179
+ pnl = self._agent.portfolio.total_pnl(mid)
180
+ inv = self._agent.portfolio.position
181
+ reward = (pnl - self._last_pnl - self.inventory_penalty * inv * inv) / lob.tick_size
182
+ self._last_pnl = pnl
183
+ terminated = self._t >= self.warmup + self.horizon
184
+ return self._obs(), float(reward), terminated, False, self._info()
185
+
186
+ def render(self) -> str | None:
187
+ """A one-line text summary when ``render_mode`` is ``"ansi"``, otherwise ``None``."""
188
+ if self.render_mode != "ansi" or self._agent is None:
189
+ return None
190
+ info = self._info()
191
+ return f"t={info['t']} mid={info['mid']:.2f} inventory={info['inventory']} pnl={info['pnl']:.2f}"
192
+
193
+ # --- helpers --------------------------------------------------------------
194
+
195
+ def _mid(self, fallback: float) -> float:
196
+ assert self.market is not None
197
+ mid = self.market.sim.lob.midprice()
198
+ return mid if mid is not None else fallback
199
+
200
+ def _obs(self) -> Obs:
201
+ assert self.market is not None
202
+ assert self._agent is not None
203
+ lob = self.market.sim.lob
204
+ spread = lob.spread()
205
+ raw = np.array(
206
+ [
207
+ self._agent.portfolio.position / self.inv_limit,
208
+ spread / lob.tick_size if spread is not None else 0.0,
209
+ imbalance(lob, levels=3) or 0.0,
210
+ self._last_move,
211
+ sum(self._moves) / len(self._moves) if self._moves else 0.0,
212
+ (self.warmup + self.horizon - self._t) / self.horizon,
213
+ ],
214
+ dtype=np.float32,
215
+ )
216
+ return np.clip(raw, self._obs_low, self._obs_high)
217
+
218
+ def _info(self) -> dict[str, Any]:
219
+ assert self._agent is not None
220
+ p = self._agent.portfolio
221
+ return {"t": self._t, "mid": self._last_mid, "inventory": p.position, "pnl": self._last_pnl, "volume": p.volume}
@@ -0,0 +1,93 @@
1
+ """Event-driven simulation, strategies and analytics built on the `microbook` matching engine."""
2
+
3
+ from .agents import (
4
+ FundamentalValue,
5
+ HawkesConfig,
6
+ HawkesProcess,
7
+ InformedConfig,
8
+ InformedTrader,
9
+ MetaorderConfig,
10
+ MetaorderTrader,
11
+ NoiseConfig,
12
+ NoiseTrader,
13
+ )
14
+ from .analytics import (
15
+ TimeSeries,
16
+ format_table,
17
+ inventory_stats,
18
+ markouts,
19
+ max_drawdown,
20
+ mid_at,
21
+ pnl_stats,
22
+ strategy_report,
23
+ )
24
+ from .events import Event, EventType
25
+ from .execution_metrics import ExecutionMetrics, FillRecord
26
+ from .metrics import imbalance
27
+ from .orderflow import FlowConfig, PoissonOrderFlow
28
+ from .portfolio import Portfolio
29
+ from .scenarios import Market, MarketConfig, build_market
30
+ from .simulator import MarketSimulator, SimResult
31
+ from .strategies_mm import (
32
+ AdaptiveConfig,
33
+ AdaptiveMarketMaker,
34
+ AvellanedaStoikovConfig,
35
+ AvellanedaStoikovMarketMaker,
36
+ )
37
+ from .strategy import Action, MarketMaker, Strategy, TWAPExecutor, TwoSidedQuoter
38
+
39
+ __all__ = [
40
+ "Action",
41
+ "AdaptiveConfig",
42
+ "AdaptiveMarketMaker",
43
+ "AvellanedaStoikovConfig",
44
+ "AvellanedaStoikovMarketMaker",
45
+ "Event",
46
+ "EventType",
47
+ "ExecutionMetrics",
48
+ "FillRecord",
49
+ "FlowConfig",
50
+ "FundamentalValue",
51
+ "HawkesConfig",
52
+ "HawkesProcess",
53
+ "InformedConfig",
54
+ "InformedTrader",
55
+ "Market",
56
+ "MarketConfig",
57
+ "MarketMaker",
58
+ "MarketSimulator",
59
+ "MetaorderConfig",
60
+ "MetaorderTrader",
61
+ "NoiseConfig",
62
+ "NoiseTrader",
63
+ "PoissonOrderFlow",
64
+ "Portfolio",
65
+ "SimResult",
66
+ "Strategy",
67
+ "TWAPExecutor",
68
+ "TimeSeries",
69
+ "TwoSidedQuoter",
70
+ "build_market",
71
+ "format_table",
72
+ "imbalance",
73
+ "inventory_stats",
74
+ "markouts",
75
+ "max_drawdown",
76
+ "mid_at",
77
+ "pnl_stats",
78
+ "strategy_report",
79
+ ]
80
+
81
+
82
+ _DEPRECATED = {"AdaptiveMMConfig": "AdaptiveConfig"}
83
+
84
+
85
+ def __getattr__(name: str) -> object:
86
+ """Resolve deprecated aliases (removed in 2.0) with a warning."""
87
+ if name in _DEPRECATED:
88
+ import warnings
89
+
90
+ new = _DEPRECATED[name]
91
+ warnings.warn(f"microbook.sim.{name} is deprecated; use {new}", DeprecationWarning, stacklevel=2)
92
+ return globals()[new]
93
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")