Coverage for scripts/profile_subsystems.py: 100%

210 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""cProfile + wall-clock harness for main.py's per-bar subsystems OTHER 

2than inference (see scripts/profile_inference.py for that one). 

3 

4A sibling of profile_inference.py, not an extension of it - the input 

5shapes are completely different per subsystem (dict-of-scalars vs. 

6dict-of-lists vs. flat feature vectors), and that file's own docstring 

7scopes it specifically to "the neural-net inference step." Shares its 

8percentile()/summarize_durations() helpers rather than duplicating them 

9(already unit-tested in tests/test_profile_inference.py). 

10 

11Covers, each pure and Lean-free by construction: 

12- regime -> regime/market_regime.py::build_market_regime_vector() 

13- topology -> topology/market_topology.py::build_market_topology() 

14- learned_topology -> topology/learned_topology.py::apply_learned_topology() 

15- liquidity -> liquidity/market_liquidity.py::build_liquidity_decision() 

16- gating -> moe/gating.py::build_gating_decision() 

17- analyzer -> analyzer/market_analyzer.py::build_market_analysis_decision() 

18- indicators -> the 7 pure functions in features/technical_indicators.py, 

19 each timed INDEPENDENTLY (not summed) so a dominant one 

20 is visible rather than averaged away 

21- options -> risk/asset_class_router.py::route_multi_leg_option_sizing() 

22 (V4.9 Priority 7) - a synthetic multi-strike/multi- 

23 expiry chain plus a representative strategy-name mix 

24 covering every shape family (including the always- 

25 skipped covered_protective/collar and the 

26 arbitrage_detector_enabled-gated arbitrage families, 

27 so the workload exercises route_multi_leg_option_sizing()'s 

28 own skip logic too, not just its selector dispatch), 

29 timing the whole per-bar dispatch loop end-to-end. 

30 Deliberately does NOT cover 

31 main.py::_build_options_chains_payload() - see the 

32 scope-decision paragraph below, same Lean-only 

33 constraint _build_model_input() itself has. 

34 

35Deliberate scope decision: main.py::_build_model_input() itself is NOT 

36profiled here. Confirmed harder than "not cleanly synthesizable" (the 

37original framing) - main.py does `from AlgorithmImports import *` at 

38module level, and `class AetherQuantAlgorithm(QCAlgorithm)` fails 

39`NameError: name 'QCAlgorithm' is not defined` when imported outside a 

40real Lean process (`AlgorithmImports` resolves to an empty stub locally, 

41just enough for IDE linting, not a usable `QCAlgorithm` base class) - so 

42there is no way to construct even a bare, `__new__`-only instance of the 

43class from a plain host-side script, let alone profile a bound method on 

44one. Profiling its underlying pure indicator primitives (the 

45`indicators` workload above) instead is a documented partial-coverage 

46choice, not silent scope-narrowing. The only way to measure this method 

47for real is in-process instrumentation during an actual `lean backtest .` 

48run - see development/Problems.md's #16/#17 side-channel-log precedent 

49and the entry for this specific method. 

50 

51Usage: 

52 python scripts/profile_subsystems.py [--iterations N] [--sort cumulative] 

53 [--regime] [--topology] [--learned-topology] [--liquidity] 

54 [--gating] [--analyzer] [--indicators] [--options] 

55 (no subsystem flags -> profiles all of them) 

56 

57Writes a pstats dump (plus tail-latency report) per subsystem to 

58scripts/profile_subsystems_output.txt (overwritten each run) and prints 

59both to stdout. 

60""" 

61 

62from __future__ import annotations 

63 

64import argparse 

65import cProfile 

66import pstats 

67import random 

68import sys 

69import time 

70from pathlib import Path 

71 

72ROOT_DIR = Path(__file__).resolve().parent.parent 

73sys.path.insert(0, str(ROOT_DIR)) 

74 

75from analyzer import build_market_analysis_decision # noqa: E402 

76from features.technical_indicators import ( # noqa: E402 

77 average_true_range_pct, 

78 bollinger_pctb, 

79 cross_sectional_momentum_rank, 

80 distance_from_52w_high, 

81 macd_histogram_normalized, 

82 relative_strength_index, 

83 volume_zscore, 

84) 

85from liquidity import build_liquidity_decision # noqa: E402 

86from moe import build_gating_decision # noqa: E402 

87from regime import build_market_regime_vector # noqa: E402 

88from risk.asset_class_router import route_multi_leg_option_sizing # noqa: E402 

89from scripts.profile_inference import summarize_durations # noqa: E402 

90from topology import apply_learned_topology, build_market_topology # noqa: E402 

91 

92OUTPUT_PATH = Path(__file__).resolve().parent / "profile_subsystems_output.txt" 

93SYNTHETIC_SYMBOLS = [f"SYM{i:02d}" for i in range(30)] # matches this project's real universe size 

94 

95 

96# --------------------------------------------------------------------------- 

97# regime 

98# --------------------------------------------------------------------------- 

99 

100 

101def build_regime_workload(iterations: int, seed: int = 7) -> list[dict]: 

102 rng = random.Random(seed) 

103 return [ 

104 { 

105 "momentum_5d": rng.uniform(-0.1, 0.1), 

106 "momentum_20d": rng.uniform(-0.1, 0.1), 

107 "rolling_volatility_20d": rng.uniform(0.0, 0.05), 

108 "drawdown_20d": rng.uniform(-0.3, 0.0), 

109 "average_correlation": rng.uniform(-1.0, 1.0), 

110 } 

111 for _ in range(iterations) 

112 ] 

113 

114 

115def run_regime_workload(pregenerated: list[dict]) -> list[float]: 

116 durations: list[float] = [] 

117 for features in pregenerated: 

118 start = time.perf_counter() 

119 build_market_regime_vector(features) 

120 durations.append(time.perf_counter() - start) 

121 return durations 

122 

123 

124# --------------------------------------------------------------------------- 

125# topology (deterministic) 

126# --------------------------------------------------------------------------- 

127 

128 

129def build_topology_workload(iterations: int, n_symbols: int = 30, seed: int = 7) -> list[dict]: 

130 rng = random.Random(seed) 

131 symbols = SYNTHETIC_SYMBOLS[:n_symbols] 

132 return [ 

133 { 

134 "returns_by_symbol": {sym: [rng.uniform(-0.03, 0.03) for _ in range(25)] for sym in symbols}, 

135 "regime_labels_by_symbol": {sym: rng.choice(["bullish", "bearish", "neutral"]) for sym in symbols}, 

136 } 

137 for _ in range(iterations) 

138 ] 

139 

140 

141def run_topology_workload(pregenerated: list[dict]) -> list[float]: 

142 durations: list[float] = [] 

143 for inputs in pregenerated: 

144 start = time.perf_counter() 

145 build_market_topology(inputs["returns_by_symbol"], inputs["regime_labels_by_symbol"]) 

146 durations.append(time.perf_counter() - start) 

147 return durations 

148 

149 

150# --------------------------------------------------------------------------- 

151# topology (correlation-stability cache, development/Problems.md#36) - 

152# build_topology_workload() above generates fully INDEPENDENT random 

153# returns every iteration (maximally decorrelated bar-to-bar by 

154# construction), so it can never show any benefit from a bar-to-bar 

155# correlation-staleness cache no matter how the cache itself performs. 

156# This sibling workload generates correlated returns from a slowly- 

157# drifting single-factor model instead (each symbol's per-bar return is 

158# `loading * common_factor + fresh idiosyncratic noise`, only the per- 

159# symbol loadings drift slowly bar-to-bar) - keeping every individual 

160# return draw fully fresh/realistic-variance (an earlier version of this 

161# generator instead random-walked each raw return value bar-to-bar, 

162# which silently produced near-constant, numerically degenerate per- 

163# symbol variance after enough steps - the same class of "0/0-like 

164# ill-conditioned" issue features/bond_features.py's 

165# empirical_duration_beta() bug (development/Problems.md#10) hit, just in 

166# synthetic test data instead of production code this time). Unlike 

167# every other workload in this file, this one is deliberately stateful 

168# across iterations (threading previous_positions/previous_correlations 

169# from one call to the next), matching 

170# main.py::_build_topology_payload()'s real per-bar call pattern. Run 

171# `aq profile --topology --topology-cached` together for a direct, 

172# same-run side-by-side comparison. 

173# --------------------------------------------------------------------------- 

174 

175 

176def build_topology_cache_workload( 

177 iterations: int, n_symbols: int = 30, seed: int = 7, loading_drift: float = 0.02, window: int = 25 

178) -> list[dict]: 

179 rng = random.Random(seed) 

180 symbols = SYNTHETIC_SYMBOLS[:n_symbols] 

181 loadings = {symbol: rng.uniform(-1.0, 1.0) for symbol in symbols} 

182 returns_by_symbol: dict[str, list[float]] = {symbol: [] for symbol in symbols} 

183 regime_labels_by_symbol = {sym: rng.choice(["bullish", "bearish", "neutral"]) for sym in symbols} 

184 workload = [] 

185 # Runs `window` extra bars up front to fill every symbol's rolling 

186 # window before the first recorded iteration - otherwise early 

187 # iterations would have progressively growing (not fixed-length) 

188 # return series, an unrealistic shape no real bar ever has. 

189 for _ in range(iterations + window): 

190 common_factor = rng.uniform(-0.02, 0.02) 

191 for symbol in symbols: 

192 loadings[symbol] = max(-1.0, min(1.0, loadings[symbol] + rng.uniform(-loading_drift, loading_drift))) 

193 series = returns_by_symbol[symbol] 

194 series.append(loadings[symbol] * common_factor + rng.uniform(-0.02, 0.02)) 

195 if len(series) > window: 

196 series.pop(0) 

197 if len(returns_by_symbol[symbols[0]]) == window: 

198 workload.append( 

199 { 

200 "returns_by_symbol": {symbol: list(returns_by_symbol[symbol]) for symbol in symbols}, 

201 "regime_labels_by_symbol": dict(regime_labels_by_symbol), 

202 } 

203 ) 

204 return workload[:iterations] 

205 

206 

207def run_topology_cache_workload(pregenerated: list[dict]) -> list[float]: 

208 """Threads previous_positions/previous_correlations from one iteration 

209 to the next - deliberately stateful, unlike every other workload here, 

210 because that statefulness (reusing the prior bar's result) is exactly 

211 what's being measured. correlation_stability_tolerance matches 

212 config.json's shipped phase_v2.topology.correlation_stability_tolerance 

213 default.""" 

214 durations: list[float] = [] 

215 previous_positions: dict[str, tuple[float, float]] | None = None 

216 previous_correlations: dict[tuple[str, str], float] | None = None 

217 for inputs in pregenerated: 

218 start = time.perf_counter() 

219 result = build_market_topology( 

220 inputs["returns_by_symbol"], 

221 inputs["regime_labels_by_symbol"], 

222 previous_positions=previous_positions, 

223 previous_correlations=previous_correlations, 

224 correlation_stability_tolerance=0.02, 

225 ) 

226 durations.append(time.perf_counter() - start) 

227 previous_positions = {node.symbol: (node.x, node.y) for node in result.nodes} 

228 previous_correlations = result.correlations 

229 return durations 

230 

231 

232# --------------------------------------------------------------------------- 

233# topology (learned overlay) - reuses ONE precomputed deterministic 

234# topology per iteration's symbol_features, not regenerated each call 

235# (regenerating it would double-count deterministic topology cost into 

236# this subsystem's own number). 

237# --------------------------------------------------------------------------- 

238 

239 

240def build_learned_topology_workload(iterations: int, n_symbols: int = 30, seed: int = 7) -> list[dict]: 

241 rng = random.Random(seed) 

242 symbols = SYNTHETIC_SYMBOLS[:n_symbols] 

243 returns_by_symbol = {sym: [rng.uniform(-0.03, 0.03) for _ in range(25)] for sym in symbols} 

244 deterministic = build_market_topology(returns_by_symbol).to_dict() 

245 return [ 

246 { 

247 "deterministic_topology": deterministic, 

248 "symbol_features": { 

249 sym: {"momentum_20d": rng.uniform(-0.1, 0.1), "rolling_volatility_20d": rng.uniform(0.0, 0.05)} 

250 for sym in symbols 

251 }, 

252 } 

253 for _ in range(iterations) 

254 ] 

255 

256 

257def run_learned_topology_workload(pregenerated: list[dict]) -> list[float]: 

258 """No trained ml/topology_model.json is assumed present - model=None 

259 exercises apply_learned_topology()'s graceful-degrade path only. This 

260 is a documented limitation of this subsystem's number, not a bug: a 

261 real trained model's cost is architecture-dependent and this harness 

262 doesn't assume one exists on disk (matching load_real_exports()'s own 

263 "missing exports just print a warning, never raise" posture).""" 

264 durations: list[float] = [] 

265 for inputs in pregenerated: 

266 start = time.perf_counter() 

267 apply_learned_topology(inputs["deterministic_topology"], inputs["symbol_features"], model=None) 

268 durations.append(time.perf_counter() - start) 

269 return durations 

270 

271 

272# --------------------------------------------------------------------------- 

273# liquidity 

274# --------------------------------------------------------------------------- 

275 

276 

277def build_liquidity_workload(iterations: int, seed: int = 7) -> list[dict]: 

278 rng = random.Random(seed) 

279 return [ 

280 { 

281 "close": rng.uniform(10.0, 500.0), 

282 "volume": rng.uniform(1e5, 1e7), 

283 "target_weight": rng.uniform(-0.2, 0.2), 

284 "portfolio_value": 1_000_000.0, 

285 "annualized_volatility": rng.uniform(0.1, 0.6), 

286 "dynamic_spread": rng.uniform(0.0001, 0.01), 

287 } 

288 for _ in range(iterations) 

289 ] 

290 

291 

292def run_liquidity_workload(pregenerated: list[dict]) -> list[float]: 

293 durations: list[float] = [] 

294 for inputs in pregenerated: 

295 start = time.perf_counter() 

296 build_liquidity_decision(**inputs) 

297 durations.append(time.perf_counter() - start) 

298 return durations 

299 

300 

301# --------------------------------------------------------------------------- 

302# gating 

303# --------------------------------------------------------------------------- 

304 

305 

306def _synthetic_expert_training_metrics() -> dict: 

307 return { 

308 "experts": { 

309 name: { 

310 "quality_gate": {"quality_status": "stable", "gating_eligible": True}, 

311 "validation": {"balanced_accuracy": 0.55}, 

312 "backtest": {"balanced_accuracy": 0.53, "mcc": 0.06}, 

313 } 

314 for name in ("bullish", "bearish", "sideways", "volatility") 

315 } 

316 } 

317 

318 

319def build_gating_workload(iterations: int, seed: int = 7) -> list[dict]: 

320 rng = random.Random(seed) 

321 metrics = _synthetic_expert_training_metrics() 

322 return [ 

323 { 

324 "regime": {"confidence": rng.uniform(0.0, 1.0), "risk_regime": "risk_neutral"}, 

325 "expert_training_metrics": metrics, 

326 "expert_probabilities": { 

327 "bullish": rng.uniform(0.0, 1.0), 

328 "bearish": rng.uniform(0.0, 1.0), 

329 "sideways": rng.uniform(0.0, 1.0), 

330 "volatility": rng.uniform(0.0, 1.0), 

331 }, 

332 "baseline_probability_up": rng.uniform(0.0, 1.0), 

333 } 

334 for _ in range(iterations) 

335 ] 

336 

337 

338def run_gating_workload(pregenerated: list[dict]) -> list[float]: 

339 durations: list[float] = [] 

340 for inputs in pregenerated: 

341 start = time.perf_counter() 

342 build_gating_decision(**inputs) 

343 durations.append(time.perf_counter() - start) 

344 return durations 

345 

346 

347# --------------------------------------------------------------------------- 

348# analyzer 

349# --------------------------------------------------------------------------- 

350 

351 

352def build_analyzer_workload(iterations: int, seed: int = 7) -> list[dict]: 

353 rng = random.Random(seed) 

354 return [ 

355 { 

356 "signal_name": rng.choice(["buy", "sell", "hold", "short"]), 

357 "confidence": rng.uniform(0.0, 1.0), 

358 "probability_up": rng.uniform(0.0, 1.0), 

359 "target_weight": rng.uniform(-0.2, 0.2), 

360 "regime": {"confidence": rng.uniform(0.0, 1.0), "risk_regime": "risk_neutral"}, 

361 "gating": {"decision_source": "baseline_and_experts"}, 

362 "trading_eligible": True, 

363 "trade_lock_active": False, 

364 } 

365 for _ in range(iterations) 

366 ] 

367 

368 

369def run_analyzer_workload(pregenerated: list[dict]) -> list[float]: 

370 durations: list[float] = [] 

371 for inputs in pregenerated: 

372 start = time.perf_counter() 

373 build_market_analysis_decision(**inputs) 

374 durations.append(time.perf_counter() - start) 

375 return durations 

376 

377 

378# --------------------------------------------------------------------------- 

379# indicators - 7 pure primitives, timed INDEPENDENTLY so a dominant one is 

380# visible rather than averaged into one number. 

381# --------------------------------------------------------------------------- 

382 

383 

384def build_indicators_workload(iterations: int, seed: int = 7) -> list[dict]: 

385 rng = random.Random(seed) 

386 return [ 

387 { 

388 "closes": [rng.uniform(10.0, 500.0) for _ in range(260)], 

389 "highs": [rng.uniform(10.0, 500.0) for _ in range(260)], 

390 "lows": [rng.uniform(10.0, 500.0) for _ in range(260)], 

391 "volumes": [rng.uniform(1e5, 1e7) for _ in range(260)], 

392 "momentum_by_symbol": {sym: rng.uniform(-0.1, 0.1) for sym in SYNTHETIC_SYMBOLS}, 

393 } 

394 for _ in range(iterations) 

395 ] 

396 

397 

398def run_indicators_workload(pregenerated: list[dict]) -> dict[str, list[float]]: 

399 """Returns one duration list PER indicator function (not summed) - 

400 see module docstring for why.""" 

401 per_function: dict[str, list[float]] = { 

402 "relative_strength_index": [], 

403 "average_true_range_pct": [], 

404 "bollinger_pctb": [], 

405 "volume_zscore": [], 

406 "cross_sectional_momentum_rank": [], 

407 "macd_histogram_normalized": [], 

408 "distance_from_52w_high": [], 

409 } 

410 for inputs in pregenerated: 

411 closes, highs, lows, volumes = inputs["closes"], inputs["highs"], inputs["lows"], inputs["volumes"] 

412 

413 start = time.perf_counter() 

414 relative_strength_index(closes) 

415 per_function["relative_strength_index"].append(time.perf_counter() - start) 

416 

417 start = time.perf_counter() 

418 average_true_range_pct(highs, lows, closes) 

419 per_function["average_true_range_pct"].append(time.perf_counter() - start) 

420 

421 start = time.perf_counter() 

422 bollinger_pctb(closes) 

423 per_function["bollinger_pctb"].append(time.perf_counter() - start) 

424 

425 start = time.perf_counter() 

426 volume_zscore(volumes) 

427 per_function["volume_zscore"].append(time.perf_counter() - start) 

428 

429 start = time.perf_counter() 

430 cross_sectional_momentum_rank(inputs["momentum_by_symbol"], SYNTHETIC_SYMBOLS[0]) 

431 per_function["cross_sectional_momentum_rank"].append(time.perf_counter() - start) 

432 

433 start = time.perf_counter() 

434 macd_histogram_normalized(closes) 

435 per_function["macd_histogram_normalized"].append(time.perf_counter() - start) 

436 

437 start = time.perf_counter() 

438 distance_from_52w_high(closes) 

439 per_function["distance_from_52w_high"].append(time.perf_counter() - start) 

440 

441 return per_function 

442 

443 

444# --------------------------------------------------------------------------- 

445# options (V4.9 Priority 7) - route_multi_leg_option_sizing() end-to-end. 

446# --------------------------------------------------------------------------- 

447 

448# One representative strategy_name per shape family, covering every branch 

449# route_multi_leg_option_sizing() itself takes: the 10 reachable vega_budget/ 

450# margin-tier families (vertical/straddle/strangle/butterfly/calendar/ 

451# iron_condor/iron_butterfly/backspread/ladder/naked), the 2 always-skipped 

452# covered_protective/collar names (main.py sizes those separately - see 

453# route_multi_leg_option_sizing()'s own docstring), and the 3 

454# arbitrage_detector_enabled-gated arbitrage families (never fire here since 

455# no real mispricing exists in synthetic data, but still exercise that 

456# branch's own dispatch/skip logic, not just the reachable families'). 

457_OPTIONS_STRATEGY_NAME_MIX = [ 

458 "bull_call_spread", # vertical 

459 "straddle", # straddle 

460 "strangle", # strangle 

461 "butterfly_call", # butterfly 

462 "call_calendar_spread", # calendar 

463 "iron_condor", # iron_condor 

464 "iron_butterfly", # iron_butterfly 

465 "call_backspread", # backspread 

466 "bear_call_ladder", # ladder 

467 "naked_call", # naked 

468 "covered_call", # covered_protective (always skipped by design) 

469 "protective_collar", # collar (always skipped by design) 

470 "box_spread", # arbitrage_box (needs arbitrage_detector_enabled) 

471 "conversion", # arbitrage_conversion 

472 "jelly_roll", # arbitrage_jelly_roll 

473] 

474 

475 

476def _synthetic_options_chain(n_strikes: int = 13, expiries: tuple[str, ...] = ("2026-08-21", "2026-09-18")) -> list[dict]: 

477 """Multi-strike, multi-expiry chain - vega peaks ATM and decays with 

478 distance (same shape tests/test_options_strategy_multileg.py's own 

479 fixture uses, so every reachable shape family's selector can actually 

480 find a usable set of legs), with a SECOND, higher-vega expiry (unlike 

481 that test fixture's single-expiry default) so the calendar family - 

482 the only one needing 2 distinct expiries - is exercisable too.""" 

483 rows = [] 

484 center = 100.0 

485 step = 5.0 

486 start_strike = center - (n_strikes // 2) * step 

487 for expiry_index, expiry in enumerate(expiries): 

488 for i in range(n_strikes): 

489 strike = start_strike + i * step 

490 call_delta = max(0.02, min(0.98, 0.5 + (center - strike) * 0.02)) 

491 put_delta = call_delta - 1.0 

492 distance = abs(strike - center) 

493 # Farther expiry carries more vega per contract (real vega 

494 # term structure) - a flat vega curve across expiries would 

495 # make the calendar family's near/far net vega cancel to 0. 

496 vega = max(0.1, (3.0 - distance * 0.15) * (1.0 + 0.3 * expiry_index)) 

497 rows.append({ 

498 "symbol": f"C{strike:.0f}_{expiry}", "right": "call", "strike": strike, "expiry": expiry, 

499 "delta": call_delta, "vega": vega, "bid": 1.0, "ask": 1.1, "iv": 0.25, 

500 }) 

501 rows.append({ 

502 "symbol": f"P{strike:.0f}_{expiry}", "right": "put", "strike": strike, "expiry": expiry, 

503 "delta": put_delta, "vega": vega, "bid": 1.0, "ask": 1.1, "iv": 0.25, 

504 }) 

505 return rows 

506 

507 

508def build_options_workload(iterations: int, seed: int = 7) -> list[dict]: 

509 rng = random.Random(seed) 

510 chain = _synthetic_options_chain() 

511 return [ 

512 { 

513 "enabled_strategy_names": list(_OPTIONS_STRATEGY_NAME_MIX), 

514 "signal_name": rng.choice(["buy", "sell", "short"]), 

515 "confidence": rng.uniform(0.3, 1.0), 

516 "available_chain": chain, 

517 "portfolio_value": 1_000_000.0, 

518 "underlying_price": 100.0, 

519 "volatility_view": rng.choice(["short_vol", "long_vol", "neutral"]), 

520 "risk_tier_preference": rng.choice(["defined_risk_first", "margin_efficient_first"]), 

521 "margin_family_enabled": rng.random() < 0.5, 

522 "arbitrage_detector_enabled": rng.random() < 0.5, 

523 } 

524 for _ in range(iterations) 

525 ] 

526 

527 

528def run_options_workload(pregenerated: list[dict]) -> list[float]: 

529 durations: list[float] = [] 

530 for inputs in pregenerated: 

531 start = time.perf_counter() 

532 route_multi_leg_option_sizing( 

533 inputs["enabled_strategy_names"], inputs["signal_name"], inputs["confidence"], 

534 inputs["available_chain"], inputs["portfolio_value"], inputs["underlying_price"], 

535 inputs["volatility_view"], inputs["risk_tier_preference"], inputs["margin_family_enabled"], 

536 target_delta_at_full_confidence=0.6, max_vega_budget_pct_of_equity=0.02, 

537 short_leg_delta_offset=0.20, contract_multiplier=100.0, 

538 target_margin_utilization=0.20, max_margin_utilization=0.40, 

539 pct_of_underlying_value=0.20, min_pct_of_underlying_value=0.10, 

540 arbitrage_detector_enabled=inputs["arbitrage_detector_enabled"], 

541 ) 

542 durations.append(time.perf_counter() - start) 

543 return durations 

544 

545 

546SUBSYSTEM_RUNNERS = { 

547 "regime": (build_regime_workload, run_regime_workload), 

548 "topology": (build_topology_workload, run_topology_workload), 

549 "topology-cached": (build_topology_cache_workload, run_topology_cache_workload), 

550 "learned-topology": (build_learned_topology_workload, run_learned_topology_workload), 

551 "liquidity": (build_liquidity_workload, run_liquidity_workload), 

552 "gating": (build_gating_workload, run_gating_workload), 

553 "analyzer": (build_analyzer_workload, run_analyzer_workload), 

554 "indicators": (build_indicators_workload, run_indicators_workload), 

555 "options": (build_options_workload, run_options_workload), 

556} 

557 

558 

559def _report_tail_latency(name: str, durations: list[float], out) -> None: 

560 tail_latency = summarize_durations(durations) 

561 lines = [f" {key}: {value:.4f} ms" for key, value in tail_latency.items()] 

562 header = f"--- {name} ---" 

563 print(header) 

564 print("\n".join(lines)) 

565 out.write(header + "\n") 

566 out.write("\n".join(lines) + "\n\n") 

567 

568 

569def main() -> None: 

570 parser = argparse.ArgumentParser(description=__doc__) 

571 # Default is far lower than profile_inference.py's 10,000 - a real, 

572 # surprising finding from building this harness: build_market_topology() 

573 # costs ~400-500ms per call at this project's real ~30-symbol universe 

574 # size (likely its O(n^2)-ish correlation/embedding math, default 

575 # embedding_iterations=100), orders of magnitude above every other 

576 # subsystem here. 10,000 iterations of that alone would take over an 

577 # hour - 200 is enough for a stable percentile read across all 7 

578 # subsystems in well under 2 minutes total. Override with --iterations 

579 # for a longer, more stable run of a specific --<subsystem>. 

580 parser.add_argument("--iterations", type=int, default=200) 

581 parser.add_argument("--sort", default="cumulative") 

582 for name in SUBSYSTEM_RUNNERS: 

583 parser.add_argument(f"--{name}", action="store_true", help=f"Profile only the {name} subsystem") 

584 args = parser.parse_args() 

585 

586 requested = [name for name in SUBSYSTEM_RUNNERS if getattr(args, name.replace("-", "_"))] 

587 if not requested: 

588 requested = list(SUBSYSTEM_RUNNERS) 

589 

590 with OUTPUT_PATH.open("w", encoding="utf-8") as out: 

591 out.write(f"--iterations {args.iterations} --subsystems {','.join(requested)}\n\n") 

592 for name in requested: 

593 build_fn, run_fn = SUBSYSTEM_RUNNERS[name] 

594 pregenerated = build_fn(args.iterations) 

595 

596 profiler = cProfile.Profile() 

597 profiler.enable() 

598 result = run_fn(pregenerated) 

599 profiler.disable() 

600 

601 if name == "indicators": 

602 for function_name, durations in result.items(): 

603 _report_tail_latency(f"indicators::{function_name}", durations, out) 

604 else: 

605 _report_tail_latency(name, result, out) 

606 

607 stats = pstats.Stats(profiler, stream=out).sort_stats(args.sort) 

608 stats.print_stats(20) 

609 out.write("\n") 

610 

611 print(f"\nFull pstats + tail-latency dump written to {OUTPUT_PATH}") 

612 

613 

614if __name__ == "__main__": 

615 main()