Coverage for scripts/profile_main_tick.py: 100%
149 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Time main.py's per-tick feature path outside Lean (V6.0.0, todo lead 7).
3`scripts/profile_subsystems.py` could not profile `main.py` ("it only runs inside Lean"), but the first-bar smoke test
4already builds the real algorithm against a permissive stub. This does the same, fills every symbol's windows from the real
5Lean zips, and then runs, for N timed days, what `on_data` runs per tick before inference:
7 topology payload (`_build_topology_payload`), macro / bond / alt-data / sensitivity-driver payloads, and
8 `_build_model_input` for every symbol
10reporting wall time per stage and (with --cprofile) the hottest functions. It is a micro-benchmark of the same code the
11Lean run executes, so a speed-up measured here is comparable with the TimingProbe stages of a backtest.
13 python scripts/profile_main_tick.py [--warm 300] [--days 20] [--cprofile] [--json PATH]
14"""
16from __future__ import annotations
18import argparse
19import cProfile
20import datetime
21import io
22import json
23import pstats
24import re
25import sys
26import types
27import zipfile
28from pathlib import Path
29from time import process_time as perf_counter # CPU time: a busy machine does not move it
30from unittest.mock import MagicMock
32ROOT_DIR = Path(__file__).resolve().parents[1]
33sys.path.insert(0, str(ROOT_DIR))
36class _PermissiveQCAlgorithm:
37 """Any PUBLIC attribute is a MagicMock (QCAlgorithm's surface is huge); private ones must be set by main.py."""
39 def __getattr__(self, name):
40 if name.startswith("_"):
41 raise AttributeError(name)
42 value = MagicMock(name=name)
43 object.__setattr__(self, name, value)
44 return value
47def build_algorithm(start: datetime.datetime):
48 """The real `AetherQuantAlgorithm`, initialised and `_ensure_ready()`-ed against the repository's config and ml/."""
49 import os
51 os.chdir(ROOT_DIR)
52 stub = types.ModuleType("AlgorithmImports")
53 stub.QCAlgorithm = _PermissiveQCAlgorithm
54 stub.Slice = object
55 stub.time = datetime.time
56 sys.modules["AlgorithmImports"] = stub
57 sys.modules.pop("main", None)
58 import main
60 algorithm = main.AetherQuantAlgorithm()
61 algorithm._write_state = lambda *args, **kwargs: None
62 algorithm.Debug = lambda message: None
63 algorithm.Log = lambda message: None
64 algorithm.Time = start
65 for _ in range(120):
66 try:
67 if "_initialized_once" not in algorithm.__dict__:
68 algorithm.initialize()
69 algorithm.__dict__["_initialized_once"] = True
70 algorithm._ensure_ready()
71 break
72 except NameError as error:
73 match = re.search(r"name '(\w+)' is not defined", str(error))
74 if not match:
75 raise
76 main.__dict__[match.group(1)] = MagicMock(name=match.group(1))
77 return algorithm
80def read_bars(config: dict, ticker_asset: dict) -> list[tuple[datetime.date, dict]]:
81 scale = 1.0 / 10_000.0 if ticker_asset["security_type"] == "equity" else 1.0
82 with zipfile.ZipFile(ROOT_DIR / ticker_asset["data_path"]) as archive:
83 member = next(name for name in archive.namelist() if name.endswith(".csv"))
84 lines = archive.read(member).decode("utf-8").splitlines()
85 bars = []
86 for line in lines:
87 fields = line.split(",")
88 day = datetime.date(int(fields[0][:4]), int(fields[0][4:6]), int(fields[0][6:8]))
89 volume = float(fields[5]) if len(fields) > 5 and ticker_asset["security_type"] != "forex" else 0.0
90 bars.append((day, {"open": float(fields[1]) * scale, "high": float(fields[2]) * scale, "low": float(fields[3]) * scale,
91 "close": float(fields[4]) * scale, "volume": volume}))
92 return bars
95def feed_day(algorithm, bars_by_symbol: dict, day: datetime.date) -> None:
96 """Append one day's bar of every symbol that has one, the way on_data's window block does."""
97 from main import ALT_DATA_PUBLICATION_LAG_DAYS, CROSS_ASSET_SENSITIVITY_DRIVERS, series_value_asof
99 drivers = algorithm.phase1.get("features", {}).get("cross_asset_sensitivity", {}).get("drivers", CROSS_ASSET_SENSITIVITY_DRIVERS)
100 lags = {**ALT_DATA_PUBLICATION_LAG_DAYS, **algorithm.phase1.get("features", {}).get("alt_data_publication_lag_days", {})}
101 levels = {key: series_value_asof(algorithm.fred_series.get(name, []), day, lags.get(name, 0)) for key, name in drivers.items()}
102 for symbol, by_day in bars_by_symbol.items():
103 bar = by_day.get(day)
104 if bar is None:
105 continue
106 algorithm.symbol_windows[symbol].append(bar)
107 algorithm.symbol_long_windows[symbol].append(bar["close"])
108 algorithm.symbol_treasury_10yr_history[symbol].append(None)
109 for key, history in algorithm.symbol_sensitivity_driver_history[symbol].items():
110 history.append(levels.get(key))
113def main() -> int:
114 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
115 parser.add_argument("--warm", type=int, default=300, help="days of history fed before timing (windows hold up to 260 bars)")
116 parser.add_argument("--days", type=int, default=20, help="timed days")
117 parser.add_argument("--end", default="2024-06-28", help="last timed day (a weekday inside every class's data)")
118 parser.add_argument("--repeat", type=int, default=1, help="repeat the timed days; the fastest repeat is reported")
119 parser.add_argument("--scalar-beta", action="store_true", help="A/B: force the pre-V6.0.0 scalar OLS in the sensitivity betas")
120 parser.add_argument("--cprofile", action="store_true")
121 parser.add_argument("--json", default=None)
122 args = parser.parse_args()
124 if args.scalar_beta:
125 import features.bond_features as bond_features
127 bond_features._VECTOR_BETA_MIN_LENGTH = 10**9
128 config = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8"))
129 end = datetime.date.fromisoformat(args.end)
130 algorithm = build_algorithm(datetime.datetime.combine(end, datetime.time(16, 0)))
131 assets = {str(asset["ticker"]): asset for asset in config["phase1"]["universe"]["assets"]}
132 symbol_by_ticker = {str(s): s for s in algorithm.symbols}
133 bars_by_symbol = {}
134 for key, symbol in symbol_by_ticker.items():
135 ticker = algorithm.asset_lookup[key]["ticker"]
136 bars_by_symbol[symbol] = dict(read_bars(config, assets[ticker]))
137 calendar = sorted({day for by_day in bars_by_symbol.values() for day in by_day if day <= end})
138 timed = calendar[-args.days:]
139 warm = calendar[-(args.days + args.warm):-args.days]
140 for day in warm:
141 feed_day(algorithm, bars_by_symbol, day)
143 best_stages = None
144 calls = 0
145 profiler = cProfile.Profile() if args.cprofile else None
146 if profiler:
147 profiler.enable()
148 for _repeat in range(max(1, args.repeat)):
149 stages = {"topology_payload": 0.0, "macro_bond_alt_payloads": 0.0, "build_model_input": 0.0}
150 calls = 0
151 for day in timed:
152 if _repeat == 0:
153 feed_day(algorithm, bars_by_symbol, day)
154 algorithm.Time = datetime.datetime.combine(day, datetime.time(16, 0))
155 started = perf_counter()
156 algorithm.latest_topology_payload = algorithm._build_topology_payload()
157 stages["topology_payload"] += perf_counter() - started
158 started = perf_counter()
159 algorithm.latest_macro_payload = algorithm._build_macro_payload()
160 algorithm.latest_bond_payload = algorithm._build_bond_payload()
161 algorithm.latest_alt_data_payload = algorithm._build_alt_data_payload()
162 algorithm.latest_sensitivity_driver_levels = algorithm._build_sensitivity_driver_levels()
163 stages["macro_bond_alt_payloads"] += perf_counter() - started
164 nodes = {node["symbol"]: node for node in algorithm.latest_topology_payload.get("nodes", [])}
165 started = perf_counter()
166 for symbol in algorithm.symbols:
167 if len(algorithm.symbol_windows[symbol]) >= 2:
168 algorithm._build_model_input(symbol, nodes.get(str(symbol)))
169 calls += 1
170 stages["build_model_input"] += perf_counter() - started
171 if best_stages is None or sum(stages.values()) < sum(best_stages.values()):
172 best_stages = stages
173 stages = best_stages
174 if profiler:
175 profiler.disable()
176 per_day = {name: 1000.0 * value / max(1, len(timed)) for name, value in stages.items()}
177 report = {"days": len(timed), "symbols": len(algorithm.symbols), "model_input_calls": calls,
178 "ms_per_day": per_day, "ms_per_model_input_call": 1000.0 * stages["build_model_input"] / max(1, calls)}
179 print(json.dumps(report, indent=1))
180 if profiler:
181 buffer = io.StringIO()
182 pstats.Stats(profiler, stream=buffer).sort_stats("cumulative").print_stats(28)
183 print(buffer.getvalue())
184 if args.json:
185 Path(args.json).write_text(json.dumps(report, indent=1), encoding="utf-8")
186 return 0
189if __name__ == "__main__":
190 raise SystemExit(main())