cleolob 0.3.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,27 @@
1
+ Metadata-Version: 2.4
2
+ Name: cleolob
3
+ Version: 0.3.0
4
+ Summary: Reproducible limit-order-book execution research laboratory
5
+ Requires-Python: >=3.11
6
+ License-File: LICENSE
7
+ Requires-Dist: numpy>=1.26
8
+ Requires-Dist: pandas>=2.0
9
+ Requires-Dist: gymnasium>=0.29
10
+ Requires-Dist: pydantic>=2.0
11
+ Requires-Dist: PyYAML>=6.0
12
+ Provides-Extra: rl
13
+ Requires-Dist: stable-baselines3>=2.3; extra == "rl"
14
+ Requires-Dist: tensorboard>=2.16; extra == "rl"
15
+ Provides-Extra: plots
16
+ Requires-Dist: plotly>=5.20; extra == "plots"
17
+ Provides-Extra: web
18
+ Requires-Dist: fastapi>=0.110; extra == "web"
19
+ Requires-Dist: uvicorn>=0.29; extra == "web"
20
+ Requires-Dist: plotly>=5.20; extra == "web"
21
+ Requires-Dist: streamlit>=1.35; extra == "web"
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest>=8.0; extra == "dev"
24
+ Requires-Dist: ruff>=0.9; extra == "dev"
25
+ Requires-Dist: build>=1.2; extra == "dev"
26
+ Requires-Dist: wheel>=0.44; extra == "dev"
27
+ Dynamic: license-file
@@ -0,0 +1,46 @@
1
+ cleolob-0.3.0.dist-info/licenses/LICENSE,sha256=46mU2C5kSwOnkqkw9XQAJlhBL2JAf1_uCD8lVcXyMRg,7652
2
+ lob/__init__.py,sha256=kLQagXFAWt_wHpvFmjPQ1DU6RotTdxr5tiuBQBx6oyg,1005
3
+ lob/__main__.py,sha256=SUwyY45wT1IsqUILKZWA9lZqyEY6VugRVAK3nthPOhI,1370
4
+ lob/accounting.py,sha256=kv-egaontwnAkSqYpDAP8wCA3yh8nQYIPmzCc3c52xQ,5330
5
+ lob/artifacts.py,sha256=oojAC8rSH5Z2GHfiJtEtXvHgn7prUxL9LQEiH2vwrRU,3768
6
+ lob/benchmarks.py,sha256=ShkboOVH4anhnr7Ao0fyAKQPqEeePM-BukBoQKk2K_k,2060
7
+ lob/calibration.py,sha256=TGg6WsrYU00KPJm-TEs0CezEvK5nT6pPo5uEGVOLE5U,26223
8
+ lob/cli.py,sha256=M-zD3bWysj0TahR5CpeQARWy2wg63N8kOhrF_sCJm70,14630
9
+ lob/config.py,sha256=THgL_OqWx0jDYnc3ZPppc-uqOvXK4CBQFAq3ddVKQw0,18702
10
+ lob/controls.py,sha256=rn3L0nx01-Z4byTNnUdnl1uxk2drmy5OedRFr0RrNr4,35752
11
+ lob/core_study.py,sha256=YkuZae3M2QDaB0RSVrzbCea9Bq5xItkF6AlAnKo24Pg,36700
12
+ lob/data_download.py,sha256=D8boSbkTlW-7ljOqGCb4AVDo4x3jOR6XHaSYIta6Fj0,10678
13
+ lob/engine.py,sha256=uWw8FyGPuPeu87y7ppqno9cRM0CVbN6WCg_us8BpQ0s,35433
14
+ lob/execution.py,sha256=YKKXdlX6yxI8lpn5dTPd-O_cvE2Brfa87UOqOfJYiHs,22168
15
+ lob/generalization.py,sha256=LJNWm515KZmlQSiPtWBanV86dnCYsCG3ilucBuX63EY,31958
16
+ lob/mbo.py,sha256=2nzd0T7wUYmY5e_S3TBlhN2v0K2p6EfsVfWP6jdxO-o,27271
17
+ lob/performance.py,sha256=0BSQFMTVgUYXI7Fat2ciJdU8gASkFMpr2BKjbxhHD0E,12602
18
+ lob/policy_study.py,sha256=mbje4a5jZgb-PuJtAXNSMH9bFW_8zyO70TSeFWBY-c8,29100
19
+ lob/portfolio.py,sha256=P6iMtHmdZd6xT6FHSTuC_KclvbXEkA8VCO_t0w8Dc10,40068
20
+ lob/risk.py,sha256=QxB7FZskS6P9ADrcINj9ArmYFTK3uJQXDvyTZD84wFA,7463
21
+ lob/rl_env.py,sha256=IsNTmmf6ekzAET7VwF9pY7OA7bfFmpq_KRiH1s2gYaQ,15721
22
+ lob/robustness.py,sha256=7k0B_Oqe6d3SQ3WVKknn6JoXFc1YRNpAvhev8FMoOmw,20238
23
+ lob/runner.py,sha256=TD_x7AVaDrF2nflzv4kAqkZHQVqynN4AxXYe9i16xNM,17669
24
+ lob/scenarios.py,sha256=-Mm6gJeXV-cthutFUfKtpzIWgSDJT1WAG1InNV605h4,2312
25
+ lob/settlement.py,sha256=LwBEyA0wAkL2FGxv18oKwqxSZWF0uJuOLiWsmevCd0w,3599
26
+ lob/smoke.py,sha256=sENs0c_a6bJl1c9_fcJSW-oQIAxdNwaEz5czttxGlOI,4481
27
+ lob/stats.py,sha256=mUStYp8-Sb8bsIGpKdVYSykJAqeqFTdskvd8RFxjwMQ,7683
28
+ lob/zi_calibration.py,sha256=Kw5r0YmpNVFWQdB5RBW9zQjVYkudegjarDvnT89tdV0,33689
29
+ lob/experiments/__init__.py,sha256=vWJxKzvE-54LIa_vaH5DYfW6Id23UkUpx3CULpcpuHA,272
30
+ lob/experiments/design.py,sha256=aADmUjHwM8vZOHsapGUAPNqOOolW4IT_4qVaZxRUBAM,3214
31
+ lob/experiments/registry.py,sha256=bMYneBYORjghzsscIrEUoAlU2jLkblUKRvH78A5dTIA,6616
32
+ lob/experiments/report.py,sha256=9AelEsR7k--b6N4_6_Eg2OTxf2BbcbVn0nJYXzD5Nq8,4521
33
+ lob/experiments/runner.py,sha256=7SknjGIRlNwx9WLBZ6i3CdP_I2bDs9lG1GptwihokDA,9340
34
+ lob/replay/__init__.py,sha256=FEA8Szv_HYvlfc1HDLvnA0Bq-JBWrv-5R7DHUQ9RRqY,788
35
+ lob/replay/assessment.py,sha256=bhODjCbPOGVx4_JNCHlCDg954QXrqLQaBLcld8Mkv3c,18083
36
+ lob/replay/book.py,sha256=3_VNpi19qPstp6Oy4vrNibIF_ioRMjNouw_ry7bwp7k,10559
37
+ lob/replay/engine.py,sha256=rypSH86J_78Xc677D37xOBmwIOYG57-Efu5w1PpXGHw,5072
38
+ lob/replay/io.py,sha256=IqfuZg2JAMV8xAr6Wqgynoaut1d94vMdwwaWmXaHzXY,6023
39
+ lob/replay/l2.py,sha256=-Khmq3AlgWrngUYMm7ghfFo5pC2vLLhuEeLwkXTB9dI,15261
40
+ lob/replay/schema.py,sha256=rHp-J3tf1RMMq8eUQ8uWBNKrfmhf_sQzDajbsFq4HWI,8851
41
+ lob/replay/validation.py,sha256=NLrDPtbE6_zieO7sdLUWcmEOLTpy8canJv7mDUus2tY,4951
42
+ cleolob-0.3.0.dist-info/METADATA,sha256=qrvlzLotmNQxTy8rLpg58rlz-nYs5aUvf6CTS2iZUYo,908
43
+ cleolob-0.3.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
44
+ cleolob-0.3.0.dist-info/entry_points.txt,sha256=ckRiGiIehwCpTTOt9OuAjm2aZCEePIDJioFoYo2GX8s,38
45
+ cleolob-0.3.0.dist-info/top_level.txt,sha256=03AhYCqqQXsQbWcycTfD6w5A6fZUmw510oEdHKjr0AY,4
46
+ cleolob-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ cleo = lob.cli:main
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
@@ -0,0 +1 @@
1
+ lob
lob/__init__.py ADDED
@@ -0,0 +1,17 @@
1
+ """LOB Execution Lab — event-driven limit order book simulation and optimal execution."""
2
+ from .engine import ExchangeSimulator, Order, OrderBook, OrderStatus, OrderType, Side, SimConfig, TimeInForce, Trade
3
+ from .accounting import FeeConfig, Ledger
4
+ from .risk import ExecutionRisk, RiskConfig
5
+ from .execution import (AlmgrenChrissAgent, ExecutionAgent, ExecutionReport, POVAgent,
6
+ ScheduleAgent, TWAPAgent, VWAPAgent, build_report,
7
+ estimate_volume_profile)
8
+ from .rl_env import LOBExecutionEnv
9
+ from .scenarios import SCENARIOS, scenario_params
10
+
11
+ __all__ = [
12
+ "ExchangeSimulator", "Order", "OrderBook", "OrderType", "Side", "SimConfig", "Trade",
13
+ "OrderStatus", "TimeInForce", "FeeConfig", "Ledger", "RiskConfig", "ExecutionRisk",
14
+ "ExecutionAgent", "ScheduleAgent", "TWAPAgent", "VWAPAgent", "AlmgrenChrissAgent",
15
+ "POVAgent", "ExecutionReport", "build_report", "estimate_volume_profile",
16
+ "LOBExecutionEnv", "SCENARIOS", "scenario_params",
17
+ ]
lob/__main__.py ADDED
@@ -0,0 +1,29 @@
1
+ """Smoke test: 10 simulated seconds of background flow, then a liquidity shock."""
2
+ from __future__ import annotations
3
+
4
+ from .engine import ExchangeSimulator, Order, OrderType, Side, SimConfig
5
+
6
+ if __name__ == "__main__":
7
+ sim = ExchangeSimulator(SimConfig())
8
+ for _ in range(300):
9
+ sim.step(0.1)
10
+ ts = sim.cfg.tick_size
11
+ bids, asks = sim.book.depth(5)
12
+ print(f"[t={sim.t:.0f}s] trades={len(sim.book.trades)} mid={sim.book.mid() * ts:.2f} "
13
+ f"spread={sim.book.spread()} tick(s)")
14
+ print(" bids:", [(round(p * ts, 2), v) for p, v in bids])
15
+ print(" asks:", [(round(p * ts, 2), v) for p, v in asks])
16
+
17
+ # Liquidity shock: 3,000-share market sell, then watch resilience refill the bid side.
18
+ mid_before = sim.book.mid()
19
+ trades = sim.book.process(Order(10**9, Side.SELL, 3000, OrderType.MARKET, "DEMO", sim.t),
20
+ sim.t)
21
+ vwap = sum(t.price * t.qty for t in trades) / sum(t.qty for t in trades)
22
+ print(f"\n[shock] sold {sum(t.qty for t in trades):,} @ vwap {vwap * ts:.4f} "
23
+ f"(mid was {mid_before * ts:.4f} -> slippage "
24
+ f"{(mid_before - vwap) / mid_before * 1e4:.1f} bps)")
25
+ for k in range(1, 4):
26
+ sim.step(2.0)
27
+ bids, _ = sim.book.depth(3)
28
+ print(f"[t=+{2 * k}s] best bids after refill:",
29
+ [(round(p * ts, 2), v) for p, v in bids])
lob/accounting.py ADDED
@@ -0,0 +1,115 @@
1
+ """Owner-specific cash, inventory, fees and average-cost PnL accounting.
2
+
3
+ Prices accepted by the ledger are currency. Trade prices remain integer ticks.
4
+ Fees are recognised when a fill occurs; maker rebates may be negative. Initial
5
+ inventory is endowed at its stated cost basis, never recorded as trading profit.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ from dataclasses import asdict, dataclass
11
+ from typing import Any, Mapping
12
+
13
+ from .engine import Side, Trade
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class FeeConfig:
18
+ maker_bps: float = 0.0
19
+ taker_bps: float = 0.0
20
+ per_share: float = 0.0
21
+
22
+ def __post_init__(self) -> None:
23
+ for name, value in asdict(self).items():
24
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
25
+ raise ValueError(f"{name} must be finite")
26
+ if self.per_share < 0 or self.taker_bps < 0:
27
+ raise ValueError("per_share and taker_bps must be nonnegative")
28
+
29
+ def charge(self, price: float, qty: int, *, maker: bool = False) -> float:
30
+ if not math.isfinite(price) or price < 0 or isinstance(qty, bool) or not isinstance(qty, int) or qty < 0:
31
+ raise ValueError("fee price and integer quantity must be finite and nonnegative")
32
+ return price * qty * (self.maker_bps if maker else self.taker_bps) / 1e4 + qty * self.per_share
33
+
34
+
35
+ def fee_config(value: FeeConfig | Mapping[str, Any] | None) -> FeeConfig:
36
+ return value if isinstance(value, FeeConfig) else FeeConfig(**dict(value or {}))
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class AccountSnapshot:
41
+ cash: float
42
+ inventory: int
43
+ average_cost: float
44
+ gross_realized_pnl: float
45
+ unrealized_pnl: float
46
+ total_fees: float
47
+ realized_pnl: float
48
+ equity: float
49
+ total_pnl: float
50
+
51
+
52
+ class Ledger:
53
+ """A single owner's signed position using moving-average cost basis."""
54
+
55
+ def __init__(self, *, inventory: int = 0, average_cost: float = 0.0,
56
+ cash: float = 0.0, fees: FeeConfig | Mapping[str, Any] | None = None) -> None:
57
+ if isinstance(inventory, bool) or not isinstance(inventory, int):
58
+ raise ValueError("inventory must be an integer")
59
+ if not math.isfinite(average_cost) or average_cost < 0 or not math.isfinite(cash):
60
+ raise ValueError("initial cash and cost basis must be finite; basis must be nonnegative")
61
+ if inventory and average_cost <= 0:
62
+ raise ValueError("nonzero initial inventory requires a positive cost basis")
63
+ self.inventory = inventory
64
+ self.average_cost = float(average_cost) if inventory else 0.0
65
+ self.cash = float(cash)
66
+ self.initial_equity = self.cash + inventory * self.average_cost
67
+ self.fees = fee_config(fees)
68
+ self.total_fees = 0.0
69
+ self.gross_realized_pnl = 0.0
70
+ self.filled_qty = 0
71
+
72
+ def apply_fill(self, side: Side, price: float, qty: int, *, maker: bool = False) -> float:
73
+ if not isinstance(side, Side) or isinstance(qty, bool) or not isinstance(qty, int) or qty <= 0:
74
+ raise ValueError("fill side and positive integer quantity required")
75
+ if not math.isfinite(price) or price <= 0:
76
+ raise ValueError("fill price must be positive and finite")
77
+ signed_qty = side.value * qty
78
+ old = self.inventory
79
+ updated = old + signed_qty
80
+ if old == 0 or old * signed_qty > 0:
81
+ self.average_cost = (abs(old) * self.average_cost + qty * price) / abs(updated)
82
+ else:
83
+ closing = min(abs(old), qty)
84
+ self.gross_realized_pnl += closing * (price - self.average_cost) * (1 if old > 0 else -1)
85
+ if updated == 0:
86
+ self.average_cost = 0.0
87
+ elif old * updated < 0:
88
+ self.average_cost = price
89
+ fee = self.fees.charge(price, qty, maker=maker)
90
+ self.inventory = updated
91
+ self.cash -= signed_qty * price + fee
92
+ self.total_fees += fee
93
+ self.filled_qty += qty
94
+ return fee
95
+
96
+ def apply_trade(self, trade: Trade, owner: str, tick_size: float) -> float:
97
+ if tick_size <= 0 or not math.isfinite(tick_size):
98
+ raise ValueError("tick_size must be positive and finite")
99
+ taker, maker = trade.taker_owner == owner, trade.maker_owner == owner
100
+ if taker == maker:
101
+ raise ValueError("trade must identify owner on exactly one side")
102
+ side = trade.taker_side if taker else trade.taker_side.opposite
103
+ return self.apply_fill(side, trade.price * tick_size, trade.qty, maker=maker)
104
+
105
+ def snapshot(self, mark: float) -> AccountSnapshot:
106
+ if not math.isfinite(mark) or mark < 0:
107
+ raise ValueError("mark must be finite and nonnegative")
108
+ unrealized = self.inventory * (mark - self.average_cost)
109
+ equity = self.cash + self.inventory * mark
110
+ pnl = self.gross_realized_pnl + unrealized - self.total_fees
111
+ if not math.isclose(equity - self.initial_equity, pnl, abs_tol=1e-7, rel_tol=1e-10):
112
+ raise ArithmeticError("cash/inventory PnL identity failed")
113
+ return AccountSnapshot(self.cash, self.inventory, self.average_cost,
114
+ self.gross_realized_pnl, unrealized, self.total_fees,
115
+ self.gross_realized_pnl - self.total_fees, equity, pnl)
lob/artifacts.py ADDED
@@ -0,0 +1,82 @@
1
+ """Compact, portable research evidence; no absolute machine paths in metadata."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import platform
8
+ import subprocess
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from .config import canonical_json
13
+ from .experiments.registry import PROJECT_ROOT, runtime_metadata, sha256_file, source_manifest, write_json
14
+
15
+
16
+ def portable_provenance() -> dict[str, Any]:
17
+ runtime = runtime_metadata()
18
+ runtime.pop("executable", None)
19
+ runtime["cpu"] = platform.processor() or os.environ.get("PROCESSOR_IDENTIFIER", "unknown")
20
+ runtime["logical_cpu_count"] = os.cpu_count()
21
+ if os.name == "nt":
22
+ try:
23
+ import winreg
24
+ with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
25
+ r"HARDWARE\DESCRIPTION\System\CentralProcessor\0") as key:
26
+ runtime["cpu"] = winreg.QueryValueEx(key, "ProcessorNameString")[0].strip()
27
+ except OSError:
28
+ pass
29
+ commit, dirty = None, None
30
+ try:
31
+ commit = subprocess.check_output(
32
+ ["git", "rev-parse", "HEAD"], cwd=PROJECT_ROOT, text=True,
33
+ stderr=subprocess.DEVNULL, timeout=5).strip()
34
+ dirty = bool(subprocess.check_output(
35
+ ["git", "status", "--porcelain"], cwd=PROJECT_ROOT, text=True,
36
+ stderr=subprocess.DEVNULL, timeout=5).strip())
37
+ except (OSError, subprocess.SubprocessError):
38
+ pass
39
+ source = source_manifest()
40
+ return {"git_commit": commit, "git_dirty": dirty, "runtime": runtime,
41
+ "source_files": source,
42
+ "source_sha256": hashlib.sha256(canonical_json(source).encode()).hexdigest()}
43
+
44
+
45
+ def seal_artifacts(root: str | Path) -> dict:
46
+ root = Path(root).resolve(strict=True)
47
+ files = {}
48
+ for path in sorted(root.rglob("*")):
49
+ if path.is_symlink():
50
+ raise ValueError("artifact symlinks are not supported")
51
+ if path.is_file() and path != root / "checksums.json":
52
+ files[path.relative_to(root).as_posix()] = sha256_file(path)
53
+ if not files:
54
+ raise ValueError("cannot seal an empty artifact")
55
+ result = {"format": "cleolob-compact-v1", "algorithm": "sha256", "files": files}
56
+ write_json(root / "checksums.json", result)
57
+ return result
58
+
59
+
60
+ def verify_artifacts(root: str | Path) -> dict:
61
+ root = Path(root).resolve(strict=True)
62
+ manifest = json.loads((root / "checksums.json").read_text(encoding="utf-8"))
63
+ if (manifest.get("format") != "cleolob-compact-v1" or manifest.get("algorithm") != "sha256"
64
+ or not isinstance(manifest.get("files"), dict) or not manifest["files"]):
65
+ raise ValueError("unsupported or empty artifact manifest")
66
+ issues = []
67
+ actual = {p.relative_to(root).as_posix() for p in root.rglob("*")
68
+ if p.is_file() and p != root / "checksums.json"}
69
+ if actual != set(manifest["files"]):
70
+ issues.append("artifact file set changed")
71
+ for name, digest in manifest["files"].items():
72
+ target = root / name
73
+ # Require canonical portable relative names, even when reading on Windows.
74
+ if (not name or "\\" in name or ":" in name or name.startswith("/")
75
+ or any(part in {"", ".", ".."} for part in name.split("/"))
76
+ or not target.resolve().is_relative_to(root)
77
+ or target.is_symlink() or any(p.is_symlink() for p in target.parents if p != root)):
78
+ issues.append(f"unsafe artifact: {name}")
79
+ elif not target.is_file() or sha256_file(target) != digest:
80
+ issues.append(f"checksum mismatch: {name}")
81
+ return {"valid": not issues, "issues": issues, "files": len(manifest["files"]),
82
+ "meaning": "byte integrity only; not independent scientific validation"}
lob/benchmarks.py ADDED
@@ -0,0 +1,42 @@
1
+ """Measured local throughput; correctness checks bracket each timed workload."""
2
+ from __future__ import annotations
3
+
4
+ import platform
5
+ import statistics
6
+ import time
7
+ import tracemalloc
8
+ from typing import Any
9
+
10
+ from .engine import Order, OrderBook, OrderType, Side
11
+
12
+
13
+ def benchmark_matching(pairs: int = 2000, repeats: int = 3) -> dict[str, Any]:
14
+ if not 1 <= pairs <= 100_000 or not 1 <= repeats <= 10:
15
+ raise ValueError("pairs must be 1..100000 and repeats 1..10")
16
+ rates = []
17
+ for _ in range(repeats):
18
+ book = OrderBook()
19
+ started = time.perf_counter()
20
+ for index in range(pairs):
21
+ now = float(index)
22
+ book.process(Order(2 * index + 1, Side.SELL, 10, OrderType.LIMIT, "maker", now, price=10001), now)
23
+ book.process(Order(2 * index + 2, Side.BUY, 10, OrderType.MARKET, "taker", now), now)
24
+ elapsed = time.perf_counter() - started
25
+ if len(book.trades) != pairs or book.orders:
26
+ raise AssertionError("matching benchmark failed fill/book reconciliation")
27
+ book.assert_invariants()
28
+ rates.append(2 * pairs / elapsed)
29
+ # Memory instrumentation changes timing; measure it in a separate untimed pass.
30
+ tracemalloc.start()
31
+ book = OrderBook()
32
+ for index in range(pairs):
33
+ book.process(Order(index + 1, Side.BUY, 10, OrderType.LIMIT, "maker", 0.0, price=10000), 0.0)
34
+ _, peak = tracemalloc.get_traced_memory()
35
+ tracemalloc.stop()
36
+ book.assert_invariants()
37
+ return {"workload": "alternating one resting limit and one fully matching market order",
38
+ "orders_per_repeat": 2 * pairs, "fills_per_repeat": pairs, "repeats": repeats,
39
+ "orders_per_second_median": statistics.median(rates), "orders_per_second_samples": rates,
40
+ "resting_orders_memory_count": pairs, "python_tracemalloc_peak_bytes": peak,
41
+ "python": platform.python_version(), "platform": platform.platform(),
42
+ "note": "Local Python microbenchmark, not full market throughput; no latency/agent/replay workload included."}