microstructure-sim 1.0.0__tar.gz

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.
Files changed (61) hide show
  1. microstructure_sim-1.0.0/.gitignore +63 -0
  2. microstructure_sim-1.0.0/CHANGELOG.md +144 -0
  3. microstructure_sim-1.0.0/CITATION.cff +24 -0
  4. microstructure_sim-1.0.0/LICENSE +21 -0
  5. microstructure_sim-1.0.0/PKG-INFO +615 -0
  6. microstructure_sim-1.0.0/README.md +572 -0
  7. microstructure_sim-1.0.0/benchmarks/bench_book.py +153 -0
  8. microstructure_sim-1.0.0/benchmarks/bench_sim.py +31 -0
  9. microstructure_sim-1.0.0/benchmarks/profile_book.py +33 -0
  10. microstructure_sim-1.0.0/examples/_plotting.py +312 -0
  11. microstructure_sim-1.0.0/examples/compare_market_makers.py +171 -0
  12. microstructure_sim-1.0.0/examples/quickstart.py +63 -0
  13. microstructure_sim-1.0.0/examples/real_data_facts.py +307 -0
  14. microstructure_sim-1.0.0/examples/replay_lobster.py +103 -0
  15. microstructure_sim-1.0.0/examples/rl_market_making.py +163 -0
  16. microstructure_sim-1.0.0/examples/static_flow.py +51 -0
  17. microstructure_sim-1.0.0/examples/stylized_facts.py +216 -0
  18. microstructure_sim-1.0.0/pyproject.toml +110 -0
  19. microstructure_sim-1.0.0/src/microbook/__init__.py +30 -0
  20. microstructure_sim-1.0.0/src/microbook/book.py +553 -0
  21. microstructure_sim-1.0.0/src/microbook/order.py +86 -0
  22. microstructure_sim-1.0.0/src/microbook/py.typed +0 -0
  23. microstructure_sim-1.0.0/src/microbook/replay.py +673 -0
  24. microstructure_sim-1.0.0/src/microbook/rl.py +221 -0
  25. microstructure_sim-1.0.0/src/microbook/sim/__init__.py +93 -0
  26. microstructure_sim-1.0.0/src/microbook/sim/agents.py +495 -0
  27. microstructure_sim-1.0.0/src/microbook/sim/analytics.py +199 -0
  28. microstructure_sim-1.0.0/src/microbook/sim/events.py +41 -0
  29. microstructure_sim-1.0.0/src/microbook/sim/execution_metrics.py +217 -0
  30. microstructure_sim-1.0.0/src/microbook/sim/metrics.py +20 -0
  31. microstructure_sim-1.0.0/src/microbook/sim/orderflow.py +70 -0
  32. microstructure_sim-1.0.0/src/microbook/sim/portfolio.py +83 -0
  33. microstructure_sim-1.0.0/src/microbook/sim/scenarios.py +145 -0
  34. microstructure_sim-1.0.0/src/microbook/sim/simulator.py +274 -0
  35. microstructure_sim-1.0.0/src/microbook/sim/strategies_mm.py +190 -0
  36. microstructure_sim-1.0.0/src/microbook/sim/strategy.py +352 -0
  37. microstructure_sim-1.0.0/src/microbook/stylized.py +324 -0
  38. microstructure_sim-1.0.0/src/microbook/types.py +119 -0
  39. microstructure_sim-1.0.0/tests/data/kraken_trades.json +14 -0
  40. microstructure_sim-1.0.0/tests/test_analytics.py +75 -0
  41. microstructure_sim-1.0.0/tests/test_book_model.py +235 -0
  42. microstructure_sim-1.0.0/tests/test_cancel.py +13 -0
  43. microstructure_sim-1.0.0/tests/test_docs.py +50 -0
  44. microstructure_sim-1.0.0/tests/test_docs_snippets.py +104 -0
  45. microstructure_sim-1.0.0/tests/test_execution_metrics.py +280 -0
  46. microstructure_sim-1.0.0/tests/test_market.py +13 -0
  47. microstructure_sim-1.0.0/tests/test_matching.py +14 -0
  48. microstructure_sim-1.0.0/tests/test_modify.py +63 -0
  49. microstructure_sim-1.0.0/tests/test_order_types.py +156 -0
  50. microstructure_sim-1.0.0/tests/test_pnl_math.py +16 -0
  51. microstructure_sim-1.0.0/tests/test_portfolio.py +70 -0
  52. microstructure_sim-1.0.0/tests/test_price_time_priority.py +13 -0
  53. microstructure_sim-1.0.0/tests/test_public_api.py +170 -0
  54. microstructure_sim-1.0.0/tests/test_real_data_facts.py +127 -0
  55. microstructure_sim-1.0.0/tests/test_regressions.py +134 -0
  56. microstructure_sim-1.0.0/tests/test_replay.py +264 -0
  57. microstructure_sim-1.0.0/tests/test_rl.py +94 -0
  58. microstructure_sim-1.0.0/tests/test_sim_determinism.py +52 -0
  59. microstructure_sim-1.0.0/tests/test_simulator.py +190 -0
  60. microstructure_sim-1.0.0/tests/test_strategies.py +116 -0
  61. microstructure_sim-1.0.0/tests/test_stylized.py +300 -0
@@ -0,0 +1,63 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.pyo
5
+ *.pyd
6
+ *.so
7
+ *.egg
8
+ *.egg-info/
9
+ dist/
10
+ build/
11
+ wheels/
12
+ *.whl
13
+ .eggs/
14
+
15
+ # Virtual environments
16
+ .venv/
17
+ venv/
18
+ env/
19
+ .env
20
+
21
+ # Distribution / packaging
22
+ MANIFEST
23
+
24
+ # Testing & coverage
25
+ .pytest_cache/
26
+ .hypothesis/
27
+ .coverage
28
+ .coverage.*
29
+ htmlcov/
30
+ coverage.xml
31
+ *.cover
32
+
33
+ # Type checkers
34
+ .mypy_cache/
35
+ .dmypy.json
36
+ .pyright/
37
+ .ruff_cache/
38
+
39
+ # Jupyter
40
+ .ipynb_checkpoints/
41
+ *.ipynb
42
+
43
+ # IDE
44
+ .vscode/
45
+ .idea/
46
+ *.swp
47
+ *.swo
48
+ *~
49
+
50
+ # OS
51
+ .DS_Store
52
+ Thumbs.db
53
+
54
+ # Claude Code
55
+ .claude/
56
+
57
+ # Profiling output
58
+ *.prof
59
+ *.lprof
60
+ site/
61
+
62
+ # Downloaded market data (examples/real_data_facts.py)
63
+ examples/.data/
@@ -0,0 +1,144 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0
4
+
5
+ The first stable release. From here on microbook follows Semantic Versioning: the public API, defined in the
6
+ stability policy, changes incompatibly only in a major release, and deprecated names keep working until then.
7
+ Seeded results reproduce the numbers published for 0.4.0. It adds a documentation site with tested examples, a comparison
8
+ with real market data, and the files a community project needs.
9
+
10
+ ### Changed
11
+ - Version 1.0.0; the package classifier is now "Development Status :: 5 - Production/Stable".
12
+
13
+ ### Added
14
+ - Python 3.14 support: tested in CI (3.10–3.14), and the native build is tested on 3.10 and 3.14.
15
+ - pre-commit hooks (ruff lint and format, YAML/TOML checks); `pre-commit` is in the `dev` extra.
16
+ - A coverage floor: `pytest --cov` fails below 90% branch coverage.
17
+ - Docstrings on every public module, class, function and method, enforced by ruff's `D1` rules on `src/`.
18
+ - `microbook.sim` now exports `FlowConfig`, `PoissonOrderFlow`, `imbalance`, `inventory_stats`, `max_drawdown` and `mid_at`, which were reachable only through submodules. `microbook.replay` exports `PRICE_SCALE`.
19
+ - `__all__` in `microbook.book`, `microbook.order` and `microbook.types`.
20
+ - A stability policy (README, "Stability and versioning"): SemVer from 1.0, a definition of the public API, deprecation rules and a reproducibility promise.
21
+ - A documentation site (MkDocs Material, `pip install -e ".[docs]"`, `mkdocs serve`) with an API reference
22
+ generated from the docstrings. CI builds it with `--strict`, so a broken link or cross-reference fails the build,
23
+ and `tests/test_docs.py` checks that the reference lists every public name.
24
+ - Docstrings on every field of the public dataclasses and named tuples (configs, records, results), so the
25
+ reference documents every setting. Cross-references in docstrings now use Markdown links instead of Sphinx roles.
26
+ - `tests/test_public_api.py` pins every public name and checks each one is documented. Golden digests of two seeded runs (`tests/test_sim_determinism.py`) check that results are identical on every supported Python and on the compiled build.
27
+ - Documentation pages: Getting started; concepts (matching engine, simulation time and latency, the market model,
28
+ realism and the stylized facts, metrics); guides (comparing strategies, replaying LOBSTER data, reinforcement
29
+ learning, performance and the native build).
30
+ - `tests/test_docs_snippets.py` runs every Python snippet in the docs and checks that it prints the output shown
31
+ under it, so the documentation cannot drift from the code.
32
+ - The GitHub Pages site now serves the documentation at its root and the Market Maker Playground at
33
+ `/playground/`. The package metadata has a `Documentation` URL.
34
+ - `examples/real_data_facts.py`: downloads a fixed day of public Kraken BTC/USD trades (cached after the first run)
35
+ and measures the same stylized facts as `examples/stylized_facts.py`, side by side with the realistic preset. Its
36
+ parsing and paging are tested offline on a fixture (`tests/test_real_data_facts.py`).
37
+ - A simulator-vs-real-market table (README and the Realism page): the realistic preset next to one day of Kraken
38
+ BTC/USD, with the caveats of the comparison.
39
+ - `CONTRIBUTING.md`, `CODE_OF_CONDUCT.md` (Contributor Covenant 2.1), `SECURITY.md`, issue forms for bug reports
40
+ and feature requests, a pull-request template, and `CITATION.cff` with a "Citing" section in the README.
41
+
42
+ ### Deprecated
43
+ - `AdaptiveMMConfig` is now `AdaptiveConfig`, named like every other config (`NoiseConfig`, `AvellanedaStoikovConfig`, ...). The old name still works and warns.
44
+ - `TimeSeries.spr` and `TimeSeries.imb` are now `TimeSeries.spread` and `TimeSeries.imbalance`, matching the keys of `TimeSeries.as_dict()`. The old attributes still work and warn. Constructing a `TimeSeries` with the keywords `spr=` or `imb=` no longer works.
45
+
46
+ All deprecated names will be removed in 2.0.
47
+
48
+ ### Fixed
49
+ - `hill_tail_index` returned a division-by-zero error instead of NaN when the largest values in the tail were all
50
+ equal, as happens with returns of prices on a coarse tick grid.
51
+
52
+ ### Removed
53
+ - `microbook.sim.metrics.spread`, a wrapper around `LimitOrderBook.spread()`; use the method.
54
+ - `microbook.sim.agents.poisson` is now private (`_poisson`). It is an internal sampler, not part of the API.
55
+
56
+ ## 0.4.0
57
+
58
+ Replays historical data, adds a reinforcement-learning environment and a browser demo, and completes the realistic market: it now reproduces order-sign memory and square-root impact as well.
59
+
60
+ ### Added
61
+ - **Historical replay** (`microbook.replay`): LOBSTER message/orderbook readers and writer, `HistoricalFlow` (replays messages into a `MarketSimulator`, so any strategy can trade against real order flow), `build_replay`, and `check_reconstruction` (rebuilt book vs the recorded snapshot after every message). A strategy is filled when history reaches its queue position, and the historical book is corrected so passive strategies leave it intact.
62
+ - `synthetic_day()`: LOBSTER-format days from an independent FIFO reference model, for trying the pipeline and testing without licensed data. Reconstruction of these is exact.
63
+ - `LimitOrderBook.reduce(order_id, qty)` (cancel-by-size, keeps priority) and `Action.reduce`. Covered by the model-based differential test.
64
+ - `Strategy.same_time_timers`: lets a strategy schedule a timer at the current time (used by the replay to apply one message per wake-up).
65
+ - `examples/replay_lobster.py`.
66
+ - **Reinforcement learning** (`microbook.rl.MarketMakingEnv`, optional extra `[rl]`): a Gymnasium environment for market making in the closed-loop market, passing Gymnasium's environment checker. `examples/rl_market_making.py` trains a linear policy with the cross-entropy method; on held-out seeds it matches the hand-written `MarketMaker` rule.
67
+ - Tests: 146 → 172 (replay, RL environment, `reduce` in the model-based test, order-sign memory and impact of the realistic preset).
68
+ - Release workflow: tag `vX.Y.Z` to build, check and publish to PyPI (trusted publishing) and create a GitHub release.
69
+ - **Browser demo** (`docs/demo/`, published to GitHub Pages by `.github/workflows/pages.yml`): the Market Maker Playground runs the simulator client-side with Pyodide in a Web Worker. You choose the market, the market maker, latency and informed flow, and it charts price vs fundamental, PnL, inventory and markouts. Light and dark themes, keyboard-accessible charts and a data table view.
70
+ - Optional native build: `HATCH_BUILD_HOOK_ENABLE_MYPYC=true pip install ...` compiles the engine with mypyc (throughput 521k → 597k msg/s; 10–20% end to end). Off by default; CI tests the compiled wheel on Python 3.10 and 3.13.
71
+
72
+ ### Changed
73
+ - **`MarketConfig.realistic()` now reproduces the two facts 0.3 missed.** Order-sign autocorrelation decays as `lag^-0.52` (0.39 / 0.31 / 0.05 / 0.02 at lags 1 / 10 / 100 / 1000; was 0.16 / 0.12 / 0.01 / 0.00), and the impact prefactor is `Y = 0.49 ± 0.02` (was 0.08), with a concave impact curve (exponent 0.51). Metaorders now split into 2-share children sent every step (`MetaorderConfig(rate=0.03, size_alpha=1.4, child_qty=2, child_rate=1.0)`), informed arrivals are less frequent (`rate=0.3`) and noise orders cancel faster (`cancel_prob=0.03`). Return statistics hold: Hill index 2.7, lag-1 autocorrelation of 100-step returns −0.01, volatility clustering unchanged. Runs with the preset are not reproducible across 0.3 → 0.4.
74
+ - Known limitation: Y scales with metaorder execution speed in this model, unlike real markets.
75
+ - `LimitOrderBook`: the market-order stop key is an integer sentinel instead of `-inf` (needed by mypyc; no behaviour change).
76
+
77
+ ## 0.3.0
78
+
79
+ Makes the closed-loop market statistically realistic and adds the tools to check it.
80
+
81
+ ### Added
82
+ - `microbook.stylized`: return sampling, autocorrelation, excess kurtosis, Hill tail index, aggressor-sign series, power-law fits, metaorder impact curves and a one-call `stylized_facts()` summary. The functions are pure and work on plain sequences, so they apply to historical data too.
83
+ - Stochastic volatility in `FundamentalValue` (`vol_of_vol`, `vol_persistence`): log-volatility is a mean-reverting AR(1), normalized so the average variance is unchanged. With `vol_of_vol=0` the path is identical to 0.2.
84
+ - `HawkesProcess` / `HawkesConfig`: self-exciting noise market orders (`NoiseConfig.market_hawkes`) at the same mean rate.
85
+ - `MetaorderTrader` / `MetaorderConfig`: institutions splitting Pareto-sized orders into child market orders. Completed metaorders are exposed as `Market.metaorders` for impact measurement.
86
+ - `InformedConfig.qty_per_tick` / `max_qty`: informed trade size can scale with the mispricing.
87
+ - `MarketConfig.realistic()`: a calibrated preset with all of the above. It reproduces fat tails (Hill index ≈ 3), aggregational Gaussianity, near-zero return autocorrelation and volatility clustering.
88
+ - `examples/stylized_facts.py` and `docs/figures/stylized_facts.png`.
89
+ - Dependabot updates for GitHub Actions and pip.
90
+ - Tests: 121 → 146.
91
+
92
+ ### Known gaps
93
+ - Order-sign autocorrelation decays faster than the empirical `lag^-0.5`.
94
+ - Metaorder impact is about six times below the square-root law (`Y ≈ 0.08` vs 0.5–1).
95
+
96
+ ## 0.2.0
97
+
98
+ A rewrite of the matching engine and a major extension of the simulator.
99
+
100
+ ### Fixed
101
+ - **Duplicate order ids** orphaned the earlier order (still matchable, no longer cancelable). They are now rejected.
102
+ - **`modify()` that crossed the spread discarded its fills**, so trades never reached portfolios or metrics. Fills are now returned in the `ExecutionReport` and attributed by the simulator.
103
+ - **Invalid `modify()` destroyed the order** (e.g. `new_qty=-3` cancelled it, then returned `False`). Requests are validated first and rejections leave the order untouched.
104
+ - A no-op `modify()` (same price and quantity) lost queue priority.
105
+ - **Fees were deducted from cash but missing from mark-to-market PnL.**
106
+ - **Slippage vs arrival was diluted** by fills without a registered arrival mid (the denominator used all fills). Spread capture had the same defect.
107
+ - `TWAPExecutor` traded into a one-sided book and recorded an arrival mid of `0.0`, producing slippage of about 100.
108
+ - **`AdaptiveMarketMaker` "skew" widened or narrowed the spread instead of shifting it.** When short it quoted a crossed market (bid above ask), and the imbalance lean had the wrong sign.
109
+ - Bid-level insertion copied the whole price list on every insert, and cancel rebuilt the whole queue (O(n)).
110
+ - `SimResult.pnl_series` did not exist unless a SNAPSHOT event had fired.
111
+ - `examples/run_mm_vs_flow.py` had a syntax error.
112
+
113
+ ### Added
114
+ - Integer tick grid (`LimitOrderBook(tick_size=...)`); off-grid prices are rejected.
115
+ - Order types and time-in-force: `MARKET`, `LIMIT` × `GTC` / `IOC` / `FOK`, plus `post_only`.
116
+ - Self-trade prevention (`STPMode.CANCEL_RESTING` / `CANCEL_INCOMING`), keyed on `Order.owner`.
117
+ - `submit()` returning an `ExecutionReport` (status, fills, resting / cancelled quantity, reason).
118
+ - Book queries: `spread`, `microprice`, `queue_ahead`, `volume_at`, `get_order`, `check_invariants`.
119
+ - Simulator: order-entry **latency** per strategy, strategy **timers**, `on_start` / `on_fill` / `on_report` hooks, unique-name validation, `schedule_snapshots`, mid-price path, and inventory series.
120
+ - Closed-loop market agents: `FundamentalValue`, `NoiseTrader` (zero-intelligence), `InformedTrader`; `build_market()` scenario.
121
+ - `AvellanedaStoikovMarketMaker` (finite and rolling horizon) and the `TwoSidedQuoter` base class.
122
+ - Analytics: markouts, PnL statistics (drawdown, Sharpe), inventory statistics, `strategy_report`, `format_table`.
123
+ - Maker/taker fee schedule in `Portfolio`.
124
+ - Tests: model-based differential testing against a reference book (Hypothesis), property tests for PnL accounting, zero-sum and determinism checks (38 → 121 tests).
125
+ - Tooling: hatchling build, ruff, mypy `--strict`, coverage, and GitHub Actions CI on Python 3.10–3.13.
126
+
127
+ ### Changed (breaking)
128
+ - `LimitOrderBook.modify()` returns an `ExecutionReport` instead of `bool`; use `.accepted`.
129
+ - Market orders are `Order.market(...)` / `order_type=OrderType.MARKET`. The `setattr(order, "_is_market", True)` hack no longer works (`Order` uses slots).
130
+ - `place_limit` / `place_market` raise `OrderRejected` when the book refuses an order.
131
+ - `Fill` and `ExecutionReport` are `NamedTuple`s. Construction is about 2× faster than frozen dataclasses on the matching hot path.
132
+ - `Portfolio.fee_per_share` is replaced by `maker_fee` / `taker_fee`; `mark_to_market` is now net of fees.
133
+ - `MarketMaker.tick_size` and `AdaptiveMMConfig.tick_size` default to the book's tick (was `1.0`).
134
+ - Market makers are post-only and never quote through the opposite touch; unchanged quotes keep their queue priority.
135
+ - Spread capture is measured against the **pre-trade** mid (was the post-trade mid).
136
+ - `MarketSimulator()` with no book now uses self-trade prevention (`CANCEL_RESTING`).
137
+ - `MarketSimulator.run()` accumulates into `sim.result` across calls.
138
+ - `Strategy.on_fills` (an unused stub) is replaced by `on_fill`; `_next_ts` is replaced by `next_order_id`.
139
+ - Removed `microbook.sim.runner` (use `MarketSimulator.schedule_snapshots`) and the empty `microbook.matching`.
140
+ - Examples and benchmarks moved out of the installed package into `examples/` and `benchmarks/`.
141
+
142
+ ### Performance
143
+ On a realistic message mix (55% adds, 35% cancels, 10% aggressive), Apple M2, Python 3.12:
144
+ throughput 139k → 484k msg/s; cancel p50 13.8 µs → 0.5 µs.
@@ -0,0 +1,24 @@
1
+ cff-version: 1.2.0
2
+ message: "If you use microbook in your research, please cite it as below."
3
+ type: software
4
+ title: "microbook: a price-time priority matching engine and event-driven market microstructure simulator"
5
+ abstract: >-
6
+ A price-time priority limit order book and an event-driven market simulator
7
+ for studying liquidity provision, execution quality and adverse selection, in
8
+ pure Python. It includes a closed-loop market of noise, informed and metaorder
9
+ traders that reproduces the stylized facts of real markets, historical replay
10
+ of LOBSTER data, and a reinforcement-learning environment for market making.
11
+ authors:
12
+ - given-names: "Alex Chidera"
13
+ family-names: "Umeasalugo"
14
+ version: "1.0.0"
15
+ license: MIT
16
+ repository-code: "https://github.com/Space-Paragon1/Market-Microstructure-Simulator"
17
+ url: "https://space-paragon1.github.io/Market-Microstructure-Simulator/"
18
+ keywords:
19
+ - market microstructure
20
+ - limit order book
21
+ - matching engine
22
+ - market making
23
+ - agent-based simulation
24
+ - stylized facts
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alex Chidera Umeasalugo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.