Coverage for aq_cli.py: 100%

3753 statements  

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

1"""`aq` — a thin convenience CLI wrapping Aether Quant's day-to-day commands. 

2 

3Matches this codebase's existing CLI convention exactly (see 

4`retraining/orchestrator.py`'s `argparse` + `subparsers.add_parser(...)` 

5shape) - a single-file dispatcher, not a framework. Every subcommand other 

6than `trade-lock` and `fetch` is a thin `subprocess.run(...)` wrapper around 

7a command that already exists and is already documented elsewhere 

8(README.md, development/infrastructure.md) - no logic is reimplemented 

9here, this file only saves typing. `trade-lock` and `fetch` are the two 

10exceptions: they call `risk/manual_override.py` and 

11`data_pipeline/fetch.py` directly, in-process, no subprocess. 

12 

13Deliberately scoped for v1 - wraps the commands already in daily use, not 

14every command mentioned anywhere in the project. Designed to be extended 

15incrementally: add a new `subparsers.add_parser(...)` block plus one `elif` 

16branch in `main()` for each new command, following the existing pattern. 

17 

18Install once (registers the `aq` command on PATH inside the active venv): 

19 pip install -e . 

20Then: 

21 aq --help 

22""" 

23 

24from __future__ import annotations 

25 

26import argparse 

27import copy 

28import difflib 

29import itertools 

30import json 

31import os 

32import re 

33import shutil 

34import subprocess 

35import sys 

36import time 

37import urllib.request 

38import uuid 

39from collections.abc import Callable, Iterator, Mapping, Sequence 

40from datetime import date 

41from importlib.metadata import version as installed_version 

42from pathlib import Path 

43 

44# Heavy modules load on first use (`aq --help` used to import pandas through data_pipeline.fetch, 5.7 s on the 4 GB PC). 

45# A name reads through `_lazy(name)`, which honours a value a test has set on this module first. 

46_LAZY_NAMES = { 

47 "fetch_adhoc_asset": "data_pipeline.fetch", "IBNotConfiguredError": "data_pipeline.ib_backfill", "attempt_connection": "data_pipeline.ib_backfill", 

48 "connect_ib": "data_pipeline.ib_backfill", "disconnect_ib": "data_pipeline.ib_backfill", "fetch_future_historical_bars": "data_pipeline.ib_backfill", 

49 "fetch_option_historical_bars": "data_pipeline.ib_backfill", "ib_readiness_status": "data_pipeline.ib_backfill", 

50 "load_futures_contract_specs": "data_pipeline.ib_backfill", "secret_env": "execution.secrets_io", 

51 "read_kill_switch_manual_override": "risk.manual_override", "read_manual_trade_lock_override": "risk.manual_override", 

52 "write_kill_switch_manual_override": "risk.manual_override", "write_manual_trade_lock_override": "risk.manual_override", 

53} 

54_FETCH_ASSET_CLASSES = ("crypto", "stock", "futures", "options", "forex") # data_pipeline.fetch.ASSET_CLASSES (a test keeps them equal) 

55 

56 

57def __getattr__(name: str): 

58 if name in _LAZY_NAMES: 

59 import importlib 

60 

61 value = getattr(importlib.import_module(_LAZY_NAMES[name]), name) 

62 globals()[name] = value 

63 return value 

64 raise AttributeError(f"module 'aq_cli' has no attribute {name!r}") 

65 

66 

67def _lazy(name: str): 

68 return globals()[name] if name in globals() else __getattr__(name) 

69 

70 

71IB_ASSET_CLASSES = ("futures", "options") 

72 

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

74CONFIG_PATH = ROOT_DIR / "config.json" 

75LEAN_JSON_PATH = ROOT_DIR / "lean.json" 

76WEBUI_DIR = ROOT_DIR / "webui" 

77README_PATH = ROOT_DIR / "README.md" 

78ML_DIR = ROOT_DIR / "ml" 

79FORMAL_DIR = ROOT_DIR / "formal" 

80FORMAL_CASES_DIR = ROOT_DIR / "aether_quant" / "_formal_cases" 

81 

82PACKAGE_NAME = "aether-quant" 

83UPDATE_CACHE_PATH = Path.home() / ".aq" / "update_check.json" 

84UPDATE_CHECK_INTERVAL_SECONDS = 24 * 60 * 60 

85UPDATE_CHECK_TIMEOUT_SECONDS = 2 

86 

87# `lean backtest .` resolves quantconnect/lean:latest by default when no 

88# --image is given - a MUTABLE tag, so Docker re-checks and re-pulls 

89# whatever layers changed on every single run, even against an already- 

90# fully-cached local image (confirmed directly: a ~42.5GB re-pull kicked 

91# off on this exact machine because Docker Hub's `latest` had moved to a 

92# newer build than what was cached). Pinned here to a specific numbered 

93# QuantConnect build tag instead (confirmed to exist on Docker Hub) so 

94# every clone of this repo - not just this machine - gets a byte- 

95# identical, one-time-download engine image that never silently re-pulls. 

96# To intentionally move to a newer Lean engine: pull the new tag by hand 

97# first (`docker pull quantconnect/lean:<new-tag>`), confirm it works, 

98# then bump this constant - never let it drift back to `latest`. 

99PINNED_LEAN_ENGINE_IMAGE = "quantconnect/lean:17900" 

100# Local derivative used by `aq backtest` by default. It is built once from 

101# PINNED_LEAN_ENGINE_IMAGE and installs the packages this project needs but 

102# the official image does not provide (redis, httpx - see requirements/ 

103# lean-runtime.txt). Keeping them in the image avoids Lean CLI's Windows-host 

104# bind mount of a generated requirements.txt file, which fails on some 

105# Docker Desktop setups. Tag is DERIVED from PINNED_LEAN_ENGINE_IMAGE's own 

106# tag, never a second hardcoded copy - _ensure_local_lean_engine_image()'s 

107# cache check is a `docker image inspect` on this exact tag, so if the two 

108# constants could drift apart, bumping the pinned base without remembering 

109# to bump this one too would silently keep reusing a stale local image 

110# built from the old base forever. 

111LOCAL_LEAN_ENGINE_IMAGE = f"aether-quant-lean:{PINNED_LEAN_ENGINE_IMAGE.rsplit(':', 1)[-1]}" 

112 

113_ANSI_ESCAPE_PATTERN = re.compile(r"\x1b\[[0-9;]*m") 

114 

115 

116def _run(cmd: list[str], cwd: Path = ROOT_DIR) -> int: 

117 """Runs a command with inherited stdout/stderr (live output), returns its exit code.""" 

118 result = subprocess.run(cmd, cwd=str(cwd), check=False) 

119 return result.returncode 

120 

121 

122def _find_quantconnect_lean_binary() -> str | None: 

123 """Plain `lean` on PATH is ambiguous on machines with `elan` (Lean 4, the 

124 theorem prover) installed - it ships its own `lean` binary under the same 

125 name as QuantConnect's Lean CLI (`pip install lean`). Disambiguate by 

126 checking `--version` output (Lean 4 prints "Lean (version 4...."; the 

127 QuantConnect CLI does not), preferring this repo's own venv first.""" 

128 bin_dir_name = "Scripts" if sys.platform == "win32" else "bin" 

129 binary_name = "lean.exe" if sys.platform == "win32" else "lean" 

130 candidates = [str(ROOT_DIR / ".venv" / bin_dir_name / binary_name)] 

131 on_path = shutil.which("lean") 

132 if on_path: 

133 candidates.append(on_path) 

134 

135 for candidate in candidates: 

136 if candidate != on_path and not Path(candidate).exists(): 

137 continue 

138 try: 

139 # the CLI's own startup takes 20-40 s on the 4 GB dev PC under memory pressure: 30 s reported a real CLI as missing 

140 result = subprocess.run([candidate, "--version"], capture_output=True, text=True, timeout=120, check=False) 

141 except (FileNotFoundError, OSError, subprocess.TimeoutExpired): 

142 continue 

143 if "Lean (version" not in (result.stdout or "") + (result.stderr or ""): 

144 return candidate 

145 return None 

146 

147 

148def _ensure_local_lean_engine_image() -> bool: 

149 """Build the small project-specific LEAN image when it is not cached.""" 

150 image_check = subprocess.run( 

151 ["docker", "image", "inspect", LOCAL_LEAN_ENGINE_IMAGE], 

152 cwd=str(ROOT_DIR), 

153 stdout=subprocess.DEVNULL, 

154 stderr=subprocess.DEVNULL, check=False, 

155 ) 

156 if image_check.returncode == 0: 

157 return True 

158 

159 dockerfile = ROOT_DIR / "Dockerfile.lean" 

160 if not dockerfile.is_file(): 

161 print(f"error: missing local LEAN image definition: {dockerfile}", file=sys.stderr) 

162 return False 

163 

164 print( 

165 f"Building {LOCAL_LEAN_ENGINE_IMAGE} from {PINNED_LEAN_ENGINE_IMAGE} " 

166 "(one-time setup; the large base image is reused)..." 

167 ) 

168 return _run( 

169 [ 

170 "docker", 

171 "build", 

172 "--file", 

173 str(dockerfile), 

174 "--tag", 

175 LOCAL_LEAN_ENGINE_IMAGE, 

176 "--build-arg", 

177 f"LEAN_BASE_IMAGE={PINNED_LEAN_ENGINE_IMAGE}", 

178 str(ROOT_DIR), 

179 ] 

180 ) == 0 

181 

182 

183def _parse_simple_version(value: str) -> tuple[int, ...] | None: 

184 """Best-effort "X.Y.Z" -> (X, Y, Z) parse. Returns None for anything that 

185 isn't a clean dotted-integer release version - dev/local builds (e.g. 

186 setuptools-scm's "0.1.dev35+gc744f9ca4.d20260704" fallback for untagged 

187 installs) simply never get flagged as outdated, which is the correct 

188 behavior here.""" 

189 try: 

190 return tuple(int(part) for part in value.split(".")) 

191 except ValueError: 

192 return None 

193 

194 

195def _iso_date(value: str) -> str: 

196 """Validates --start/--end as strict ISO 8601 YYYY-MM-DD, matching the 

197 convention used everywhere else in this repo (config.json, 

198 yfinance_backfill.py) - rejects other formats (e.g. DD.MM.YYYY) with a 

199 clear error instead of a confusing downstream yfinance failure.""" 

200 try: 

201 date.fromisoformat(value) 

202 except ValueError as exc: 

203 raise argparse.ArgumentTypeError(f"invalid date {value!r} - expected ISO 8601 YYYY-MM-DD") from exc 

204 return value 

205 

206 

207def _read_update_cache() -> dict: 

208 if not UPDATE_CACHE_PATH.exists(): 

209 return {} 

210 try: 

211 return json.loads(UPDATE_CACHE_PATH.read_text(encoding="utf-8")) 

212 except (OSError, ValueError): 

213 return {} 

214 

215 

216def _write_update_cache(latest_version: str) -> None: 

217 UPDATE_CACHE_PATH.parent.mkdir(parents=True, exist_ok=True) 

218 payload = {"last_checked": time.time(), "latest_version": latest_version} 

219 UPDATE_CACHE_PATH.write_text(json.dumps(payload), encoding="utf-8") 

220 

221 

222def _fetch_latest_version_from_pypi() -> str | None: 

223 try: 

224 url = f"https://pypi.org/pypi/{PACKAGE_NAME}/json" 

225 with urllib.request.urlopen(url, timeout=UPDATE_CHECK_TIMEOUT_SECONDS) as response: 

226 payload = json.loads(response.read().decode("utf-8")) 

227 return payload["info"]["version"] 

228 except Exception: 

229 return None 

230 

231 

232def _latest_known_version() -> str | None: 

233 cache = _read_update_cache() 

234 last_checked = cache.get("last_checked", 0) 

235 if time.time() - last_checked < UPDATE_CHECK_INTERVAL_SECONDS: 

236 return cache.get("latest_version") 

237 

238 # Update the cache timestamp even on a failed fetch, so an offline user 

239 # doesn't pay the network timeout again on every single command - only 

240 # once per interval. 

241 latest = _fetch_latest_version_from_pypi() 

242 _write_update_cache(latest or cache.get("latest_version", "")) 

243 return latest or cache.get("latest_version") 

244 

245 

246def check_for_update() -> None: 

247 """Prints a one-line notice to stderr if a newer aether-quant release is 

248 available on PyPI. Never raises, never blocks a real command by more 

249 than the short network timeout, and only actually checks PyPI once per 

250 24h (cached in ~/.aq/update_check.json). Opt out with 

251 AQ_SKIP_UPDATE_CHECK=1 (e.g. for CI/scripted usage).""" 

252 if os.environ.get("AQ_SKIP_UPDATE_CHECK"): 

253 return 

254 try: 

255 installed = installed_version(PACKAGE_NAME) 

256 latest = _latest_known_version() 

257 if not latest: 

258 return 

259 installed_tuple = _parse_simple_version(installed) 

260 latest_tuple = _parse_simple_version(latest) 

261 if installed_tuple is None or latest_tuple is None: 

262 return 

263 if installed_tuple < latest_tuple: 

264 print( 

265 f"aq: a newer version is available ({latest}, you have {installed}) - " 

266 f"upgrade with: pip install --upgrade {PACKAGE_NAME}", 

267 file=sys.stderr, 

268 ) 

269 except Exception: 

270 pass 

271 

272 

273TRAIN_RUNS_DIR: Path | None = None # the run folders' root; tests point it at a temporary folder 

274MULTITASK_OBJECTIVES = ("mse", "soft_spearman", "listnet") 

275TRAIN_SETTINGS = ( 

276 "dataset_only", "init_only", "experts_only", "candidate", "gating_only", "multitask_only", "sequence_only", "topology_only", 

277 "strategy_selector_only", "rl_sizing_only", "walk_forward", "step_days", "mode", "include_multitask", "include_sequence", "metrics", 

278 "resume_run_id", "seed", "ranking_objective", "memory_profile", 

279) 

280 

281 

282TRAIN_COMPANIONS = { 

283 "step_days": ("walk_forward",), "mode": ("walk_forward",), "include_multitask": ("walk_forward",), "include_sequence": ("walk_forward",), 

284 "resume_run_id": ("walk_forward",), "metrics": ("walk_forward",), "seed": ("multitask_only", "sequence_only"), 

285 "ranking_objective": ("multitask_only", "sequence_only"), 

286} 

287 

288 

289def companion_errors(args: argparse.Namespace, table: Mapping[str, Sequence[str]]) -> list[str]: 

290 """`--x needs --y` for each flag given without one of the flags it only works with (#417: they used to be ignored).""" 

291 problems = [] 

292 for flag, parents in table.items(): 

293 value = getattr(args, flag, None) 

294 if value in (None, False, [], "") or any(getattr(args, parent, None) not in (None, False, [], "") for parent in parents): 

295 continue 

296 problems.append(f"--{flag.replace('_', '-')} needs {' or '.join('--' + parent.replace('_', '-') for parent in parents)}") 

297 return problems 

298 

299 

300def _train_runs_dir() -> Path: 

301 return TRAIN_RUNS_DIR or ROOT_DIR / "ml" / "cycle" 

302 

303 

304def cmd_train(args: argparse.Namespace) -> int: 

305 """`aq train`: every mode records a run folder (`ml/cycle/train_<id>/`) when it starts, so `aq train --resume` continues a 

306 stopped run with its own settings: finished steps are skipped, a walk-forward continues its windows, the sequence trainer its 

307 checkpoint (V6.6.10). `--init-only` takes seconds and keeps no folder.""" 

308 from retraining import run_resume 

309 

310 runs = _train_runs_dir() 

311 if getattr(args, "list_runs", False): 

312 rows = run_resume.list_runs(runs, ["train_", "retrain_"], last_step="report") 

313 print(json.dumps(rows, indent=2, default=str) if getattr(args, "json", False) else run_resume.render_runs(rows)) 

314 return 0 

315 problems = companion_errors(args, TRAIN_COMPANIONS) 

316 if problems: 

317 print("aq train: " + "; ".join(problems), file=sys.stderr) 

318 return 2 

319 if getattr(args, "dry_run", False): 

320 mode = next((name for name in TRAIN_SETTINGS[:11] if getattr(args, name, False)), "full pipeline") 

321 settings = {name: getattr(args, name, None) for name in TRAIN_SETTINGS if getattr(args, name, None) not in (None, False)} 

322 print(f"aq train would run: {mode} with {settings or 'the config.json defaults'}") 

323 return 0 

324 resume = getattr(args, "resume", None) 

325 folder: Path | None = None 

326 if resume: 

327 folder = run_resume.find_resumable(runs, "train_", None if resume == "latest" else resume) 

328 if folder is None: 

329 print("aq train --resume: no stopped `aq train` run to continue (`aq train --list-runs` lists them)", file=sys.stderr) 

330 return 1 

331 record = run_resume.read_json(folder / run_resume.RECORD, {}) or {} 

332 if record.get("finished"): 

333 print(f"aq train --resume: run {folder.name[len('train_'):]} already finished") 

334 return 0 

335 args = argparse.Namespace(**{**vars(args), **record.get("settings", {})}) 

336 done = run_resume.done_steps(folder) 

337 print(f"aq train: resuming run {folder.name[len('train_'):]}" + (f" (done: {', '.join(done)})" if done else "")) 

338 elif not getattr(args, "init_only", False): 

339 folder = runs / f"train_{run_resume.new_run_id()}" 

340 run_resume.start_record(folder, {"settings": {name: getattr(args, name, None) for name in TRAIN_SETTINGS}, "version_ids": {}}) 

341 print(f"aq train: run {folder.name[len('train_'):]} (after a stop: aq train --resume)") 

342 code = _train_steps(args, folder, resumed=bool(resume)) 

343 if code == 0 and folder is not None: 

344 run_resume.update_record(folder, finished=True) 

345 return code 

346 

347 

348def _profile_flag(memory_profile: str) -> list[str]: 

349 return ["--memory-profile", memory_profile] if memory_profile and memory_profile != "standard" else [] 

350 

351 

352def _train_step(folder: Path | None, step: str, action: Callable[[], int]) -> int: 

353 """One step of a recorded run: skipped when the run finished it before, marked done when it exits 0.""" 

354 from retraining import run_resume 

355 

356 if folder is not None and step in run_resume.done_steps(folder): 

357 print(f"aq train: {step} finished before - skipped") 

358 return 0 

359 code = action() 

360 if code == 0 and folder is not None: 

361 run_resume.mark_done(folder, step, code) 

362 return code 

363 

364 

365def _train_version_id(folder: Path | None, step: str, prefix: str) -> str: 

366 """A step's version id, kept in the run's record so a resumed step writes into the same version folder (and finds its checkpoint).""" 

367 from retraining import run_resume 

368 

369 assert folder is not None, "only --init-only runs without a folder, and it trains no versioned step" 

370 record = run_resume.read_json(folder / run_resume.RECORD, {}) or {} 

371 version_ids = record.get("version_ids") or {} 

372 if step not in version_ids: 

373 version_ids[step] = f"{prefix}-{uuid.uuid4()}" 

374 run_resume.update_record(folder, version_ids=version_ids) 

375 return version_ids[step] 

376 

377 

378def _train_steps(args: argparse.Namespace, folder: Path | None, *, resumed: bool = False) -> int: 

379 seed = getattr(args, "seed", None) 

380 ranking_objective = getattr(args, "ranking_objective", None) 

381 profile = getattr(args, "memory_profile", None) or "standard" 

382 if getattr(args, "multitask_only", False) and ranking_objective not in (None, *MULTITASK_OBJECTIVES): 

383 print(f"aq train: --ranking-objective {ranking_objective} needs the sequence trainer's row context (--sequence-only); " 

384 f"the multitask trainer takes {', '.join(MULTITASK_OBJECTIVES)}", file=sys.stderr) 

385 return 2 

386 

387 def gating() -> int: 

388 return _train_gating_only(version_id=_train_version_id(folder, "gating", "gating-only"), memory_profile=profile) 

389 

390 def multitask() -> int: 

391 return _train_multitask_only(seed=seed, ranking_objective=ranking_objective, version_id=_train_version_id(folder, "multitask", "multitask-only"), 

392 memory_profile=profile) 

393 

394 def sequence() -> int: 

395 return _train_sequence_only(seed=seed, ranking_objective=ranking_objective, version_id=_train_version_id(folder, "sequence", "sequence-only"), 

396 memory_profile=profile, resume=resumed) 

397 

398 for flag, step, action in ( 

399 ("gating_only", "gating", gating), ("multitask_only", "multitask", multitask), ("sequence_only", "sequence", sequence), 

400 ("topology_only", "topology", _train_topology_only), ("strategy_selector_only", "strategy_selector", _train_strategy_selector_only), 

401 ("rl_sizing_only", "rl_sizing", _train_rl_sizing_only), 

402 ): 

403 if getattr(args, flag, False): 

404 return _train_step(folder, step, action) 

405 cmd = [sys.executable, "train.py"] 

406 # A fully bare `aq train` (no scope flag at all) is the only case that 

407 # chains gating/multitask/sequence training on top of train.py's own 

408 # baseline+experts run below - --dataset-only/--init-only/--experts-only/ 

409 # --candidate/--walk-forward all still mean exactly what they say and stop there. 

410 candidate = getattr(args, "candidate", False) 

411 bare_run = not (args.dataset_only or args.init_only or args.experts_only or args.walk_forward or candidate) 

412 if args.dataset_only: 

413 cmd.append("--dataset-only") 

414 elif args.init_only: 

415 cmd.append("--init-only") 

416 elif args.experts_only: 

417 cmd.append("--experts-only") 

418 elif candidate: 

419 version_id = _train_version_id(folder, "candidate", "candidate") 

420 cmd += ["--candidate", "--version-id", version_id] 

421 elif args.walk_forward: 

422 cmd.append("--walk-forward") 

423 if args.step_days is not None: 

424 cmd += ["--step-days", str(args.step_days)] 

425 if args.mode is not None: 

426 cmd += ["--mode", args.mode] 

427 if getattr(args, "include_multitask", False): 

428 cmd.append("--include-multitask") 

429 if getattr(args, "include_sequence", False): 

430 cmd.append("--include-sequence") 

431 if getattr(args, "metrics", None) is not None: 

432 cmd += ["--metrics", args.metrics] 

433 resume_run_id = getattr(args, "resume_run_id", None) 

434 if folder is not None: 

435 # train.py writes the walk-forward's id here before its first window; a resumed run continues that run's windows 

436 id_file = folder / "walk_forward_run_id" 

437 if resume_run_id is None and id_file.exists(): 

438 resume_run_id = id_file.read_text(encoding="utf-8").strip() or None 

439 cmd += ["--run-id-file", str(id_file)] 

440 if resume_run_id is not None: 

441 cmd += ["--resume-run-id", resume_run_id] 

442 if profile != "standard" and not args.init_only: 

443 cmd += ["--memory-profile", profile] 

444 

445 returncode = _train_step(folder, "train_py", lambda: _run(cmd)) 

446 if returncode == 0 and candidate: 

447 print(f"aq train --candidate: trained into ml/versions/{version_id}/ (the active ml/ is untouched).") 

448 if returncode != 0 or not bare_run: 

449 return returncode 

450 

451 # Each of these installs straight into active ml/ the same way its own 

452 # --gating-only/--multitask-only/--sequence-only flag does - a bare 

453 # `aq train` genuinely trains baseline + experts + gating + multitask + 

454 # sequence, not just the first two. Stops at the first failure rather 

455 # than silently continuing with a partially-updated active model. 

456 for stage_name, stage_fn in (("gating", gating), ("multitask", multitask), ("sequence", sequence)): 

457 returncode = _train_step(folder, stage_name, stage_fn) 

458 if returncode != 0: 

459 print(f"aq train: stopped after {stage_name} training failed (exit {returncode}).", file=sys.stderr) 

460 return returncode 

461 return 0 

462 

463 

464def _train_gating_only(version_id: str | None = None, memory_profile: str = "standard") -> int: 

465 """`aq train --gating-only`: trains the learned gating blend 

466 (train_gating.py) and installs it straight into active ml/, mirroring 

467 what `train.py --experts-only` already does for the expert models. 

468 

469 train_gating.py always writes to ml/versions/<version_id>/ (same 

470 versioned-candidate convention every other trainer in this project 

471 uses), so this generates a throwaway version-id, runs the trainer, 

472 then copies the 3 resulting artifacts into active ml/ - the same 

473 manual promotion-simulation step already documented for verifying this 

474 trainer, skipping the full retraining/validate/backtest/commit/promote 

475 pipeline since this is an ad-hoc, user-triggered run, not a scheduled 

476 candidate. `version_id` and `memory_profile` (V6.6.10) come from a recorded `aq train` run.""" 

477 version_id = version_id or f"gating-only-{uuid.uuid4()}" 

478 returncode = _run([sys.executable, "train_gating.py", "--version-id", version_id, *_profile_flag(memory_profile)]) 

479 if returncode != 0: 

480 return returncode 

481 

482 version_dir = ROOT_DIR / "ml" / "versions" / version_id 

483 artifact_names = ("gating_model.json", "gating_feature_schema.json", "gating_training_metrics.json") 

484 if any(not (version_dir / name).exists() for name in artifact_names): 

485 print( 

486 "aq train --gating-only: train_gating.py exited 0 but skipped writing artifacts " 

487 "(likely insufficient validation/backtest rows) - active ml/ left unchanged.", 

488 file=sys.stderr, 

489 ) 

490 return 0 

491 

492 ml_dir = ROOT_DIR / "ml" 

493 for name in artifact_names: 

494 shutil.copy2(version_dir / name, ml_dir / name) 

495 print(f"aq train --gating-only: copied {', '.join(artifact_names)} into active ml/.") 

496 return 0 

497 

498 

499def _train_multitask_only( 

500 seed: int | None = None, ranking_objective: str | None = None, version_id: str | None = None, memory_profile: str = "standard", 

501) -> int: 

502 """`aq train --multitask-only`: trains the joint direction+magnitude+ 

503 volatility model (train_multitask.py) and installs it straight into 

504 active ml/ - identical shape to _train_gating_only() above, including 

505 the throwaway version-id / manual promotion-simulation / "skipped must 

506 never look like failed" handling. 

507 

508 seed/ranking_objective (V5.1 Phase 3, item 1) - passed straight 

509 through to train_multitask.py's own --seed/--ranking-objective flags 

510 when provided, the `aq`-level entry point for the seed-ensembling/ 

511 ranking-objective-A/B workflow that previously required calling the 

512 script directly.""" 

513 version_id = version_id or f"multitask-only-{uuid.uuid4()}" 

514 cmd = [sys.executable, "train_multitask.py", "--version-id", version_id, *_profile_flag(memory_profile)] 

515 if seed is not None: 

516 cmd += ["--seed", str(seed)] 

517 if ranking_objective is not None: 

518 cmd += ["--ranking-objective", ranking_objective] 

519 returncode = _run(cmd) 

520 if returncode != 0: 

521 return returncode 

522 

523 version_dir = ROOT_DIR / "ml" / "versions" / version_id 

524 artifact_names = ("multitask_model.json", "multitask_feature_schema.json", "multitask_training_metrics.json") 

525 if any(not (version_dir / name).exists() for name in artifact_names): 

526 print( 

527 "aq train --multitask-only: train_multitask.py exited 0 but skipped writing artifacts " 

528 "(likely insufficient train/validation/backtest rows) - active ml/ left unchanged.", 

529 file=sys.stderr, 

530 ) 

531 return 0 

532 

533 ml_dir = ROOT_DIR / "ml" 

534 for name in artifact_names: 

535 shutil.copy2(version_dir / name, ml_dir / name) 

536 print(f"aq train --multitask-only: copied {', '.join(artifact_names)} into active ml/.") 

537 return 0 

538 

539 

540def _train_sequence_only( 

541 seed: int | None = None, ranking_objective: str | None = None, version_id: str | None = None, memory_profile: str = "standard", 

542 resume: bool = False, 

543) -> int: 

544 """`aq train --sequence-only`: trains the Phase 2 causal-TCN sequence 

545 encoder (train_sequence.py) and installs it straight into active ml/ - 

546 identical shape to _train_multitask_only()/_train_gating_only() above. 

547 

548 seed/ranking_objective - see _train_multitask_only()'s identical 

549 docstring. `resume` (V6.6.10, a resumed `aq train` run): continue from the version's per-epoch checkpoint (the low profile keeps one).""" 

550 version_id = version_id or f"sequence-only-{uuid.uuid4()}" 

551 cmd = [sys.executable, "train_sequence.py", "--version-id", version_id, *_profile_flag(memory_profile), *(["--resume"] if resume else [])] 

552 if seed is not None: 

553 cmd += ["--seed", str(seed)] 

554 if ranking_objective is not None: 

555 cmd += ["--ranking-objective", ranking_objective] 

556 returncode = _run(cmd) 

557 if returncode != 0: 

558 return returncode 

559 

560 version_dir = ROOT_DIR / "ml" / "versions" / version_id 

561 artifact_names = ("sequence_model.json", "sequence_feature_schema.json", "sequence_training_metrics.json") 

562 if any(not (version_dir / name).exists() for name in artifact_names): 

563 print( 

564 "aq train --sequence-only: train_sequence.py exited 0 but skipped writing artifacts " 

565 "(likely insufficient train/validation/backtest rows) - active ml/ left unchanged.", 

566 file=sys.stderr, 

567 ) 

568 return 0 

569 

570 ml_dir = ROOT_DIR / "ml" 

571 for name in artifact_names: 

572 shutil.copy2(version_dir / name, ml_dir / name) 

573 print(f"aq train --sequence-only: copied {', '.join(artifact_names)} into active ml/.") 

574 return 0 

575 

576 

577def _train_topology_only() -> int: 

578 """`aq train --topology-only`: trains the learned topology overlay 

579 (train_topology.py) and installs it straight into active ml/ - 

580 identical shape to _train_multitask_only()/_train_gating_only()/ 

581 _train_sequence_only() above. 

582 

583 Different data source and a real prerequisite the other three 

584 trainers don't have: train_topology.py fits over realized trading 

585 outcomes pulled from Postgres (AETHER_POSTGRES_DSN env var, read by 

586 train_topology.py itself - no DSN plumbing needed here), and needs 

587 at least phase_v2.topology_learning.training.min_training_events 

588 (default 500) usable events from a lookback_days (default 90) window. 

589 That data only accumulates from runs with the full stack (Postgres + 

590 the audit worker) up - on a fresh checkout, or before Postgres has 

591 been running long enough, this is expected to hit the "skipped" 

592 branch below, not the "artifacts written" one. development/ 

593 Problems.md #56 has the full offset-scale story this trainer feeds.""" 

594 version_id = f"topology-only-{uuid.uuid4()}" 

595 returncode = _run([sys.executable, "train_topology.py", "--version-id", version_id]) 

596 if returncode != 0: 

597 return returncode 

598 

599 version_dir = ROOT_DIR / "ml" / "versions" / version_id 

600 artifact_names = ("topology_model.json", "topology_feature_schema.json", "topology_training_metrics.json") 

601 if any(not (version_dir / name).exists() for name in artifact_names): 

602 print( 

603 "aq train --topology-only: train_topology.py exited 0 but skipped writing artifacts " 

604 "(fewer than min_training_events realized-outcome events in the lookback window - needs " 

605 "Postgres up and the audit worker running long enough to accumulate them) - active ml/ left " 

606 "unchanged.", 

607 file=sys.stderr, 

608 ) 

609 return 0 

610 

611 ml_dir = ROOT_DIR / "ml" 

612 for name in artifact_names: 

613 shutil.copy2(version_dir / name, ml_dir / name) 

614 print(f"aq train --topology-only: copied {', '.join(artifact_names)} into active ml/.") 

615 return 0 

616 

617 

618def _train_strategy_selector_only() -> int: 

619 """`aq train --strategy-selector-only`: trains the learned multi-leg 

620 strategy-selector model (train_strategy_selector.py, V4.7, 

621 development/Problems.md #29's own framing) and installs it straight 

622 into active ml/ - identical shape to _train_topology_only()/ 

623 _train_multitask_only()/_train_gating_only()/_train_sequence_only() 

624 above. 

625 

626 Different, and much harder to satisfy, prerequisite than any of the 

627 other four: train_strategy_selector.py fits over 

628 "option_strategy_outcome" experience events (Postgres, 

629 AETHER_POSTGRES_DSN env var), which only main.py:: 

630 _emit_option_strategy_outcome_if_pending() can ever emit - and that 

631 only fires for a multi-leg OPTION position that was actually opened 

632 AND closed. Unlike train_topology.py (dormant only until enough 

633 Postgres VOLUME accumulates from an already-running system), this 

634 trainer has NO data source at all until real option positions 

635 actually trade - confirmed during scoping research that every options 

636 code path in this repo is still IB-unverified with zero option assets 

637 in the live universe. Expect the "skipped" branch below on every run 

638 in this environment, indefinitely - see train_strategy_selector.py's 

639 own module docstring for the full story.""" 

640 version_id = f"strategy-selector-only-{uuid.uuid4()}" 

641 returncode = _run([sys.executable, "train_strategy_selector.py", "--version-id", version_id]) 

642 if returncode != 0: 

643 return returncode 

644 

645 version_dir = ROOT_DIR / "ml" / "versions" / version_id 

646 artifact_names = ( 

647 "strategy_selector_model.json", 

648 "strategy_selector_feature_schema.json", 

649 "strategy_selector_training_metrics.json", 

650 ) 

651 if any(not (version_dir / name).exists() for name in artifact_names): 

652 print( 

653 "aq train --strategy-selector-only: train_strategy_selector.py exited 0 but skipped writing " 

654 "artifacts (no option_strategy_outcome events yet - needs real option positions to have actually " 

655 "traded and closed) - active ml/ left unchanged.", 

656 file=sys.stderr, 

657 ) 

658 return 0 

659 

660 ml_dir = ROOT_DIR / "ml" 

661 for name in artifact_names: 

662 shutil.copy2(version_dir / name, ml_dir / name) 

663 print(f"aq train --strategy-selector-only: copied {', '.join(artifact_names)} into active ml/.") 

664 return 0 

665 

666 

667def _train_rl_sizing_only() -> int: 

668 """`aq train --rl-sizing-only`: trains the offline contextual-bandit 

669 sizing overlay (train_rl_sizing.py, development/Problems.md #71) and 

670 installs it straight into active ml/ - identical shape to 

671 _train_topology_only()/_train_strategy_selector_only() above. 

672 

673 Different, but much more tractable, prerequisite than either of those 

674 two: train_rl_sizing.py reads ml/datasets/{validation,backtest}_dataset.csv 

675 - NOT Postgres, NOT real option trades - so this can run any time a 

676 normal `python train.py` has already produced a multitask model and 

677 the standard dataset files. Requires phase1.features.input_set to 

678 already include Component D's 3 alt-data feature names (a retrain 

679 with those in the schema) - see train_rl_sizing.py's own module 

680 docstring for the full honest framing (full-information contextual 

681 bandit, NOT off-policy RL) and risk/rl_sizing.py for the abandon 

682 criteria this feature should be judged against before ever being 

683 enabled by default.""" 

684 version_id = f"rl-sizing-only-{uuid.uuid4()}" 

685 returncode = _run([sys.executable, "train_rl_sizing.py", "--version-id", version_id]) 

686 if returncode != 0: 

687 return returncode 

688 

689 version_dir = ROOT_DIR / "ml" / "versions" / version_id 

690 artifact_names = ("rl_sizing_model.json", "rl_sizing_feature_schema.json", "rl_sizing_training_metrics.json") 

691 if any(not (version_dir / name).exists() for name in artifact_names): 

692 print( 

693 "aq train --rl-sizing-only: train_rl_sizing.py exited 0 but skipped writing artifacts " 

694 "(fewer than min_training_rows usable rows, or the multitask model/dataset files are missing) - " 

695 "active ml/ left unchanged.", 

696 file=sys.stderr, 

697 ) 

698 return 0 

699 

700 ml_dir = ROOT_DIR / "ml" 

701 for name in artifact_names: 

702 shutil.copy2(version_dir / name, ml_dir / name) 

703 print(f"aq train --rl-sizing-only: copied {', '.join(artifact_names)} into active ml/.") 

704 return 0 

705 

706 

707def _sync_doc_facts_best_effort() -> None: 

708 """A full `aq test` also refreshes the numbers the docs quote; a scratch README under test leaves the real docs alone.""" 

709 if README_PATH != ROOT_DIR / "README.md": 

710 return 

711 try: 

712 import docs_facts 

713 

714 docs_facts.sync_docs(docs_facts.tracked_docs(ROOT_DIR), docs_facts.compute_facts(ROOT_DIR), blocks=docs_facts.compute_blocks(ROOT_DIR)) 

715 except Exception as error: 

716 print(f"warning: docs facts not refreshed ({error})", file=sys.stderr) 

717 

718 

719def _run_captured(cmd: list[str], cwd: Path = ROOT_DIR) -> tuple[int, str]: 

720 """Like _run(), but also captures combined stdout+stderr while still 

721 streaming it live to the terminal - used only by cmd_test, which needs 

722 the captured text afterward to parse the real pass/fail count for the 

723 README badge. Kept as its own function, separate from _run() (every 

724 other subprocess-wrapping command's single choke point - see this 

725 module's test file docstring), specifically so tests can mock this one 

726 choke point without silently falling through to a real subprocess call 

727 the way mocking only `_run` would (that exact gap previously let 

728 `aq test`'s own test recursively spawn a real, full pytest run on every 

729 invocation of the suite).""" 

730 process = subprocess.Popen( 

731 cmd, 

732 cwd=str(cwd), 

733 stdout=subprocess.PIPE, 

734 stderr=subprocess.STDOUT, 

735 text=True, 

736 bufsize=1, 

737 ) 

738 output_lines = [] 

739 for line in process.stdout: 

740 print(line, end="") 

741 output_lines.append(line) 

742 process.wait() 

743 return process.returncode, "".join(output_lines) 

744 

745 

746# Subsystem -> tests/*.py filenames, used only when the user passes one or 

747# more --<subsystem> flags to filter the run. Not required to be exhaustive 

748# (the default, flag-less `aq test` just runs tests/ directly - marker-based 

749# exclusion, not this mapping, is what makes that complete) but kept 

750# reasonably complete so the flags are actually useful for "test every 

751# subsystem" one at a time. test_lean_backtest_ml_coverage.py is 

752# deliberately absent from every bucket - it's gated by the lean_backtest 

753# marker (see --lean/--full below), never by a subsystem flag. 

754# 

755# Hand-maintained, not derived from the filesystem - real drift found and 

756# fixed once already (~14 files, including a whole missing "audit" bucket, 

757# had silently fallen off every group). tests/test_aq_cli.py:: 

758# test_subsystem_test_files_maps_every_real_test_file_to_exactly_one_bucket() 

759# now locks in "every real test file (except the one deliberate exclusion 

760# above) is in exactly one bucket" so a new test file missing from every 

761# bucket fails CI instead of quietly working only via the flag-less 

762# default run. 

763_SUBSYSTEM_TEST_FILES: dict[str, list[str]] = { 

764 "cli": [ 

765 # V6.7.1: the developer and testing commands 

766 "test_aq_devtools.py", "test_aq_testtools.py", 

767 # V6.6.10: `aq models` 

768 "test_aq_models_cli.py", 

769 "test_aq_cli.py", "test_generate_backtest_report.py", "test_generate_evaluation_report.py", "test_readme_research.py", "test_topology_sizing_research.py", "test_ml_manifest.py", 

770 "test_lean_config_render.py", "test_dockerignore_secrets.py", "test_secret_scan.py", 

771 "test_profile_inference.py", "test_profile_subsystems.py", "test_lean_runtime_imports.py", 

772 "test_order_events_audit.py", 

773 # V5.4.7 - json_safety.py + the CLI help-surface/README-sync guards. 

774 "test_json_safety.py", "test_cli_help_surface.py", 

775 # V6.6.5 

776 "test_hello_world.py", "test_lite_install.py", 

777 # V6.6.5 

778 "test_notebooks.py", 

779 # V6.6.5 

780 "test_aq_accounts_cli.py", 

781 ], 

782 "lab": [ 

783 # V6.7.1: the model lab, its datasets and features, and its commands 

784 "test_feature_registry.py", "test_lab_dataset.py", "test_spec.py", "test_run_registry.py", "test_report_html.py", "test_model_templates.py", 

785 "test_objectives.py", "test_trainer.py", "test_run_evaluation.py", "test_sweep.py", "test_explain.py", "test_model_export.py", "test_data_explore.py", 

786 "test_architectures.py", "test_losses.py", "test_training_utils.py", "test_aq_lab_cli.py", 

787 ], 

788 "audit": [ 

789 # V6.6.7: each module's own test file 

790 "test_redis_queue.py", 

791 "test_hash_chain.py", "test_audit_queue.py", "test_postgres_audit.py", 

792 "test_audit_postgres_worker.py", "test_audit_status_export.py", 

793 ], 

794 "risk": [ 

795 "test_risk_controls.py", "test_asset_class_router.py", "test_futures_risk.py", 

796 "test_forex_risk.py", 

797 "test_order_gate.py", "test_position_sizing.py", "test_backtest_gate.py", 

798 "test_validation_gate.py", "test_manual_override.py", "test_rl_sizing.py", 

799 # V5.1 Phase 6 (production safety) - risk/kill_switch.py, 

800 # execution/reconciliation.py (grouped here, not a dedicated 

801 # "execution" bucket, alongside every other production-safety 

802 # risk mechanism in this list). 

803 "test_kill_switch.py", "test_v664_mutation_safety.py", "test_reconciliation.py", 

804 # V6.6.5 

805 "test_kelly.py", "test_vol_target.py", 

806 ], 

807 "portfolio": [ 

808 # V6.6.7: each module's own test file 

809 "test_book_construction.py", "test_hrp_allocation.py", "test_book_optimizer.py", "test_v669_fixes.py", "test_model_book.py", 

810 "test_portfolio_book_construction.py", "test_options_strategy.py", "test_cash_sweep.py", 

811 "test_target_weights.py", "test_financing.py", "test_premia_signals.py", "test_daily_target_weights.py", 

812 "test_options_strategy_multileg.py", "test_options_arbitrage_detector.py", 

813 "test_options_margin_sizing.py", 

814 "test_options_greeks.py", "test_simulated_portfolio.py", "test_options_assignment_risk.py", 

815 # V5.1 Phase 1 (development/Problems.md #73) - portfolio/rank_signal.py. 

816 "test_rank_signal.py", "test_direction_overlay.py", 

817 # V5.3.5 (development/Problems.md #102) - portfolio/rolling_ic_gate.py. 

818 "test_rolling_ic_gate.py", 

819 # V5.5.0 (Problems.md #128) - portfolio/legacy_sleeve.py. 

820 "test_legacy_sleeve.py", 

821 # V5.7.0 - portfolio/forex_sleeve.py. 

822 "test_forex_sleeve.py", 

823 # V5.8.0 - portfolio/sleeve_guard.py, portfolio/class_sleeve.py. 

824 "test_sleeve_guard.py", "test_class_sleeve.py", 

825 # V6.4.4 - portfolio/trend_sleeve.py. 

826 "test_trend_sleeve.py", 

827 # V6.6.1 - portfolio/signal_construction.py, portfolio/generation_blend.py. 

828 "test_signal_construction.py", "test_generation_blend.py", 

829 # V6.6.5 

830 "test_neutrality.py", 

831 ], 

832 "features": [ 

833 # V6.6.7: each module's own test file 

834 "test_training_splits.py", "test_wide_panel.py", 

835 "test_bond_features.py", "test_derivatives_macro_features.py", "test_macro_features.py", 

836 "test_technical_indicators.py", "test_train_bond_features.py", 

837 "test_train_derivatives_macro_features.py", "test_train_macro_features.py", 

838 "test_train_asset_class_context_features.py", "test_train_cross_sectional_features.py", 

839 "test_train_indicators.py", "test_alt_data_features.py", "test_train_alt_data_features.py", 

840 # V5.6.0 (Problems.md #135) - features/cross_asset_timing.py. 

841 "test_cross_asset_timing.py", "test_fx_carry.py", "test_overlap_vs_sharpe_analysis.py", "test_v560_fixes.py", "test_compare_training_variants.py", "test_make_variant_configs.py", "test_train_forex_fill_forward.py", 

842 # V5.1 Phase 2 (item 8 / F2) - features/cross_asset_sensitivity.py. 

843 "test_cross_asset_sensitivity.py", "test_train_cross_asset_sensitivity.py", 

844 # V5.8.0 - features/fx_signals.py. 

845 "test_fx_signals.py", 

846 # V6.4.4 - features/cross_sectional_inputs.py (ranked model inputs). 

847 "test_cross_sectional_inputs.py", 

848 # V6.4.3 - features/cross_sectional_norm.py, features/asof_beta_labels.py. 

849 "test_cross_sectional_norm.py", "test_asof_beta_labels.py", 

850 ], 

851 "data-pipeline": [ 

852 # V6.6.7: each module's own test file 

853 "test_bar_synthesis.py", "test_cftc_cot.py", "test_edgar_facts.py", "test_factor_library.py", "test_finra_short_volume.py", "test_sec_form345.py", "test_v2_manifest.py", 

854 "test_sp500_membership.py", "test_binance_archive.py", "test_wide_info.py", "test_net_retry.py", 

855 "test_alt_data_v650.py", "test_build_pre2013_root.py", "test_fetch.py", "test_ib_backfill.py", "test_fred_backfill.py", "test_yfinance_backfill.py", 

856 "test_dividend_backfill.py", "test_factor_file_backfill.py", "test_filing_text.py", 

857 "test_refresh_lean_interest_rate.py", 

858 # V5.8.0 - data_pipeline/data_audit.py. 

859 "test_data_audit.py", 

860 # V6.0.0 - scripts/refresh_universe_availability.py. 

861 "test_refresh_universe_availability.py", 

862 # V6.6.5 

863 "test_public_candles.py", 

864 ], 

865 "webui": [ 

866 "test_neural_network_state.py", "test_assets_status.py", "test_status_export.py", 

867 "test_rank_ic_monitor.py", "test_observation_metrics.py", "test_strategy_catalog.py", 

868 "test_api_server.py", 

869 # V6.6.5 

870 "test_dashboard_demo.py", 

871 # V6.6.5 

872 "test_auth.py", "test_auth_io.py", "test_api_auth.py", 

873 ], 

874 "ml": [ 

875 # V6.6.7: each module's own test file 

876 "test_gating.py", 

877 "test_train_cross_sectional.py", 

878 # V6.0.0 - extra-horizon (rank_60d) targets and heads. 

879 "test_v600_extra_horizon.py", 

880 "test_build_holdout_dataset.py", "test_splice_holdout_dataset.py", "test_holdout_report.py", "test_v610_model_ensemble.py", 

881 "test_v620_model_inputs.py", 

882 "test_compare_datasets.py", "test_model_candidate_research.py", "test_build_legacy_probability.py", 

883 "test_as_live_levers.py", 

884 "test_expert_models.py", "test_expert_datasets.py", "test_gating_network.py", "test_train_gating.py", 

885 "test_train_multitask.py", "test_train_multitask_architecture.py", "test_train_sequence.py", 

886 "test_train_sequence_architecture.py", "test_train_pipeline.py", "test_train_ranking_validation.py", 

887 "test_train_walk_forward_windows.py", "test_train_topology.py", "test_learned_topology.py", 

888 "test_exported_model.py", "test_market_topology.py", "test_market_regime.py", "test_regime_model_input.py", 

889 # V6.6.8 (#380): the C++ kernel, run under ASan/UBSan by CI's cpp-sanitizers job (skips where it is not built) 

890 "test_cpp_inference_kernel.py", 

891 "test_market_analyzer.py", "test_market_liquidity.py", 

892 "test_train_strategy_selector.py", "test_strategy_selector_inference.py", 

893 "test_parallel_inference.py", "test_train_threshold_and_early_stop.py", 

894 "test_train_select_model_context_columns.py", "test_train_rl_sizing.py", 

895 # V5.1 Phase 2 (item 5 of the roadmap) - train.py::build_residual_rank_targets(). 

896 "test_train_residual_rank_targets.py", 

897 # V5.7.0 - label purge, scaler reuse, holdout config, FX carry column, rank groups, trading eligibility. 

898 "test_v570_training_fixes.py", 

899 # V5.8.0 - training-pipeline round file. 

900 "test_v580_training_fixes.py", 

901 # V5.1 Phase 3 (items 1, 10, 11) - cross-sectional batching, ranking 

902 # losses, optimizer/schedule/SWA/smoothing helpers. 

903 "test_train_cross_sectional_batching.py", "test_train_ranking_loss.py", "test_train_optimizer_and_swa.py", 

904 # V5.1 Phase 4 (item 4) - multi-model walk-forward subprocess/net- 

905 # performance-simulation helpers. 

906 "test_walk_forward_multimodel.py", 

907 # V5.2.8 (Problems.md #94) - train.py::compute_gate_friendliness_weight_by_date(). 

908 "test_train_gate_friendliness.py", 

909 ], 

910 "retraining": [ 

911 # V6.6.7: each module's own test file 

912 "test_artifacts.py", "test_orchestrator.py", "test_planning.py", "test_postgres_registry.py", "test_worker.py", 

913 "test_retraining_artifacts.py", "test_retraining_orchestrator.py", "test_retraining_planning.py", 

914 "test_retraining_postgres_registry.py", "test_retraining_worker.py", "test_trigger_worker.py", 

915 "test_triggers.py", "test_vault_client.py", "test_vault_commands.py", "test_vault_contract.py", "test_vault_record.py", "test_lean_backtest.py", 

916 "test_v2_pipeline_manifest.py", 

917 # V5.1 Phase 6 (production safety) - retraining/auto_rollback.py. 

918 "test_auto_rollback.py", 

919 # V6.6.9 

920 "test_artifact_pins.py", 

921 # V6.6.10: training on a small machine (lazy windows, profiles, the memory probe) and its CI proof 

922 "test_slicing.py", "test_lowmem_proof.py", 

923 # V6.6.10: resumable runs (the run folder, `aq train --resume`, `--list-runs`, `aq pipeline run --resume`) 

924 "test_run_resume.py", "test_aq_train_resume.py", 

925 # V6.6.10: the example models anyone can install (the catalog and its build) 

926 "test_model_catalog.py", "test_build_example_models.py", 

927 ], 

928 "notifications": ["test_telegram_alerts.py", "test_telegram_client.py", "test_telegram_worker.py", "test_postgres_telegram.py"], 

929 "storage": ["test_postgres_triggers.py", "test_postgres_worker.py", "test_config_cache.py", "test_runtime_config_io.py", "test_experience_queue.py"], 

930 "live": [ 

931 "test_live_credentials.py", "test_live_credentials_io.py", "test_paper_readiness.py", 

932 "test_paper_readiness_io.py", "test_paper_readiness_report.py", "test_paper_readiness_scheduler.py", 

933 # V5.5.0 - main.py's order-path methods against a minimal Lean stub (the first unit coverage 

934 # main.py has ever had - tests/test_main_wiring.py's own docstring says what it does NOT prove). 

935 "test_main_wiring.py", "test_main_on_data_target_weights.py", "test_main_ensure_ready_smoke.py", 

936 # V6.6.5 

937 "test_cost_models.py", 

938 # V6.6.5 

939 "test_secrets.py", "test_secrets_io.py", "test_secrets_property.py", 

940 # V6.6.5 

941 "test_accounts.py", "test_accounts_io.py", "test_field_test.py", "test_main_accounts.py", 

942 # V6.6.5 

943 "test_accounts_parity.py", 

944 # V6.6.5 

945 "test_live_readiness.py", "test_live_readiness_io.py", "test_backup_postgres.py", 

946 ], 

947 "evaluation": [ 

948 # V6.6.10: the multi-asset push's rules and verdicts, its stage driver 

949 "test_multi_asset_round.py", "test_v6610_research.py", "test_alpha_behaviour.py", "test_pipeline.py", "test_project_template.py", "test_model_cycle_row.py", 

950 # V6.6.9: the model book's research, its stages and the chunked dataset reader 

951 "test_model_book_research.py", "test_model_book_round.py", "test_dataset_io.py", 

952 # V6.6.7: each module's own test file 

953 "test_audit_runners.py", "test_benchmark_comparison.py", "test_factor_neutralization_check.py", "test_tranche_book.py", "test_wide_context.py", 

954 # V6.6.1 - the third round's tools, and generations that hand over. 

955 "test_model_audit.py", "test_walk_forward_linear.py", "test_research_round.py", "test_alpha_decay.py", "test_generation_registry.py", "test_v664_mutation_ledgers.py", "test_generation_ledger.py", 

956 "test_glide_calibration.py", "test_cycle_daily.py", "test_research_cycle.py", "test_cycle_retrain.py", "test_aq_cycle_cli.py", "test_cycle_lean.py", 

957 "test_v660_fixes.py", "test_power_analysis.py", "test_research_cells.py", "test_wide_signals.py", "test_v660_research.py", "test_v660_round2.py", 

958 "test_target_weights_engine.py", "test_trial_ledger.py", "test_premia_research.py", "test_v650_lean.py", "test_v650_scripts.py", 

959 # V6.4.3 - the research and audit tools. 

960 "test_research_harness.py", "test_pbo.py", "test_factor_spanning.py", "test_overfit_diagnostics.py", 

961 "test_leakage_audit.py", "test_research_probes.py", "test_sim_lean_calibration.py", "test_trial_registry.py", 

962 # V6.4.4 - the trend sleeve simulator and the alpha proof. 

963 "test_trend_sleeve_backtest.py", "test_alpha_proof.py", "test_gate_replica_audit.py", "test_forward_ledger.py", 

964 # V6.6.4 - a fourth round: crypto and filing signals, the late-session fix, property tests, the re-pin. 

965 "test_v664_late_session.py", "test_crypto_signals.py", "test_filing_signals.py", "test_v664_crypto_gbm.py", "test_v664_write_rounds.py", "test_v664_sanity.py", 

966 "test_v664_properties.py", "test_v664_eos_repin.py", "test_round_builders.py", "test_v664_register_observers.py", "test_k09_decide.py", 

967 "test_research_runners.py", 

968 "test_rank_book_simulator.py", "test_book_neutrality.py", "test_cost_model.py", 

969 "test_model_predictions.py", "test_evaluation_state.py", "test_sector_map.py", 

970 # V5.1 Phase 5 (item 9) - evaluation/ablation.py. 

971 "test_ablation.py", 

972 # V5.1 (Problems.md) - evaluation/rank_signal_calibration.py. 

973 "test_rank_signal_calibration.py", 

974 # V5.2.6 (Problems.md) - evaluation/confidence_threshold_calibration.py. 

975 "test_confidence_threshold_calibration.py", 

976 # V5.2.8 (Problems.md #94) - evaluation/kill_switch_replay.py. 

977 "test_kill_switch_replay.py", 

978 # V5.3.1 (Problems.md #34/#96) - evaluation/limit_fill_simulator.py. 

979 "test_limit_fill_simulator.py", 

980 # V5.3.5 (Problems.md #102) - evaluation/rank_ic_core.py, 

981 # evaluation/rolling_ic_gate_calibration.py, evaluation/ 

982 # rolling_ic_gate_replay.py. 

983 "test_rank_ic_core.py", "test_rolling_ic_gate_calibration.py", "test_rolling_ic_gate_replay.py", 

984 # V5.3.5.3 (Problems.md #91/#100) - evaluation/feature_reconciliation.py. 

985 "test_feature_reconciliation.py", 

986 "test_feature_parity.py", 

987 "test_promotion_gate_era_rule.py", 

988 "test_impact_model.py", 

989 "test_v543_new_features.py", 

990 "test_bar_synthesis_parity.py", 

991 "test_rollback_hardening.py", 

992 "test_rl_sizing_v541.py", 

993 "test_monte_carlo.py", 

994 # V5.4.4 - evaluation/public_benchmarks.py (SP500 + 60-40 public 

995 # baselines) and the HRP live-book-sizing integration tests. 

996 "test_public_benchmarks.py", 

997 "test_hrp_book_sizing.py", 

998 # V5.4.7 - full-system bug-hunt round file (#120-#125). 

999 "test_v547_bug_hunt.py", 

1000 # V5.5.0 - offline/live execution parity round (#127-#129): the 

1001 # round file plus one file per new module. 

1002 "test_v550_parity_fixes.py", 

1003 "test_v550_backtest_findings.py", 

1004 "test_backtest_audit.py", 

1005 # V6.0.0 - Lean run attribution (evaluation/lean_attribution.py). 

1006 "test_lean_attribution.py", 

1007 # V6.0.0 - simulator execution parity (cadence, next-open fills, resize / cooldown / trailing stop, replay). 

1008 "test_v600_simulator_parity.py", "test_v610_simulator_parity.py", "test_v610_research.py", "test_prepare_v610_candidates.py", 

1009 "test_v600_forex_parity.py", "test_v610_forex_holidays.py", 

1010 "test_v600_late_bar_cross_asset.py", 

1011 "test_v600_sensitivity_vector.py", 

1012 "test_v600_across_symbols.py", 

1013 "test_v600_config_decisions.py", "test_v610_config_decisions.py", "test_v620_config_decisions.py", 

1014 "test_lean_calibration.py", 

1015 # V6.2.0 - Lean's statistics reproduced exactly (risk-free file, day count, counterfactual returns). 

1016 "test_lean_statistics.py", 

1017 # V6.3.0 - the README's Backtest Statistics (evaluation/backtest_statistics.py, evaluation/lean_report.py). 

1018 "test_backtest_statistics.py", "test_lean_benchmarks.py", "test_lean_report.py", "test_readme_statistics.py", "test_build_trial_registry.py", 

1019 "test_v620_cash_sweep_parity.py", 

1020 "test_v620_dedupe.py", "test_v620_tranche_book.py", "test_v620_research.py", 

1021 # V6.3.0 - the R-KILL / R-STAGGER2 clauses and the release-band parity round. 

1022 "test_v630_research.py", "test_v630_round.py", 

1023 # V6.4.0 - Lean book-call probabilities, the paper protocol, calibration, engaged-day skill, the crypto bootstrap. 

1024 "test_classification_parity.py", "test_paper_protocol.py", "test_probability_calibration.py", 

1025 "test_engaged_day_skill.py", "test_trade_bootstrap.py", "test_v640_round.py", "test_data_append_guard.py", "test_v640_research.py", "test_codespace_session_v640.py", 

1026 "test_codespace_session_v644.py", "test_freeze_run_config.py", "test_lean_verdict.py", 

1027 "test_book_variant_research.py", 

1028 "test_crypto_fee_research.py", 

1029 "test_forex_keep_or_drop.py", 

1030 "test_live_parity.py", 

1031 "test_volatility_threshold_calibration.py", 

1032 "test_performance_probe.py", 

1033 # V5.7.0 - incremental rolling-IC state (evaluation/rolling_ic_series.py). 

1034 "test_rolling_ic_series.py", 

1035 # V5.7.0 - kill switch / member sizing / HRP / per-name impact in the offline simulator. 

1036 "test_v570_live_mechanisms.py", 

1037 # V5.7.0 - evaluation/fill_price_audit.py (aq evaluate --audit-fills). 

1038 "test_fill_price_audit.py", 

1039 # V5.8.0 - audit tools (class IC, gate, heads, feature quality) and the release's parity round file. 

1040 "test_class_ic_audit.py", "test_gate_audit.py", "test_head_audit.py", "test_feature_quality_audit.py", 

1041 "test_ml_cleanup.py", 

1042 "test_class_sleeve_research.py", 

1043 "test_v580_live_parity.py", 

1044 # V6.6.5 

1045 "test_backtest_api.py", "test_overfitting.py", "test_signal_tools.py", 

1046 ], 

1047 # V5.5.0 - repo-level guards about the repo itself (CI workflow shape, the 

1048 # `aq test --ruff` flag, packaging lists, docs links, CI helper scripts), 

1049 # split out of the `evaluation` catch-all they used to be hidden in so a 

1050 # failure in one of them names its own bucket in CI's subsystem matrix. 

1051 # V6.4.3 - the Lean 4 differential cases (formal/) and the proof findings' round file. 

1052 "formal": [ 

1053 "test_formal_cases_drift.py", "test_formal_differential_order_gate.py", "test_formal_differential_hash_chain.py", 

1054 "test_formal_differential_book_neutrality.py", "test_formal_differential_book_construction.py", 

1055 "test_formal_differential_risk_controls.py", "test_formal_differential_kill_switch.py", 

1056 "test_formal_differential_position_sizing.py", "test_formal_differential_cost_model.py", 

1057 "test_formal_differential_reconciliation.py", "test_formal_differential_sleeve_guard.py", 

1058 "test_formal_differential_json_safety.py", "test_v643_formal_findings.py", "test_formal_differential_generation_blend.py", "test_formal_differential_generation_glide.py", 

1059 "test_formal_differential_admission.py", "test_formal_differential_session_resolve.py", "test_formal_differential_holdout_once.py", "test_check_axioms.py", "test_formal_no_sorry.py", "test_verification_matrix.py", 

1060 "test_formal_inventory.py", 

1061 # V6.6.10: the new specs' differential tests 

1062 "test_formal_differential_no_trade_band.py", "test_formal_differential_paper_loss_guard.py", "test_formal_differential_multi_asset_rules.py", 

1063 "test_formal_differential_window_index.py", "test_formal_differential_kelly.py", "test_formal_differential_inverse_vol_share.py", 

1064 "test_formal_differential_sharpe_clauses.py", "test_formal_differential_book_guards.py", 

1065 # V6.6.5 

1066 "test_formal_differential_account_overrides.py", "test_formal_differential_authorize.py", 

1067 # V6.6.7 (#368-#376): ten more specs 

1068 "test_formal_differential_rl_sizing.py", "test_formal_differential_drawdown_guard.py", "test_formal_differential_backtest_gate.py", "test_formal_differential_auto_rollback.py", "test_formal_differential_premia_caps.py", 

1069 "test_formal_differential_rebalance.py", "test_formal_differential_cash_sweep.py", "test_formal_differential_dynamic_targets.py", "test_formal_differential_forex_cap.py", "test_formal_differential_vol_target.py", 

1070 "test_formal_differential_model_book_guard.py", 

1071 ], 

1072 "meta": [ 

1073 "test_ci_workflows.py", "test_aq_test_ruff_flag.py", "test_packaging_modules.py", "test_docs_links.py", "test_docs_facts.py", 

1074 # V6.4.3 - the aether_quant library's public surface and quickstart. 

1075 "test_aether_quant_api.py", "test_aether_quant_quickstart.py", "test_aether_quant_coverage.py", "test_install_hooks.py", "test_module_has_test.py", "test_mutation_check.py", 

1076 # V6.6.7 (#361, #363): the Scorecard guards (hash locks, pins) and the fuzz targets 

1077 "test_scorecard_pins.py", "test_lock_requirements.py", "test_requirement_locks.py", "test_fuzz_targets.py", "test_fuzz_runner.py", 

1078 "test_aq_cli_coverage_changed.py", "test_coverage_misses.py", "test_scripts_readme.py", 

1079 "test_ci_scripts.py", "test_codespace_lean_scripts.py", "test_lean_smoke_scripts.py", "test_v644_fixes.py", "test_readme_freshness.py", 

1080 # V6.6.5 

1081 "test_public_docstrings.py", 

1082 # V6.6.5 

1083 "test_docs_site.py", 

1084 # V6.6.5 

1085 "test_licensing.py", 

1086 # V6.6.6 

1087 "test_test_badge.py", "test_coverage_scope.py", "test_notebook_sources.py", "test_cpp_inference_ext_setup.py", 

1088 # V6.6.8 (#379) 

1089 "test_ruff_config.py", 

1090 ], 

1091 # V6.6.6 (#359): one test file per script under scripts/, so `aq test --coverage` reaches every tracked line 

1092 "scripts": [ 

1093 "test_v669_book.py", "test_model_book_decide.py", "test_check_artifact_pins.py", 

1094 "test_render_lean_credentials.py", "test_exception_scope.py", "test_main_option_order.py", 

1095 "test_coinbase_listing_dates.py", "test_fetch_cash_sweep_data.py", "test_gate_sweep_score_stage.py", "test_gate_value_compare.py", 

1096 "test_promotion_gate_null_gate_scheme.py", "test_script_entry_points.py", "test_v643_rcal4.py", "test_v643_sector_cap_frequency.py", 

1097 "test_v650_install.py", "test_v650_write_rules.py", "test_v660_build_panel.py", "test_v660_crypto_splices.py", "test_v660_rescore_v650.py", 

1098 "test_v660_sanity.py", "test_v660_verdict.py", "test_v660_write_rules.py", "test_v661_glide.py", "test_v661_model_audit.py", 

1099 "test_v661_replay_check.py", "test_v661_sanity.py", "test_v661_write_round3.py", "test_v664_drop_eos.py", "test_v664_table_smoke.py", 

1100 "test_active_baseline.py", "test_build_crypto_wide_root.py", "test_build_docs.py", "test_build_hello_sample.py", "test_build_wide_root.py", 

1101 "test_coverage_badge.py", "test_cycle_decide.py", "test_extend_frozen_weights.py", "test_field_test_services.py", 

1102 "test_forex_sleeve_research.py", "test_gate_research.py", "test_library_gate.py", 

1103 "test_make_live_plumbing_config.py", "test_make_option_main_config.py", "test_predict_sweep_bt1.py", "test_profile_main_tick.py", 

1104 "test_promotion_gate_null_calibration.py", "test_run_lean_cli_windows.py", "test_sleeve_alpha_check.py", "test_v643_microbench.py", 

1105 "test_v644_make_configs.py", "test_v644_rcal5.py", "test_v650_ml_scores.py", "test_v660_venue_coverage.py", "test_v660_venue_study.py", 

1106 "test_type_completeness.py", "test_v666_coverage_risk.py", 

1107 "test_v666_coverage_experience.py", "test_v666_coverage_library.py", "test_v666_coverage_monitoring.py", 

1108 "test_v666_coverage_notifications.py", "test_v666_coverage_performance.py", "test_v666_coverage_topology.py", 

1109 "test_v666_coverage_workers.py", 

1110 "test_aq_cli_evaluate_audits.py", "test_aq_cli_evaluate_book.py", "test_aq_cli_evaluate_calibrations.py", "test_aq_cli_evaluate_lean.py", 

1111 "test_aq_cli_evaluate_reconcile_book.py", "test_aq_cli_evaluate_reconcile_features.py", "test_aq_cli_evaluate_runs.py", 

1112 "test_v666_coverage_features.py", 

1113 "test_aq_cli_commands.py", "test_aq_cli_cycle.py", 

1114 "test_aq_cli_verify.py", 

1115 "test_aq_cli_last_branches.py", 

1116 "test_research_round_stages.py", "test_retraining_orchestrator_stages.py", 

1117 "test_retraining_remaining.py", 

1118 "test_module_entry_points.py", "test_yfinance_backfill_more.py", 

1119 "test_dividend_factor_backfill_more.py", "test_edgar_facts_more.py", "test_fred_backfill_more.py", 

1120 "test_data_pipeline_small_more.py", 

1121 "test_options_margin_sizing_more.py", "test_options_strategy_selectors.py", 

1122 "test_portfolio_gaps_more.py", 

1123 "test_portfolio_guards_more.py", 

1124 "test_lean_attribution_more.py", "test_paper_readiness_more.py", 

1125 "test_backtest_statistics_more.py", 

1126 "test_alpha_proof_more.py", 

1127 "test_audit_runners_more.py", 

1128 "test_evaluation_small_more.py", 

1129 "test_run_flows_more.py", 

1130 "test_readme_research_more.py", 

1131 "test_evaluation_tail_more.py", "test_features_tail_more.py", 

1132 "test_exported_model_fallbacks.py", 

1133 "test_parallel_inference_more.py", 

1134 "test_execution_tail_more.py", 

1135 "test_train_cross_sectional_more.py", "test_train_topology_more.py", 

1136 "test_v640_research_runtime.py", 

1137 "test_v643_research_runtime.py", "test_v644_research_runtime.py", 

1138 "test_v610_research_runtime.py", "test_v620_research_runtime.py", "test_v630_research_runtime.py", 

1139 "test_v660_research_runtime.py", 

1140 "test_v650_research_runtime.py", 

1141 "test_v660_round2_runtime.py", 

1142 "test_v650_lean_runtime.py", 

1143 "test_v650_amendment2_runtime.py", 

1144 "test_v650_instrument_runtime.py", 

1145 "test_v660_lean_runtime.py", 

1146 "test_cycle_lean_runtime.py", 

1147 "test_lean_calibration_runtime.py", 

1148 "test_profile_inference_runtime.py", 

1149 "test_lean_smoke_runtime.py", 

1150 "test_field_test_runtime.py", 

1151 "test_main_option_scenarios_runtime.py", 

1152 "test_feature_parity_audit_runtime.py", 

1153 "test_build_filing_signals_runtime.py", 

1154 "test_gate_sweep_runtime.py", 

1155 "test_build_wide_info_runtime.py", 

1156 "test_wheel_smoke_runtime.py", 

1157 "test_v664_eos_repin_runtime.py", 

1158 "test_data_append_refresh_runtime.py", 

1159 "test_book_variant_research_runtime.py", 

1160 "test_as_live_levers_runtime.py", 

1161 "test_class_sleeve_research_runtime.py", 

1162 "test_crypto_fee_research_runtime.py", 

1163 "test_prepare_v610_candidates_runtime.py", 

1164 "test_model_candidate_research_runtime.py", 

1165 "test_crypto_graduation_research_runtime.py", 

1166 "test_build_notebooks_runtime.py", 

1167 "test_build_legacy_probability_runtime.py", 

1168 "test_topology_sizing_research_runtime.py", 

1169 "test_build_holdout_data_runtime.py", "test_build_holdout_dataset_runtime.py", 

1170 "test_holdout_report_runtime.py", "test_k09_decide_runtime.py", 

1171 "test_forex_keep_or_drop_runtime.py", 

1172 "test_rl_sizing_research_runtime.py", "test_select_feature_subset_runtime.py", 

1173 "test_compare_training_variants_runtime.py", 

1174 "test_v664_register_observers_runtime.py", 

1175 "test_main_world_book.py", "test_main_model_book_mode.py", "test_main_world_config.py", "test_main_world_more.py", "test_main_world_options.py", "test_main_world_risk.py", 

1176 "test_main_world_setup.py", "test_main_world_signals.py", "test_main_world_target_weights.py", 

1177 "test_main_world_bars.py", "test_main_world_options_more.py", 

1178 "test_main_world_tail.py", 

1179 "test_main_world_last.py", 

1180 "test_main_world_final.py", 

1181 "test_main_world_residue.py", 

1182 "test_main_world_closing.py", 

1183 "test_train_mains_runtime.py", "test_train_rl_sizing_runtime.py", 

1184 "test_train_pipeline_runtime.py", "test_train_runtime_gaps_a.py", 

1185 "test_train_runtime_gaps_b.py", 

1186 "test_coverage_tails_a.py", "test_coverage_tails_b.py", 

1187 "test_rank_book_legacy_step.py", 

1188 "test_target_weights_engine_tails.py", 

1189 "test_live_parity_tails.py", 

1190 "test_premia_research_context.py", 

1191 "test_wide_context_cells.py", 

1192 "test_coverage_tails_c.py", 

1193 "test_ci_divergence_fixes.py", 

1194 ], 

1195} 

1196 

1197 

1198_CHANGED_COVERAGE_LIMIT = 40 # more changed modules than this is a phase: run the full `aq test --coverage` 

1199 

1200 

1201def _changed_python_files(run=subprocess.run) -> list[str]: 

1202 """Tracked .py files outside tests/ that differ from HEAD, plus new ones git would commit (V6.6.7, #367).""" 

1203 def lines(command: list[str]) -> list[str]: 

1204 return [line.strip() for line in run(command, cwd=ROOT_DIR, capture_output=True, text=True, check=False).stdout.splitlines() if line.strip()] 

1205 

1206 found = lines(["git", "diff", "--name-only", "--diff-filter=ACMR", "HEAD", "--", "*.py"]) 

1207 found += lines(["git", "ls-files", "--others", "--exclude-standard", "--", "*.py"]) 

1208 return sorted({path.replace("\\", "/") for path in found if not path.replace("\\", "/").startswith("tests/")}) 

1209 

1210 

1211def _changed_test_files(run=subprocess.run) -> list[str]: 

1212 def lines(command: list[str]) -> list[str]: 

1213 return [line.strip() for line in run(command, cwd=ROOT_DIR, capture_output=True, text=True, check=False).stdout.splitlines() if line.strip()] 

1214 

1215 found = lines(["git", "diff", "--name-only", "--diff-filter=ACMR", "HEAD", "--", "tests/test_*.py"]) 

1216 found += lines(["git", "ls-files", "--others", "--exclude-standard", "--", "tests/test_*.py"]) 

1217 return sorted({Path(path).name for path in found}) 

1218 

1219 

1220def _module_needles(path: str) -> list[str]: 

1221 """What a test that exercises `path` names: its dotted module, its file path, or (for a script) its stem.""" 

1222 posix = path.replace("\\", "/") 

1223 stem = posix[:-3] if posix.endswith(".py") else posix 

1224 needles = [stem.replace("/", "."), posix] 

1225 if posix.startswith("scripts/") or "/" not in posix: 

1226 needles.append(f'"{Path(stem).name}"') 

1227 needles.append(Path(stem).name) 

1228 return needles 

1229 

1230 

1231_LEAN_BACKTEST_TEST_FILE = "test_lean_backtest_ml_coverage.py" 

1232 

1233 

1234def _tests_for_changed(changed: list[str], registered: set[str], grep) -> list[str]: 

1235 """Registered test files that name a changed module. `grep(needle)` returns the test file names containing it. A test 

1236 that names a changed module but is in no group is an error: an unregistered test never runs in its subsystem. The real 

1237 Lean run is the one file deliberately in no group (it runs only under --lean), so it is neither chosen nor an error.""" 

1238 chosen: set[str] = set() 

1239 unregistered: set[str] = set() 

1240 for path in changed: 

1241 for needle in _module_needles(path): 

1242 for name in grep(needle): 

1243 if name != _LEAN_BACKTEST_TEST_FILE: 

1244 (chosen if name in registered else unregistered).add(name) 

1245 if unregistered: 

1246 raise SystemExit(f"test files outside _SUBSYSTEM_TEST_FILES: {sorted(unregistered)} (register them in aq_cli.py)") 

1247 return sorted(chosen) 

1248 

1249 

1250def _git_grep_tests(needle: str, run=subprocess.run) -> list[str]: 

1251 result = run(["git", "grep", "-l", "-F", "--untracked", needle, "--", "tests/test_*.py"], cwd=ROOT_DIR, capture_output=True, text=True, check=False) 

1252 return [Path(line.strip()).name for line in result.stdout.splitlines() if line.strip()] 

1253 

1254 

1255COVERAGE_DIR = "coverage-report" # V6.6.10: every coverage output in one folder (pyproject's [tool.coverage.*] point here too) 

1256 

1257 

1258def _coverage_json_covers(json_path: Path, changed: list[str]) -> bool: 

1259 """True when a coverage.json written after every changed file shows each of them with no missing line.""" 

1260 if not json_path.exists(): 

1261 return False 

1262 stamp = json_path.stat().st_mtime 

1263 if any((ROOT_DIR / path).exists() and (ROOT_DIR / path).stat().st_mtime > stamp for path in changed): 

1264 return False 

1265 try: 

1266 files = {name.replace("\\", "/"): report for name, report in json.loads(json_path.read_text(encoding="utf-8")).get("files", {}).items()} 

1267 except (OSError, ValueError): 

1268 return False 

1269 return all(path in files and not files[path].get("missing_lines") for path in changed) 

1270 

1271 

1272def _run_changed_coverage(*, run=subprocess.run, grep=None, runner=None) -> int: 

1273 """`aq test --coverage --changed` (V6.6.7, #367): the fast gate before a commit. The tests that name each changed module 

1274 run under coverage, and every changed file must reach 100%. A fresh full run's coverage.json that already shows them 

1275 covered passes at once; more than `_CHANGED_COVERAGE_LIMIT` changed modules is a phase, so the full gate is asked for.""" 

1276 changed = _changed_python_files(run) 

1277 if not changed: 

1278 print("coverage --changed: no changed module") 

1279 return 0 

1280 if _coverage_json_covers(ROOT_DIR / COVERAGE_DIR / "coverage.json", changed): 

1281 print(f"coverage --changed: coverage.json is newer than the {len(changed)} changed file(s) and shows them at 100%") 

1282 return 0 

1283 if len(changed) > _CHANGED_COVERAGE_LIMIT: 

1284 print(f"coverage --changed: {len(changed)} changed modules, too many for the fast gate: run `aq test --coverage`") 

1285 return 1 

1286 registered = {name for names in _SUBSYSTEM_TEST_FILES.values() for name in names} 

1287 tests = sorted(set(_tests_for_changed(changed, registered, grep or (lambda needle: _git_grep_tests(needle, run)))) | (set(_changed_test_files(run)) & registered)) 

1288 if not tests: 

1289 print(f"coverage --changed: no test names {changed}: write one (AGENTS.md 'Coverage: 100% after every commit')") 

1290 return 1 

1291 data = ROOT_DIR / COVERAGE_DIR / ".coverage.changed" 

1292 data.parent.mkdir(parents=True, exist_ok=True) 

1293 data.unlink(missing_ok=True) 

1294 env = {**os.environ, "COVERAGE_FILE": str(data)} 

1295 execute = runner or (lambda cmd: run(cmd, cwd=ROOT_DIR, env=env, check=False).returncode) 

1296 print(f"coverage --changed: {len(changed)} module(s), {len(tests)} test file(s)", flush=True) 

1297 worst = execute([sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "-m", "not lean_backtest", 

1298 "--cov", "--cov-report=", "--cov-fail-under=0", *[f"tests/{name}" for name in tests]]) 

1299 report = execute([sys.executable, "-m", "coverage", "report", f"--data-file={data}", "--show-missing", "--fail-under=100", 

1300 f"--include={','.join(changed)}"]) 

1301 return worst or report 

1302 

1303 

1304def _run_coverage(args: argparse.Namespace) -> int: 

1305 """`aq test --coverage`: one pytest process per registered group, each appending to `.coverage` (a group's own total is 

1306 partial, so its gate is off), then `coverage report` and `coverage json` over the combined data.""" 

1307 if getattr(args, "changed", False): 

1308 return _run_changed_coverage() 

1309 data = Path(os.environ.get("COVERAGE_FILE") or ROOT_DIR / COVERAGE_DIR / ".coverage") 

1310 data.parent.mkdir(parents=True, exist_ok=True) 

1311 data.unlink(missing_ok=True) 

1312 chosen = [name for name in _SUBSYSTEM_TEST_FILES if getattr(args, name.replace("-", "_"), False)] 

1313 worst = 0 

1314 for name in chosen or list(_SUBSYSTEM_TEST_FILES): 

1315 print(f"== coverage: {name}", flush=True) 

1316 files = [f"tests/{file}" for file in dict.fromkeys(_SUBSYSTEM_TEST_FILES[name])] 

1317 cmd = [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "-m", "not lean_backtest", 

1318 "--cov", "--cov-append", "--cov-report=", "--cov-fail-under=0", *files] 

1319 worst = max(worst, _run(cmd)) 

1320 report = _run([sys.executable, "-m", "coverage", "report", "--show-missing", "--skip-covered"]) 

1321 _run([sys.executable, "-m", "coverage", "json", "-q", "-o", str(data.with_name("coverage.json"))]) 

1322 return worst or report 

1323 

1324 

1325TEST_COMPANIONS = {"group": ("paths",), "target": ("paths",), "watch": ("impacted", "paths")} 

1326 

1327 

1328def cmd_test(args: argparse.Namespace) -> int: 

1329 """Runs pytest with live-streamed output (same UX as a plain 

1330 subprocess.run), while also capturing it so a full run that passed can 

1331 sync the docs' facts afterward (the test badge is CI's, V6.6.6). 

1332 

1333 Default (no flags): excludes tests/test_lean_backtest_ml_coverage.py's 

1334 lean_backtest-marked tests - a real `lean backtest .` run there takes 

1335 over an hour wall-clock, and this repo's own .venv happens to have a 

1336 real Lean CLI installed, so that file's skipif alone never actually 

1337 skipped it. --lean/--full opts back in. --parallel adds pytest-xdist's 

1338 -n auto (off by default - multiple workers each importing torch is a 

1339 real OOM risk on memory-constrained dev machines). One or more 

1340 --<subsystem> flags restrict the run to _SUBSYSTEM_TEST_FILES' 

1341 filenames for those subsystems instead of the whole tree. 

1342 

1343 V5.3.10 - --ruff: runs `ruff check .` BEFORE pytest so a lint failure 

1344 fails fast without paying the full suite's wall-clock first (mirrors 

1345 ci.yml's python-lint job; single source of truth for the invocation).""" 

1346 if getattr(args, "ruff", False): 

1347 import subprocess as _sp 

1348 

1349 ruff_exit = _sp.run(["ruff", "check", "."], check=False).returncode 

1350 if ruff_exit != 0: 

1351 print(f"ruff check failed (exit {ruff_exit}) - fix lint findings before running the suite.") 

1352 return ruff_exit 

1353 

1354 import aq_testtools 

1355 

1356 paths = list(getattr(args, "paths", None) or []) 

1357 if paths and paths[0] in aq_testtools.TEST_VERBS: 

1358 return aq_testtools.run_verb(args) 

1359 problems = companion_errors(args, TEST_COMPANIONS) 

1360 if problems: 

1361 print("aq test: " + "; ".join(problems), file=sys.stderr) 

1362 return 2 

1363 if getattr(args, "list_groups", False): 

1364 rows = {name: len(files) for name, files in _SUBSYSTEM_TEST_FILES.items()} 

1365 print(json.dumps(rows, indent=2) if getattr(args, "json", False) else "\n".join(f"--{name:<14} {count} test files" for name, count in rows.items())) 

1366 return 0 

1367 if getattr(args, "light_hypothesis", False): 

1368 os.environ["HYPOTHESIS_PROFILE"] = "light" 

1369 if getattr(args, "coverage", False): 

1370 return _run_coverage(args) 

1371 extra = [*(["-k", args.k] if getattr(args, "k", None) else []), *(["--lf"] if getattr(args, "lf", False) else [])] 

1372 if getattr(args, "repeat", None): 

1373 return aq_testtools.run_repeat(args, extra) 

1374 if getattr(args, "impacted", False): 

1375 impacted = aq_testtools.impacted_tests() 

1376 if not impacted and not getattr(args, "watch", False): 

1377 print("aq test --impacted: no test names a changed module") 

1378 return 0 

1379 paths = [f"tests/{name}" for name in impacted] 

1380 

1381 cmd = [sys.executable, "-m", "pytest", "--color=yes", "--durations=15", f"--junitxml={ROOT_DIR / aq_testtools.JUNIT_LAST}", *extra] 

1382 

1383 subsystem_files: list[str] = [] 

1384 for name in _SUBSYSTEM_TEST_FILES: 

1385 if getattr(args, name.replace("-", "_"), False): 

1386 subsystem_files.extend(_SUBSYSTEM_TEST_FILES[name]) 

1387 is_filtered_run = bool(subsystem_files) 

1388 

1389 if paths: 

1390 cmd.extend(paths) 

1391 is_filtered_run = True 

1392 elif is_filtered_run: 

1393 cmd.extend(f"tests/{name}" for name in dict.fromkeys(subsystem_files)) 

1394 else: 

1395 cmd.append("tests/") 

1396 

1397 if getattr(args, "lean", False) or getattr(args, "full", False): 

1398 if is_filtered_run: 

1399 cmd.append("tests/test_lean_backtest_ml_coverage.py") 

1400 else: 

1401 cmd.extend(["-m", "not lean_backtest"]) 

1402 

1403 if getattr(args, "parallel", False): 

1404 cmd.extend(["-n", "auto"]) 

1405 if getattr(args, "dry_run", False): 

1406 print(" ".join(cmd)) 

1407 return 0 

1408 (ROOT_DIR / aq_testtools.JUNIT_LAST).parent.mkdir(parents=True, exist_ok=True) 

1409 if getattr(args, "watch", False): 

1410 def once() -> int: 

1411 current = cmd 

1412 if getattr(args, "impacted", False): 

1413 tests = [f"tests/{name}" for name in aq_testtools.impacted_tests()] 

1414 if not tests: 

1415 print("nothing impacted yet; waiting for a change") 

1416 return 0 

1417 current = [part for part in cmd if not part.startswith("tests/")] + tests 

1418 return _run(current) 

1419 

1420 return aq_testtools.watch(once) 

1421 

1422 exit_code, output = _run_captured(cmd) 

1423 

1424 captured = _ANSI_ESCAPE_PATTERN.sub("", output) 

1425 # only a full, unfiltered run syncs the docs: the test badge itself is CI's (scripts/test_badge.py, pages.yml) 

1426 if re.search(r"\d+ passed", captured) and not is_filtered_run: 

1427 _sync_doc_facts_best_effort() 

1428 

1429 return exit_code 

1430 

1431 

1432def cmd_backtest(args: argparse.Namespace) -> int: 

1433 lean_binary = _find_quantconnect_lean_binary() 

1434 if lean_binary is None: 

1435 print("error: QuantConnect Lean CLI not found (checked .venv and PATH).", file=sys.stderr) 

1436 return 1 

1437 # The default is a small local derivative of the pinned official image. 

1438 # It contains redis in the image itself, so Lean CLI does not need to 

1439 # create and Windows-bind-mount a generated requirements.txt file. 

1440 # --image remains an escape hatch for deliberately selecting another 

1441 # engine image without editing this file. 

1442 engine_image = args.image or LOCAL_LEAN_ENGINE_IMAGE 

1443 lean_command = [lean_binary, "backtest", ".", "--image", engine_image] 

1444 frozen_dir = ML_DIR / "evaluation" / "run_configs" 

1445 pending = frozen_dir / "_pending.json" 

1446 if getattr(args, "dry_run", False): # before the image check: a dry run builds and touches nothing 

1447 print(" ".join(lean_command)) 

1448 print(f"config frozen to {pending} and renamed to <run>.json; publishing {'off' if getattr(args, 'no_publish', False) else 'on (README, reports)'}") 

1449 return 0 

1450 if not args.image and not _ensure_local_lean_engine_image(): 

1451 return 1 

1452 frozen_dir.mkdir(parents=True, exist_ok=True) 

1453 shutil.copy2(CONFIG_PATH, pending) 

1454 before = _lean_run_names() 

1455 # Lean CLI creates config/startup files with tempfile.mkdtemp(). On some 

1456 # Windows Docker Desktop installations those Python-created directories 

1457 # are not readable by Docker, while ordinary host files are. Run through 

1458 # the project wrapper so every generated temp directory receives 

1459 # Docker-readable inherited permissions before the container is created. 

1460 windows_wrapper = ROOT_DIR / "scripts" / "run_lean_cli_windows.py" 

1461 if sys.platform == "win32" and windows_wrapper.is_file(): 

1462 lean_command = [sys.executable, str(windows_wrapper), *lean_command[1:]] 

1463 exit_code = _run(lean_command) 

1464 created = sorted(_lean_run_names() - before) # not _resolve_lean_run_dir: it prefers the README pin to the new run 

1465 after = ROOT_DIR / "backtests" / created[-1] if created else None 

1466 if after is not None: 

1467 pending.replace(frozen_dir / f"{after.name}.json") 

1468 print(f"froze this run's config: {frozen_dir / (after.name + '.json')}") 

1469 if getattr(args, "no_publish", False): 

1470 print("--no-publish: the README, the charts and the evaluation reports were left as they were; " 

1471 f"aq evaluate --lean-report --backtest-dir {after.name if after else '<run>'} writes them when wanted") 

1472 return exit_code 

1473 # Attempt the README update regardless of exit_code, NOT only on == 0. 

1474 # On a resource-constrained machine Lean's Python-interpreter teardown 

1475 # can exceed its own hardcoded 10-second shutdown-isolator budget and 

1476 # make `lean backtest` return a NON-zero exit code even though the 

1477 # backtest itself fully completed and wrote valid results - a cosmetic 

1478 # "PythonInitializer.Shutdown() ... Operation timed out" error that 

1479 # fires AFTER statistics are already saved (see development/Problems.md). 

1480 # update_readme_from_latest_backtest() self-guards: it only ever picks a 

1481 # backtest folder whose result JSON has BOTH non-empty statistics and a 

1482 # non-empty equity curve, so calling it after a genuinely-failed run 

1483 # (e.g. an init-timeout that produced no statistics) is a safe no-op. 

1484 # Decoupling the README update from Lean's flaky shutdown-phase exit 

1485 # code is the robust fix - the exit code is still returned to the caller. 

1486 try: 

1487 from generate_backtest_report import update_readme_from_latest_backtest 

1488 

1489 if update_readme_from_latest_backtest(): 

1490 print("Updated README.md's Backtest Statistics overview.") 

1491 except Exception as error: 

1492 print(f"warning: failed to update README.md's backtest results ({error})", file=sys.stderr) 

1493 # Also refreshes Other Metrics (Lean-vs-offline comparison) with this 

1494 # backtest's fresh Sharpe, rather than leaving it stale until the next 

1495 # `aq evaluate` run - same self-guarding, never-fail contract as above. 

1496 _refresh_readme_evaluation_sections() 

1497 # V6.3.0 - every run-folder tool and the Backtest Statistics for the new run (`aq evaluate --lean-report`). 

1498 try: 

1499 run_dir = _resolve_lean_run_dir(argparse.Namespace(backtest_dir=None)) 

1500 if run_dir is not None: 

1501 report_args = build_parser().parse_args(["evaluate", "--lean-report"]) 

1502 _run_lean_report(report_args, json.loads(CONFIG_PATH.read_text(encoding="utf-8")), run_dir, pin=False) 

1503 except Exception as error: 

1504 print(f"warning: the Lean report failed ({error})", file=sys.stderr) 

1505 if exit_code != 0: 

1506 print( 

1507 "note: `lean backtest` returned a non-zero exit code. If the run reached the end date and " 

1508 "statistics were written, this is most likely the benign Python-shutdown timeout on a " 

1509 "resource-constrained machine (development/Problems.md) - the README was still updated from " 

1510 "the completed results above. Check the backtest log if unsure the run actually finished.", 

1511 file=sys.stderr, 

1512 ) 

1513 return exit_code 

1514 

1515 

1516def _lean_run_names() -> set[str]: 

1517 """The run folders under backtests/ (Lean names each run by its start time).""" 

1518 root = ROOT_DIR / "backtests" 

1519 return {path.name for path in root.iterdir() if path.is_dir()} if root.is_dir() else set() 

1520 

1521 

1522def _run_config_for(run_dir: Path, config: dict) -> dict: 

1523 """The config a Lean run ran with (its frozen copy), else `config`, saying so: an old run's own caps and classes may differ.""" 

1524 from evaluation.lean_attribution import run_config_path 

1525 

1526 snapshot = run_config_path(run_dir, ROOT_DIR) 

1527 if snapshot is None: 

1528 print(f"note: no frozen config for {run_dir.name}; using the current config.json", file=sys.stderr) 

1529 return config 

1530 return json.loads(snapshot.read_text(encoding="utf-8")) 

1531 

1532 

1533# One flag per scripts/profile_subsystems.py subsystem - same 

1534# established loop-generated-flags convention as _SUBSYSTEM_TEST_FILES 

1535# above (`aq test --cli --risk` etc.), applied to `aq profile` instead of 

1536# `aq test`. Values aren't used (dispatch is by attribute presence, same 

1537# as cmd_test()) - a plain tuple would do, kept as a dict of Nones so the 

1538# iteration pattern below reads identically to _SUBSYSTEM_TEST_FILES's. 

1539_PROFILE_SUBSYSTEM_FLAGS: dict[str, None] = { 

1540 "regime": None, "topology": None, "topology-cached": None, "learned-topology": None, "liquidity": None, 

1541 "gating": None, "analyzer": None, "indicators": None, "options": None, 

1542} 

1543 

1544 

1545def cmd_profile(args: argparse.Namespace) -> int: 

1546 """Wraps scripts/profile_inference.py (default) - the cProfile+wall- 

1547 clock harness for main.py's per-bar inference hot path (see 

1548 development/Problems.md for what it found: weight-array/batched-stack 

1549 caching, expert-loop batching, and _conv1d_causal vectorization, 

1550 -89.2% total profiled cost) - or, when any --<subsystem> flag is set, 

1551 scripts/profile_subsystems.py instead (regime/topology/topology-cached/ 

1552 liquidity/gating/analyzer/indicators/options - everything else main.py 

1553 calls per bar that inference profiling never covered; --topology-cached 

1554 exercises development/Problems.md#36's correlation-stability cache 

1555 against slowly-drifting synthetic data, since --topology's fully 

1556 independent per-iteration returns can never show that cache's 

1557 benefit; --options exercises risk/asset_class_router.py:: 

1558 route_multi_leg_option_sizing() end-to-end, V4.9 Priority 7). Same 

1559 subprocess-wrapper convention every other non-`trade-lock`/`fetch` 

1560 command follows (_run(), not an in-process import). 

1561 

1562 --batched/--no-gc/--bucket-report/--parallel/--pool-workers/ 

1563 --symbols-per-bar only have meaning for the inference path (no batched 

1564 variant, GC-isolation/bucketing diagnostic, or process-pool benchmark 

1565 exists for these pure subsystem functions) - combining any of them 

1566 with a subsystem flag is a user error, rejected loudly rather than 

1567 silently ignored. --parallel (V4.9 Priority 6) runs a real 

1568 ProcessPoolExecutor benchmark of inference/parallel_inference.py's 

1569 run_symbol_inference() against a sequential baseline, answering that 

1570 module's own never-measured IPC/pickling break-even warning.""" 

1571 subsystem_flags = [name for name in _PROFILE_SUBSYSTEM_FLAGS if getattr(args, name.replace("-", "_"), False)] 

1572 inference_only_flags = args.batched or args.no_gc or args.bucket_report or args.parallel 

1573 if subsystem_flags and inference_only_flags: 

1574 print( 

1575 "error: --batched/--no-gc/--bucket-report/--parallel only apply to inference profiling, not --<subsystem> flags", 

1576 file=sys.stderr, 

1577 ) 

1578 return 1 

1579 

1580 if subsystem_flags: 

1581 cmd = [sys.executable, "scripts/profile_subsystems.py"] 

1582 if args.iterations is not None: 

1583 cmd.extend(["--iterations", str(args.iterations)]) 

1584 cmd.extend(["--sort", args.sort]) 

1585 cmd.extend(f"--{name}" for name in subsystem_flags) 

1586 return _run(cmd) 

1587 

1588 cmd = [sys.executable, "scripts/profile_inference.py"] 

1589 if args.iterations is not None: 

1590 cmd.extend(["--iterations", str(args.iterations)]) 

1591 cmd.extend(["--sort", args.sort]) 

1592 if args.batched: 

1593 cmd.append("--batched") 

1594 if args.no_gc: 

1595 cmd.append("--no-gc") 

1596 if args.bucket_report: 

1597 cmd.append("--bucket-report") 

1598 if args.parallel: 

1599 cmd.append("--parallel") 

1600 if args.pool_workers is not None: 

1601 cmd.extend(["--pool-workers", str(args.pool_workers)]) 

1602 if args.symbols_per_bar is not None: 

1603 cmd.extend(["--symbols-per-bar", str(args.symbols_per_bar)]) 

1604 return _run(cmd) 

1605 

1606 

1607def _result_ids(folder: Path) -> list[str]: 

1608 """The result JSONs of a Lean run folder (those with statistics), by id.""" 

1609 ids = [] 

1610 for candidate in sorted(folder.glob("*.json")): 

1611 if candidate.stem.isdigit(): 

1612 ids.append(candidate.stem) 

1613 return ids 

1614 

1615 

1616def cmd_report(args: argparse.Namespace) -> int: 

1617 backtests = ROOT_DIR / "backtests" 

1618 if not args.backtest_dir: 

1619 folders = sorted((path for path in backtests.iterdir() if path.is_dir()), key=lambda folder: folder.stat().st_mtime, reverse=True)[:10] if backtests.is_dir() else [] 

1620 if not folders: 

1621 print("no Lean runs in backtests/") 

1622 return 1 

1623 for folder in folders: 

1624 print(f"{folder.name} result ids: {', '.join(_result_ids(folder)) or '-'}") 

1625 print("aq report RUN [RESULT_ID]") 

1626 return 0 

1627 if not args.result_id: 

1628 ids = _result_ids(backtests / args.backtest_dir) 

1629 if len(ids) != 1: 

1630 print(f"aq report: {args.backtest_dir} holds {len(ids)} results ({', '.join(ids) or 'none'}): give RESULT_ID", file=sys.stderr) 

1631 return 2 

1632 args.result_id = ids[0] 

1633 lean_binary = _find_quantconnect_lean_binary() 

1634 if lean_binary is None: 

1635 print("error: QuantConnect Lean CLI not found (checked .venv and PATH).", file=sys.stderr) 

1636 return 1 

1637 backtest_dir = ROOT_DIR / "backtests" / args.backtest_dir 

1638 return _run( 

1639 [ 

1640 lean_binary, 

1641 "report", 

1642 "--backtest-results", 

1643 str(backtest_dir / f"{args.result_id}.json"), 

1644 "--report-destination", 

1645 str(backtest_dir / "report.html"), 

1646 "--overwrite", 

1647 ] 

1648 ) 

1649 

1650 

1651def cmd_research(args: argparse.Namespace) -> int: 

1652 """`aq research` (V6.4.3): IC, non-overlapping and HAC t-stats, bootstrap CI, era stability and decay of any signal on 

1653 the validation and backtest splits (evaluation/research_harness.py).""" 

1654 from evaluation.research_runners import run_signal_report 

1655 

1656 horizons = tuple(int(value) for value in str(args.horizons).split(",") if value.strip()) 

1657 import pandas as pd 

1658 

1659 from evaluation.signal_tools import validate_signal_frame 

1660 

1661 problems = validate_signal_frame(pd.read_csv(args.signal, dtype={"date": str, "ticker": str})) if Path(args.signal).exists() else {"errors": []} 

1662 if problems["errors"]: 

1663 print("aq research: the signal file has errors:\n" + "\n".join(f" {line}" for line in problems["errors"]), file=sys.stderr) 

1664 return 1 

1665 report = run_signal_report(Path(args.signal), args.dataset, horizons=horizons) 

1666 out = Path(args.out) if args.out else ML_DIR / "evaluation" / "signal_report.json" 

1667 _write_evaluation_json(out, report) 

1668 if getattr(args, "json", False): 

1669 print(json.dumps(report, indent=2, default=str)) 

1670 return 0 

1671 for split, entry in report["splits"].items(): 

1672 for horizon in horizons: 

1673 row = entry.get(f"h{horizon}") 

1674 if row and row["num_dates"]: 

1675 print(f"{split:10s} h{horizon:<3d} IC {row['mean_ic']:+.4f} t {row['t']:.2f} non-overlap t {row['nonoverlap_t']:.2f} " 

1676 f"HAC t {row['hac_t']:.2f} CI {row['ci95']}") 

1677 print(f"wrote {out}") 

1678 return 0 

1679 

1680 

1681def _cycle_research(args: argparse.Namespace) -> int: 

1682 """`aq cycle research <stage>`: one stage of a pre-registered round (evaluation/research_round.py). Selection reads free cells only.""" 

1683 from evaluation import research_round as rounds 

1684 

1685 stage = args.stage 

1686 if stage == "rules": 

1687 payload = json.loads(Path(args.draft).read_text(encoding="utf-8")) 

1688 print(rounds.write_rules(payload, Path(args.round))) 

1689 return 0 

1690 spec = rounds.load_round(Path(args.round), root=ROOT_DIR) 

1691 score_dir = spec.out_dir / "scores" 

1692 holdout_ledger = ROOT_DIR / rounds.HOLDOUT_LEDGER 

1693 if stage in ("score", "placebo"): 

1694 cell = rounds._load_selection_cell(spec, ROOT_DIR) 

1695 if stage == "score": 

1696 rounds.stage_score(spec, cell=cell, score_dir=score_dir, only=tuple(args.only or ()), force=args.force, emit=lambda line: print(line, flush=True)) 

1697 else: 

1698 rounds.stage_placebo(spec, cell=cell, score_dir=score_dir, draws=args.draws, force=args.force, emit=lambda line: print(line, flush=True)) 

1699 return 0 

1700 if stage == "gate": 

1701 print(json.dumps(rounds.stage_gate(spec), indent=1)) 

1702 elif stage == "pbo": 

1703 print(json.dumps(rounds.stage_pbo(spec, root=ROOT_DIR), indent=1)) 

1704 elif stage == "report": 

1705 print(json.dumps({key: value for key, value in rounds.stage_report(spec, alpha_fn=_round_alpha_fn()).items() if key != "trials"}, indent=1)) 

1706 elif stage == "freeze": 

1707 if not args.trial: 

1708 print("freeze needs --trial", file=sys.stderr) 

1709 return 2 

1710 path, digest = rounds.stage_freeze(spec, {"trial": args.trial}, holdout_ledger=holdout_ledger) 

1711 print(f"{path} {digest}") 

1712 elif stage == "hold": 

1713 if not args.trial or not args.digest: 

1714 print("hold needs --trial and --digest", file=sys.stderr) 

1715 return 2 

1716 import datetime as _datetime 

1717 

1718 created = _datetime.datetime.now(_datetime.timezone.utc).replace(microsecond=0).isoformat() 

1719 verdict = rounds.stage_hold( 

1720 spec, args.trial, root=ROOT_DIR, freeze_path=spec.out_dir / f"freeze_{args.trial}.json", digest=args.digest, holdout_ledger=holdout_ledger, 

1721 created_at=created, score_dir=score_dir, alpha_fn=_round_alpha_fn(), 

1722 ) 

1723 print(json.dumps(verdict, indent=1, default=str)) 

1724 return 0 

1725 

1726 

1727def _round_alpha_fn(): 

1728 """Alpha of a sleeve's daily series against SPY, AGG and BTC on the wide root, on a session basis.""" 

1729 from evaluation.alpha_proof import alpha_regression, benchmark_daily_returns, to_sessions 

1730 

1731 assets = {"phase1": {"universe": {"assets": [ 

1732 {"ticker": "SPY", "security_type": "equity", "data_path": "data/equity/usa/daily/spy.zip"}, 

1733 {"ticker": "AGG", "security_type": "equity", "data_path": "data/equity/usa/daily/agg.zip"}, 

1734 {"ticker": "BTCUSD", "security_type": "crypto", "data_path": "data/crypto/coinbase/daily/btcusd_trade.zip"}, 

1735 ]}}} 

1736 

1737 def alpha(series): 

1738 bench = benchmark_daily_returns(ROOT_DIR, assets, ("SPY", "AGG", "BTCUSD"), start=str(series.index.min()), end=str(series.index.max()), data_dir="data_wide", required=False) 

1739 return alpha_regression(to_sessions(series, bench.index), bench) 

1740 

1741 return alpha 

1742 

1743 

1744def _generations_dir() -> Path: 

1745 return ML_DIR / "generations" 

1746 

1747 

1748def _cycle_ledger_rows(args: argparse.Namespace) -> list[dict]: 

1749 """The generations' ledger from `--ledger-file`, or from the branch the scheduled Action writes. No branch yet reads as empty.""" 

1750 from evaluation.forward_ledger import read_ledger 

1751 

1752 if getattr(args, "ledger_file", None): 

1753 return read_ledger(Path(args.ledger_file)) 

1754 fetched = subprocess.run(["git", "fetch", "--quiet", "origin", "forward-ledger:forward-ledger"], cwd=ROOT_DIR, capture_output=True, text=True, encoding="utf-8", check=False) 

1755 if fetched.returncode != 0: 

1756 print("warning: could not fetch origin/forward-ledger: reading the local branch, which may be old", file=sys.stderr) 

1757 result = subprocess.run(["git", "show", "forward-ledger:forward/generations.jsonl"], cwd=ROOT_DIR, capture_output=True, text=True, encoding="utf-8", check=False) 

1758 return [json.loads(line) for line in result.stdout.splitlines() if line.strip()] if result.returncode == 0 else [] 

1759 

1760 

1761def _cycle_status(args: argparse.Namespace, *, write: bool = True) -> dict: 

1762 from dataclasses import asdict 

1763 

1764 from evaluation.generation_ledger import judge_generations 

1765 from evaluation.generation_registry import load_registry 

1766 from evaluation.research_cycle import due_actions, read_json_or, sessions_since_retrain, status_view 

1767 

1768 registry = load_registry(_generations_dir() / "registry.json") 

1769 policy = read_json_or(_generations_dir() / "policy.json", {}) 

1770 rows = _cycle_ledger_rows(args) 

1771 judged = judge_generations(rows) 

1772 entries = {name: asdict(entry) for name, entry in registry.items()} 

1773 session = rows[-1]["payload"].get("session") if rows else None 

1774 keys = _broker_keys_present() 

1775 sessions = sorted({row["payload"].get("session") for row in rows if row["payload"].get("session")}) 

1776 behind = 0 

1777 if session: 

1778 import datetime as _datetime 

1779 

1780 import numpy as np 

1781 

1782 behind = int(np.busday_count(session, _datetime.datetime.now(_datetime.timezone.utc).date().isoformat())) 

1783 actions = due_actions( 

1784 entries, judged, session=session, sessions_behind=behind, sessions_since_retrain=sessions_since_retrain(ML_DIR / "cycle", sessions), broker_keys=keys, record_started=bool(rows), 

1785 policy_enabled=bool(policy.get("enabled")), model_age_days=_installed_model_age_days(), 

1786 ) 

1787 view = status_view(entries, judged, actions, session=session, policy=policy) 

1788 if write: 

1789 (_generations_dir() / "status.json").write_text(json.dumps(view, indent=1, sort_keys=True) + "\n", encoding="utf-8", newline="\n") 

1790 return view 

1791 

1792 

1793def _installed_model_age_days() -> float | None: 

1794 """Days since the installed sequence model was written (the age `main.py` checks against the kill switch's limit), or None with no model.""" 

1795 import time as _time 

1796 

1797 path = ML_DIR / "sequence_model.json" 

1798 return max(0.0, (_time.time() - path.stat().st_mtime) / 86400.0) if path.exists() else None 

1799 

1800 

1801def _cycle_promote(args: argparse.Namespace) -> int: 

1802 """A change of stage, by rule. It refuses anything R-ADMIT1 doesn't allow, and it never touches a broker setting or a live flag.""" 

1803 from dataclasses import replace 

1804 

1805 from evaluation.generation_ledger import evidence_for, generation_state, judge_generations, rows_for 

1806 from evaluation.generation_registry import append_lifecycle, lifecycle_is_intact, load_registry, next_stage, save_registry 

1807 

1808 registry_path = _generations_dir() / "registry.json" 

1809 registry = load_registry(registry_path) 

1810 if args.generation not in registry: 

1811 print(f"{args.generation} is not in the registry", file=sys.stderr) 

1812 return 2 

1813 generation = registry[args.generation] 

1814 rows = _cycle_ledger_rows(args) 

1815 judged = judge_generations(rows) 

1816 if judged["chain_valid"] is False: 

1817 print("the generations' chain is broken: no stage moves on it", file=sys.stderr) 

1818 return 1 

1819 mine = rows_for(rows, args.generation) 

1820 state = generation_state(generation, mine) 

1821 returns = {row["session"]: float(row["session_return"]) for row in mine if row.get("status") == "ok" and row.get("session_return") is not None} 

1822 allocations = judged.get("latest_allocation") or {} 

1823 shares = allocations.get("shares") or {} 

1824 others = {name: value for name, value in shares.items() if name != args.generation} 

1825 incumbent = max(others, key=lambda name: others[name]) if others else None 

1826 theirs = {row["session"]: float(row["session_return"]) for row in rows_for(rows, incumbent) if row.get("status") == "ok" and row.get("session_return") is not None} if incumbent else None 

1827 evidence = evidence_for(generation, (judged.get("generations") or {}).get(args.generation, {}), incumbent_returns=theirs, own_returns=returns, holdouts_spent=(_generations_dir() / "holdout_ledger.jsonl").exists(), state=state) 

1828 allowed = next_stage(generation, evidence) 

1829 full_book = args.to == "active" and generation.stage == "ramping" and float(shares.get(args.generation, 0.0)) >= 1.0 

1830 # A generation with no capital left may retire by hand: that takes risk off. 

1831 retiring = args.to == "retired" and generation.stage in ("active", "fading", "winding_down", "ramping") 

1832 if args.to != allowed and not full_book and not retiring: 

1833 print(f"refused: {args.generation} is {generation.stage}, and the rule allows {allowed}, not {args.to}", file=sys.stderr) 

1834 return 2 

1835 import datetime as _datetime 

1836 

1837 created = _datetime.datetime.now(_datetime.timezone.utc).replace(microsecond=0).isoformat() 

1838 registry[args.generation] = replace(generation, stage=args.to) 

1839 save_registry(registry_path, registry) 

1840 lifecycle = _generations_dir() / "lifecycle.jsonl" 

1841 append_lifecycle(lifecycle, event="stage", payload={"generation": args.generation, "from": generation.stage, "to": args.to, "share": float(shares.get(args.generation, 0.0))}, created_at=created) 

1842 print(f"{args.generation}: {generation.stage} -> {args.to}; lifecycle intact: {lifecycle_is_intact(lifecycle)[0]}") 

1843 return 0 

1844 

1845 

1846def _cycle_schedule(args: argparse.Namespace) -> int: 

1847 """Renders the weekly job. `install` registers it only on a machine that passes the RAM preflight, and never in a dry run.""" 

1848 from evaluation.research_cycle import install_command, ram_preflight, render_schedule 

1849 

1850 platform = args.platform or ("windows" if sys.platform == "win32" else "linux") 

1851 text = render_schedule(platform, repo=ROOT_DIR, host=args.host) 

1852 print(text) 

1853 if args.schedule_command == "show" or args.dry_run: 

1854 return 0 

1855 preflight = ram_preflight(args.host) 

1856 if not preflight["ok"]: 

1857 print(f"refusing to schedule a retrain here: {preflight['reason']}", file=sys.stderr) 

1858 return 2 

1859 task = ML_DIR / "cycle" / ("schedule.xml" if platform == "windows" else "schedule.cron") 

1860 task.parent.mkdir(parents=True, exist_ok=True) 

1861 task.write_text(text, encoding="utf-16" if platform == "windows" else "utf-8", newline="\n") 

1862 return subprocess.run(install_command(platform, task_file=task), cwd=ROOT_DIR, check=False).returncode 

1863 

1864 

1865def _cycle_retrain(args: argparse.Namespace) -> int: 

1866 command = [sys.executable, str(ROOT_DIR / "scripts" / "cycle_retrain.py"), *(["--host", args.host] if args.host else [])] 

1867 if getattr(args, "estimate", False): 

1868 return subprocess.run([*command, "--estimate"], cwd=ROOT_DIR, check=False).returncode 

1869 if getattr(args, "list_runs", False): 

1870 return subprocess.run([*command, "--list-runs"], cwd=ROOT_DIR, check=False).returncode 

1871 if getattr(args, "resume", None): 

1872 # V6.6.10: the run folder holds its own settings (resume.json), so nothing else is needed 

1873 return subprocess.run([*command, "--resume", *([] if args.resume == "latest" else [args.resume])], cwd=ROOT_DIR, check=False).returncode 

1874 if not args.host: 

1875 print("name a --host (local or codespace), or --resume a stopped run", file=sys.stderr) 

1876 return 2 

1877 if args.if_due: 

1878 view = _cycle_status(args, write=False) 

1879 if not any(str(item.get("action", "")).startswith("aq cycle retrain") for item in view["due"]): 

1880 print("no retrain due") 

1881 return 0 

1882 if args.procedure: 

1883 command += ["--procedure", args.procedure] 

1884 elif not args.smoke: 

1885 print("name a --procedure, or run --smoke", file=sys.stderr) 

1886 return 2 

1887 if args.smoke: 

1888 command.append("--smoke") 

1889 if args.dry_run: 

1890 command.append("--dry-run") 

1891 # V6.6.10: these were dropped on the way to the script 

1892 if getattr(args, "memory_profile", "standard") != "standard": 

1893 command += ["--memory-profile", args.memory_profile] 

1894 if getattr(args, "min_ram_gb", None) is not None: 

1895 command += ["--min-ram-gb", str(args.min_ram_gb)] 

1896 if getattr(args, "score_end", None): 

1897 command += ["--score-end", args.score_end] 

1898 return subprocess.run(command, cwd=ROOT_DIR, check=False).returncode 

1899 

1900 

1901def cmd_cycle(args: argparse.Namespace) -> int: 

1902 """`aq cycle`: the research cycle, research round to retirement of a generation.""" 

1903 command = args.cycle_command 

1904 if command == "research": 

1905 return _cycle_research(args) 

1906 if command == "status": 

1907 view = _cycle_status(args) 

1908 print(json.dumps(view, indent=1, default=str)) # the view is JSON either way; --json is accepted for the rubric's read convention 

1909 return 0 if view["chain_valid"] is not False else 1 

1910 if command == "daily": 

1911 extra = ["--dry-run"] if args.dry_run else [] 

1912 ledger = args.ledger_file or str(ML_DIR / "cycle" / "generations.jsonl") 

1913 return subprocess.run([sys.executable, str(ROOT_DIR / "scripts" / "cycle_daily.py"), "--ledger", ledger, *extra], cwd=ROOT_DIR, check=False).returncode 

1914 if command == "decide": 

1915 return subprocess.run( 

1916 [sys.executable, str(ROOT_DIR / "scripts" / "cycle_decide.py"), "--generation", args.generation, "--weights", args.weights, "--ledger", args.ledger_file, "--session", args.session], cwd=ROOT_DIR, check=False, 

1917 ).returncode 

1918 if command == "retrain": 

1919 return _cycle_retrain(args) 

1920 if command == "promote": 

1921 return _cycle_promote(args) 

1922 if command == "schedule": 

1923 return _cycle_schedule(args) 

1924 raise SystemExit(f"unknown cycle command {command}") 

1925 

1926 

1927def _formal_sorry_hits() -> list[str]: 

1928 hits = [] 

1929 for path in sorted((FORMAL_DIR / "AetherFormal").glob("*.lean")): 

1930 for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): 

1931 if re.search(r"\b(sorry|admit)\b", line): 

1932 hits.append(f"{path.relative_to(ROOT_DIR)}:{number}") 

1933 return hits 

1934 

1935 

1936def cmd_prove(args: argparse.Namespace) -> int: 

1937 """`aq prove` (V6.4.3): builds the Lean 4 proofs in formal/ (Mathlib comes from its cache: `lake exe cache get`) and, 

1938 with --regen-cases, rewrites aether_quant/_formal_cases/, the inputs and Lean-computed outputs that 

1939 tests/test_formal_differential_*.py run the Python functions against. --check-sorry only scans the specs for an 

1940 unfinished proof and needs no Lean install.""" 

1941 if getattr(args, "list", False): 

1942 specs = sorted(path.stem for path in (FORMAL_DIR / "AetherFormal").glob("*.lean")) 

1943 print(json.dumps(specs) if getattr(args, "json", False) else "\n".join(specs)) 

1944 return 0 

1945 if args.check_sorry: 

1946 hits = _formal_sorry_hits() 

1947 if getattr(args, "json", False): 

1948 print(json.dumps({"unfinished": hits})) 

1949 return 1 if hits else 0 

1950 for hit in hits: 

1951 print(f"unfinished proof: {hit}") 

1952 print(f"{len(hits)} sorry/admit in formal/AetherFormal/") 

1953 return 1 if hits else 0 

1954 lake = shutil.which("lake") 

1955 if lake is None: 

1956 print("lake not found: install elan (https://github.com/leanprover/elan), then `lake exe cache get` in formal/", 

1957 file=sys.stderr) 

1958 return 2 

1959 target = f"AetherFormal.{args.module}" if args.module else "AetherFormal" 

1960 exit_code = _run([lake, "build", target], cwd=FORMAL_DIR) 

1961 if exit_code or not args.regen_cases: 

1962 return exit_code 

1963 # interpreted, so no Mathlib C code has to be compiled for an executable 

1964 exit_code = _run([lake, "env", "lean", "--run", "AetherFormal/GenCases.lean", str(FORMAL_CASES_DIR)], cwd=FORMAL_DIR) 

1965 if exit_code: 

1966 return exit_code 

1967 from aether_quant.formal import spec_sha256 

1968 

1969 for path in sorted(FORMAL_CASES_DIR.glob("*.json")): 

1970 data = json.loads(path.read_text(encoding="utf-8")) 

1971 data["spec_sha256"] = spec_sha256(FORMAL_DIR, data["spec_files"]) 

1972 path.write_text(json.dumps(data, indent=1) + "\n", encoding="utf-8", newline="\n") # LF on Windows too: package data ships byte-identical 

1973 print(f"regenerated {len(list(FORMAL_CASES_DIR.glob('*.json')))} case files in {FORMAL_CASES_DIR.relative_to(ROOT_DIR)}") 

1974 return 0 

1975 

1976 

1977def cmd_api(args: argparse.Namespace) -> int: 

1978 host, port = getattr(args, "host", "127.0.0.1"), getattr(args, "port", 8001) 

1979 if getattr(args, "check", False): 

1980 import urllib.error 

1981 

1982 try: 

1983 with urllib.request.urlopen(f"http://{host}:{port}/health", timeout=5) as response: 

1984 print(f"api at {host}:{port}: {response.status} {response.read(200).decode('utf-8', 'replace')}") 

1985 return 0 if response.status < 400 else 1 

1986 except (urllib.error.URLError, OSError) as error: 

1987 print(f"api at {host}:{port} is not answering: {error}", file=sys.stderr) 

1988 return 1 

1989 return _run([sys.executable, "-m", "uvicorn", "monitoring.api_server:app", "--host", host, "--port", str(port), *(["--reload"] if getattr(args, "reload", True) else [])]) 

1990 

1991 

1992DASHBOARD_IMAGE = "ghcr.io/leon1706-lol/aether-quant-dashboard:latest" 

1993 

1994 

1995def dashboard_docker_command(*, image: str, port: int, data: str | None) -> list[str]: 

1996 """`docker run` for the dashboard image: demo data by default, or a mounted tree (a real run's visualization/ and ml/).""" 

1997 command = ["docker", "run", "--rm", "-p", f"127.0.0.1:{int(port)}:8000"] 

1998 if data: 

1999 command += ["-v", f"{Path(data).resolve()}:/app/data:ro", "-e", "AQ_DASHBOARD_ROOT=/app/data", "-e", "AQ_DASHBOARD_DEMO=0"] 

2000 return command + [image] 

2001 

2002 

2003def cmd_webui(args: argparse.Namespace) -> int: 

2004 if getattr(args, "docker", False): 

2005 image = args.image 

2006 if args.build: 

2007 image = "aether-quant-dashboard:latest" 

2008 code = _run(["docker", "build", "--target", "dashboard", "-t", image, "."]) 

2009 if code: 

2010 return code 

2011 print(f"dashboard on http://localhost:{args.port} ({'demo data' if not args.data else args.data}); Ctrl+C stops it") 

2012 if getattr(args, "open", False): 

2013 import webbrowser 

2014 

2015 webbrowser.open(f"http://localhost:{args.port}") 

2016 return _run(dashboard_docker_command(image=image, port=args.port, data=args.data)) 

2017 npm = "npm.cmd" if sys.platform == "win32" else "npm" 

2018 if getattr(args, "open", False): 

2019 import webbrowser 

2020 

2021 webbrowser.open(f"http://localhost:{args.port}") 

2022 return _run([npm, "run", "dev", "--", "--port", str(getattr(args, "port", 8080))], cwd=WEBUI_DIR) 

2023 

2024 

2025def _docker(command: list[str], args: argparse.Namespace) -> int: 

2026 if getattr(args, "dry_run", False): 

2027 print(" ".join(command)) 

2028 return 0 

2029 if shutil.which("docker") is None: 

2030 print("aq docker: docker is not installed or not on PATH", file=sys.stderr) 

2031 return 1 

2032 if not _docker_running(): 

2033 print("aq docker: Docker is not running: start Docker Desktop (or the docker daemon), then retry", file=sys.stderr) 

2034 return 1 

2035 return _run(command) 

2036 

2037 

2038def _docker_running() -> bool: 

2039 try: 

2040 return subprocess.run(["docker", "info"], capture_output=True, timeout=30, check=False).returncode == 0 

2041 except (OSError, subprocess.TimeoutExpired): 

2042 return False 

2043 

2044 

2045def cmd_docker_up(args: argparse.Namespace) -> int: 

2046 if args.all: 

2047 # "engine" is the one consolidated build (aether-quant-engine) that 

2048 # backs the app AND every worker below - see docker-compose.yml's 

2049 # own comment on the `engine` service and requirements/README.md. 

2050 services = [ 

2051 "redis", 

2052 "postgres", 

2053 "engine", 

2054 "experience-worker", 

2055 "audit-worker", 

2056 "performance-trigger-worker", 

2057 "retraining-worker", 

2058 "telegram-worker", 

2059 ] 

2060 return _docker(["docker", "compose", "up", "-d", *services], args) 

2061 if args.lean: 

2062 return _docker(["docker", "compose", "--profile", "lean", "up", "-d"], args) 

2063 return _docker(["docker", "compose", "up", "-d", "redis", "postgres"], args) 

2064 

2065 

2066def cmd_docker_build(args: argparse.Namespace) -> int: 

2067 return _docker(["docker", "compose", "build", *(["--no-cache"] if getattr(args, "no_cache", False) else []), "engine"], args) 

2068 

2069 

2070def cmd_docker_down(args: argparse.Namespace) -> int: 

2071 return _docker(["docker", "compose", "down"], args) 

2072 

2073 

2074def cmd_docker_ps(args: argparse.Namespace) -> int: 

2075 return _docker(["docker", "compose", "ps"], args) 

2076 

2077 

2078def cmd_docker_logs(args: argparse.Namespace) -> int: 

2079 return _docker(["docker", "compose", "logs", "--tail", str(args.tail), *(["-f"] if args.follow else []), *([args.service] if args.service else [])], args) 

2080 

2081 

2082def cmd_render_lean_config(args: argparse.Namespace) -> int: 

2083 """Render the gitignored lean.live.json from .env.live / AETHER_* env vars. 

2084 The tracked lean.json stays all-empty; live/paper deploy uses the rendered 

2085 file via `--lean-config`. See execution/lean_config_render.py.""" 

2086 from execution.lean_config_render import build_render_environment, write_rendered_config 

2087 

2088 account = getattr(args, "account", None) or None 

2089 base = Path(args.base) if args.base else LEAN_JSON_PATH 

2090 default_out = "lean.live.json" if not account or account == "default" else f"lean.live.{account}.json" 

2091 out = Path(args.out) if args.out else ROOT_DIR / default_out 

2092 env_file = Path(args.env_file) if args.env_file else ROOT_DIR / ".env.live" 

2093 

2094 try: 

2095 filled = write_rendered_config(base, out, build_render_environment(env_file=env_file, account_id=account), account_id=account) 

2096 except ValueError as exc: 

2097 print(f"Error: {exc}", file=sys.stderr) 

2098 return 1 

2099 except FileNotFoundError as exc: 

2100 print(f"Error: {exc}", file=sys.stderr) 

2101 return 1 

2102 

2103 # Credential-load audit event (development/Problems.md #42) - field 

2104 # NAMES only, matching the print statement below. A short-lived local 

2105 # AuditQueue (this is a one-shot CLI invocation, not a long-running 

2106 # process like main.py's) - never blocks/raises on a Redis hiccup. 

2107 try: 

2108 from audit import CREDENTIAL_LOAD, AuditQueue, build_audit_event 

2109 

2110 config = json.loads(CONFIG_PATH.read_text(encoding="utf-8")) if CONFIG_PATH.exists() else {} 

2111 audit_config = config.get("phase_v2", {}).get("audit_log", {}) 

2112 AuditQueue( 

2113 enabled=bool(audit_config.get("enabled", True)), 

2114 stream_name=str(audit_config.get("redis_stream", "aether:audit")), 

2115 ).push(build_audit_event(CREDENTIAL_LOAD, {"loaded_fields": filled}, actor="cli")) 

2116 except Exception: 

2117 pass 

2118 

2119 if filled: 

2120 # Field NAMES only - never the secret values. 

2121 print(f"Rendered {out} with {len(filled)} field(s): {', '.join(filled)}") 

2122 else: 

2123 print( 

2124 f"Rendered {out}, but NO secret fields were populated - check that " 

2125 f"{env_file} exists and its AETHER_* values are set." 

2126 ) 

2127 from execution.lean_config_render import validate_live_crypto_route 

2128 

2129 try: 

2130 route_config = json.loads(CONFIG_PATH.read_text(encoding="utf-8")) if CONFIG_PATH.exists() else {} 

2131 except (OSError, ValueError): 

2132 route_config = {} 

2133 for warning in validate_live_crypto_route(route_config, filled): 

2134 print(f"WARNING: {warning}", file=sys.stderr) 

2135 print(f"Deploy against it with Lean's --lean-config {out}") 

2136 return 0 

2137 

2138 

2139def _accounts_or_error(): 

2140 from execution.accounts_io import load_accounts 

2141 

2142 config = json.loads(CONFIG_PATH.read_text(encoding="utf-8")) if CONFIG_PATH.exists() else {} 

2143 return load_accounts(ROOT_DIR, config.get("phase_v2", {})) 

2144 

2145 

2146def cmd_users(args: argparse.Namespace) -> int: 

2147 """`aq users add|list|remove` (V6.6.5, #350): dashboard and API users. A token is printed once and stored only as a hash.""" 

2148 from monitoring.auth import Role, make_user, new_token 

2149 from monitoring.auth_io import load_users, save_users, users_file 

2150 

2151 try: 

2152 users = list(load_users()) 

2153 except ValueError as exc: 

2154 print(f"error: {users_file()} is invalid: {exc}", file=sys.stderr) 

2155 return 1 

2156 if args.users_command == "list" and getattr(args, "json", False): 

2157 print(json.dumps([{"name": user.name, "role": user.role.name.lower(), "accounts": list(user.accounts)} for user in users], indent=2)) 

2158 return 0 

2159 if args.users_command == "rotate": 

2160 match = next((user for user in users if user.name == args.name), None) 

2161 if match is None: 

2162 print(f"no user {args.name}", file=sys.stderr) 

2163 return 1 

2164 import aq_devtools 

2165 

2166 if not aq_devtools.confirm(f"issue {args.name} a new token and revoke the old one?", assume_yes=getattr(args, "yes", False)): 

2167 return 2 

2168 token = new_token() 

2169 users = [make_user(user.name, user.role, token, accounts=list(user.accounts)) if user.name == args.name else user for user in users] 

2170 save_users(tuple(users)) 

2171 print(f"rotated {args.name}'s token; the old one no longer works") 

2172 print(f"token (shown once, store it now): {token}") 

2173 return 0 

2174 if args.users_command == "list": 

2175 if not users: 

2176 print(f"no users ({users_file()}): the API reads are open and nothing can write") 

2177 for user in users: 

2178 print(f"{user.name:<24} {user.role.name.lower():<9} accounts {','.join(user.accounts)}") 

2179 return 0 

2180 if args.users_command == "remove": 

2181 kept = [user for user in users if user.name != args.name] 

2182 if len(kept) == len(users): 

2183 print(f"no user {args.name}", file=sys.stderr) 

2184 return 1 

2185 import aq_devtools 

2186 

2187 if not aq_devtools.confirm(f"remove {args.name} and revoke their token?", assume_yes=getattr(args, "yes", False)): 

2188 return 2 

2189 save_users(tuple(kept)) 

2190 print(f"removed {args.name}; their token no longer works") 

2191 return 0 

2192 if any(user.name == args.name for user in users): 

2193 print(f"user {args.name} exists; remove it first to issue a new token", file=sys.stderr) 

2194 return 1 

2195 try: 

2196 role = Role.parse(args.role) 

2197 token = new_token() 

2198 accounts = [item.strip() for item in (args.accounts or "*").split(",") if item.strip()] 

2199 users.append(make_user(args.name, role, token, accounts=accounts)) 

2200 except ValueError as exc: 

2201 print(f"error: {exc}", file=sys.stderr) 

2202 return 2 

2203 path = save_users(tuple(users)) 

2204 print(f"added {args.name} ({role.name.lower()}, accounts {','.join(accounts)}) to {path}") 

2205 print(f"token (shown once, store it now): {token}") 

2206 print("the API now requires a bearer token on every /api route but /api/health") 

2207 return 0 

2208 

2209 

2210def cmd_live_readiness(args: argparse.Namespace) -> int: 

2211 """`aq live-readiness` (V6.6.5, #352): the paper-to-live scorecard, measured. Exit 1 unless every check passes.""" 

2212 from execution.live_readiness import render_markdown 

2213 from execution.live_readiness_io import readiness_scorecard, write_scorecard 

2214 

2215 paper_check = None 

2216 if args.paper_check: 

2217 try: 

2218 paper_check = json.loads(Path(args.paper_check).read_text(encoding="utf-8")) 

2219 except (OSError, ValueError) as exc: 

2220 print(f"error: cannot read {args.paper_check}: {exc}", file=sys.stderr) 

2221 return 2 

2222 scorecard = readiness_scorecard(ROOT_DIR, args.account or None, paper_check=paper_check) 

2223 if args.markdown: 

2224 print(render_markdown(scorecard)) 

2225 else: 

2226 doc = scorecard.to_dict() 

2227 print(f"{'READY' if scorecard.ready else 'NOT READY'} for live capital (account {scorecard.account}): " 

2228 f"{doc['counts']['pass']} pass, {doc['counts']['fail']} fail, {doc['counts']['unknown']} unknown (unknown counts as fail)") 

2229 for metric in scorecard.metrics: 

2230 print(f" [{metric.status:^7}] {metric.group:<10} {metric.label}: {metric.value if metric.value is not None else '-'} (needs {metric.threshold})") 

2231 if not args.no_write: 

2232 path = write_scorecard(ROOT_DIR, scorecard) 

2233 print(f"wrote {path.relative_to(ROOT_DIR).as_posix()}") 

2234 if args.docs: 

2235 from execution.live_readiness_io import write_docs_block 

2236 

2237 target = ROOT_DIR / "docs" / "live" / "paper-to-live.md" 

2238 print(f"{'updated' if write_docs_block(target, render_markdown(scorecard)) else 'no AQ:READINESS markers in'} {target.relative_to(ROOT_DIR).as_posix()}") 

2239 if args.json: 

2240 from json_safety import atomic_write_json 

2241 

2242 atomic_write_json(Path(args.json), scorecard.to_dict(), indent=2) 

2243 return 0 if scorecard.ready else 1 

2244 

2245 

2246def cmd_accounts(args: argparse.Namespace) -> int: 

2247 """`aq accounts list|validate|status` (V6.6.5, #349).""" 

2248 try: 

2249 accounts = _accounts_or_error() 

2250 except ValueError as exc: 

2251 print(f"accounts.json is invalid: {exc}", file=sys.stderr) 

2252 return 1 

2253 if args.accounts_command == "validate": 

2254 if getattr(args, "print_json", False): 

2255 print(json.dumps({"valid": True, "accounts": [account.id for account in accounts]})) 

2256 return 0 

2257 print(f"accounts.json valid: {len(accounts)} account(s) ({', '.join(account.id for account in accounts)}); every override tightens the config") 

2258 return 0 

2259 if args.accounts_command == "list": 

2260 if getattr(args, "print_json", False): 

2261 print(json.dumps([{"id": account.id, "broker": account.broker, "environment": account.lean_environment, "mode": account.mode, 

2262 "description": account.description} for account in accounts], indent=2)) 

2263 return 0 

2264 for account in accounts: 

2265 print(f"{account.id:<16} {account.broker:<20} {account.lean_environment:<24} mode {account.mode or '(config)':<12} {account.description}") 

2266 return 0 

2267 from execution.accounts_io import account_status_rows 

2268 

2269 rows = account_status_rows(ROOT_DIR, accounts) 

2270 for row in rows: 

2271 missing = f" missing {', '.join(row['secrets_missing'])}" if row["secrets_missing"] else "" 

2272 print(f"{row['id']:<16} {row['broker']:<20} secrets {row['secrets']}{missing}; state {row['state']}; reconciliation breach {row['reconciliation_breach']}") 

2273 if args.json: 

2274 from json_safety import atomic_write_json 

2275 

2276 atomic_write_json(Path(args.json), {"accounts": rows}, indent=2) 

2277 return 0 

2278 

2279 

2280def live_container_name(account) -> str: 

2281 return "aether-quant-lean-live" if account.is_default else f"aether-quant-lean-live-{account.id}" 

2282 

2283 

2284def live_compose_commands(account, *, lean_config: str) -> tuple[list[list[str]], dict[str, str]]: 

2285 """The commands `aq live up` runs and the environment it runs them with (pure, for the tests).""" 

2286 name = live_container_name(account) 

2287 env = {"LEAN_LIVE_ENVIRONMENT": account.lean_environment, "LEAN_LIVE_CONFIG": lean_config, "AQ_ACCOUNT": "" if account.is_default else account.id} 

2288 commands = [ 

2289 ["docker", "compose", "--profile", "lean-live", "run", "-d", "--name", name, "-e", f"AQ_ACCOUNT={env['AQ_ACCOUNT']}", "lean-live"], 

2290 ["docker", "update", "--restart", "unless-stopped", name], 

2291 ] 

2292 return commands, env 

2293 

2294 

2295def _status_of_container(name: str) -> tuple[int, str]: 

2296 """(exit code, state) of one container: running, exited, or not found.""" 

2297 try: 

2298 result = subprocess.run(["docker", "inspect", "-f", "{{.State.Status}}", name], capture_output=True, text=True, check=False) 

2299 except FileNotFoundError: 

2300 return 1, "unknown (docker not found)" 

2301 return (0, result.stdout.strip()) if result.returncode == 0 else (1, "not found") 

2302 

2303 

2304def cmd_live(args: argparse.Namespace) -> int: 

2305 """`aq live up|down --account <id>` (V6.6.5, #349): one Lean live deployment per account, never with a looser config.""" 

2306 from execution.accounts import resolve_account 

2307 

2308 try: 

2309 account = resolve_account(_accounts_or_error(), args.account) 

2310 except ValueError as exc: 

2311 print(f"error: {exc}", file=sys.stderr) 

2312 return 1 

2313 name = live_container_name(account) 

2314 if args.live_command == "status": 

2315 code, out = _status_of_container(name) 

2316 print(json.dumps({"account": account.id, "container": name, "state": out}) if getattr(args, "json", False) else f"account {account.id}: container {name} {out}") 

2317 return code 

2318 if args.live_command == "down": 

2319 if args.dry_run: 

2320 print(f" docker rm -f {name}") 

2321 return 0 

2322 return _run(["docker", "rm", "-f", name]) 

2323 rendered = "lean.live.json" if account.is_default else f"lean.live.{account.id}.json" 

2324 lean_config = rendered if (ROOT_DIR / rendered).exists() else "lean.json" 

2325 if account.broker != "paper" and lean_config == "lean.json": 

2326 suffix = "" if account.is_default else f" --account {account.id}" 

2327 print(f"error: {rendered} is missing; run `aq render-lean-config{suffix}` first", file=sys.stderr) 

2328 return 1 

2329 commands, env = live_compose_commands(account, lean_config=lean_config) 

2330 print(f"account {account.id}: {account.broker} via {account.lean_environment}, config {lean_config}, container {name}") 

2331 if args.dry_run: 

2332 for command in commands: 

2333 print(" " + " ".join(command)) 

2334 return 0 

2335 if account.lean_environment != "live-paper": 

2336 import aq_devtools 

2337 

2338 if not aq_devtools.confirm(f"start LIVE trading for account {account.id} ({account.broker}, real money)?", assume_yes=getattr(args, "yes", False)): 

2339 return 2 

2340 child_env = {**os.environ, **env} 

2341 for command in commands: 

2342 code = subprocess.run(command, cwd=ROOT_DIR, env=child_env, check=False).returncode 

2343 if code: 

2344 return code 

2345 return 0 

2346 

2347 

2348def cmd_secrets(args: argparse.Namespace) -> int: 

2349 """`aq secrets status|set|delete` (V6.6.5, #348): where each credential comes from, never its value.""" 

2350 from execution.secrets import SECRET_NAMES 

2351 from execution.secrets_io import all_secret_status, keyring_delete, keyring_set 

2352 

2353 account = args.account or None 

2354 if args.secrets_command == "status": 

2355 rows = all_secret_status(account) 

2356 width = max(len(row["name"]) for row in rows) 

2357 print(f"secrets for account {account or 'default'} (values are never shown)") 

2358 for row in rows: 

2359 where = row["where"] or "-" 

2360 flag = "stored safely" if row["stored_safely"] else ("plain environment variable" if row["resolved"] else "not set") 

2361 print(f" {str(row['name']).ljust(width)} {'yes' if row['resolved'] else 'no '} {flag:<26} {where}") 

2362 if args.json: 

2363 from json_safety import atomic_write_json 

2364 

2365 atomic_write_json(Path(args.json), {"account": account or "default", "secrets": rows}, indent=2) 

2366 return 0 

2367 name = str(args.name).upper() 

2368 if name not in SECRET_NAMES: 

2369 print(f"unknown secret {name}; known: {', '.join(SECRET_NAMES)}", file=sys.stderr) 

2370 return 2 

2371 if args.secrets_command == "set": 

2372 import getpass 

2373 

2374 value = getpass.getpass(f"{name} for account {account or 'default'} (input hidden): ") 

2375 if not value: 

2376 print("nothing entered; nothing stored", file=sys.stderr) 

2377 return 1 

2378 try: 

2379 keyring_set(name, value, account) 

2380 except RuntimeError as exc: 

2381 print(f"error: {exc}", file=sys.stderr) 

2382 return 1 

2383 print(f"stored {name} in the OS keyring (service aether-quant)") 

2384 return 0 

2385 import aq_devtools 

2386 

2387 if not aq_devtools.confirm(f"delete {name} for account {account or 'default'} from the OS keyring?", assume_yes=getattr(args, "yes", False)): 

2388 return 2 

2389 removed = keyring_delete(name, account) 

2390 print(f"{'removed' if removed else 'nothing stored for'} {name}") 

2391 return 0 

2392 

2393 

2394def cmd_secrets_check(args: argparse.Namespace) -> int: 

2395 """Fail (non-zero) if secrets are about to be committed: a populated 

2396 secret field in the tracked lean.json, or a tracked real `.env` file. 

2397 Backs .githooks/pre-commit. Pure detection lives in 

2398 execution/secret_scan.py.""" 

2399 from execution.secret_scan import find_populated_secret_fields, is_tracked_env_secret 

2400 

2401 problems: list[str] = [] 

2402 

2403 if LEAN_JSON_PATH.exists(): 

2404 try: 

2405 lean_config = json.loads(LEAN_JSON_PATH.read_text(encoding="utf-8")) 

2406 except (json.JSONDecodeError, OSError) as exc: 

2407 print(f"Error reading lean.json: {exc}", file=sys.stderr) 

2408 return 1 

2409 populated = find_populated_secret_fields(lean_config) 

2410 if populated: 

2411 problems.append( 

2412 "lean.json has populated secret field(s) that must not be committed " 

2413 f"(render them into gitignored lean.live.json instead): {', '.join(populated)}" 

2414 ) 

2415 

2416 # Ask git which files are tracked; flag any real .env among them. Degrades 

2417 # gracefully (skips this check) outside a git repo or without git on PATH. 

2418 try: 

2419 tracked = subprocess.run( 

2420 ["git", "ls-files"], cwd=str(ROOT_DIR), capture_output=True, text=True, check=False 

2421 ) 

2422 if tracked.returncode == 0: 

2423 for path in tracked.stdout.splitlines(): 

2424 if is_tracked_env_secret(path): 

2425 problems.append(f"tracked secret file must not be committed: {path}") 

2426 except (OSError, FileNotFoundError): 

2427 pass 

2428 

2429 if getattr(args, "json", False): 

2430 print(json.dumps({"passed": not problems, "problems": problems}, indent=2)) 

2431 return 1 if problems else 0 

2432 if problems: 

2433 print("aq secrets-check FAILED:", file=sys.stderr) 

2434 for problem in problems: 

2435 print(f" - {problem}", file=sys.stderr) 

2436 return 1 

2437 

2438 print("aq secrets-check passed: no committed secrets detected.") 

2439 return 0 

2440 

2441 

2442def cmd_audit_log(args: argparse.Namespace) -> int: 

2443 """Query the tamper-evident audit log (development/Problems.md #42) - 

2444 order placement, credential loads, live-mode transitions. Requires 

2445 AETHER_POSTGRES_DSN (same var every other Postgres-backed `aq` command 

2446 uses) - the audit-worker service must have drained at least one batch 

2447 from Redis into Postgres for anything to show up here (see 

2448 docker-compose.yml's audit-worker service / `python -m audit.postgres_worker`).""" 

2449 import psycopg 

2450 

2451 from audit import fetch_all_events_ordered, fetch_recent_events, verify_chain 

2452 

2453 dsn = _lazy("secret_env")("POSTGRES_DSN", "") 

2454 if not dsn: 

2455 print("error: AETHER_POSTGRES_DSN is not set.", file=sys.stderr) 

2456 return 1 

2457 

2458 try: 

2459 conn = psycopg.connect(dsn, autocommit=False) 

2460 except Exception as exc: 

2461 print(f"error: could not connect to Postgres: {exc}", file=sys.stderr) 

2462 return 1 

2463 

2464 try: 

2465 if args.verify: 

2466 rows = fetch_all_events_ordered(conn) 

2467 valid, broken_index = verify_chain(rows) 

2468 if not rows: 

2469 print("aq audit-log --verify: table is empty — trivially valid.") 

2470 return 0 

2471 if valid: 

2472 print(f"aq audit-log --verify: chain intact across {len(rows)} entries.") 

2473 return 0 

2474 broken_row = rows[broken_index] 

2475 print( 

2476 f"aq audit-log --verify: CHAIN BROKEN at entry {broken_index} " 

2477 f"(event_id={broken_row['event_id']}, event_type={broken_row['event_type']}, " 

2478 f"created_at={broken_row['created_at']}) — tampering or data loss detected.", 

2479 file=sys.stderr, 

2480 ) 

2481 return 1 

2482 

2483 since = None 

2484 if args.since: 

2485 from datetime import datetime as _datetime 

2486 from datetime import timezone as _timezone 

2487 

2488 since = _datetime.fromisoformat(args.since).replace(tzinfo=_timezone.utc) 

2489 rows = fetch_recent_events(conn, event_type=args.event_type, since=since, limit=args.limit) 

2490 if getattr(args, "until", None): 

2491 rows = [row for row in rows if str(row["created_at"])[:10] <= args.until] 

2492 if getattr(args, "export", None): 

2493 with Path(args.export).open("w", encoding="utf-8", newline="\n") as handle: 

2494 for row in rows: 

2495 handle.write(json.dumps(row, default=str) + "\n") 

2496 print(f"wrote {len(rows)} entries to {args.export}") 

2497 return 0 

2498 if getattr(args, "json", False): 

2499 print(json.dumps(rows, indent=2, default=str)) 

2500 return 0 

2501 if not rows: 

2502 print("aq audit-log: no matching entries.") 

2503 return 0 

2504 for row in rows: 

2505 print(f"{row['created_at']} {row['event_type']:<20} {row['actor']:<8} {json.dumps(row['payload'])}") 

2506 return 0 

2507 finally: 

2508 conn.close() 

2509 

2510 

2511RETRAIN_STAGES = ("plan", "train", "train_topology", "train_gating", "train_multitask", "train_sequence", "train_strategy_selector", "validate", "backtest", 

2512 "commit", "promote", "rollback", "status", "auto-rollback") 

2513 

2514 

2515def cmd_retrain(args: argparse.Namespace) -> int: 

2516 command = [sys.executable, "-m", "retraining.orchestrator", args.stage, *args.retrain_args] 

2517 if getattr(args, "dry_run", False): 

2518 print(" ".join(command)) 

2519 return 0 

2520 return _run(command) 

2521 

2522 

2523# Phase 4.8 - whole-universe bulk-backfill scripts, each its own standalone 

2524# argparse/__main__ module with a PLURAL filter (--tickers/--series nargs="*", 

2525# --apply) - genuinely different from cmd_fetch()'s single-ticker/ad-hoc IB 

2526# tool below, which does NOT wire to or overlap with any of these three. 

2527# None of them was reachable via `aq` before this - purely a discoverability 

2528# wrapper, zero new backfill logic (each script's own main()/argparse is 

2529# unchanged and still works standalone via `python -m data_pipeline.<module>`). 

2530_BACKFILL_MODULE_BY_TARGET: dict[str, str] = { 

2531 "dividends": "data_pipeline.dividend_backfill", 

2532 "fred": "data_pipeline.fred_backfill", 

2533 "yfinance": "data_pipeline.yfinance_backfill", 

2534} 

2535 

2536 

2537def cmd_backfill(args: argparse.Namespace) -> int: 

2538 return _run([sys.executable, "-m", _BACKFILL_MODULE_BY_TARGET[args.target], *args.backfill_args]) 

2539 

2540 

2541def cmd_paper_readiness(args: argparse.Namespace) -> int: 

2542 if getattr(args, "json", False): 

2543 from execution.paper_readiness_report import build_paper_readiness_view 

2544 

2545 dsn = _lazy("secret_env")("POSTGRES_DSN", "") 

2546 if not dsn: 

2547 print("aq paper-readiness: AETHER_POSTGRES_DSN is not set (the checks read the trading history in Postgres)", file=sys.stderr) 

2548 return 1 

2549 import psycopg 

2550 

2551 conn = psycopg.connect(dsn, autocommit=False) 

2552 try: 

2553 view = build_paper_readiness_view(conn, json.loads(CONFIG_PATH.read_text(encoding="utf-8"))) 

2554 finally: 

2555 conn.close() 

2556 print(json.dumps(view, indent=2, default=str)) 

2557 return 0 if view.get("ready", False) else 1 

2558 return _run([sys.executable, "-m", "execution.paper_readiness_report"]) 

2559 

2560 

2561def cmd_clean(args: argparse.Namespace) -> int: 

2562 """`aq clean ml|coverage|caches|build`: list (and with --apply, delete) regenerable files. Never backtests/, data/ or the 

2563 active models.""" 

2564 import shutil 

2565 

2566 import aq_devtools 

2567 

2568 if getattr(args, "target", "ml") != "ml": 

2569 finder = {"coverage": aq_devtools.coverage_paths, "caches": aq_devtools.cache_paths, "build": aq_devtools.build_paths}[args.target] 

2570 return aq_devtools.clean_paths(finder(ROOT_DIR), apply=args.apply, assume_yes=getattr(args, "yes", False), as_json=args.json, root=ROOT_DIR) 

2571 from evaluation.ml_cleanup import plan_ml_cleanup 

2572 

2573 plan = plan_ml_cleanup( 

2574 ML_DIR, keep_versions=args.keep_versions, keep_backups=args.keep_backups, 

2575 strip_walk_forward_datasets=args.strip_walk_forward_datasets, 

2576 ) 

2577 gigabytes = plan["total_bytes"] / 1e9 

2578 if args.json: 

2579 print(json.dumps(plan, indent=2)) 

2580 else: 

2581 print(f"ml/ cleanup plan: {len(plan['items'])} items, {gigabytes:.2f} GB; protected {len(plan['protected'])} paths; " 

2582 f"active version ids {plan['active_version_ids']}") 

2583 for item in sorted(plan["items"], key=lambda entry: -entry["bytes"])[:40]: 

2584 print(f" {item['bytes'] / 1e6:10.1f} MB {item['kind']:<20} {item['path']} ({item['reason']})") 

2585 if not args.apply: 

2586 if not args.json: 

2587 print("dry run: nothing deleted (pass --apply to delete the items above)") 

2588 return 0 

2589 if not aq_devtools.confirm(f"delete {len(plan['items'])} ml/ items ({gigabytes:.2f} GB)?", assume_yes=getattr(args, "yes", False)): 

2590 return 2 

2591 for item in plan["items"]: 

2592 path = Path(item["path"]) 

2593 if path.is_dir(): 

2594 shutil.rmtree(path, ignore_errors=True) 

2595 elif path.is_file(): 

2596 path.unlink(missing_ok=True) 

2597 print(f"deleted {len(plan['items'])} items ({gigabytes:.2f} GB)") 

2598 return 0 

2599 

2600 

2601def _override_target(args: argparse.Namespace) -> Path: 

2602 """config.json for the default account; state/accounts/<id>/overrides.json for a named one (V6.6.5, #349).""" 

2603 account_id = getattr(args, "account", None) 

2604 if not account_id or account_id == "default": 

2605 return CONFIG_PATH 

2606 from execution.accounts import override_path, resolve_account 

2607 

2608 target = override_path(ROOT_DIR, resolve_account(_accounts_or_error(), account_id)) 

2609 target.parent.mkdir(parents=True, exist_ok=True) 

2610 if not target.exists(): 

2611 target.write_text("{}", encoding="utf-8") 

2612 return target 

2613 

2614 

2615def _audit_override(switch: str, value: object, target: Path) -> None: 

2616 """A manual safety override is a live-mode transition: recorded in the audit log when Redis is there, never blocking.""" 

2617 try: 

2618 from audit import LIVE_MODE_TRANSITION, AuditQueue, build_audit_event 

2619 

2620 config = json.loads(CONFIG_PATH.read_text(encoding="utf-8")) if CONFIG_PATH.exists() else {} 

2621 audit_config = config.get("phase_v2", {}).get("audit_log", {}) 

2622 AuditQueue(enabled=bool(audit_config.get("enabled", True)), stream_name=str(audit_config.get("redis_stream", "aether:audit"))).push( 

2623 build_audit_event(LIVE_MODE_TRANSITION, {"event": "manual_override", "switch": switch, "value": value, "target": target.name}, actor="cli")) 

2624 except Exception: # the audit log is best effort here; the override itself is what the operator asked for 

2625 pass 

2626 

2627 

2628_LOOSENING = {("trade_lock", False), ("trade_lock", None), ("kill_switch", False), ("kill_switch", None)} 

2629 

2630 

2631def _override_change(args: argparse.Namespace, switch: str, value: object, current: object, target: Path, write) -> int: 

2632 """Shared by trade-lock and kill-switch: --dry-run prints old -> new; loosening a safety switch asks first.""" 

2633 if getattr(args, "dry_run", False): 

2634 print(f"{switch} override: {current} -> {value} in {target.name} (dry run)") 

2635 return 0 

2636 if (switch, value) in _LOOSENING: 

2637 import aq_devtools 

2638 

2639 if not aq_devtools.confirm(f"loosen the {switch.replace('_', ' ')} ({current} -> {value})?", assume_yes=getattr(args, "yes", False)): 

2640 return 2 

2641 write(value, target) 

2642 _audit_override(switch, value, target) 

2643 return 0 

2644 

2645 

2646def cmd_trade_lock(args: argparse.Namespace) -> int: 

2647 target = _override_target(args) 

2648 current = _lazy("read_manual_trade_lock_override")(target) 

2649 if getattr(args, "status", False) and getattr(args, "json", False): 

2650 print(json.dumps({"trade_lock_override": current, "target": str(target)})) 

2651 return 0 

2652 if not getattr(args, "status", False): 

2653 value = True if args.on else False if args.off else None 

2654 code = _override_change(args, "trade_lock", value, current, target, _lazy("write_manual_trade_lock_override")) 

2655 if code or getattr(args, "dry_run", False): 

2656 return code 

2657 print({True: "Trade lock override: ON (trading forced paused).", False: "Trade lock override: OFF (trading forced resumed, even past a sticky total-drawdown lock).", 

2658 None: "Trade lock override: AUTO (back to today's default automatic behavior)."}[value]) 

2659 return 0 

2660 label = {True: "ON (forced paused)", False: "OFF (forced resumed)", None: "AUTO (automatic behavior)"}[current] 

2661 print(f"Trade lock override: {label}") 

2662 return 0 

2663 

2664 

2665def _cmd_kill_switch_history(args: argparse.Namespace) -> int: 

2666 """Queries the SAME tamper-evident audit log as `aq audit-log` 

2667 (development/Problems.md #42), filtering for kill-switch trips. main.py's 

2668 Phase 6 wiring pushes a trip as a LIVE_MODE_TRANSITION event with 

2669 payload {"event": "kill_switch_tripped", ...} - LIVE_MODE_TRANSITION is 

2670 reused rather than registering a new EVENT_TYPES entry (audit/redis_queue.py 

2671 fixes that tuple; build_audit_event() raises ValueError on anything else).""" 

2672 import psycopg 

2673 

2674 from audit import LIVE_MODE_TRANSITION, fetch_recent_events 

2675 

2676 dsn = _lazy("secret_env")("POSTGRES_DSN", "") 

2677 if not dsn: 

2678 print("error: AETHER_POSTGRES_DSN is not set.", file=sys.stderr) 

2679 return 1 

2680 

2681 try: 

2682 conn = psycopg.connect(dsn, autocommit=False) 

2683 except Exception as exc: 

2684 print(f"error: could not connect to Postgres: {exc}", file=sys.stderr) 

2685 return 1 

2686 

2687 try: 

2688 rows = fetch_recent_events(conn, event_type=LIVE_MODE_TRANSITION, limit=args.limit) 

2689 trip_rows = [row for row in rows if row["payload"].get("event") == "kill_switch_tripped"] 

2690 if not trip_rows: 

2691 print("aq kill-switch --history: no kill-switch trips recorded.") 

2692 return 0 

2693 for row in trip_rows: 

2694 print(f"{row['created_at']} {json.dumps(row['payload'])}") 

2695 return 0 

2696 finally: 

2697 conn.close() 

2698 

2699 

2700def cmd_kill_switch(args: argparse.Namespace) -> int: 

2701 target = _override_target(args) 

2702 if args.history: 

2703 return _cmd_kill_switch_history(args) 

2704 current = _lazy("read_kill_switch_manual_override")(target) 

2705 if getattr(args, "status", False) and getattr(args, "json", False): 

2706 print(json.dumps({"kill_switch_override": current, "target": str(target)})) 

2707 return 0 

2708 if not getattr(args, "status", False): 

2709 value = True if args.arm else False if args.disarm else None 

2710 code = _override_change(args, "kill_switch", value, current, target, _lazy("write_kill_switch_manual_override")) 

2711 if code or getattr(args, "dry_run", False): 

2712 return code 

2713 print({True: "Kill switch override: ARMED (forced evaluation active, even if phase_v2.risk.kill_switch.enabled is false).", 

2714 False: "Kill switch override: DISARMED (forced off, even if phase_v2.risk.kill_switch.enabled is true).", 

2715 None: "Kill switch override: AUTO (defers to phase_v2.risk.kill_switch.enabled)."}[value]) 

2716 return 0 

2717 label = {True: "ARMED (forced on)", False: "DISARMED (forced off)", None: "AUTO (defers to config)"}[current] 

2718 print(f"Kill switch override: {label}") 

2719 return 0 

2720 

2721 

2722class ConfigPathError(Exception): 

2723 """Raised by _get_config_value/_set_config_value for a bad dotted path.""" 

2724 

2725 

2726def _get_config_value(config: dict, dotted_path: str) -> object: 

2727 node = config 

2728 walked: list[str] = [] 

2729 for segment in dotted_path.split("."): 

2730 walked.append(segment) 

2731 if not isinstance(node, dict) or segment not in node: 

2732 raise ConfigPathError(f"no such config key: {'.'.join(walked)!r}") 

2733 node = node[segment] 

2734 return node 

2735 

2736 

2737def _coerce_config_value(raw: str) -> object: 

2738 """JSON-first parsing so true/false/123/0.5/[...]/{...} all become their 

2739 real type automatically; anything that isn't valid JSON on its own 

2740 (e.g. a bare word) is kept as a plain string.""" 

2741 try: 

2742 return json.loads(raw) 

2743 except json.JSONDecodeError: 

2744 return raw 

2745 

2746 

2747def _set_config_value(config: dict, dotted_path: str, raw_value: str) -> tuple[object, object, bool]: 

2748 """Mutates `config` in place. Returns (old_value, new_value, type_changed) - 

2749 deliberately does not refuse to overwrite a list/dict: the caller wants 

2750 full read/write access to every key, not just scalars. Safety instead 

2751 comes from always reporting old -> new (and a type-change warning) to 

2752 the caller, plus the automatic config.json.bak snapshot cmd_config() 

2753 writes before every set.""" 

2754 *parents, leaf = dotted_path.split(".") 

2755 node = config 

2756 for segment in parents: 

2757 if not isinstance(node, dict) or segment not in node: 

2758 raise ConfigPathError(f"no such config key: {dotted_path!r}") 

2759 node = node[segment] 

2760 if not isinstance(node, dict) or leaf not in node: 

2761 raise ConfigPathError(f"no such config key: {dotted_path!r}") 

2762 old_value = node[leaf] 

2763 new_value = _coerce_config_value(raw_value) 

2764 node[leaf] = new_value 

2765 return old_value, new_value, type(old_value) is not type(new_value) 

2766 

2767 

2768def _iter_leaf_paths(node: object, prefix: str = "") -> Iterator[str]: 

2769 """Recursively yields every dot-joined leaf path under `node`. A "leaf" 

2770 is any non-dict value (or an empty dict) - list-valued keys show up as 

2771 one leaf, never expanded per-element.""" 

2772 if isinstance(node, dict) and node: 

2773 for key, value in node.items(): 

2774 yield from _iter_leaf_paths(value, f"{prefix}.{key}" if prefix else key) 

2775 else: 

2776 yield prefix 

2777 

2778 

2779def _reject_duplicates(pairs: list[tuple[str, object]]) -> dict: 

2780 keys = [key for key, _ in pairs] 

2781 duplicated = sorted({key for key in keys if keys.count(key) > 1}) 

2782 if duplicated: 

2783 raise ValueError(f"duplicate key(s) {duplicated}") 

2784 return dict(pairs) 

2785 

2786 

2787def _validate_json_config(json_path: Path, args: argparse.Namespace) -> int: 

2788 """Parse with duplicate keys refused and NaN/inf refused, and for config.json load it through main.py's own readers.""" 

2789 problems: list[str] = [] 

2790 text = json_path.read_text(encoding="utf-8") 

2791 try: 

2792 json.loads(text, object_pairs_hook=_reject_duplicates, parse_constant=lambda name: (_ for _ in ()).throw(ValueError(f"{name} is not valid JSON"))) 

2793 except ValueError as error: 

2794 problems.append(str(error)) 

2795 if not problems and json_path == CONFIG_PATH: 

2796 config = json.loads(text) 

2797 for section in ("phase1", "phase_v2"): 

2798 if not isinstance(config.get(section), dict): 

2799 problems.append(f"{section} is missing or not an object") 

2800 if not problems: 

2801 from inference.exported_model import resolve_model_ensemble_config 

2802 from portfolio.legacy_sleeve import resolve_legacy_signal_params 

2803 

2804 for label, reader in (("model ensemble", lambda: resolve_model_ensemble_config(config)), ("legacy signal", lambda: resolve_legacy_signal_params(config, 0.5))): 

2805 try: 

2806 reader() 

2807 except (KeyError, TypeError, ValueError) as error: 

2808 problems.append(f"{label}: {type(error).__name__}: {error}") 

2809 if getattr(args, "json", False): 

2810 print(json.dumps({"file": json_path.name, "valid": not problems, "problems": problems}, indent=2)) 

2811 else: 

2812 print(f"{json_path.name}: valid" if not problems else f"{json_path.name}: " + "; ".join(problems)) 

2813 return 1 if problems else 0 

2814 

2815 

2816def _dispatch_json_config_command(args: argparse.Namespace, json_path: Path, command_attr: str) -> int: 

2817 """Shared dispatch for `aq config`/`aq lean` - both are the same 

2818 dump/get/set/keys tool over a single flat JSON file, just pointed at a 

2819 different path. See cmd_config()/cmd_lean().""" 

2820 data = json.loads(json_path.read_text(encoding="utf-8")) 

2821 command = getattr(args, command_attr, None) 

2822 

2823 try: 

2824 if command is None: 

2825 print(json.dumps(data, indent=2)) 

2826 return 0 

2827 

2828 if command == "get": 

2829 value = _get_config_value(data, args.dotted_path) 

2830 if getattr(args, "json", False): 

2831 print(json.dumps(value, indent=2)) 

2832 else: 

2833 print(value if isinstance(value, str) else json.dumps(value, indent=2)) 

2834 return 0 

2835 

2836 if command == "keys": 

2837 root = _get_config_value(data, args.dotted_prefix) if args.dotted_prefix else data 

2838 paths = list(_iter_leaf_paths(root, args.dotted_prefix or "")) 

2839 print(json.dumps(paths, indent=2) if getattr(args, "json", False) else "\n".join(paths)) 

2840 return 0 

2841 

2842 if command == "diff": 

2843 import aq_devtools 

2844 

2845 return aq_devtools.cmd_json_diff(json_path, args) 

2846 

2847 if command == "validate": 

2848 return _validate_json_config(json_path, args) 

2849 

2850 if command == "set": 

2851 if json_path == LEAN_JSON_PATH: 

2852 from execution.secret_scan import is_secret_field 

2853 

2854 if is_secret_field(args.dotted_path.split(".")[-1]) and str(args.value).strip(): 

2855 print(f"error: {args.dotted_path} is a secret: lean.json stays empty (store it with `aq secrets set`, then `aq render-lean-config`)", file=sys.stderr) 

2856 return 1 

2857 preview = copy.deepcopy(data) 

2858 old_value, new_value, type_changed = _set_config_value(preview, args.dotted_path, args.value) 

2859 if type_changed and old_value is not None and not getattr(args, "force", False): 

2860 print(f"error: {args.dotted_path} would change type from {type(old_value).__name__} to {type(new_value).__name__} " 

2861 f"({old_value!r} -> {new_value!r}); pass --force if that is meant", file=sys.stderr) 

2862 return 1 

2863 if getattr(args, "dry_run", False): 

2864 print(f"{args.dotted_path}: {old_value!r} -> {new_value!r} (dry run)") 

2865 return 0 

2866 shutil.copy2(json_path, json_path.with_suffix(".json.bak")) 

2867 data = preview 

2868 json_path.write_text(json.dumps(data, indent=4) + "\n", encoding="utf-8") 

2869 print(f"{args.dotted_path}: {old_value!r} -> {new_value!r}") 

2870 if type_changed: 

2871 print( 

2872 f"WARNING: type changed from {type(old_value).__name__} to {type(new_value).__name__} " 

2873 f"for {args.dotted_path}", 

2874 file=sys.stderr, 

2875 ) 

2876 if json_path == CONFIG_PATH and args.dotted_path == "phase_v2.inference_parallelism.enabled" and new_value: 

2877 print( 

2878 "WARNING: phase_v2.inference_parallelism.enabled=true - development/Problems.md #65 " 

2879 "measured this ProcessPoolExecutor pool as dramatically slower than sequential on " 

2880 "Windows' spawn start method (never measured on Linux/fork). main.py will also log " 

2881 "this at startup on Windows if the pool actually starts.", 

2882 file=sys.stderr, 

2883 ) 

2884 return 0 

2885 

2886 if command == "preset": 

2887 return _dispatch_config_preset_command(args, data, json_path) 

2888 except ConfigPathError as error: 

2889 print(f"error: {error}", file=sys.stderr) 

2890 return 1 

2891 

2892 return 1 

2893 

2894 

2895def _dispatch_config_preset_command(args: argparse.Namespace, data: dict, json_path: Path) -> int: 

2896 """`aq config preset` (V5.1 Phase 1) - list/show/apply a named 

2897 dotted-key-override block from phase_v2.presets. Reuses 

2898 _get_config_value()/_set_config_value() so backup/type-coercion/old->new 

2899 printing are IDENTICAL to a manual `aq config set` per key - a preset 

2900 is just several `set` calls applied together, never a separate write 

2901 path. Only registered under `config` (not `lean` - presets are a 

2902 config.json-only concept).""" 

2903 presets_root = data.get("phase_v2", {}).get("presets", {}) 

2904 preset_names = sorted(name for name in presets_root if name != "active") 

2905 

2906 if args.preset_list: 

2907 active = presets_root.get("active") 

2908 for name in preset_names: 

2909 print(f"{name}{' (active)' if name == active else ''}") 

2910 return 0 

2911 

2912 if args.preset_show: 

2913 preset_values = presets_root.get(args.preset_show) 

2914 if preset_values is None: 

2915 print(f"error: no such preset {args.preset_show!r} - available: {preset_names}", file=sys.stderr) 

2916 return 1 

2917 print(json.dumps(preset_values, indent=2)) 

2918 return 0 

2919 

2920 if args.preset_apply: 

2921 preset_values = presets_root.get(args.preset_apply) 

2922 if preset_values is None: 

2923 print(f"error: no such preset {args.preset_apply!r} - available: {preset_names}", file=sys.stderr) 

2924 return 1 

2925 

2926 # Validate every dotted path resolves BEFORE writing anything - 

2927 # apply the whole preset or none. A partial apply that failed 

2928 # halfway through would leave config.json in a mixed state no 

2929 # preset actually describes. 

2930 for dotted_path in preset_values: 

2931 _get_config_value(data, dotted_path) 

2932 

2933 if args.preset_dry_run: 

2934 for dotted_path, new_value in preset_values.items(): 

2935 old_value = _get_config_value(data, dotted_path) 

2936 print(f"{dotted_path}: {old_value!r} -> {new_value!r} (dry run)") 

2937 return 0 

2938 

2939 shutil.copy2(json_path, json_path.with_suffix(".json.bak")) 

2940 for dotted_path, new_value in preset_values.items(): 

2941 old_value, applied_value, type_changed = _set_config_value(data, dotted_path, json.dumps(new_value)) 

2942 print(f"{dotted_path}: {old_value!r} -> {applied_value!r}") 

2943 if type_changed: 

2944 print(f"WARNING: type changed for {dotted_path}", file=sys.stderr) 

2945 if "active" in presets_root: 

2946 _set_config_value(data, "phase_v2.presets.active", json.dumps(args.preset_apply)) 

2947 json_path.write_text(json.dumps(data, indent=4) + "\n", encoding="utf-8") 

2948 return 0 

2949 

2950 # No flag given - print the whole presets block, same "bare command 

2951 # dumps everything" convention as `aq config` itself. 

2952 print(json.dumps(presets_root, indent=2)) 

2953 return 0 

2954 

2955 

2956def cmd_config(args: argparse.Namespace) -> int: 

2957 return _dispatch_json_config_command(args, CONFIG_PATH, "config_command") 

2958 

2959 

2960def cmd_lean(args: argparse.Namespace) -> int: 

2961 return _dispatch_json_config_command(args, LEAN_JSON_PATH, "lean_command") 

2962 

2963 return 1 

2964 

2965 

2966def cmd_fetch(args: argparse.Namespace) -> int: 

2967 ib = None 

2968 fetch_fn = None 

2969 extra_metadata = None 

2970 if args.asset_class in IB_ASSET_CLASSES: 

2971 if args.expiry is None: 

2972 print(f"error: --expiry is required for asset_class={args.asset_class!r}", file=sys.stderr) 

2973 return 1 

2974 if args.asset_class == "options" and (args.strike is None or args.right is None): 

2975 print("error: --strike and --right are required for asset_class='options'", file=sys.stderr) 

2976 return 1 

2977 

2978 config = json.loads(CONFIG_PATH.read_text(encoding="utf-8")) 

2979 lean_config = json.loads(LEAN_JSON_PATH.read_text(encoding="utf-8")) 

2980 try: 

2981 ib = _lazy("connect_ib")(config, lean_config) 

2982 except _lazy("IBNotConfiguredError") as error: 

2983 print(f"error: {error}", file=sys.stderr) 

2984 return 1 

2985 

2986 family_ticker = args.family_ticker or args.ticker.upper() 

2987 if args.asset_class == "futures": 

2988 contract_spec = _lazy("load_futures_contract_specs")().get(args.ticker.upper(), {}) 

2989 fetch_fn = lambda symbol, start, end: _lazy("fetch_future_historical_bars")( # noqa: E731 

2990 ib, symbol, contract_spec, start, end, contract_month=args.contract_month 

2991 ) 

2992 extra_metadata = {"family_ticker": family_ticker} 

2993 if args.contract_month: 

2994 extra_metadata["contract_month"] = args.contract_month 

2995 else: 

2996 fetch_fn = lambda symbol, start, end: _lazy("fetch_option_historical_bars")( # noqa: E731 

2997 ib, symbol, args.expiry, args.strike, args.right, start, end 

2998 ) 

2999 extra_metadata = { 

3000 "family_ticker": family_ticker, 

3001 "strike": args.strike, 

3002 "expiry": args.expiry, 

3003 "right": args.right, 

3004 } 

3005 

3006 try: 

3007 fetch_kwargs = {"fetch_fn": fetch_fn} if fetch_fn is not None else {} 

3008 report = _lazy("fetch_adhoc_asset")( 

3009 args.asset_class, args.ticker, args.start, args.end, apply=args.apply, 

3010 extra_metadata=extra_metadata, **fetch_kwargs, 

3011 ) 

3012 finally: 

3013 if ib is not None: 

3014 _lazy("disconnect_ib")(ib) 

3015 

3016 if getattr(args, "json", False): 

3017 print(json.dumps(report, indent=2, default=str)) 

3018 return 1 if report["action"] == "no_data_returned" else 0 

3019 label = "APPLY" if args.apply else "DRY RUN" 

3020 print(f"{label} — {report['ticker']} ({report['yahoo_symbol']}): {report['action']}, rows_fetched={report['rows_fetched']}") 

3021 if report["suggested_available_from"]: 

3022 print(f" date range fetched: {report['suggested_available_from']} .. {report['suggested_available_to']}") 

3023 print(f" data_path: {report['data_path']}") 

3024 

3025 if report["config_status"] == "added": 

3026 print(f" config.json: added a new {report['ticker']} asset block to phase1.universe.assets[]") 

3027 elif report["config_status"] == "already_exists": 

3028 print( 

3029 f" config.json: {report['ticker']} is already configured - left untouched. " 

3030 "Use data_pipeline/yfinance_backfill.py to extend an existing asset's date range instead." 

3031 ) 

3032 

3033 if not args.apply: 

3034 print("\nDry run only — nothing was written. Re-run with --apply to write the zip file and update config.json.") 

3035 elif report["action"] == "written": 

3036 print("\nReady to prepare training: run `python train.py --dataset-only` to confirm this ticker's asset quality, then `python train.py` when ready.") 

3037 

3038 return 1 if report["action"] == "no_data_returned" else 0 

3039 

3040 

3041def _broker_keys_present() -> bool: 

3042 """Both venues' keys are on hand: in the rendered `lean.live.json` or a stored secret (file, Docker secret, env, keyring). 

3043 The tracked lean.json stays empty by design (`aq secrets-check`), so it is never the only place looked (V6.6.5, #348).""" 

3044 from evaluation.research_cycle import read_json_or 

3045 from execution.secrets_io import load_secret 

3046 

3047 rendered = read_json_or(ROOT_DIR / "lean.live.json", {}) 

3048 ib = str(rendered.get("ib-account") or "").strip() or load_secret("IB_ACCOUNT").value is not None 

3049 coinbase = str(rendered.get("coinbase-api-key") or "").strip() or load_secret("COINBASE_API_KEY").value is not None 

3050 return bool(ib) and bool(coinbase) 

3051 

3052 

3053def cmd_ib(_args: argparse.Namespace) -> int: 

3054 config = json.loads(CONFIG_PATH.read_text(encoding="utf-8")) 

3055 lean_config = json.loads(LEAN_JSON_PATH.read_text(encoding="utf-8")) 

3056 rendered = ROOT_DIR / "lean.live.json" 

3057 if rendered.exists(): # the secret-bearing render (`aq render-lean-config`) overlays the empty template 

3058 try: 

3059 lean_config = {**lean_config, **json.loads(rendered.read_text(encoding="utf-8"))} 

3060 except (OSError, ValueError): 

3061 pass 

3062 status = _lazy("ib_readiness_status")(config, lean_config) 

3063 if getattr(_args, "json", False): 

3064 result = {"status": status} 

3065 if status not in ("disabled", "enabled_but_lean_credentials_missing"): 

3066 reachable, detail = _lazy("attempt_connection")(config, lean_config) 

3067 result.update(reachable=reachable, detail=detail) 

3068 print(json.dumps(result, indent=2)) 

3069 return 0 if status == "disabled" or result.get("reachable") else 1 

3070 

3071 if status == "disabled": 

3072 print("IB: disabled (phase_v2.ib.enabled is false)") 

3073 print(" Enable with: aq config set phase_v2.ib.enabled true") 

3074 return 0 

3075 

3076 if status == "enabled_but_lean_credentials_missing": 

3077 print("IB: enabled in config.json, but no IB credentials are rendered (lean.live.json)") 

3078 print(" Store them with: aq secrets set IB_ACCOUNT (and IB_USER_NAME, IB_PASSWORD), then aq render-lean-config") 

3079 print(" The tracked lean.json stays empty: aq secrets-check fails a commit that fills it.") 

3080 return 1 

3081 

3082 reachable, detail = _lazy("attempt_connection")(config, lean_config) 

3083 if reachable: 

3084 print(f"IB: {detail} (connected to {config['phase_v2']['ib'].get('host')}:{config['phase_v2']['ib'].get('port')})") 

3085 return 0 

3086 

3087 print(f"IB: enabled and credentialed, but not reachable — {detail}") 

3088 print(" Check that TWS or IB Gateway is running and logged in on the configured host/port.") 

3089 return 1 

3090 

3091 

3092def cmd_assets(_args: argparse.Namespace) -> int: 

3093 """`aq assets status`: one command reporting full multi-asset-class 

3094 readiness at a glance - IB, the futures_risk/options_risk feature 

3095 flags, how many futures contract specs are loaded, how much of the 

3096 FRED yield-curve cache is populated, and how many futures/options 

3097 assets are actually configured in config.json's universe. Read-only 

3098 reporting only - basic enable/disable of any of these already works 

3099 today via the generic 

3100 `aq config set phase_v2.{ib,futures_risk,options_risk}.enabled true|false` 

3101 (_dispatch_json_config_command), same as cmd_ib's own "Enable with" 

3102 hint. 

3103 

3104 The actual report is built by monitoring/assets_status.py:: 

3105 build_assets_status() - shared with the webui's `/api/assets-status` 

3106 endpoint so the readiness logic is defined exactly once.""" 

3107 from monitoring.assets_status import build_assets_status 

3108 

3109 config = json.loads(CONFIG_PATH.read_text(encoding="utf-8")) 

3110 lean_config = json.loads(LEAN_JSON_PATH.read_text(encoding="utf-8")) 

3111 report = build_assets_status(config, lean_config) 

3112 if getattr(_args, "json", False): 

3113 print(json.dumps(report, indent=2, default=str)) 

3114 return 0 

3115 

3116 print(f"IB: {report['ib_status']}") 

3117 print(f"futures_risk.enabled: {report['futures_risk_enabled']}") 

3118 print(f"options_risk.enabled: {report['options_risk_enabled']}") 

3119 tickers = ", ".join(report["futures_contract_specs_tickers"]) or "none" 

3120 print(f"Futures contract specs loaded: {report['futures_contract_specs_loaded']} ({tickers})") 

3121 most_recent = report["fred_cache_most_recent_date"] or "never populated" 

3122 print(f"FRED cache: {report['fred_cache_series_count']} series populated, most recent date: {most_recent}") 

3123 print(f"Configured futures assets: {report['configured_futures_assets']}") 

3124 print(f"Configured options assets: {report['configured_options_assets']}") 

3125 # V5.1 Phase 2, Step 2.5 - development/Problems.md: derivatives macro 

3126 # features are computed every dataset build, but deliberately left out 

3127 # of phase1.features.input_set (constant 0.0 with no futures/options 

3128 # contract subscribed - see build_dataset_manifest()'s 

3129 # computed_but_unused_features list for the code-enforced version of 

3130 # this same fact). 

3131 derivatives_in_input_set = config.get("phase1", {}).get("features", {}).get("derivatives_in_input_set", False) 

3132 status = "in input_set" if derivatives_in_input_set else "computed, NOT in input_set" 

3133 print( 

3134 "Derivatives macro features (futures_term_structure_slope, options_put_call_ratio, " 

3135 f"options_implied_vol_skew): {status} - needs a futures/options contract subscribed " 

3136 "(IB-gated) to carry real signal; flip phase1.features.derivatives_in_input_set " 

3137 "once one is." 

3138 ) 

3139 

3140 return 0 

3141 

3142 

3143def _apply_preset_in_memory(config: dict, preset: dict) -> dict: 

3144 """Applies a phase_v2.presets.<name> dotted-key overlay to an IN-MEMORY 

3145 deep copy of `config` only - `aq evaluate --preset` must never write 

3146 config.json (that is `aq config preset --apply`'s job, a separate 

3147 command). Reuses _set_config_value()'s own dotted-path resolution - 

3148 json.dumps() round-trips each already-typed preset value through the 

3149 same string-coercion path `aq config set` uses, so both entry points 

3150 share one implementation and can never silently disagree on how a 

3151 dotted path resolves.""" 

3152 overlaid = copy.deepcopy(config) 

3153 for dotted_path, value in preset.items(): 

3154 _set_config_value(overlaid, dotted_path, json.dumps(value)) 

3155 return overlaid 

3156 

3157 

3158def _write_evaluation_json(path: Path, payload: object) -> None: 

3159 path.parent.mkdir(parents=True, exist_ok=True) 

3160 path.write_text(json.dumps(payload, indent=2, default=str), encoding="utf-8") 

3161 

3162 

3163def _refresh_readme_evaluation_sections() -> None: 

3164 """Best-effort call to generate_evaluation_report.py after any `aq 

3165 evaluate` flag that could have changed what's on ml/evaluation/ or 

3166 ml/versions/walk-forward-*/ - mirrors cmd_backtest()'s own "a report- 

3167 generation bug must never fail the real command" contract. Lazily 

3168 imported for the same reason as this function's pandas/torch imports 

3169 above: every other `aq` subcommand's startup must stay unaffected.""" 

3170 try: 

3171 from generate_evaluation_report import update_readme_evaluation_sections 

3172 

3173 update_readme_evaluation_sections() 

3174 except Exception as exc: 

3175 print(f"warning: README evaluation-section refresh failed: {exc}", file=sys.stderr) 

3176 

3177 

3178def _run_lean_report(args: argparse.Namespace, config: dict, run_dir: Path, *, pin: bool) -> int: 

3179 """`aq evaluate --lean-report`: evaluation/lean_report.py's steps against one run, each through cmd_evaluate on a copy 

3180 of `args`; a failing step is reported and the rest still run. Returns 1 when any step failed.""" 

3181 from evaluation.lean_report import lean_report_steps 

3182 

3183 if pin: 

3184 try: 

3185 from generate_backtest_report import update_readme_from_latest_backtest 

3186 

3187 update_readme_from_latest_backtest(backtest_dir=run_dir) 

3188 except Exception as exc: 

3189 print(f"warning: Lean headline refresh failed: {exc}", file=sys.stderr) 

3190 failed = [] 

3191 for label, overrides in lean_report_steps(config): 

3192 step_args = argparse.Namespace(**vars(args)) 

3193 for key, value in overrides.items(): 

3194 setattr(step_args, key, value) 

3195 step_args.backtest_dir = str(run_dir) 

3196 print(f"--- {label} ({run_dir.name})") 

3197 try: 

3198 exit_code = cmd_evaluate(step_args) 

3199 except Exception as exc: 

3200 print(f"warning: {label} failed: {exc}", file=sys.stderr) 

3201 exit_code = 1 

3202 if exit_code: 

3203 failed.append(label) 

3204 print(f"Lean report for {run_dir.name}: {len(failed)} step(s) failed{': ' + ', '.join(failed) if failed else ''}") 

3205 return 1 if failed else 0 

3206 

3207 

3208def _phase_deflation_inputs() -> dict | None: 

3209 """N and the trial variance from the ledgers, once V6.6.0's selection has candidates. Before then the registry's cross-window 

3210 spread stands, as `alpha_proof.period_report` documents.""" 

3211 from evaluation.trial_ledger import deflation_inputs, read_ledger 

3212 

3213 evaluation = ML_DIR / "evaluation" 

3214 registry_path = evaluation / "trial_registry.json" 

3215 current = read_ledger(evaluation / "v660" / "trial_ledger.jsonl") 

3216 if not registry_path.exists() or not any(entry["role"] == "candidate" for entry in current): 

3217 return None 

3218 registry = json.loads(registry_path.read_text(encoding="utf-8")) 

3219 earlier = [*read_ledger(evaluation / "v650" / "trial_ledger.jsonl"), *read_ledger(evaluation / "v669" / "trial_ledger.jsonl"), 

3220 *read_ledger(evaluation / "v6610" / "trial_ledger.jsonl"), *read_ledger(evaluation / "v6610" / "book2" / "trial_ledger.jsonl")] 

3221 return deflation_inputs([*earlier, *current], registry, "v660_selection") 

3222 

3223 

3224def _forward_ledger_rows(args: argparse.Namespace) -> list[dict]: 

3225 """The ledger from `--ledger-file`, or from the branch the scheduled Action writes.""" 

3226 if getattr(args, "ledger_file", None): 

3227 from evaluation.forward_ledger import read_ledger 

3228 

3229 return read_ledger(Path(args.ledger_file)) 

3230 branch = getattr(args, "ledger_branch", None) or "forward-ledger" 

3231 subprocess.run(["git", "fetch", "--quiet", "origin", f"{branch}:{branch}"], cwd=ROOT_DIR, check=False) 

3232 shown = subprocess.run(["git", "show", f"{branch}:forward/ledger.jsonl"], cwd=ROOT_DIR, capture_output=True, text=True, encoding="utf-8", check=False) 

3233 if shown.returncode != 0: 

3234 return [] 

3235 return [json.loads(line) for line in shown.stdout.splitlines() if line.strip()] 

3236 

3237 

3238def _resolve_lean_run_dir(args: argparse.Namespace) -> Path | None: 

3239 """`--backtest-dir`, else the README pin, else the newest finished Lean run: the same run for every Lean-reading flag.""" 

3240 from generate_backtest_report import resolve_lean_run_dir 

3241 

3242 return resolve_lean_run_dir(getattr(args, "backtest_dir", None), ROOT_DIR / "backtests") 

3243 

3244 

3245def _blend_raw_scores_for_dataset(dataset, config: dict, sequence_window_default: int, ml_dir: Path | None = None): 

3246 """The live path's rank score for every dataset row: the config-driven, 

3247 promotion-gate-aware head blend (portfolio/rank_signal.py), NOT the 

3248 single hard-coded head the idealized `--rank-book` run scores with. 

3249 Mirrors the block --calibrate-book-spread / --replay-rolling-ic-gate 

3250 each carry inline (this file's established duplication convention); 

3251 new callers use this one. Returns (raw_scores, policy). `ml_dir` (V6.0.0) 

3252 scores the models of another directory, e.g. a candidate's 

3253 ml/versions/<id>, without installing them.""" 

3254 from evaluation import compute_blended_raw_scores, predict_heads 

3255 

3256 ml_dir = Path(ml_dir) if ml_dir is not None else ML_DIR 

3257 from portfolio.rank_signal import resolve_rank_signal_policy 

3258 

3259 training_metrics_by_model: dict[str, dict | None] = {} 

3260 for model_name, metrics_filename in ( 

3261 ("sequence", "sequence_training_metrics.json"), 

3262 ("multitask", "multitask_training_metrics.json"), 

3263 ): 

3264 metrics_path = ml_dir / metrics_filename 

3265 training_metrics_by_model[model_name] = ( 

3266 json.loads(metrics_path.read_text(encoding="utf-8")) if metrics_path.exists() else None 

3267 ) 

3268 policy = resolve_rank_signal_policy(training_metrics_by_model, config) 

3269 active_heads = [head_name for head_name, weight in policy["heads"].items() if weight > 0.0] 

3270 

3271 from evaluation.model_predictions import predict_heads_ensemble 

3272 from inference.exported_model import load_ensemble_member_exports, resolve_model_ensemble_config 

3273 

3274 ensemble = resolve_model_ensemble_config(config) 

3275 predictions_by_model_head: dict[str, dict[str, object]] = {} 

3276 for model_kind_for_head in policy["model_priority"]: 

3277 model_filename, schema_filename = _EVALUATE_MODEL_ARTIFACTS[model_kind_for_head] 

3278 model_path = ml_dir / model_filename 

3279 schema_path = ml_dir / schema_filename 

3280 if not model_path.exists() or not schema_path.exists(): 

3281 continue # best-effort - a missing model falls through to the next model_priority entry 

3282 feature_schema = json.loads(schema_path.read_text(encoding="utf-8")) 

3283 # V6.4.4: ranked inputs (phase1.features.cross_sectional_inputs) feed the multitask model only, as in main.py. 

3284 model_frame = dataset 

3285 if model_kind_for_head == "multitask": 

3286 from features.cross_sectional_inputs import apply_cross_sectional_inputs 

3287 

3288 model_frame = apply_cross_sectional_inputs(dataset, config, feature_schema["model_input_names"]) 

3289 # V6.1.0: a seed ensemble (phase_v2.model_ensemble) replaces the single export, exactly as main.py loads it. 

3290 members = ( 

3291 load_ensemble_member_exports(ml_dir / ensemble[f"{model_kind_for_head}_dir"]) if ensemble["enabled"] else [] 

3292 ) 

3293 predict_kwargs = dict( 

3294 model_kind=model_kind_for_head, 

3295 sequence_feature_schema=feature_schema if model_kind_for_head == "sequence" else None, 

3296 configured_window_size=int(sequence_window_default), 

3297 batched=True, # V5.8.0: chunked batched interpreters (same values to ~1e-15, bounded memory, far faster) 

3298 ) 

3299 if members: 

3300 predictions_by_model_head[model_kind_for_head] = predict_heads_ensemble( 

3301 model_frame, members, feature_schema["model_input_names"], list(active_heads), **predict_kwargs 

3302 ) 

3303 else: 

3304 model_export = json.loads(model_path.read_text(encoding="utf-8")) 

3305 predictions_by_model_head[model_kind_for_head] = predict_heads( 

3306 model_frame, model_export, feature_schema["model_input_names"], list(active_heads), **predict_kwargs 

3307 ) 

3308 return compute_blended_raw_scores(dataset, predictions_by_model_head, policy), policy 

3309 

3310 

3311def _universe_asset_metadata(config: dict) -> tuple[dict[str, str], dict[str, bool]]: 

3312 """({ticker: asset_class}, {ticker: trading_eligible}) - the per-symbol 

3313 fields main.py hands the book. asset_class falls back to security_type 

3314 exactly as main.py does (bond ETFs are security_type equity, 

3315 asset_class bond); eligibility comes from the dataset manifest and is 

3316 False for every asset class whose trading is disabled in the config.""" 

3317 from risk.asset_class_router import book_candidate_trading_eligible 

3318 

3319 asset_class_by_ticker = { 

3320 asset["ticker"]: str(asset.get("asset_class") or asset.get("security_type")) 

3321 for asset in config.get("phase1", {}).get("universe", {}).get("assets", []) 

3322 } 

3323 manifest_path = ML_DIR / "dataset_manifest.json" 

3324 trading_eligible_by_ticker: dict[str, bool] = {} 

3325 if manifest_path.exists(): 

3326 manifest = json.loads(manifest_path.read_text(encoding="utf-8")) 

3327 trading_eligible_by_ticker = { 

3328 ticker: bool(quality.get("trading_eligible", False)) 

3329 for ticker, quality in (manifest.get("asset_quality") or {}).items() 

3330 } 

3331 phase_v2 = config.get("phase_v2", {}) 

3332 class_flags = [bool(phase_v2.get(key, {}).get("enabled", False)) for key in ("futures_risk", "options_risk", "forex_risk")] 

3333 # V5.8.0 - a class governed by an enabled sleeve (forex with forex trading on, bond) takes no main-book slot, 

3334 # exactly as main.py::_sleeve_class_for_asset() keeps it out of the live candidates. 

3335 sleeve_classes = set() 

3336 if phase_v2.get("forex_sleeve", {}).get("enabled", False) and phase_v2.get("forex_risk", {}).get("enabled", False): 

3337 sleeve_classes.add("forex") 

3338 if phase_v2.get("bond_sleeve", {}).get("enabled", False): 

3339 sleeve_classes.add("bond") 

3340 from portfolio.book_construction import crypto_core_only_settings, crypto_graduate_excluded 

3341 

3342 core_only, core_names = crypto_core_only_settings(phase_v2.get("class_weight_caps")) 

3343 for asset in config.get("phase1", {}).get("universe", {}).get("assets", []): 

3344 ticker = asset["ticker"] 

3345 trading_eligible_by_ticker[ticker] = book_candidate_trading_eligible( 

3346 trading_eligible_by_ticker.get(ticker, True), asset_class_by_ticker[ticker], *class_flags 

3347 ) and asset_class_by_ticker[ticker] not in sleeve_classes and not crypto_graduate_excluded( 

3348 ticker, asset_class_by_ticker[ticker], core_only, core_names 

3349 ) 

3350 return asset_class_by_ticker, trading_eligible_by_ticker 

3351 

3352 

3353def _default_book_history_path(diagnostics_config: dict) -> Path: 

3354 """The book-history file the reconcile tools read by default: the newest per-run file when 

3355 `phase_v2.diagnostics.book_history.per_run_files` produced any (V5.7.0), else the cumulative `output_path`.""" 

3356 cumulative = ROOT_DIR / diagnostics_config.get("output_path", "visualization/book_history.jsonl") 

3357 per_run_dir = cumulative.with_suffix("") 

3358 newest = sorted(per_run_dir.glob("*.jsonl")) if per_run_dir.is_dir() else [] 

3359 chosen = newest[-1] if newest else cumulative 

3360 note = _book_history_note(chosen) 

3361 if note: 

3362 print(note, file=sys.stderr) 

3363 return chosen 

3364 

3365 

3366def _book_history_note(chosen: Path) -> str | None: 

3367 """#418: a target-weights run writes no book history, so after one the newest file belongs to an older member-book run. 

3368 Says so when the latest Lean run's frozen config (or, without one, config.json) is a target-weights run.""" 

3369 from evaluation.backtest_audit import member_book_runs 

3370 

3371 run_dir = _resolve_lean_run_dir(argparse.Namespace(backtest_dir=None)) 

3372 frozen = ML_DIR / "evaluation" / "run_configs" / f"{run_dir.name}.json" if run_dir is not None else None 

3373 source = frozen if frozen is not None and frozen.exists() else CONFIG_PATH 

3374 try: 

3375 config = json.loads(source.read_text(encoding="utf-8")) 

3376 except (OSError, ValueError): 

3377 return None 

3378 if member_book_runs(config): 

3379 return f"book history: {chosen.name}" 

3380 latest = run_dir.name if run_dir is not None else "the latest run" 

3381 return (f"book history: {chosen.name} is an older member-book run's; {latest} traded target weights ({source.name}) and wrote no book history" 

3382 " (pass --book-history-path to choose)") 

3383 

3384 

3385def _core_quality_tickers() -> frozenset[str]: 

3386 """Tickers the dataset manifest tags quality_tier == "core" (main.py gives core crypto the zero-volume fallback).""" 

3387 manifest_path = ML_DIR / "dataset_manifest.json" 

3388 if not manifest_path.exists(): 

3389 return frozenset() 

3390 manifest = json.loads(manifest_path.read_text(encoding="utf-8")) 

3391 return frozenset( 

3392 ticker for ticker, quality in (manifest.get("asset_quality") or {}).items() if quality.get("quality_tier") == "core" 

3393 ) 

3394 

3395 

3396def _read_dataset_rows( 

3397 path: Path, 

3398 *, 

3399 columns: list[str] | None = None, 

3400 ticker: str | None = None, 

3401 only_training_eligible: bool = False, 

3402 chunksize: int = 50_000, 

3403): 

3404 """Returns a pandas DataFrame. Chunked read of a dataset CSV that keeps only the requested columns / one ticker's rows / 

3405 training-eligible rows - the full 250-column frame is ~330 MB resident and the reconciliation 

3406 tools only ever need a sliver of it (the 4 GB dev PC kills them otherwise).""" 

3407 import pandas as pd 

3408 

3409 wanted = None if columns is None else set(columns) 

3410 usecols = None if wanted is None else (lambda name: name in wanted) 

3411 parts = [] 

3412 for chunk in pd.read_csv(path, usecols=usecols, chunksize=chunksize): 

3413 if ticker is not None and "ticker" in chunk.columns: 

3414 chunk = chunk[chunk["ticker"] == ticker] 

3415 if only_training_eligible and "training_eligible" in chunk.columns: 

3416 chunk = chunk[chunk["training_eligible"]] 

3417 parts.append(chunk) 

3418 return pd.concat(parts, ignore_index=True) if parts else pd.DataFrame() 

3419 

3420 

3421def _reconciliation_dataset_columns() -> list[str]: 

3422 """date/ticker/eligibility plus every model input of the sequence and multitask schemas.""" 

3423 columns = {"date", "ticker", "training_eligible"} 

3424 for _model_filename, schema_filename in _EVALUATE_MODEL_ARTIFACTS.values(): 

3425 schema_path = ML_DIR / schema_filename 

3426 if schema_path.exists(): 

3427 columns.update(json.loads(schema_path.read_text(encoding="utf-8")).get("model_input_names", [])) 

3428 return sorted(columns) 

3429 

3430 

3431_EVALUATE_MODEL_ARTIFACTS = { 

3432 "sequence": ("sequence_model.json", "sequence_feature_schema.json"), 

3433 "multitask": ("multitask_model.json", "multitask_feature_schema.json"), 

3434} 

3435 

3436 

3437def _print_v580_audit_summary(flag: str, audit: dict) -> None: 

3438 """One short human summary per V5.8.0 audit (the JSON holds everything).""" 

3439 if flag == "ic_by_class": 

3440 print(f"Class IC audit ({audit['split']}, {audit['rows']} rows):") 

3441 for target, decomposition in audit["heads"].items(): 

3442 pooled, between = decomposition["pooled"], decomposition["between"] 

3443 print(f" {target}: pooled={pooled['mean_ic']} (t {pooled['hac_t']:.2f}) between-class={between['mean_ic']} " 

3444 f"class share of pooled={decomposition['class_share_of_pooled']}") 

3445 for kind, stats in decomposition["within"].items(): 

3446 print(f" within {kind}: {stats['mean_ic']} (t {stats['hac_t']:.2f}, {stats['num_dates']} dates)") 

3447 elif flag == "audit_gates": 

3448 print(f"Gate audit ({audit['split']}): {audit['num_vetoed']}/{audit['num_decisions']} dates vetoed " 

3449 f"(share {audit['veto_share']}), false vetoes {audit['num_false_vetoes']} " 

3450 f"({audit['false_veto_share_of_vetoes']}), resolved-gate veto share {audit['resolved_gate_veto_share']}") 

3451 print(f" state vs resolved trailing IC: corr={audit['state_vs_resolved_correlation']} " 

3452 f"gap={audit['state_minus_resolved_mean_gap']}; mean forward IC all={audit['mean_forward_ic_all']} " 

3453 f"vetoed={audit['mean_forward_ic_vetoed']}") 

3454 elif flag == "audit_data": 

3455 print(f"Data audit ({audit['data_root']}): {audit['num_assets']} assets, flagged {len(audit['flagged'])}: {audit['flagged']}") 

3456 for ticker in audit["flagged"]: 

3457 print(f" {ticker}: {audit['assets'][ticker].get('problems')}") 

3458 elif flag == "audit_heads": 

3459 print(f"Head audit: {audit['num_passed']}/{audit['num_components']} components pass") 

3460 for row in audit["rows"]: 

3461 mark = "PASS" if row["passed"] else "FAIL" 

3462 path = " [live path]" if row["in_decision_path"] else "" 

3463 print(f" {mark} {row['component']}: {row['metric']} = {row['value']}{path}") 

3464 print(f" failing in the live path: {audit['failing_in_decision_path'] or 'none'}") 

3465 policy = audit.get("rank_signal_policy") or {} 

3466 if policy.get("demotion_fallback"): 

3467 print(f" WARNING rank signal: every decision head failed its gate {policy.get('failed_heads')}; " 

3468 f"live trades the configured blend {policy.get('heads')}") 

3469 else: 

3470 flags = audit["flags"] 

3471 print(f"Feature audit: {len(audit['features'])} features; ticker-ID suspects {flags['ticker_id_suspects']}") 

3472 for kind, names in flags["constant_for_class"].items(): 

3473 print(f" constant for {kind}: {names}") 

3474 print(f" IC sign unstable across splits: {len(flags['ic_sign_unstable'])}") 

3475 

3476 

3477EVALUATE_COMPANIONS = { 

3478 "symbol": ("reconcile_features",), "book_history_path": ("reconcile_book_history", "reconcile_features", "audit_backtest", "lean_report"), "replay_hysteresis": ("reconcile_book_history",), 

3479 "reconcile_run_index": ("reconcile_book_history", "reconcile_features"), "reconcile_all_runs": ("reconcile_book_history", "reconcile_features"), "hysteresis_survives_veto": ("replay_hysteresis",), 

3480 "variants": ("ablation",), "run_id": ("walk_forward_summary",), "limit_fill_offset_sweep": ("simulate_limit_fills",), 

3481 "period": ("audit_backtest", "lean_report", "attribute_lean"), "max_open_sessions": ("audit_backtest", "lean_report"), 

3482 "interest_rate_file": ("lean_stats", "lean_report"), "trading_days": ("lean_stats", "lean_report"), "reference_dir": ("paper_check",), 

3483 "trial_returns": ("pbo",), "signal": ("factor_spanning",), "calibration_file": ("calibrate_sim_lean",), "permutation": ("audit_features",), 

3484 "data_root": ("audit_data",), "ledger_branch": ("forward_ledger",), "ledger_file": ("forward_ledger",), 

3485} 

3486EVALUATE_GROUPS = ( 

3487 ("Rank book", ("--rank-book", "--capacity", "--stress", "--all", "--as-live", "--preset", "--account", "--model", "--head", "--split", "--dataset")), 

3488 ("Calibration", ("--calibrate-edge", "--calibrate-book-spread", "--calibrate-confidence-threshold", "--calibrate-rolling-ic-floor", "--calibrate-volatility-threshold")), 

3489 ("Monte Carlo", ("--monte-carlo", "--mc-runs", "--mc-block-size", "--mc-seed", "--mc-method")), 

3490 ("Lean run tools", ("--lean-report", "--lean-stats", "--lean-monte-carlo", "--attribute-lean", "--audit-backtest", "--audit-fills", "--alpha-proof", "--backtest-stats", 

3491 "--paper-check", "--classification-parity", "--backtest-dir")), 

3492 ("Audits", ("--audit-gates", "--audit-data", "--audit-heads", "--audit-leakage", "--audit-features", "--ic-by-class", "--overfit-report", "--classification", "--factor-exposure")), 

3493 ("Research", ("--pbo", "--factor-spanning", "--calibrate-sim-lean", "--benchmarks", "--ablation", "--walk-forward-summary", "--forward-ledger")), 

3494 ("Reconcile and replay", ("--reconcile-features", "--reconcile-book-history", "--replay-kill-switch", "--replay-rolling-ic-gate", "--simulate-limit-fills")), 

3495) 

3496 

3497 

3498def cmd_evaluate(args: argparse.Namespace) -> int: 

3499 """`aq evaluate`: offline, cost-aware evaluation of the cross-sectional 

3500 rank book (V5.1 Phase 0, development/Problems.md) - turns "how good is 

3501 this rank prediction" into "what would this have earned net of fees", 

3502 the question nothing else in this codebase answers 

3503 (train.py::compute_strategy_metrics() simulates a long-only 

3504 1-day-direction strategy gross of costs, not the rank book, not net of 

3505 cost). Runs every dataset row through inference/exported_model.py (the 

3506 SAME torch-free interpreter main.py's live decision path uses) and 

3507 evaluation/rank_book_simulator.py's simulate_rank_book() (which itself 

3508 reuses portfolio/book_construction.py's build_rank_based_book() and 

3509 portfolio/book_neutrality.py's apply_book_neutrality()) - so every 

3510 number this prints is the offline mirror of live behavior, not a 

3511 separately re-derived approximation. 

3512 

3513 Heavy imports (pandas/numpy/evaluation/inference) are deliberately 

3514 LAZY, inside this function body, not at module top - the same 

3515 convention cmd_assets() already follows for monitoring.assets_status - 

3516 so every other `aq` subcommand's startup stays exactly as fast as 

3517 before this command existed. 

3518 """ 

3519 if getattr(args, "list", False): 

3520 for title, flags in EVALUATE_GROUPS: 

3521 print(f"{title}: {' '.join(flags)}") 

3522 return 0 

3523 problems = companion_errors(args, EVALUATE_COMPANIONS) 

3524 if problems: 

3525 print("aq evaluate: " + "; ".join(problems), file=sys.stderr) 

3526 return 2 

3527 import pandas as pd 

3528 

3529 from evaluation import capacity_curve, predict_head, predict_heads, simulate_rank_book, stress_test_costs 

3530 from execution.cost_model import commission_bps_by_ticker 

3531 from features import load_sector_mapping 

3532 

3533 config = json.loads(CONFIG_PATH.read_text(encoding="utf-8")) 

3534 if getattr(args, "account", None): 

3535 from execution.accounts_io import load_account_config 

3536 

3537 # V6.6.5 (#349): the account's tightened limits, through the same apply_risk_overrides main.py runs 

3538 config = load_account_config(config, args.account, ROOT_DIR) 

3539 

3540 if getattr(args, "preset", None): 

3541 presets = config.get("phase_v2", {}).get("presets", {}) 

3542 preset = presets.get(args.preset) 

3543 if preset is None: 

3544 available = sorted(name for name in presets if name != "active") 

3545 print(f"error: unknown preset {args.preset!r} - available: {available or 'none configured yet'}", file=sys.stderr) 

3546 return 1 

3547 config = _apply_preset_in_memory(config, preset) 

3548 

3549 # V6.3.0 - `aq evaluate --lean-report`: every run-folder tool for one Lean run, then the README (`aq backtest` runs it). 

3550 if getattr(args, "lean_report", False): 

3551 run_dir = _resolve_lean_run_dir(args) 

3552 if run_dir is None or not run_dir.exists(): 

3553 print("error: no backtest folder found - pass --backtest-dir PATH.", file=sys.stderr) 

3554 return 1 

3555 return _run_lean_report(args, config, run_dir, pin=bool(getattr(args, "backtest_dir", None))) 

3556 

3557 # V6.3.0 - `aq evaluate --backtest-stats`: the README's Backtest Statistics for one Lean run; no dataset, no model. 

3558 if getattr(args, "forward_ledger", False): 

3559 import datetime as _datetime 

3560 

3561 import numpy as np 

3562 

3563 from evaluation.forward_ledger import judge_ledger 

3564 

3565 ledger_rows = _forward_ledger_rows(args) 

3566 today = _datetime.datetime.now(_datetime.timezone.utc).date() 

3567 last_session = max((row["payload"]["session"] for row in ledger_rows), default=None) 

3568 weekdays = [str(day) for day in np.arange(np.datetime64(last_session, "D") + np.timedelta64(1, "D"), np.datetime64(today, "D") + np.timedelta64(1, "D"), dtype="datetime64[D]") if np.is_busday(day)] if last_session else [] 

3569 report = judge_ledger(ledger_rows, today_sessions=weekdays) 

3570 print(json.dumps(report, indent=2, default=str)) 

3571 return 0 if report["chain_valid"] else 1 

3572 

3573 if getattr(args, "alpha_proof", False): 

3574 from evaluation.alpha_proof import alpha_proof_report 

3575 from evaluation.backtest_statistics import load_trial_sharpes 

3576 

3577 run_dir = _resolve_lean_run_dir(args) 

3578 if run_dir is None or not run_dir.exists(): 

3579 print("error: no backtest folder found - pass --backtest-dir PATH or run `aq backtest` first.", file=sys.stderr) 

3580 return 1 

3581 report = alpha_proof_report(run_dir, config, ROOT_DIR, 

3582 trial_sharpes=load_trial_sharpes(ML_DIR / "evaluation" / "trial_registry.json"), 

3583 deflation=_phase_deflation_inputs(), data_dir=getattr(args, "data_dir", None) or "data") 

3584 from datetime import datetime, timezone 

3585 

3586 report["computed_at"] = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d %H:%M UTC") 

3587 out_path = ML_DIR / "evaluation" / "alpha_proof.json" 

3588 _write_evaluation_json(out_path, report) 

3589 _write_evaluation_json(ML_DIR / "evaluation" / f"alpha_proof_{run_dir.name}.json", report) 

3590 if args.json: 

3591 print(json.dumps(report, indent=2, default=str)) 

3592 else: 

3593 print(f"Alpha proof: {run_dir.name}") 

3594 for name, period in (report.get("periods") or {}).items(): 

3595 alpha = period.get("alpha") or {} 

3596 print(f" {name:9s} n={period.get('n', 0):4d} Sharpe={period.get('sharpe')} CI={period.get('sharpe_ci95')} " 

3597 f"alpha/yr={alpha.get('alpha_annual')} t={alpha.get('t_hac')} DSR={period.get('dsr')}") 

3598 verdict = report.get("r_alpha1") or {} 

3599 print(f" R-ALPHA1: {verdict.get('verdict')} {verdict.get('failed') or ''}") 

3600 print(f" Wrote {out_path}") 

3601 return 0 

3602 

3603 if getattr(args, "backtest_stats", False): 

3604 from evaluation.backtest_statistics import compute_for_run_dir 

3605 

3606 run_dir = _resolve_lean_run_dir(args) 

3607 if run_dir is None or not run_dir.exists(): 

3608 print("error: no backtest folder found - pass --backtest-dir PATH or run `aq backtest` first.", file=sys.stderr) 

3609 return 1 

3610 try: 

3611 stats = compute_for_run_dir(run_dir, config, ROOT_DIR) 

3612 except FileNotFoundError as error: 

3613 print(f"error: {error}", file=sys.stderr) 

3614 return 1 

3615 from datetime import datetime, timezone 

3616 

3617 stats["computed_at"] = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d %H:%M UTC") 

3618 out_path = ML_DIR / "evaluation" / "backtest_statistics.json" 

3619 _write_evaluation_json(out_path, stats) 

3620 if args.json: 

3621 print(json.dumps(stats, indent=2, default=str)) 

3622 else: 

3623 print(f"Backtest statistics: {run_dir.name} ({stats.get('status')})") 

3624 for section, rows in (stats.get("sections") or {}).items(): 

3625 if isinstance(rows, list) and rows and "metric" in rows[0]: 

3626 first = rows[0] 

3627 print(f" {section}: {len(rows)} rows (e.g. {first['metric']}: {first.get('portfolio')})") 

3628 print(f" Wrote {out_path}") 

3629 _refresh_readme_evaluation_sections() 

3630 return 0 

3631 

3632 # V6.4.0 (R-L11) - `aq evaluate --classification-parity`: Lean's logged book-call probabilities vs the offline head. 

3633 if getattr(args, "classification_parity", False): 

3634 from evaluation.classification_parity import classification_parity_for_run_dir 

3635 

3636 run_dir = _resolve_lean_run_dir(args) 

3637 if run_dir is None or not run_dir.exists(): 

3638 print("error: no backtest folder found - pass --backtest-dir PATH.", file=sys.stderr) 

3639 return 1 

3640 result = classification_parity_for_run_dir(run_dir, config, ROOT_DIR, dataset_path=getattr(args, "dataset", None)) 

3641 result["run"] = run_dir.name 

3642 _write_evaluation_json(ML_DIR / "evaluation" / "classification_parity.json", result) 

3643 if result.get("status") != "ok": 

3644 print(f"Classification parity ({run_dir.name}): {result.get('status')} - {result.get('reason') or 'nothing to compare'}") 

3645 return 0 

3646 deltas = result["deltas"] 

3647 print(f"Classification parity ({run_dir.name}, {result['model']} {result['head']}): matched {result['n_matched']} of " 

3648 f"{result['n_calls']} calls; accuracy delta {deltas['accuracy']:+.4f}, neg log-loss delta {deltas['neg_log_loss']:+.4f}, " 

3649 f"median |dp| {deltas['median_abs_probability_gap']:.5f}; within tolerance: {result['within_tolerance']}") 

3650 return 0 if result["within_tolerance"] in (True, None) else 1 

3651 

3652 # V6.4.0 (L12) - `aq evaluate --paper-check`: the paper-period checklist against the reference run's bands. 

3653 if getattr(args, "paper_check", False): 

3654 from evaluation.paper_protocol import band_check, paper_metrics_for_run_dir, reference_bands 

3655 from generate_backtest_report import resolve_lean_run_dir 

3656 

3657 run_dir = _resolve_lean_run_dir(args) 

3658 reference_dir = resolve_lean_run_dir(getattr(args, "reference_dir", None), ROOT_DIR / "backtests") 

3659 if run_dir is None or reference_dir is None or not run_dir.exists() or not reference_dir.exists(): 

3660 print("error: pass --backtest-dir PATH (the run to check); --reference-dir defaults to the README pin.", file=sys.stderr) 

3661 return 1 

3662 reference_config_path = None 

3663 try: 

3664 from evaluation.lean_attribution import run_config_path 

3665 

3666 reference_config_path = run_config_path(reference_dir, ROOT_DIR) 

3667 except Exception: 

3668 pass 

3669 reference_config = json.loads(reference_config_path.read_text(encoding="utf-8")) if reference_config_path else config 

3670 run = paper_metrics_for_run_dir(run_dir, config, ROOT_DIR, start=getattr(args, "start", None), end=getattr(args, "end", None)) 

3671 reference = paper_metrics_for_run_dir(reference_dir, reference_config, ROOT_DIR) 

3672 bands = reference_bands(reference["table"], reference["rebalances"], reference["slippage_by_date"]) 

3673 verdict = band_check(run["metrics"], bands) 

3674 payload = {"run": run_dir.name, "reference": reference_dir.name, "window": [getattr(args, "start", None), getattr(args, "end", None)], 

3675 "metrics": run["metrics"], "bands": bands, "verdict": verdict, 

3676 "note": "a tool dry run unless the run is a paper period of the frozen config"} 

3677 _write_evaluation_json(ML_DIR / "evaluation" / "paper_check.json", payload) 

3678 print(f"Paper check {run_dir.name} against {reference_dir.name}: {run['metrics']['rebalances']} rebalances, " 

3679 f"{run['metrics']['trading_days']} days; inside all bands: {verdict['inside']}" 

3680 + (f" (outside: {', '.join(verdict['outside'])})" if verdict["outside"] else "") 

3681 + ("" if verdict["minimum_met"] else f" - below the minimum of {verdict['minimum']}")) 

3682 return 0 

3683 

3684 # V5.5.0 (Problems.md #127/#128) - `aq evaluate --audit-backtest` audits 

3685 # ONE finished Lean run folder at order level (exposure per asset class, 

3686 # book-member vs non-member entries, duplicate/overlapping limit orders, 

3687 # holding periods, fees, Sharpe with and without a risk-free rate, gate 

3688 # vetoes, engine teardown). Early-return like the other log-vs-artifact 

3689 # tools: no dataset, no model. Not included in --all. 

3690 if getattr(args, "audit_backtest", False): 

3691 from evaluation.backtest_audit import audit_backtest_run, load_backtest_run, load_book_history 

3692 

3693 run_dir = _resolve_lean_run_dir(args) 

3694 if run_dir is None or not run_dir.exists(): 

3695 print("error: no backtest folder found - pass --backtest-dir PATH or run `aq backtest` first.", file=sys.stderr) 

3696 return 1 

3697 try: 

3698 run = load_backtest_run(run_dir) 

3699 except FileNotFoundError as error: 

3700 print(f"error: {error}", file=sys.stderr) 

3701 return 1 

3702 book_history_path = Path(getattr(args, "book_history_path", None) or (ROOT_DIR / "visualization" / "book_history.jsonl")) 

3703 # A limit order is cancelled after `unfilled_timeout_bars` equity sessions; one extra session is slack for a 

3704 # holiday, which the weekday count cannot see. 

3705 max_open_sessions = getattr(args, "max_open_sessions", None) 

3706 if max_open_sessions is None: 

3707 max_open_sessions = int(config.get("phase_v2", {}).get("limit_orders", {}).get("unfilled_timeout_bars", 3)) + 1 

3708 periods = [] 

3709 for period_text in getattr(args, "period", None) or []: 

3710 period_start, _, period_end = str(period_text).partition("..") 

3711 if not (period_start and period_end): 

3712 print(f"error: --period expects START..END (ISO dates), got {period_text!r}", file=sys.stderr) 

3713 return 1 

3714 periods.append((period_start, period_end)) 

3715 from evaluation.backtest_audit import class_by_ticker_from_config, member_book_runs 

3716 class_by_ticker = class_by_ticker_from_config(config) 

3717 run_config = _run_config_for(run_dir, config) 

3718 audit = audit_backtest_run( 

3719 run, load_book_history(book_history_path), book_run_index=getattr(args, "book_run_index", -1), 

3720 max_open_sessions=max_open_sessions, class_by_ticker=class_by_ticker, 

3721 periods=periods, member_book=member_book_runs(run_config), 

3722 ) 

3723 audit["backtest_dir"] = str(run_dir) 

3724 _write_evaluation_json(ML_DIR / "evaluation" / "backtest_audit.json", audit) 

3725 if args.json: 

3726 print(json.dumps(audit, indent=2, default=str)) 

3727 else: 

3728 print(f"Backtest audit: {run_dir.name} (run {audit['run_id']}, {audit['window']['num_days']} days)") 

3729 print(f" Lean: {audit['lean_statistics']}") 

3730 sharpe = audit["sharpe"] 

3731 no_rf = sharpe["no_risk_free"] 

3732 with_rf = sharpe["with_risk_free"] 

3733 print( 

3734 " Sharpe from equity curve: " 

3735 f"no risk-free={'n/a' if no_rf is None else f'{no_rf:.3f}'}, " 

3736 f"risk-free {sharpe['risk_free_annual_assumed']:.0%}={'n/a' if with_rf is None else f'{with_rf:.3f}'}" 

3737 ) 

3738 for name, stats in sorted(audit["exposure"].items()): 

3739 print(f" exposure {name}: mean={stats['mean']:.4f} peak={stats['peak']:.4f}") 

3740 print(f" entries by asset class: {audit['entries_by_asset_class']}") 

3741 print(f" P&L by entry bucket (gross, fees, net): {audit['pnl_by_entry_bucket']}") 

3742 orders = audit["orders"] 

3743 print( 

3744 f" overlapping same-symbol orders: {orders['num_overlapping_pairs']} " 

3745 f"(limit: {orders['num_overlapping_limit_pairs']}); limit orders open > " 

3746 f"{orders['max_open_sessions_threshold']} sessions: {orders['num_limit_orders_open_too_long']}" 

3747 ) 

3748 print(f" holding period histogram: {audit['holding_period_days']}") 

3749 print(f" P&L / fees: {audit['pnl_and_fees']}") 

3750 book = audit["book"] 

3751 if book.get("applicable", True): 

3752 print(f" book: {book['num_engaged']}/{book['num_rebalance_records']} rebalances engaged; vetoes {book['veto_reasons']}") 

3753 else: 

3754 print(f" book: not applicable ({book['reason']})") 

3755 print(f" engine teardown: {audit['teardown']}") 

3756 for period in audit.get("periods", []): 

3757 net = period["net_return"] 

3758 print( 

3759 f" period {period['start']}..{period['end']}: net {'n/a' if net is None else f'{net:+.2%}'}, " 

3760 f"max drawdown {period['max_drawdown']:.2%}, Sharpe (no risk-free) {period['sharpe_no_risk_free']}, " 

3761 f"{period['closed_trades']} closed trades, P&L {period['realized_pnl_by_class']}" 

3762 ) 

3763 print(f" Wrote {ML_DIR / 'evaluation' / 'backtest_audit.json'}") 

3764 _refresh_readme_evaluation_sections() # the Lean-vs-offline block reads this file 

3765 return 0 

3766 

3767 # V6.0.0 - `aq evaluate --attribute-lean`: one Lean run's daily P&L rebuilt per ticker and component (main book, 

3768 # legacy signal, sleeves, crypto core / graduates), reconciled with Lean's equity curve; no dataset, no model. 

3769 # V6.2.0 - `aq evaluate --lean-stats`: Lean's printed Sharpe / Sortino / PSR next to the exact replica 

3770 # (evaluation/lean_statistics.py) on the shipped and the older risk-free file, at 252 and 365 days a year. 

3771 if getattr(args, "lean_stats", False): 

3772 from evaluation.lean_statistics import statistics_table 

3773 

3774 run_dir = _resolve_lean_run_dir(args) 

3775 results = [path for path in run_dir.glob("*.json") if path.stem.isdigit()] if run_dir and run_dir.exists() else [] 

3776 if not results: 

3777 print("error: no Lean result JSON found - pass --backtest-dir PATH.", file=sys.stderr) 

3778 return 1 

3779 rate_files = {"shipped rate file": ROOT_DIR / "data" / "alternative" / "interest-rate" / "usa" / "interest-rate.csv"} 

3780 pre_v620 = ML_DIR / "evaluation" / "v620" / "interest-rate_pre_v620.csv" 

3781 if pre_v620.exists(): 

3782 rate_files["pre-V6.2 rate file"] = pre_v620 

3783 if getattr(args, "interest_rate_file", None): 

3784 rate_files = {"--interest-rate-file": Path(args.interest_rate_file)} 

3785 day_counts = (int(args.trading_days),) if getattr(args, "trading_days", None) else (252, 365) 

3786 table = statistics_table(results[0], rate_files, day_counts) 

3787 print(f"Lean statistics, {run_dir.name} (run used {table['run_trading_days_per_year']} days a year)") 

3788 print(f" Lean printed: {table['lean_printed']}") 

3789 for label, row in table["replica"].items(): 

3790 print(f" {label:28s} Sharpe {row['sharpe_ratio']:+.3f} Sortino {row['sortino_ratio']:+.3f} " 

3791 f"PSR {row['probabilistic_sharpe_ratio']:.3%} annual {row['annual_return']:+.2%} " 

3792 f"std {row['annual_standard_deviation']:.4f} rf {row['risk_free_rate']:.4%}") 

3793 out_path = ML_DIR / "evaluation" / f"lean_stats_{run_dir.name}.json" 

3794 _write_evaluation_json(out_path, dict(table, run=run_dir.name)) 

3795 print(f" Wrote {out_path}") 

3796 return 0 

3797 if getattr(args, "lean_monte_carlo", False): 

3798 from evaluation.backtest_audit import configured_run_window, daily_equity_from_chart, load_backtest_run 

3799 from evaluation.monte_carlo import run_monte_carlo 

3800 

3801 run_dir = _resolve_lean_run_dir(args) 

3802 if run_dir is None or not run_dir.exists(): 

3803 print("error: no backtest folder found - pass --backtest-dir PATH.", file=sys.stderr) 

3804 return 1 

3805 lean_result = load_backtest_run(run_dir)["result"] 

3806 equity = daily_equity_from_chart(lean_result) 

3807 configured_start, configured_end = configured_run_window(lean_result) 

3808 returns = [after / before - 1.0 for (_, before), (_, after) in itertools.pairwise(equity) if before > 0] 

3809 from evaluation.alpha_proof import measured_annualization 

3810 

3811 mc = run_monte_carlo( 

3812 returns, n_runs=int(getattr(args, "mc_runs", 1000)), block_size=int(getattr(args, "mc_block_size", 20)), 

3813 seed=int(getattr(args, "mc_seed", 42)), method=str(getattr(args, "mc_method", "block")), 

3814 periods_per_year=measured_annualization([day for day, _ in equity[1:]], fallback=365.0), 

3815 ) 

3816 payload = {key: value for key, value in mc.items() if key != "runs_curves"} 

3817 if mc.get("runs_curves") is not None: 

3818 import numpy as np 

3819 

3820 (ML_DIR / "evaluation").mkdir(parents=True, exist_ok=True) 

3821 np.savez_compressed(ML_DIR / "evaluation" / "monte_carlo_lean_curves.npz", runs_curves=mc["runs_curves"]) 

3822 payload.update(source="lean", run=run_dir.name, 

3823 first_date=configured_start.date().isoformat() if configured_start else (equity[0][0] if equity else None), 

3824 last_date=configured_end.date().isoformat() if configured_end else (equity[-1][0] if equity else None), 

3825 num_daily_returns=len(returns), 

3826 observed_total_return_pct=round((equity[-1][1] / equity[0][1] - 1.0) * 100.0, 2) if equity else None) 

3827 out_path = ML_DIR / "evaluation" / "monte_carlo_lean.json" 

3828 _write_evaluation_json(out_path, payload) 

3829 print(f"Lean Monte Carlo ({run_dir.name}, {len(returns)} daily returns): {payload.get('status')}") 

3830 if payload.get("status") == "OK": 

3831 print(f" final return p5/p50/p95 {payload['final_return_pct']['p5']}% / {payload['final_return_pct']['p50']}% / " 

3832 f"{payload['final_return_pct']['p95']}%, Sharpe p50 {payload['sharpe']['p50']}, P(negative) {payload['prob_negative_return']}") 

3833 print(f" Wrote {out_path}") 

3834 _refresh_readme_evaluation_sections() 

3835 return 0 

3836 if getattr(args, "attribute_lean", False): 

3837 from evaluation.backtest_audit import load_backtest_run 

3838 from evaluation.lean_attribution import attribute_run, find_book_history_for_run 

3839 

3840 run_dir = _resolve_lean_run_dir(args) 

3841 if run_dir is None or not run_dir.exists(): 

3842 print("error: no backtest folder found - pass --backtest-dir PATH.", file=sys.stderr) 

3843 return 1 

3844 history_path = Path(args.book_history_file) if getattr(args, "book_history_file", None) else find_book_history_for_run( 

3845 run_dir, ROOT_DIR / "visualization" / "book_history" 

3846 ) 

3847 if history_path is None or not history_path.exists(): 

3848 print("error: no per-run book history for this run - pass --book-history-file PATH.", file=sys.stderr) 

3849 return 1 

3850 history = [json.loads(line) for line in history_path.read_text(encoding="utf-8").splitlines() if line.strip()] 

3851 run = load_backtest_run(run_dir) 

3852 periods: list[tuple[str, str] | None] = [None] 

3853 for period_text in getattr(args, "period", None) or []: 

3854 period_start, _, period_end = str(period_text).partition("..") 

3855 if not (period_start and period_end): 

3856 print(f"error: --period expects START..END (ISO dates), got {period_text!r}", file=sys.stderr) 

3857 return 1 

3858 periods.append((period_start, period_end)) 

3859 # The run's own config decides its classes and core crypto names (an older run had other caps). 

3860 from evaluation.lean_attribution import run_config_path 

3861 

3862 snapshot = run_config_path(run_dir, ROOT_DIR) or ROOT_DIR / "config.json" 

3863 run_config = _run_config_for(run_dir, config) 

3864 reports = {} 

3865 for period in periods: 

3866 label = "whole_run" if period is None else f"{period[0]}..{period[1]}" 

3867 reports[label] = attribute_run(run, history, run_config, ROOT_DIR, period=period) 

3868 reconciliation = reports[label]["reconciliation"] 

3869 print(f"{run_dir.name} {label}: rebuilt net {reconciliation['rebuilt_net_usd']:+.2f} vs Lean " 

3870 f"{reconciliation['lean_net_usd']:+.2f} USD (daily r {reconciliation['daily_change_correlation']})") 

3871 for name, entry in reports[label]["components"].items(): 

3872 if entry["fills"] or entry["pnl"]: 

3873 print(f" {name:16s} gross {entry['pnl']:+9.2f} fees {entry['fee']:8.2f} net {entry['net']:+9.2f} fills {entry['fills']}") 

3874 out_path = ML_DIR / "evaluation" / "lean_attribution.json" 

3875 _write_evaluation_json(out_path, {"backtest_dir": str(run_dir), "book_history": str(history_path), 

3876 "config": str(snapshot), "reports": reports}) 

3877 print(f" Wrote {out_path}") 

3878 _refresh_readme_evaluation_sections() 

3879 return 0 

3880 

3881 # V6.4.3 - the research / audit flags (evaluation/research_runners.py): each writes one JSON and returns. 

3882 v643_flags = ( 

3883 ("audit_leakage", "leakage_audit.json"), ("overfit_report", "overfit_report.json"), ("pbo", "pbo.json"), 

3884 ("factor_spanning", "factor_spanning.json"), ("calibrate_sim_lean", "sim_lean_gap.json"), 

3885 ) 

3886 v643_requested = [(flag, filename) for flag, filename in v643_flags if getattr(args, flag, False)] 

3887 if v643_requested: 

3888 from evaluation import research_runners 

3889 

3890 for flag, filename in v643_requested: 

3891 if flag == "audit_leakage": 

3892 report = research_runners.run_audit_leakage(getattr(args, "dataset", None)) 

3893 elif flag == "overfit_report": 

3894 report = research_runners.run_overfit_report() 

3895 elif flag == "pbo": 

3896 report = research_runners.run_pbo(Path(args.trial_returns or ML_DIR / "evaluation" / "v643" / "trial_returns.parquet")) 

3897 elif flag == "factor_spanning": 

3898 if not getattr(args, "signal", None): 

3899 print("error: --factor-spanning needs --signal CSV (date,ticker,score)", file=sys.stderr) 

3900 return 1 

3901 report = research_runners.run_factor_spanning(Path(args.signal), getattr(args, "dataset", None), 

3902 split=getattr(args, "split", None) or "backtest") 

3903 else: 

3904 if not getattr(args, "calibration_file", None): 

3905 print("error: --calibrate-sim-lean needs --calibration-file (a scripts/lean_calibration.py report)", file=sys.stderr) 

3906 return 1 

3907 report = research_runners.run_sim_lean_gap(Path(args.calibration_file)) 

3908 _write_evaluation_json(ML_DIR / "evaluation" / filename, report) 

3909 print(json.dumps(report, indent=2, default=str)[:4000] if args.json else f"{flag}: wrote {ML_DIR / 'evaluation' / filename}") 

3910 return 0 

3911 

3912 # V5.8.0 - the audit flags (evaluation/audit_runners.py): each writes one JSON and returns before any book run. 

3913 v580_audits = ( 

3914 ("ic_by_class", "class_ic_audit.json"), ("audit_gates", "gate_audit.json"), ("audit_data", "data_audit.json"), 

3915 ("audit_heads", "head_audit.json"), ("audit_features", "feature_quality_audit.json"), 

3916 ) 

3917 requested = [(flag, filename) for flag, filename in v580_audits if getattr(args, flag, False)] 

3918 if requested: 

3919 from evaluation import audit_runners 

3920 

3921 split = getattr(args, "split", None) or "backtest" 

3922 dataset_arg = getattr(args, "dataset", None) 

3923 for flag, filename in requested: 

3924 if flag == "ic_by_class": 

3925 audit = audit_runners.run_ic_by_class(config, split=split, dataset_path=dataset_arg) 

3926 elif flag == "audit_gates": 

3927 audit = audit_runners.run_audit_gates(config, split=split, dataset_path=dataset_arg) 

3928 elif flag == "audit_data": 

3929 audit = audit_runners.run_audit_data(config, data_root=Path(getattr(args, "data_root", None) or (ROOT_DIR / "data"))) 

3930 elif flag == "audit_heads": 

3931 audit = audit_runners.run_audit_heads(config) 

3932 else: 

3933 audit = audit_runners.run_audit_features(config, dataset_path=dataset_arg, permutation=bool(getattr(args, "permutation", False))) 

3934 _write_evaluation_json(ML_DIR / "evaluation" / filename, audit) 

3935 if flag in ("ic_by_class", "audit_gates") and isinstance(audit.get("split"), str): 

3936 _write_evaluation_json(ML_DIR / "evaluation" / f"{Path(filename).stem}_{audit['split']}.json", audit) 

3937 if args.json: 

3938 print(json.dumps({key: value for key, value in audit.items() if key != "rows"}, indent=2, default=str)) 

3939 else: 

3940 _print_v580_audit_summary(flag, audit) 

3941 print(f" Wrote {ML_DIR / 'evaluation' / filename}") 

3942 _refresh_readme_evaluation_sections() 

3943 return 0 

3944 

3945 # V5.7.0 - `aq evaluate --audit-fills`: every fill of one finished run against the dataset's open and against the 

3946 # open in the Lean zip itself (separates execution cost from a dataset/price-source gap). No model. 

3947 if getattr(args, "audit_fills", False): 

3948 from evaluation.backtest_audit import load_backtest_run 

3949 from evaluation.fill_price_audit import audit_fills 

3950 

3951 run_dir = _resolve_lean_run_dir(args) 

3952 if run_dir is None or not run_dir.exists(): 

3953 print("error: no backtest folder found - pass --backtest-dir PATH or run `aq backtest` first.", file=sys.stderr) 

3954 return 1 

3955 try: 

3956 run = load_backtest_run(run_dir) 

3957 except FileNotFoundError as error: 

3958 print(f"error: {error}", file=sys.stderr) 

3959 return 1 

3960 opens_dataset = Path(args.dataset) if getattr(args, "dataset", None) else ML_DIR / "datasets" / "full_dataset.csv" 

3961 opens_frame = _read_dataset_rows(opens_dataset, columns=["ticker", "date", "open"]) 

3962 dataset_opens = { 

3963 (str(ticker), str(date)[:10]): float(value) 

3964 for ticker, date, value in zip(opens_frame["ticker"], opens_frame["date"], opens_frame["open"], strict=False) 

3965 } 

3966 audit = audit_fills(run, dataset_opens, ROOT_DIR / "data") 

3967 audit["backtest_dir"] = str(run_dir) 

3968 _write_evaluation_json(ML_DIR / "evaluation" / "fill_price_audit.json", audit) 

3969 if args.json: 

3970 print(json.dumps(audit, indent=2, default=str)) 

3971 else: 

3972 print(f"Fill price audit: {run_dir.name} ({audit['num_fills']} fills)") 

3973 for label, key in (("vs dataset open", "fill_vs_dataset_open"), ("vs Lean zip open", "fill_vs_zip_open")): 

3974 print(f" fills {label} (fills without a reference: {audit[key]['fills_without_reference']}):") 

3975 for group, stats in audit[key]["groups"].items(): 

3976 print(f" {group}: {stats}") 

3977 print(f" dataset open vs zip open on traded dates: {audit['dataset_open_vs_zip_open_on_traded_dates']}") 

3978 print(f" Wrote {ML_DIR / 'evaluation' / 'fill_price_audit.json'}") 

3979 _refresh_readme_evaluation_sections() 

3980 return 0 

3981 

3982 # V5.1 Phase 4 (item 4) - `aq evaluate --walk-forward-summary` reads an 

3983 # already-written ml/versions/walk-forward-*/walk_forward_summary.json 

3984 # (train.py::_run_walk_forward()'s output) rather than running anything 

3985 # itself - a completely separate, lightweight code path from every 

3986 # other --rank-book/--capacity/--stress/--calibrate-edge flag below, 

3987 # so it returns early before any of that dataset/model loading. 

3988 if getattr(args, "walk_forward_summary", False): 

3989 versions_dir = ML_DIR / "versions" 

3990 run_id = getattr(args, "run_id", None) 

3991 if run_id: 

3992 summary_path = versions_dir / run_id / "walk_forward_summary.json" 

3993 else: 

3994 candidates = sorted(versions_dir.glob("walk-forward-*/walk_forward_summary.json"), key=lambda p: p.stat().st_mtime) 

3995 summary_path = candidates[-1] if candidates else None 

3996 if summary_path is None or not summary_path.exists(): 

3997 print("error: no walk-forward summary found - run `aq train --walk-forward` first.", file=sys.stderr) 

3998 return 1 

3999 summary = json.loads(summary_path.read_text(encoding="utf-8")) 

4000 if args.json: 

4001 print(json.dumps(summary, indent=2)) 

4002 else: 

4003 print(f"Walk-forward summary ({summary_path.parent.name}): {summary.get('num_windows', 0)} windows") 

4004 for name, stats in (summary.get("summary_by_metric") or {}).items(): 

4005 bootstrap = stats.get("cross_window_bootstrap", {}) 

4006 print( 

4007 f" {name}: mean={bootstrap.get('mean_ic', 0.0):.4f} " 

4008 f"95% CI=[{bootstrap.get('lower_bound', 0.0):.4f}, {bootstrap.get('upper_bound', 0.0):.4f}]" 

4009 ) 

4010 for name, stability in (summary.get("stability_by_metric") or {}).items(): 

4011 status = "stable" if stability.get("stable") else "UNSTABLE" 

4012 print( 

4013 f" {name} stability: {status} " 

4014 f"(sign_flip_fraction={stability.get('sign_flip_fraction', 0.0):.2f}, " 

4015 f"num_windows={stability.get('num_windows', 0)})" 

4016 ) 

4017 net_performance_windows = summary.get("net_performance_by_window") or [] 

4018 if net_performance_windows: 

4019 print(f" net_performance: {len(net_performance_windows)} window(s) with a simulated book") 

4020 _refresh_readme_evaluation_sections() 

4021 return 0 

4022 

4023 # V5.3.5.3 Workstream B (development/Problems.md #91/#100) - 

4024 # `aq evaluate --reconcile-features --symbol XOM` diffs the RAW feature 

4025 # values the live path logged for one symbol (the optional 

4026 # "feature_snapshot" key on book_history.jsonl records, written when 

4027 # phase_v2.diagnostics.book_history.include_feature_snapshot is on and 

4028 # the symbol is in feature_snapshot_symbols' allowlist - see main.py's 

4029 # write site) against the SAME (ticker, date) row of full_dataset.csv - 

4030 # per-feature, not a single mismatch number: XOM is the one tracked 

4031 # ticker whose live-vs-offline divergence never resolved across 

4032 # #91/#97/#99/#100, and this is the tool that either names the exact 

4033 # diverging feature(s) or rules the lead out cleanly. 

4034 # Early-return, same precedent as --reconcile-book-history below, and 

4035 # deliberately MUCH lighter: no model artifacts, no re-inference at all 

4036 # - a pure log-vs-dataset diff. Not included in --all, 

4037 # investigation-only like --replay-kill-switch. 

4038 if getattr(args, "reconcile_features", False): 

4039 from evaluation import segment_logged_records_by_run 

4040 from evaluation.feature_reconciliation import ( 

4041 reconcile_feature_snapshot, 

4042 summarize_feature_reconciliation, 

4043 ) 

4044 

4045 target_symbol = str(getattr(args, "symbol", "") or "").strip().upper() 

4046 if not target_symbol: 

4047 print( 

4048 "error: --reconcile-features requires --symbol <TICKER> " 

4049 "(e.g. --symbol XOM).", 

4050 file=sys.stderr, 

4051 ) 

4052 return 1 

4053 

4054 book_history_path_arg = getattr(args, "book_history_path", None) 

4055 diagnostics_config = config.get("phase_v2", {}).get("diagnostics", {}).get("book_history", {}) 

4056 book_history_path = ( 

4057 Path(book_history_path_arg) 

4058 if book_history_path_arg 

4059 else _default_book_history_path(diagnostics_config) 

4060 ) 

4061 if not book_history_path.exists(): 

4062 print( 

4063 f"error: {book_history_path} not found - run a backtest with " 

4064 "phase_v2.diagnostics.book_history.enabled=true first.", 

4065 file=sys.stderr, 

4066 ) 

4067 return 1 

4068 

4069 logged_records: list[dict] = [] 

4070 with open(book_history_path, encoding="utf-8") as book_history_file: 

4071 for line_number, raw_line in enumerate(book_history_file, start=1): 

4072 stripped_line = raw_line.strip() 

4073 if not stripped_line: 

4074 continue 

4075 try: 

4076 logged_records.append(json.loads(stripped_line)) 

4077 except json.JSONDecodeError as error: 

4078 print( 

4079 f"warning: skipping malformed line {line_number} in {book_history_path}: {error}", 

4080 file=sys.stderr, 

4081 ) 

4082 if not logged_records: 

4083 print(f"error: {book_history_path} contains no usable records.", file=sys.stderr) 

4084 return 1 

4085 

4086 # Same cumulative-log discipline as --reconcile-book-history 

4087 # (#91/#97/#99): segment FIRST, default to the most recent run only. 

4088 run_segments = segment_logged_records_by_run(logged_records) 

4089 reconcile_all_runs = bool(getattr(args, "reconcile_all_runs", False)) 

4090 reconcile_run_index_arg = getattr(args, "reconcile_run_index", None) 

4091 requested_indices = ( 

4092 list(range(len(run_segments))) 

4093 if reconcile_all_runs 

4094 else [reconcile_run_index_arg if reconcile_run_index_arg is not None else -1] 

4095 ) 

4096 selected_run_indices: list[int] = [] 

4097 for raw_index in requested_indices: 

4098 normalized_index = raw_index if raw_index >= 0 else raw_index + len(run_segments) 

4099 if not (0 <= normalized_index < len(run_segments)): 

4100 print( 

4101 f"error: --reconcile-run-index {raw_index} out of range - {len(run_segments)} run(s) " 

4102 f"detected in {book_history_path}.", file=sys.stderr, 

4103 ) 

4104 return 1 

4105 selected_run_indices.append(normalized_index) 

4106 

4107 recon_dataset_path = Path(args.dataset) if getattr(args, "dataset", None) else ML_DIR / "datasets" / "full_dataset.csv" 

4108 if not recon_dataset_path.exists(): 

4109 print(f"error: {recon_dataset_path} not found - run `aq train --dataset-only` first.", file=sys.stderr) 

4110 return 1 

4111 full_dataset = _read_dataset_rows(recon_dataset_path, ticker=target_symbol) 

4112 dataset_has_ticker_column = "ticker" in full_dataset.columns 

4113 rows_by_date_ticker: dict[tuple[str, str], dict] = {} 

4114 if dataset_has_ticker_column: 

4115 # (date, ticker) -> row dict, built vectorized - O(rows) once, 

4116 # then O(1) lookups per logged snapshot below. 

4117 rows_by_date_ticker = { 

4118 (str(date), str(ticker)): row 

4119 for (date, ticker), row in full_dataset.set_index(["date", "ticker"]).to_dict("index").items() 

4120 } 

4121 

4122 # Crypto and forex bars close after the equity tick, so the features live reads at tick D are the dataset's 

4123 # PREVIOUS row (the same one-day lag the as-live simulator applies to LATE_BAR_ASSET_CLASSES). 

4124 from evaluation.live_parity import ( 

4125 LATE_BAR_ASSET_CLASSES, 

4126 forex_monday_payload_only, 

4127 forex_tick_holds_fill_forward_bar, 

4128 late_bar_offline_row, 

4129 late_bar_same_row_prefixes, 

4130 ) 

4131 

4132 target_asset_class = next( 

4133 ( 

4134 str(asset.get("asset_class") or asset.get("security_type")) 

4135 for asset in config.get("phase1", {}).get("universe", {}).get("assets", []) 

4136 if str(asset.get("ticker", "")).upper() == str(target_symbol).upper() 

4137 ), 

4138 "", 

4139 ) 

4140 lag_to_previous_row = target_asset_class in LATE_BAR_ASSET_CLASSES 

4141 from features.cross_asset_timing import resolve_forex_lean_holidays 

4142 

4143 forex_holidays = resolve_forex_lean_holidays(config, ROOT_DIR) 

4144 previous_row_date: dict[str, str] = {} 

4145 if lag_to_previous_row and dataset_has_ticker_column: 

4146 ordered_dates = sorted({str(date) for date, ticker in rows_by_date_ticker if ticker == target_symbol}) 

4147 previous_row_date = dict(zip(ordered_dates[1:], ordered_dates[:-1], strict=False)) 

4148 print(f" {target_symbol} is a {target_asset_class} symbol: own-price features at tick D are compared with the dataset's previous row, cross-asset ones with row D.") 

4149 

4150 per_run_payloads = [] 

4151 total_compared_dates = 0 

4152 for run_index in selected_run_indices: 

4153 run_records = run_segments[run_index] 

4154 records_with_snapshot = [ 

4155 record for record in run_records if isinstance(record.get("feature_snapshot"), dict) 

4156 ] 

4157 matching_snapshots = [] 

4158 snapshot_keys_seen: set[str] = set() 

4159 num_missing_offline_rows = 0 

4160 per_date_results = [] 

4161 for record in records_with_snapshot: 

4162 snapshot_entry = record["feature_snapshot"].get(target_symbol) 

4163 if snapshot_entry is None: 

4164 # Allowlist may cover several symbols; only this one's 

4165 # entries reconcile. Track near-miss keys for the error 

4166 # message so a ticker/symbol_key spelling mismatch is 

4167 # immediately visible instead of silently zero. 

4168 snapshot_keys_seen.update(str(key).upper() for key in record["feature_snapshot"]) 

4169 continue 

4170 if not isinstance(snapshot_entry, Mapping): 

4171 continue 

4172 date_str = str(record.get("date", "")) 

4173 lookup_date = previous_row_date.get(date_str, "") if lag_to_previous_row else date_str 

4174 offline_row = rows_by_date_ticker.get((lookup_date, target_symbol)) if dataset_has_ticker_column else None 

4175 if lag_to_previous_row and offline_row is not None: 

4176 same_row_prefixes = late_bar_same_row_prefixes(config) 

4177 offline_row = late_bar_offline_row(offline_row, rows_by_date_ticker.get((date_str, target_symbol)), same_row_prefixes) 

4178 if target_asset_class == "forex" and forex_tick_holds_fill_forward_bar( 

4179 date_str, previous_row_date.get(date_str), forex_holidays 

4180 ): 

4181 offline_row = forex_monday_payload_only(offline_row, same_row_prefixes) 

4182 if offline_row is None: 

4183 num_missing_offline_rows += 1 

4184 continue 

4185 per_date_results.append(reconcile_feature_snapshot(snapshot_entry, offline_row)) 

4186 matching_snapshots.append(date_str) 

4187 

4188 summary = summarize_feature_reconciliation(per_date_results) 

4189 total_compared_dates += len(per_date_results) 

4190 run_dates = [record["date"] for record in run_records if record.get("date")] 

4191 per_run_payloads.append({ 

4192 "run_metadata": { 

4193 "num_runs_detected": len(run_segments), 

4194 "selected_run_index": run_index, 

4195 "start_date": run_dates[0] if run_dates else None, 

4196 "end_date": run_dates[-1] if run_dates else None, 

4197 "num_records": len(run_records), 

4198 "num_records_scanned": len(records_with_snapshot), 

4199 "num_dates_reconciled": len(per_date_results), 

4200 "num_dates_missing_offline_row": num_missing_offline_rows, 

4201 "snapshot_symbol_keys_seen": sorted(snapshot_keys_seen), 

4202 }, 

4203 "summary": summary, 

4204 "per_date": [ 

4205 {"date": date_str, **result} 

4206 for date_str, result in zip(matching_snapshots, per_date_results, strict=False) 

4207 ], 

4208 }) 

4209 

4210 payload = dict(per_run_payloads[-1]) if per_run_payloads else {} 

4211 if len(per_run_payloads) > 1: 

4212 payload["all_runs"] = per_run_payloads 

4213 

4214 _write_evaluation_json(ML_DIR / "evaluation" / "feature_reconciliation.json", payload) 

4215 _refresh_readme_evaluation_sections() 

4216 

4217 if args.json: 

4218 print(json.dumps(payload, indent=2, default=str)) 

4219 else: 

4220 last_meta = payload.get("run_metadata", {}) 

4221 print( 

4222 f"Feature reconciliation for {target_symbol} ({book_history_path}): " 

4223 f"{last_meta.get('num_records_scanned', 0)} record(s) carried a feature_snapshot, " 

4224 f"{last_meta.get('num_dates_reconciled', 0)} reconciled against full_dataset.csv." 

4225 ) 

4226 if last_meta.get("num_dates_missing_offline_row"): 

4227 print( 

4228 f" {last_meta['num_dates_missing_offline_row']} snapshot date(s) had no matching " 

4229 "(date, ticker) row in the dataset - skipped, not counted as divergences." 

4230 ) 

4231 summary = payload.get("summary", {}) 

4232 if summary.get("num_dates", 0) == 0 or summary.get("num_dates_with_comparison", 0) == 0: 

4233 keys_hint = ", ".join(last_meta.get("snapshot_symbol_keys_seen", [])[:10]) 

4234 print( 

4235 f" NO comparable snapshots found for {target_symbol}. Either the diagnostic flags were " 

4236 "off during that run (set phase_v2.diagnostics.book_history.include_feature_snapshot=true " 

4237 f"+ add \"{target_symbol}\" to feature_snapshot_symbols, then re-run a backtest)" 

4238 + (f"; snapshot keys seen in the log: [{keys_hint}]" if keys_hint else "") 

4239 + ".", 

4240 file=sys.stderr, 

4241 ) 

4242 else: 

4243 print( 

4244 f" compared={summary['num_features_compared_per_date']['mean']:.1f} features/date avg " 

4245 f"divergent_dates={summary['dates_with_any_divergence']}/{summary['num_dates']} " 

4246 f"total_divergences={summary['total_divergences']}" 

4247 ) 

4248 top_offenders = summary.get("features_diverged_most_often", []) 

4249 if top_offenders: 

4250 print(" Worst offenders by divergence count:") 

4251 for entry in top_offenders: 

4252 print( 

4253 f" {entry['feature']}: diverged on {entry['diverged_count']} date(s) " 

4254 f"({entry['diverged_fraction']:.1%}), max_abs_delta={entry['max_abs_delta']:.6g}, " 

4255 f"mean_abs_delta={entry['mean_abs_delta']:.6g}" 

4256 ) 

4257 never_compared = summary.get("features_never_compared", []) 

4258 if never_compared: 

4259 print(f" Features present live but NEVER in the offline row: {never_compared}") 

4260 return 0 

4261 

4262 # V5.2.2 (development/Problems.md) - `aq evaluate --reconcile-book-history` 

4263 # compares a real Lean backtest's actual per-date book selections 

4264 # (logged via phase_v2.diagnostics.book_history, see main.py's write 

4265 # site) against a fresh offline re-derivation of the same raw scores - 

4266 # true ground truth instead of more indirect offline-vs-live hypothesis 

4267 # testing. Early-return, same precedent as --walk-forward-summary above: 

4268 # needs its own UNFILTERED-by-split dataset load, because a recorded 

4269 # date's required lookback context can reach into rows from a different 

4270 # split boundary (see select_context_date_range()'s own docstring for 

4271 # why naively reusing the split-filtered dataset below would be wrong). 

4272 if getattr(args, "reconcile_book_history", False): 

4273 from evaluation import ( 

4274 compute_blended_raw_scores, 

4275 reconcile_book_history_date, 

4276 replay_book_history_reconciliation, 

4277 segment_logged_records_by_run, 

4278 select_context_date_range, 

4279 summarize_book_history_reconciliation, 

4280 summarize_book_member_diversion, 

4281 summarize_universe_presence_by_symbol, 

4282 summarize_universe_snapshot_by_security_type, 

4283 ) 

4284 from portfolio.rank_signal import resolve_rank_signal_policy 

4285 

4286 book_history_path_arg = getattr(args, "book_history_path", None) 

4287 diagnostics_config = config.get("phase_v2", {}).get("diagnostics", {}).get("book_history", {}) 

4288 book_history_path = ( 

4289 Path(book_history_path_arg) 

4290 if book_history_path_arg 

4291 else _default_book_history_path(diagnostics_config) 

4292 ) 

4293 if not book_history_path.exists(): 

4294 print( 

4295 f"error: {book_history_path} not found - run a backtest with " 

4296 "phase_v2.diagnostics.book_history.enabled=true first.", 

4297 file=sys.stderr, 

4298 ) 

4299 return 1 

4300 

4301 logged_records: list[dict] = [] 

4302 with open(book_history_path, encoding="utf-8") as book_history_file: 

4303 for line_number, raw_line in enumerate(book_history_file, start=1): 

4304 stripped_line = raw_line.strip() 

4305 if not stripped_line: 

4306 continue 

4307 try: 

4308 logged_records.append(json.loads(stripped_line)) 

4309 except json.JSONDecodeError as error: 

4310 print( 

4311 f"warning: skipping malformed line {line_number} in {book_history_path}: {error}", 

4312 file=sys.stderr, 

4313 ) 

4314 

4315 if not logged_records: 

4316 print(f"error: {book_history_path} contains no usable records.", file=sys.stderr) 

4317 return 1 

4318 

4319 # V5.3.2 (development/Problems.md #91/#97/#99) - book_history.jsonl 

4320 # is a cumulative, NEVER-rotated log: every real backtest run's 

4321 # records are appended to the same file forever. Reconciling 

4322 # against it unsegmented (the pre-V5.3.2 behavior) silently merges 

4323 # unrelated runs together - confirmed against the real file: 160 of 

4324 # 174 unique dates recur across more than one run, one date in as 

4325 # many as 8 - and a --replay-hysteresis walk carries held 

4326 # allocations across a real run boundary as if it were one 

4327 # continuous backtest. Segment FIRST; default to the MOST RECENT 

4328 # run only, never a silent cross-run merge. 

4329 run_segments = segment_logged_records_by_run(logged_records) 

4330 

4331 reconcile_all_runs = bool(getattr(args, "reconcile_all_runs", False)) 

4332 reconcile_run_index_arg = getattr(args, "reconcile_run_index", None) 

4333 requested_indices = ( 

4334 list(range(len(run_segments))) 

4335 if reconcile_all_runs 

4336 else [reconcile_run_index_arg if reconcile_run_index_arg is not None else -1] 

4337 ) 

4338 selected_run_indices: list[int] = [] 

4339 for raw_index in requested_indices: 

4340 normalized_index = raw_index if raw_index >= 0 else raw_index + len(run_segments) 

4341 if not (0 <= normalized_index < len(run_segments)): 

4342 print( 

4343 f"error: --reconcile-run-index {raw_index} out of range - {len(run_segments)} run(s) " 

4344 f"detected in {book_history_path}.", file=sys.stderr, 

4345 ) 

4346 return 1 

4347 selected_run_indices.append(normalized_index) 

4348 

4349 run_metadata_by_index: dict[int, dict] = {} 

4350 for i, run_records in enumerate(run_segments): 

4351 run_dates = [record["date"] for record in run_records if record.get("date")] 

4352 run_metadata_by_index[i] = { 

4353 "num_runs_detected": len(run_segments), 

4354 "selected_run_index": i, 

4355 "start_date": run_dates[0] if run_dates else None, 

4356 "end_date": run_dates[-1] if run_dates else None, 

4357 "num_records": len(run_records), 

4358 } 

4359 

4360 recon_dataset_path = Path(args.dataset) if getattr(args, "dataset", None) else ML_DIR / "datasets" / "full_dataset.csv" 

4361 if not recon_dataset_path.exists(): 

4362 print(f"error: {recon_dataset_path} not found - run `aq train --dataset-only` first.", file=sys.stderr) 

4363 return 1 

4364 full_dataset = _read_dataset_rows( 

4365 recon_dataset_path, columns=_reconciliation_dataset_columns(), only_training_eligible=True 

4366 ) 

4367 

4368 sequence_window_default = config.get("phase_v2", {}).get("sequence_model", {}).get("window_size", 30) 

4369 training_metrics_by_model: dict[str, dict | None] = {} 

4370 for model_name, metrics_filename in ( 

4371 ("sequence", "sequence_training_metrics.json"), 

4372 ("multitask", "multitask_training_metrics.json"), 

4373 ): 

4374 metrics_path = ML_DIR / metrics_filename 

4375 training_metrics_by_model[model_name] = ( 

4376 json.loads(metrics_path.read_text(encoding="utf-8")) if metrics_path.exists() else None 

4377 ) 

4378 policy = resolve_rank_signal_policy(training_metrics_by_model, config) 

4379 active_heads = [head_name for head_name, weight in policy["heads"].items() if weight > 0.0] 

4380 

4381 # V5.3.2 (development/Problems.md #91/#97/#99) - the SAME symbol 

4382 # order main.py's self.symbols uses (config.json's 

4383 # phase1.universe.assets, in file order) - cross_sectional_rank_scores()/ 

4384 # _select_book_group() are both Python-stable sorts keyed only on 

4385 # score, so an exact tie between two symbols resolves by dict 

4386 # insertion order. Live builds its raw-scores dict in self.symbols 

4387 # order; this reconciliation tool previously built it from a pandas 

4388 # groupby (dataset row order) - a different, uncorrelated order - 

4389 # so a tied pair near a top/bottom-N boundary could pick a 

4390 # different winner offline than live with byte-identical scores. 

4391 # Re-inserting in this canonical order before it ever reaches 

4392 # cross_sectional_rank_scores() fixes that, with zero changes to 

4393 # the live decision path itself. 

4394 canonical_symbol_order = [ 

4395 str(asset.get("ticker")) for asset in config.get("phase1", {}).get("universe", {}).get("assets", []) 

4396 ] 

4397 

4398 book_config = config.get("phase_v2", {}).get("portfolio_book", {}) 

4399 strategy_mode = config.get("phase5", {}).get("backtest", {}).get("strategy_mode", "long_flat") 

4400 book_top_n = int(book_config.get("top_n", 6)) 

4401 book_bottom_n = int(book_config.get("bottom_n", 6)) if strategy_mode == "long_short" else 0 

4402 # V5.2.3 (development/Problems.md #91) - --replay-hysteresis 

4403 # switches from independently reconciling each date (the 

4404 # V5.2.2 default - can't tell a real divergence apart from 

4405 # hysteresis correctly holding an incumbent) to a walk-forward 

4406 # replay of offline's OWN selection history, carrying hysteresis 

4407 # forward the same way main.py's live book does. 

4408 replay_hysteresis = bool(getattr(args, "replay_hysteresis", False)) 

4409 hysteresis_rank_margin = float(book_config.get("hysteresis_rank_margin", 0.0)) 

4410 

4411 def _reconcile_one_run(run_records: list[dict]) -> dict: 

4412 # V5.3.2: each run gets its OWN context date range/predictions - 

4413 # previously computed once over the entire cumulative file's 

4414 # date span even when only one small run was being reconciled. 

4415 recorded_dates = sorted({record["date"] for record in run_records if record.get("date")}) 

4416 logged_records_by_date = {record["date"]: record for record in run_records if record.get("date")} 

4417 

4418 recon_min_date, recon_max_date = select_context_date_range( 

4419 full_dataset, recorded_dates, window_size=int(sequence_window_default) 

4420 ) 

4421 context_dataset = full_dataset[ 

4422 (full_dataset["date"] >= recon_min_date) & (full_dataset["date"] <= recon_max_date) 

4423 ].reset_index(drop=True) 

4424 

4425 predictions_by_model_head: dict[str, dict[str, object]] = {} 

4426 # Only the recorded dates are ever read below; the surrounding context rows exist solely to 

4427 # fill sequence windows, so they are not predicted (peak memory ~ rows on recorded dates). 

4428 recorded_row_mask = context_dataset["date"].isin(recorded_dates).to_numpy() 

4429 for model_kind_for_head in policy["model_priority"]: 

4430 recon_model_filename, recon_schema_filename = _EVALUATE_MODEL_ARTIFACTS[model_kind_for_head] 

4431 recon_model_path = ML_DIR / recon_model_filename 

4432 recon_schema_path = ML_DIR / recon_schema_filename 

4433 if not recon_model_path.exists() or not recon_schema_path.exists(): 

4434 continue # best-effort - same convention as --calibrate-book-spread above 

4435 recon_model_export = json.loads(recon_model_path.read_text(encoding="utf-8")) 

4436 recon_feature_schema = json.loads(recon_schema_path.read_text(encoding="utf-8")) 

4437 recon_feature_names = recon_feature_schema["model_input_names"] 

4438 head_predictions = predict_heads( 

4439 context_dataset, recon_model_export, recon_feature_names, list(active_heads), 

4440 model_kind=model_kind_for_head, 

4441 sequence_feature_schema=recon_feature_schema if model_kind_for_head == "sequence" else None, 

4442 configured_window_size=int(sequence_window_default), 

4443 row_mask=recorded_row_mask, 

4444 ) 

4445 predictions_by_model_head[model_kind_for_head] = head_predictions 

4446 

4447 context_dataset["raw_blended_score"] = compute_blended_raw_scores( 

4448 context_dataset, predictions_by_model_head, policy 

4449 ) 

4450 

4451 recorded_subset = context_dataset[context_dataset["date"].isin(recorded_dates)] 

4452 raw_scores_by_date: dict[str, dict[str, float]] = {} 

4453 # V5.8.0: the live main book ranks only its own pool (a class governed by an enabled sleeve, a disabled class 

4454 # and an ineligible asset take no slot), so the replay must rank that pool and not all 104 tickers. 

4455 _, pool_eligible_by_ticker = _universe_asset_metadata(config) 

4456 for recon_date, group in recorded_subset.groupby("date", sort=True): 

4457 scores_lookup = { 

4458 str(ticker): float(score) 

4459 for ticker, score in zip(group["ticker"], group["raw_blended_score"], strict=False) 

4460 if score is not None and not (isinstance(score, float) and pd.isna(score)) 

4461 and pool_eligible_by_ticker.get(str(ticker), True) 

4462 } 

4463 ordered_scores = { 

4464 ticker: scores_lookup[ticker] for ticker in canonical_symbol_order if ticker in scores_lookup 

4465 } 

4466 ordered_scores.update({t: s for t, s in scores_lookup.items() if t not in ordered_scores}) 

4467 raw_scores_by_date[recon_date] = ordered_scores 

4468 

4469 if replay_hysteresis: 

4470 ordered_logged_records = [ 

4471 logged_records_by_date[d] for d in recorded_dates if d in raw_scores_by_date 

4472 ] 

4473 per_date_results = replay_book_history_reconciliation( 

4474 ordered_logged_records, raw_scores_by_date, 

4475 top_n=book_top_n, bottom_n=book_bottom_n, hysteresis_rank_margin=hysteresis_rank_margin, 

4476 hysteresis_survives_veto=bool(getattr(args, "hysteresis_survives_veto", False)), 

4477 ) 

4478 else: 

4479 per_date_results = [ 

4480 reconcile_book_history_date( 

4481 logged_records_by_date[recon_date], raw_scores_by_symbol, 

4482 top_n=book_top_n, bottom_n=book_bottom_n, 

4483 ) 

4484 for recon_date, raw_scores_by_symbol in raw_scores_by_date.items() 

4485 ] 

4486 

4487 summary = summarize_book_history_reconciliation(per_date_results) 

4488 # Cheap and always attempted (pure, reads straight off the log's 

4489 # own "universe" keys - no re-inference) - degrades to 

4490 # num_dates_with_universe_data=0 for a log written without 

4491 # include_full_universe, never raises. V5.3.2: computed over 

4492 # this RUN's own records only, not the whole cumulative file. 

4493 universe_summary = summarize_universe_snapshot_by_security_type(run_records) 

4494 # V5.2.6 (development/Problems.md) - same "cheap, always attempted, 

4495 # degrades to zeros" contract as universe_summary above - reads 

4496 # straight off the log's own optional "book_member_decisions" key. 

4497 diversion_summary = summarize_book_member_diversion(run_records) 

4498 # V5.3.1 (development/Problems.md #91/#97) - summarize_universe_presence_by_symbol() 

4499 # does its own internal run-segmentation too, but since run_records 

4500 # is already a single run here, it always reports exactly one. 

4501 universe_presence_summary = summarize_universe_presence_by_symbol(run_records) 

4502 return { 

4503 "mode": "replay_hysteresis" if replay_hysteresis else "independent", 

4504 "per_date": per_date_results, 

4505 "summary": summary, 

4506 "universe_summary": universe_summary, 

4507 "diversion_summary": diversion_summary, 

4508 "universe_presence_summary": universe_presence_summary, 

4509 } 

4510 

4511 if reconcile_all_runs: 

4512 all_runs_payloads = [] 

4513 for i in selected_run_indices: 

4514 run_payload = _reconcile_one_run(run_segments[i]) 

4515 run_payload["run_metadata"] = run_metadata_by_index[i] 

4516 all_runs_payloads.append(run_payload) 

4517 # Top-level default keys mirror the most-recent run (last in 

4518 # selected_run_indices, since run_segments is chronological) - 

4519 # --reconcile-all-runs is additive on top of the normal default 

4520 # output, never a replacement for it. 

4521 payload = dict(all_runs_payloads[-1]) 

4522 payload["all_runs"] = all_runs_payloads 

4523 else: 

4524 selected_index = selected_run_indices[0] 

4525 payload = _reconcile_one_run(run_segments[selected_index]) 

4526 payload["run_metadata"] = run_metadata_by_index[selected_index] 

4527 

4528 _write_evaluation_json(ML_DIR / "evaluation" / "book_history_reconciliation.json", payload) 

4529 

4530 if args.json: 

4531 print(json.dumps(payload, indent=2, default=str)) 

4532 else: 

4533 def _print_run_result(run_payload: dict, label: str) -> None: 

4534 run_summary = run_payload["summary"] 

4535 run_universe_summary = run_payload["universe_summary"] 

4536 run_diversion_summary = run_payload["diversion_summary"] 

4537 run_universe_presence_summary = run_payload["universe_presence_summary"] 

4538 run_meta = run_payload["run_metadata"] 

4539 print(f"{label}{run_meta['start_date']}..{run_meta['end_date']}, {run_summary['num_dates']} dates:") 

4540 if run_summary.get("num_dates_live_vetoed"): 

4541 # V5.5.0: a vetoed live rebalance has no selection to compare - it is NOT 0% overlap. 

4542 print( 

4543 f" live VETOED {run_summary['num_dates_live_vetoed']}/{run_summary['num_dates']} dates " 

4544 f"({run_summary['live_veto_reasons']}) - excluded from the match statistics below" 

4545 ) 

4546 print( 

4547 f" exact_match={run_summary['num_dates_exact_match']}/{run_summary.get('num_dates_compared', run_summary['num_dates'])} " 

4548 f"mean_overlap_fraction={run_summary['mean_overlap_fraction']}" 

4549 ) 

4550 print( 

4551 f" mean_raw_score_delta_abs={run_summary['mean_raw_score_delta_abs']} " 

4552 f"mean_weight_delta_abs={run_summary['mean_weight_delta_abs']} " 

4553 f"({run_summary['num_dates_with_weight_logged']}/{run_summary['num_dates']} dates had a " 

4554 "logged weight)" 

4555 ) 

4556 print( 

4557 f" symbols_only_logged_total={run_summary['num_symbols_only_logged_total']} " 

4558 f"symbols_only_offline_total={run_summary['num_symbols_only_offline_total']}" 

4559 ) 

4560 if run_universe_summary["num_dates_with_universe_data"] > 0: 

4561 print( 

4562 f" Universe snapshot ({run_universe_summary['num_dates_with_universe_data']}/" 

4563 f"{run_summary['num_dates']} dates carry full-universe data):" 

4564 ) 

4565 for security_type, stats in sorted(run_universe_summary["by_security_type"].items()): 

4566 print( 

4567 f" {security_type}: mean_raw_rank_score={stats['mean_raw_rank_score']} " 

4568 f"feature_ready_rate={stats['feature_ready_rate']} " 

4569 f"trading_eligible_rate={stats['trading_eligible_rate']} " 

4570 f"(n={stats['num_symbol_dates']})" 

4571 ) 

4572 if run_diversion_summary["num_records_with_decisions"] > 0: 

4573 print( 

4574 f" Book-member diversion ({run_diversion_summary['num_records_with_decisions']}/" 

4575 f"{run_summary['num_dates']} dates carry decision data, " 

4576 f"{run_diversion_summary['total_book_member_dates']} book-member-dates total):" 

4577 ) 

4578 for action, count in sorted( 

4579 run_diversion_summary["action_counts"].items(), key=lambda item: -item[1] 

4580 ): 

4581 print(f" action={action}: {count}") 

4582 for reason, count in sorted( 

4583 run_diversion_summary["reason_counts"].items(), key=lambda item: -item[1] 

4584 ): 

4585 print(f" reason={reason}: {count}") 

4586 if run_universe_presence_summary["num_runs_detected"] > 0: 

4587 top_absent = sorted( 

4588 run_universe_presence_summary["runs"][0]["absence_rate_by_symbol"].items(), 

4589 key=lambda item: -item[1], 

4590 )[:10] 

4591 for symbol, absence_rate in top_absent: 

4592 if absence_rate > 0: 

4593 print(f" {symbol}: absent from universe on {absence_rate:.1%} of this run's dates") 

4594 

4595 print( 

4596 f"Book-history reconciliation ({book_history_path}): " 

4597 f"{payload['run_metadata']['num_runs_detected']} run(s) detected total " 

4598 "(cumulative, never-rotated log)." 

4599 ) 

4600 if replay_hysteresis: 

4601 print( 

4602 " NOTE: this reconciliation REPLAYS hysteresis (--replay-hysteresis) - offline's own " 

4603 "held allocations are carried forward date-by-date, the same way main.py's live book " 

4604 "does, WITHIN each run only (V5.3.2: never across a run boundary). The first reconciled " 

4605 "date of each run still starts from a COLD (empty) held-allocations state regardless of " 

4606 "the book's true earlier history, so early dates may show a colder-start mismatch than " 

4607 "mid-series dates." 

4608 ) 

4609 else: 

4610 print( 

4611 " NOTE: this reconciliation replays NO hysteresis (previous_allocations=None) - a " 

4612 "mismatch can mean either a real divergence OR the live book correctly holding an " 

4613 "incumbent that day's natural ranking alone wouldn't pick. Read per-date role_mismatches " 

4614 "before concluding anything is actually wrong. Pass --replay-hysteresis for the " 

4615 "hysteresis-aware alternative." 

4616 ) 

4617 if reconcile_all_runs: 

4618 num_runs = len(payload["all_runs"]) 

4619 for position, run_payload in enumerate(payload["all_runs"]): 

4620 _print_run_result(run_payload, f"Run {position + 1}/{num_runs} (") 

4621 else: 

4622 _print_run_result(payload, "Reconciled run (") 

4623 

4624 _refresh_readme_evaluation_sections() 

4625 return 0 

4626 

4627 ranking_config = config.get("phase1", {}).get("target", {}).get("ranking", {}) 

4628 net_perf_config = ranking_config.get("net_performance", {}) 

4629 if not net_perf_config: 

4630 print("error: phase1.target.ranking.net_performance is not configured.", file=sys.stderr) 

4631 return 1 

4632 

4633 dataset_path = Path(args.dataset) if getattr(args, "dataset", None) else ML_DIR / "datasets" / "full_dataset.csv" 

4634 if not dataset_path.exists(): 

4635 print(f"error: {dataset_path} not found - run `aq train --dataset-only` first.", file=sys.stderr) 

4636 return 1 

4637 

4638 model_kind = args.model or "sequence" 

4639 head = args.head or "rank_20d" 

4640 split = args.split or "backtest" 

4641 

4642 model_filename, schema_filename = _EVALUATE_MODEL_ARTIFACTS[model_kind] 

4643 model_path = ML_DIR / model_filename 

4644 schema_path = ML_DIR / schema_filename 

4645 if not model_path.exists() or not schema_path.exists(): 

4646 print(f"error: {model_path} or {schema_path} not found - run `aq train` first.", file=sys.stderr) 

4647 return 1 

4648 

4649 model_export = json.loads(model_path.read_text(encoding="utf-8")) 

4650 feature_schema = json.loads(schema_path.read_text(encoding="utf-8")) 

4651 feature_names = feature_schema["model_input_names"] 

4652 

4653 # a chunked read that keeps only this split's rows: the whole 825 MB file does not fit in the PC's memory (#389) 

4654 from evaluation.dataset_io import read_dataset_rows 

4655 

4656 dataset = read_dataset_rows(dataset_path, split=None if split == "all" else split) 

4657 # The as-live book keeps EVERY row with features (observation-only names included): main.py's percentile 

4658 # normalisation runs over all of them. The idealized runs keep the training-eligible subset as before. 

4659 as_live_dataset = None 

4660 if getattr(args, "as_live", False): 

4661 as_live_dataset = dataset if split == "all" else dataset[dataset["split"] == split].reset_index(drop=True) 

4662 if "training_eligible" in dataset.columns: 

4663 dataset = dataset[dataset["training_eligible"]].reset_index(drop=True) 

4664 if split != "all": 

4665 dataset = dataset[dataset["split"] == split].reset_index(drop=True) 

4666 if dataset.empty: 

4667 print(f"error: no rows for split={split!r} after filtering - check `aq train` has run for this window.", file=sys.stderr) 

4668 return 1 

4669 

4670 sequence_window_default = config.get("phase_v2", {}).get("sequence_model", {}).get("window_size", 30) 

4671 predictions = predict_head( 

4672 dataset, model_export, feature_names, head, 

4673 model_kind=model_kind, 

4674 sequence_feature_schema=feature_schema if model_kind == "sequence" else None, 

4675 configured_window_size=int(sequence_window_default), 

4676 ) 

4677 dataset = dataset.copy() 

4678 dataset["predicted_head"] = predictions 

4679 

4680 # V6.3.0 - the Backtest Statistics' offline classification rows: the direction_20d head (a sigmoid probability) 

4681 # against target_direction_20d at a 0.5 threshold, with the plain (unweighted) log-loss. 

4682 if getattr(args, "classification", False) or args.all: 

4683 import numpy as np 

4684 

4685 from evaluation.backtest_statistics import classification_scores 

4686 

4687 if "target_direction_20d" in dataset.columns: 

4688 probability = predict_head( 

4689 dataset, model_export, feature_names, "direction_20d", model_kind=model_kind, 

4690 sequence_feature_schema=feature_schema if model_kind == "sequence" else None, 

4691 configured_window_size=int(sequence_window_default), 

4692 ) 

4693 labels = dataset["target_direction_20d"].to_numpy(dtype=float) 

4694 usable = np.isfinite(probability) & np.isfinite(labels) 

4695 scores = classification_scores(labels[usable].astype(int), (probability[usable] >= 0.5).astype(int), probability[usable]) 

4696 scores.update(model=model_kind, split=split, threshold=0.5, head="direction_20d") 

4697 out_path = ML_DIR / "evaluation" / f"classification_scores_{model_kind}.json" 

4698 _write_evaluation_json(out_path, scores) 

4699 print(f"Classification ({model_kind} direction_20d, split={split}): n={scores['n']} accuracy={scores['accuracy']:.4f} " 

4700 f"F1={scores['f1']} neg log-loss={scores['neg_log_loss']}; wrote {out_path}") 

4701 else: 

4702 print("warning: the dataset has no target_direction_20d column - classification scores skipped.", file=sys.stderr) 

4703 

4704 sector_by_ticker = load_sector_mapping(config) 

4705 base_kwargs = dict( 

4706 prediction_column="predicted_head", 

4707 forward_return_column="target_return_1d", 

4708 ticker_column="ticker", 

4709 date_column="date", 

4710 top_n=int(net_perf_config.get("top_n", 6)), 

4711 bottom_n=int(net_perf_config.get("bottom_n", 6)), 

4712 rebalance_every_bars=int(net_perf_config.get("rebalance_every_bars", 10)), 

4713 cost_bps_per_side=float(net_perf_config.get("cost_bps_per_side", 5.0)), 

4714 commission_bps=float(net_perf_config.get("commission_bps", 1.0)), 

4715 gross_exposure=float(net_perf_config.get("gross_exposure", 1.0)), 

4716 dollar_neutral=bool(net_perf_config.get("dollar_neutral", True)), 

4717 sector_neutral=bool(net_perf_config.get("sector_neutral", True)), 

4718 sector_by_ticker=sector_by_ticker, 

4719 hysteresis_rank_margin=float(net_perf_config.get("hysteresis_rank_margin", 0.0)), 

4720 max_weight_per_name=float(net_perf_config.get("max_weight_per_name", 0.12)), 

4721 min_universe_size=int(ranking_config.get("min_universe_size", 20)), 

4722 # V5.2.1 (development/Problems.md) - both no-op by default (0/0.0/0.0), 

4723 # matching simulate_rank_book()'s own defaults exactly. 

4724 entry_lag_bars=int(net_perf_config.get("entry_lag_bars", 0)), 

4725 min_commission_usd=float(net_perf_config.get("min_commission_usd", 0.0)), 

4726 assumed_portfolio_value_usd=float(net_perf_config.get("assumed_portfolio_value_usd", 0.0)), 

4727 commission_bps_by_ticker=commission_bps_by_ticker( 

4728 config.get("phase_v2", {}).get("costs", {}), 

4729 { 

4730 str(asset.get("ticker")): str(asset.get("security_type")) 

4731 for asset in config.get("phase1", {}).get("universe", {}).get("assets", []) 

4732 }, 

4733 ) 

4734 or None, 

4735 ) 

4736 

4737 run_rank_book = bool(args.rank_book or args.all) 

4738 # V5.3.8 - Monte Carlo layer rides on top of the base rank-book run's 

4739 # daily net returns, so requesting it implicitly requests the sim. 

4740 run_monte_carlo = bool(getattr(args, "monte_carlo", False) or args.all) 

4741 if run_monte_carlo: 

4742 run_rank_book = True 

4743 # V5.4.4 - benchmark comparison: cheap (pure pandas over the dataset's 

4744 # own close pivot, no model inference), so it rides in --all and the 

4745 # README's benchmark section auto-refreshes on every full evaluate run. 

4746 run_benchmarks = bool(getattr(args, "benchmarks", False) or args.all) 

4747 run_capacity = bool(args.capacity or args.all) 

4748 run_stress = bool(args.stress or args.all) 

4749 run_calibrate = bool(args.calibrate_edge or args.all) 

4750 # V5.1 Phase 5 (item 9) - deliberately NOT bundled into --all (whose 

4751 # bundle is rank-book/capacity/stress/calibrate-edge + the V5.4.4 

4752 # benchmarks) - ablation is a heavier, opt-in-only report. 

4753 run_ablation_flag = bool(getattr(args, "ablation", False)) 

4754 # V5.1 (Problems.md) - also deliberately NOT bundled into --all, same 

4755 # reasoning as --ablation: a heavier, two-model, opt-in-only report. 

4756 run_calibrate_book_spread = bool(getattr(args, "calibrate_book_spread", False)) 

4757 # V5.2.6 (development/Problems.md) - same reasoning as 

4758 # run_calibrate_book_spread immediately above: a heavier, opt-in-only 

4759 # report, not bundled into --all. 

4760 run_calibrate_confidence_threshold = bool(getattr(args, "calibrate_confidence_threshold", False)) 

4761 # V5.3.5 (development/Problems.md #102) - same reasoning as 

4762 # run_calibrate_book_spread/run_calibrate_confidence_threshold above: a 

4763 # heavier, opt-in-only report, not bundled into --all. 

4764 run_calibrate_rolling_ic_floor = bool(getattr(args, "calibrate_rolling_ic_floor", False)) 

4765 # V5.2.8 (development/Problems.md #94) - same reasoning as --ablation/ 

4766 # --calibrate-book-spread above: a heavier, investigation-only report, 

4767 # not bundled into --all. 

4768 run_replay_kill_switch = bool(getattr(args, "replay_kill_switch", False)) 

4769 # V5.3.5 (development/Problems.md #102) - same reasoning as 

4770 # --replay-kill-switch above: a heavier, investigation-only report, 

4771 # not bundled into --all. 

4772 run_replay_rolling_ic_gate = bool(getattr(args, "replay_rolling_ic_gate", False)) 

4773 # V5.3.1 (development/Problems.md #34/#96) - same reasoning as 

4774 # --replay-kill-switch above: a heavier, investigation-only report, 

4775 # not bundled into --all. 

4776 run_simulate_limit_fills = bool(getattr(args, "simulate_limit_fills", False)) 

4777 # Bare `aq evaluate` with no flags at all defaults to --rank-book - the 

4778 # single most useful number ("is the fee drag fixed"), matching every 

4779 # other `aq` command's "sane default when no scope flag is given" 

4780 # convention (e.g. `aq test` with no subsystem flags runs everything). 

4781 # Every opt-in-only flag (not just the --all-bundled ones) must be 

4782 # included here - Problems.md bug: --calibrate-book-spread alone used 

4783 # to also silently run a whole extra --rank-book simulation because it 

4784 # wasn't counted as "a flag was given". 

4785 if not ( 

4786 run_rank_book or run_capacity or run_stress or run_calibrate or run_ablation_flag 

4787 or run_calibrate_book_spread or run_calibrate_confidence_threshold or run_calibrate_rolling_ic_floor 

4788 or run_replay_kill_switch or run_replay_rolling_ic_gate or run_simulate_limit_fills 

4789 or run_monte_carlo or run_benchmarks 

4790 or getattr(args, "as_live", False) or getattr(args, "factor_exposure", False) 

4791 or getattr(args, "calibrate_volatility_threshold", False) 

4792 or getattr(args, "classification", False) 

4793 ): 

4794 run_rank_book = True 

4795 

4796 report: dict = {} 

4797 evaluation_dir = ML_DIR / "evaluation" 

4798 

4799 if run_rank_book: 

4800 result = simulate_rank_book(dataset, **base_kwargs) 

4801 report["rank_book"] = result.to_dict() 

4802 _write_evaluation_json(evaluation_dir / "rank_book_simulation.json", report["rank_book"]) 

4803 # Additive, per-model copy alongside the unsuffixed "last run" file 

4804 # above (untouched - monitoring/evaluation_state.py's webui feed 

4805 # and existing tests depend on that exact fixed name) - lets a 

4806 # multitask run and a sequence run coexist on disk instead of the 

4807 # second silently clobbering the first, for callers (e.g. 

4808 # generate_evaluation_report.py) that want to compare both models 

4809 # at once rather than only "whichever ran last". 

4810 _write_evaluation_json(evaluation_dir / f"rank_book_simulation_{model_kind}.json", report["rank_book"]) 

4811 if not args.json: 

4812 print(f"Rank book ({model_kind}/{head}, split={split}, entry_lag_bars={base_kwargs['entry_lag_bars']}):") 

4813 print(f" gross_sharpe={result.gross_sharpe:.4f} net_sharpe={result.net_sharpe:.4f}") 

4814 print(f" gross_total_return={result.gross_total_return:.4%} net_total_return={result.net_total_return:.4%}") 

4815 print(f" net_max_drawdown={result.net_max_drawdown:.4%}") 

4816 print(f" annualized_turnover={result.annualized_turnover:.2f}x cost_drag_annual_bps={result.cost_drag_annual_bps:.2f}") 

4817 print(f" num_rebalances={result.num_rebalances} num_dates_used={result.num_dates_used}") 

4818 print(f" mean_names_long={result.mean_names_long:.2f} mean_names_short={result.mean_names_short:.2f}") 

4819 

4820 # V5.2.1 (development/Problems.md) - a Daily-resolution market 

4821 # order decided off bar N's close fills at bar N+1's open, not 

4822 # bar N's close; this simulator's own return accrual previously 

4823 # had no way to model that. ALWAYS compute and show both 

4824 # entry_lag_bars=0 (same-bar fill, what this simulator has always 

4825 # assumed) and =1 (the honest, next-bar-fill "lag tax") here, 

4826 # regardless of what net_perf_config.entry_lag_bars is configured 

4827 # to - so the gap this investigation found is never silently 

4828 # invisible again, whichever value base_kwargs happens to carry. 

4829 lag_kwargs = dict(base_kwargs) 

4830 lag_kwargs["entry_lag_bars"] = 1 

4831 lagged_result = simulate_rank_book(dataset, **lag_kwargs) 

4832 report["rank_book_entry_lag_1"] = lagged_result.to_dict() 

4833 _write_evaluation_json(evaluation_dir / "rank_book_simulation_entry_lag_1.json", report["rank_book_entry_lag_1"]) 

4834 _write_evaluation_json( 

4835 evaluation_dir / f"rank_book_simulation_entry_lag_1_{model_kind}.json", report["rank_book_entry_lag_1"] 

4836 ) 

4837 if run_monte_carlo: 

4838 # V5.3.8 - Monte Carlo layer: stationary-block bootstrap of this 

4839 # base run's daily NET returns into n_runs alternative equity 

4840 # histories. Pure core in evaluation/monte_carlo.py; heavy runs 

4841 # matrix persisted as .npz next to the JSON (README renderer owns 

4842 # the PNG), summary + avg/band curves go in the JSON. 

4843 import numpy as _np_mc 

4844 

4845 from evaluation.monte_carlo import run_monte_carlo 

4846 

4847 mc = run_monte_carlo( 

4848 result.per_date_net_return, 

4849 n_runs=int(getattr(args, "mc_runs", 1000)), 

4850 block_size=int(getattr(args, "mc_block_size", 20)), 

4851 seed=int(getattr(args, "mc_seed", 42)), 

4852 method=str(getattr(args, "mc_method", "block")), 

4853 ) 

4854 mc_payload = {k: v for k, v in mc.items() if k != "runs_curves"} 

4855 mc_payload["model_kind"] = model_kind 

4856 mc_payload["head"] = head 

4857 mc_payload["split"] = split 

4858 _write_evaluation_json(evaluation_dir / "monte_carlo.json", mc_payload) 

4859 if mc.get("runs_curves") is not None: 

4860 _np_mc.savez_compressed(evaluation_dir / "monte_carlo_curves.npz", runs_curves=_np_mc.asarray(mc["runs_curves"])) 

4861 if not args.json and mc.get("status") != "OK": 

4862 print(f"Monte Carlo {mc.get('status')}") 

4863 elif not args.json: 

4864 fr = mc["final_return_pct"] 

4865 md = mc["max_drawdown"] 

4866 sh = mc["sharpe"] 

4867 print(f"Monte Carlo ({mc['status']}): {mc['config']['n_runs']} runs " 

4868 f"(method={mc['config']['method']}, block={mc['config']['block_size']}, seed={mc['config']['seed']})") 

4869 print(f" final_return p5/p50/p95 = {fr['p5']}% / {fr['p50']}% / {fr['p95']}% | P(neg)={mc['prob_negative_return']}") 

4870 print(f" sharpe p5/p95 = {sh['p5']} / {sh['p95']} | maxDD p95 = {md['p95']}%") 

4871 if not args.json: 

4872 print("Rank book (entry_lag_bars=1, the 'lag tax' - see development/Problems.md):") 

4873 print(f" gross_sharpe={lagged_result.gross_sharpe:.4f} net_sharpe={lagged_result.net_sharpe:.4f}") 

4874 print(f" delta_net_sharpe vs entry_lag_bars=0: {lagged_result.net_sharpe - result.net_sharpe:+.4f}") 

4875 

4876 # V5.5.0 (Problems.md #128) - the as-live rank book: the SAME simulator 

4877 # fed everything main.py actually does (blended head, percentile 

4878 # hysteresis, spread + rolling-IC gates, hold-on-veto, confidence 

4879 # weights, late-bar lag for forex/crypto, one-bar entry lag, age exit), 

4880 # reported next to the idealized run so the gap is never invisible again. 

4881 if getattr(args, "as_live", False): 

4882 from evaluation.live_parity import ( 

4883 LATE_BAR_ASSET_CLASSES, 

4884 build_as_live_kwargs, 

4885 build_candidate_metadata, 

4886 build_live_mechanisms, 

4887 build_rank_groups, 

4888 lag_predictions_for_tickers, 

4889 load_live_venue_listing_dates, 

4890 main_group_tickers, 

4891 make_rolling_ic_gate_fn, 

4892 ) 

4893 from portfolio.book_construction import resolve_class_weight_caps 

4894 

4895 phase_v2_config = config.get("phase_v2", {}) 

4896 asset_class_by_ticker, trading_eligible_by_ticker = _universe_asset_metadata(config) 

4897 rank_groups = build_rank_groups(config, asset_class_by_ticker) 

4898 live_source = as_live_dataset if as_live_dataset is not None else dataset 

4899 raw_scores, live_policy = _blend_raw_scores_for_dataset(live_source, config, int(sequence_window_default)) 

4900 live_frame = live_source.copy() 

4901 live_frame["live_rank_score"] = raw_scores 

4902 late_tickers = { 

4903 ticker for ticker, asset_class in asset_class_by_ticker.items() if asset_class in LATE_BAR_ASSET_CLASSES 

4904 } 

4905 live_frame = lag_predictions_for_tickers(live_frame, prediction_column="live_rank_score", tickers=late_tickers) 

4906 rolling_ic_gate_config = phase_v2_config.get("rolling_ic_gate", {}) 

4907 gate_fn = ( 

4908 make_rolling_ic_gate_fn( 

4909 live_frame, raw_score_column="live_rank_score", gate_config=rolling_ic_gate_config, 

4910 include_tickers=main_group_tickers(rank_groups, live_frame["ticker"].unique()), 

4911 late_bar_tickers=late_tickers, 

4912 ) 

4913 if rolling_ic_gate_config.get("enabled", False) 

4914 else None 

4915 ) 

4916 as_live_kwargs = build_as_live_kwargs( 

4917 dict(base_kwargs, prediction_column="live_rank_score"), 

4918 book_config=phase_v2_config.get("portfolio_book", {}), 

4919 exits_config=phase_v2_config.get("exits", {}), 

4920 max_position_weight=float(config.get("phase6", {}).get("risk", {}).get("max_position_weight", 0.25)), 

4921 candidate_metadata=build_candidate_metadata(asset_class_by_ticker, trading_eligible_by_ticker), 

4922 rolling_ic_gate_fn=gate_fn, 

4923 topology_config=phase_v2_config.get("topology", {}), 

4924 rank_group_by_ticker=rank_groups, 

4925 venue_listing_dates=load_live_venue_listing_dates(config, ROOT_DIR), 

4926 class_weight_caps=resolve_class_weight_caps(phase_v2_config.get("class_weight_caps")), 

4927 **build_live_mechanisms(config, live_frame, core_crypto_tickers=_core_quality_tickers()), 

4928 ) 

4929 as_live_result = simulate_rank_book(live_frame, **as_live_kwargs) 

4930 idealized_result = result if run_rank_book else simulate_rank_book(dataset, **base_kwargs) 

4931 as_live_report = { 

4932 "as_live": as_live_result.to_dict(), 

4933 "idealized_net_sharpe": idealized_result.net_sharpe, 

4934 "idealized_net_total_return": idealized_result.net_total_return, 

4935 "rank_signal_policy": {key: live_policy.get(key) for key in ("heads", "model_priority", "demoted")}, 

4936 "late_bar_asset_classes_lagged_one_day": sorted(LATE_BAR_ASSET_CLASSES), 

4937 "legacy_sleeve": "excluded_zero_alpha", 

4938 "notes": [ 

4939 "Sharpe here subtracts no risk-free rate; Lean's own Sharpe does (~1.1 points at 1.3% annual vol).", 

4940 "The legacy probability-signal sleeve (phase_v2.legacy_sleeve) is not modeled: it is capped at " 

4941 "max_gross_exposure and treated as zero-alpha.", 

4942 "V5.7.0: member sizing (volatility/cost multipliers, book weight floor), the liquidity gate, the net-edge " 

4943 "gate and the kill switch are modeled with main.py's own pure functions; the learned-topology " 

4944 "multiplier and the predicted-volatility head are not (rolling volatility stands in).", 

4945 ], 

4946 } 

4947 impact_config = dict(phase_v2_config.get("costs", {}).get("impact_model", {})) 

4948 if impact_config: 

4949 impact_config["enabled"] = True 

4950 impact_result = simulate_rank_book(live_frame, **dict(as_live_kwargs, impact_model_config=impact_config)) 

4951 as_live_report["as_live_with_impact_model"] = impact_result.to_dict() 

4952 report["rank_book_as_live"] = as_live_report 

4953 as_live_report["split"] = split 

4954 _write_evaluation_json(evaluation_dir / "rank_book_simulation_as_live.json", as_live_report) 

4955 _write_evaluation_json(evaluation_dir / f"rank_book_simulation_as_live_{split}.json", as_live_report) 

4956 if not args.json: 

4957 print("Rank book AS-LIVE (blended head, live gates, hold-on-veto, confidence weights, 1-bar lag):") 

4958 print(f" idealized net_sharpe={idealized_result.net_sharpe:.4f} -> as-live net_sharpe={as_live_result.net_sharpe:.4f}") 

4959 print(f" as-live net_total_return={as_live_result.net_total_return:.4%} net_max_drawdown={as_live_result.net_max_drawdown:.4%}") 

4960 print(f" as-live rebalances={as_live_result.num_rebalances} vetoed={as_live_result.num_vetoed_rebalances} {as_live_result.veto_reasons}") 

4961 print(f" mean_names_long={as_live_result.mean_names_long:.2f} mean_names_short={as_live_result.mean_names_short:.2f}") 

4962 if impact_config: 

4963 print(f" with Almgren impact model: net_sharpe={impact_result.net_sharpe:.4f}") 

4964 

4965 # V5.5.0 (V5.4.3 follow-up) - how much of the book's return is market or 

4966 # momentum exposure rather than ranking skill. Uses the base rank-book 

4967 # run's per-date net returns. 

4968 if getattr(args, "factor_exposure", False): 

4969 from evaluation.benchmark_comparison import close_pivot_from_frame 

4970 from evaluation.factor_neutralization_check import compute_book_factor_exposure 

4971 

4972 factor_base_result = result if run_rank_book else simulate_rank_book(dataset, **base_kwargs) 

4973 factor_report = compute_book_factor_exposure( 

4974 factor_base_result.per_date, factor_base_result.per_date_net_return, close_pivot_from_frame(dataset) 

4975 ) 

4976 report["factor_exposure"] = factor_report 

4977 _write_evaluation_json(evaluation_dir / "factor_exposure.json", factor_report) 

4978 if not args.json: 

4979 if factor_report.get("status") == "OK": 

4980 print(f"Factor exposure ({factor_report['n_obs']} dates, market={factor_report['market_ticker']}):") 

4981 print(f" total_sharpe={factor_report['total_sharpe']} alpha_sharpe={factor_report['alpha_sharpe']} R2={factor_report['r_squared']}") 

4982 print(f" loadings={factor_report['loadings']} variance explained %={factor_report['factor_contribution_pct']}") 

4983 else: 

4984 print(f"Factor exposure SKIPPED: {factor_report.get('reason')}") 

4985 

4986 # V5.5.0 (Problems.md #129) - per-asset-class elevated-volatility cutoff. 

4987 if getattr(args, "calibrate_volatility_threshold", False): 

4988 from evaluation.volatility_threshold_calibration import calibrate_elevated_volatility_thresholds 

4989 from topology import ELEVATED_VOLATILITY_THRESHOLD 

4990 

4991 asset_class_by_ticker_for_vol, _ = _universe_asset_metadata(config) 

4992 volatility_report = calibrate_elevated_volatility_thresholds( 

4993 dataset, 

4994 asset_class_by_ticker_for_vol, 

4995 percentile=float(getattr(args, "volatility_threshold_percentile", 0.80)), 

4996 current_default=ELEVATED_VOLATILITY_THRESHOLD, 

4997 ) 

4998 report["volatility_threshold_calibration"] = volatility_report 

4999 _write_evaluation_json(evaluation_dir / "volatility_threshold_calibration.json", volatility_report) 

5000 if not args.json: 

5001 if volatility_report.get("status") == "OK": 

5002 print("Elevated-volatility threshold calibration (annualized, topology's own 24-return statistic):") 

5003 for asset_class, stats in sorted(volatility_report["by_asset_class"].items()): 

5004 print(f" {asset_class}: {stats}") 

5005 print(f" Suggested phase_v2.topology.elevated_volatility_threshold = {json.dumps(volatility_report['suggested_config'])}") 

5006 else: 

5007 print(f"Volatility threshold calibration SKIPPED: {volatility_report.get('reason')}") 

5008 

5009 # V5.4.4 - benchmark comparison over the SAME dataset window/split the 

5010 # rank book just ran on (the `dataset` frame is already split-filtered 

5011 # above, so the pivot - and every baseline number - is automatically 

5012 # like-for-like with the rank book's own window). Pure pandas over the 

5013 # dataset's own close columns; zero new data dependencies, zero model 

5014 # inference. Missing close column or missing SPY/TLT degrades to 

5015 # SKIPPED entries inside the report, never a crash. 

5016 if run_benchmarks: 

5017 from evaluation.benchmark_comparison import close_pivot_from_frame, run_all_baselines 

5018 

5019 benchmark_close_pivot = close_pivot_from_frame(dataset) 

5020 benchmark_report = run_all_baselines(benchmark_close_pivot) 

5021 benchmark_report["model_kind"] = model_kind 

5022 benchmark_report["head"] = head 

5023 benchmark_report["split"] = split 

5024 report["benchmarks"] = benchmark_report 

5025 _write_evaluation_json(evaluation_dir / "benchmark_comparison.json", benchmark_report) 

5026 if not args.json: 

5027 print(f"Benchmarks (split={split}, {len(benchmark_close_pivot)} dates x {benchmark_close_pivot.shape[1]} tickers):") 

5028 for baseline in benchmark_report["baselines"]: 

5029 sharpe = baseline["net_sharpe"] 

5030 sharpe_str = f"{sharpe:+.4f}" if sharpe is not None else " n/a " 

5031 print(f" {baseline['strategy']:<14} net_sharpe={sharpe_str} total_return={baseline['total_return_pct']}% [{baseline.get('status', 'OK')}]") 

5032 

5033 # V5.2.8 (development/Problems.md #94) - reuses --rank-book's own 

5034 # `result` (per_date/per_date_net_return) when that flag was also 

5035 # given, rather than recomputing simulate_rank_book() a second time; 

5036 # computes it fresh (entry_lag_bars=0, the same default --rank-book 

5037 # uses) when --replay-kill-switch is passed on its own. 

5038 if run_replay_kill_switch: 

5039 from evaluation.kill_switch_replay import ( 

5040 replay_kill_switch_over_dataset, 

5041 summarize_kill_switch_replay, 

5042 ) 

5043 

5044 kill_switch_replay_result = result if run_rank_book else simulate_rank_book(dataset, **base_kwargs) 

5045 kill_switch_config = config.get("phase_v2", {}).get("risk", {}).get("kill_switch", {}) 

5046 phase6_risk = config.get("phase6", {}).get("risk", {}) 

5047 daily_portfolio_returns = dict( 

5048 zip(kill_switch_replay_result.per_date, kill_switch_replay_result.per_date_net_return, strict=False) 

5049 ) 

5050 replay_records = replay_kill_switch_over_dataset( 

5051 kill_switch_replay_result.per_date, 

5052 daily_portfolio_returns, 

5053 kill_switch_config, 

5054 max_daily_drawdown_pct=float(phase6_risk.get("max_daily_drawdown_pct", 0.03)), 

5055 max_total_drawdown_pct=float(phase6_risk.get("max_total_drawdown_pct", 0.12)), 

5056 ) 

5057 replay_summary = summarize_kill_switch_replay(replay_records) 

5058 report["kill_switch_replay"] = {"summary": replay_summary, "per_date": replay_records} 

5059 _write_evaluation_json(evaluation_dir / "kill_switch_replay.json", report["kill_switch_replay"]) 

5060 if not args.json: 

5061 print( 

5062 f"Kill-switch replay (APPROXIMATION - see development/Problems.md #94): " 

5063 f"{replay_summary['trip_count']} trips across {replay_summary['total_dates']} dates, " 

5064 f"{replay_summary['locked_days']} locked days ({replay_summary['locked_day_fraction']:.2%})" 

5065 ) 

5066 

5067 # V5.3.1 (development/Problems.md #34/#96) - offline counterfactual: 

5068 # "how often would a real limit order have filled" without needing a 

5069 # live Lean run. Deliberately independent of --rank-book above - it 

5070 # simulates a signal firing on every row, not just book-selected ones 

5071 # (see evaluation/limit_fill_simulator.py's own docstring for why 

5072 # that's a different, complementary question, not a replay of the 

5073 # real order-events.json evidence). 

5074 if run_simulate_limit_fills: 

5075 from evaluation.limit_fill_simulator import simulate_limit_fills, sweep_limit_fill_offsets 

5076 

5077 limit_orders_config = config.get("phase_v2", {}).get("limit_orders", {}) 

5078 timeout_bars = int(limit_orders_config.get("unfilled_timeout_bars", 3)) 

5079 offset_sweep_arg = getattr(args, "limit_fill_offset_sweep", None) 

5080 if offset_sweep_arg: 

5081 offsets = [float(value) for value in offset_sweep_arg.split(",")] 

5082 limit_fill_result = sweep_limit_fill_offsets(dataset, unfilled_timeout_bars=timeout_bars, offset_multipliers=offsets) 

5083 else: 

5084 configured_offset = float(limit_orders_config.get("offset_multiplier", 1.0)) 

5085 limit_fill_result = simulate_limit_fills(dataset, unfilled_timeout_bars=timeout_bars, offset_multiplier=configured_offset) 

5086 report["limit_fill_simulation"] = limit_fill_result 

5087 _write_evaluation_json(evaluation_dir / "limit_fill_simulation.json", limit_fill_result) 

5088 if not args.json: 

5089 print(f"Limit-fill simulation (APPROXIMATION, unfilled_timeout_bars={timeout_bars}):") 

5090 if offset_sweep_arg: 

5091 for multiplier, result_for_multiplier in limit_fill_result.items(): 

5092 overall = result_for_multiplier["overall"] 

5093 print( 

5094 f" offset_multiplier={multiplier}: fill_rate={overall['fill_rate']:.2%} " 

5095 f"timeout_rate={overall['timeout_rate']:.2%} num_signals={overall['num_signals']}" 

5096 ) 

5097 else: 

5098 overall = limit_fill_result["overall"] 

5099 print( 

5100 f" overall: fill_rate={overall['fill_rate']:.2%} timeout_rate={overall['timeout_rate']:.2%} " 

5101 f"num_signals={overall['num_signals']}" 

5102 ) 

5103 for security_type, stats in sorted(limit_fill_result["by_asset_class"].items()): 

5104 print(f" {security_type}: fill_rate={stats['fill_rate']:.2%} num_signals={stats['num_signals']}") 

5105 

5106 if run_capacity: 

5107 cap = capacity_curve( 

5108 dataset, 

5109 participation_cap=float(net_perf_config.get("capacity_participation_cap", 0.01)), 

5110 base_kwargs=base_kwargs, 

5111 top_n_sweep=[int(n) for n in net_perf_config.get("capacity_top_n_sweep", [3, 6, 10, 15])], 

5112 ) 

5113 report["capacity"] = cap 

5114 _write_evaluation_json(evaluation_dir / "capacity_report.json", cap) 

5115 _write_evaluation_json(evaluation_dir / f"capacity_report_{model_kind}.json", cap) 

5116 if not args.json: 

5117 print(f"Capacity: ${cap['capacity_usd']:,.0f} (binding: {cap['binding_ticker']})") 

5118 for row in cap["per_top_n"]: 

5119 print(f" top_n={row['top_n']}: net_sharpe={row['net_sharpe']:.4f}") 

5120 

5121 if run_stress: 

5122 stress = stress_test_costs( 

5123 dataset, base_kwargs=base_kwargs, 

5124 cost_multipliers=tuple(float(m) for m in net_perf_config.get("stress_cost_multipliers", [1.0, 2.0, 3.0])), 

5125 ) 

5126 report["stress"] = stress 

5127 _write_evaluation_json(evaluation_dir / "cost_stress_report.json", {"stress": stress}) 

5128 _write_evaluation_json(evaluation_dir / f"cost_stress_report_{model_kind}.json", {"stress": stress}) 

5129 if not args.json: 

5130 print("Cost stress test:") 

5131 for row in stress: 

5132 print(f" {row['cost_multiplier']}x: net_sharpe={row['net_sharpe']:.4f} net_total_return={row['net_total_return']:.4%}") 

5133 

5134 if run_calibrate: 

5135 # A simple OLS slope-through-the-origin of forward return on 

5136 # (rank - 0.5)*2 - matches execution/cost_model.py::expected_edge_bps()'s 

5137 # own linear-in-rank-deviation model. That function documents its 

5138 # edge_bps_per_rank_unit as the FULL predicted move over 

5139 # phase_v2.costs.horizon_days (it then scales down by 

5140 # holding_bars/horizon_days itself) - so the regression must use 

5141 # the SAME horizon's forward return, not a fixed 1-day one, or the 

5142 # calibrated number is off by roughly horizon_days/1 (a ~20x 

5143 # understatement of edge at the default horizon_days=20, since a 

5144 # 1-day slope was previously being treated as a 20-day move and 

5145 # then halved again downstream). 

5146 costs_config = config.get("phase_v2", {}).get("costs", {}) 

5147 horizon_days = int(costs_config.get("horizon_days", 20)) 

5148 forward_return_column = f"target_return_{horizon_days}d" 

5149 if forward_return_column not in dataset.columns: 

5150 print( 

5151 f"warning: {forward_return_column!r} not in dataset (horizon_days={horizon_days}); " 

5152 "falling back to target_return_1d - the calibrated value will then represent a " 

5153 "1-day move, not the horizon_days move expected_edge_bps() assumes.", 

5154 file=sys.stderr, 

5155 ) 

5156 forward_return_column = "target_return_1d" 

5157 rank_deviation = (dataset["predicted_head"] - 0.5) * 2.0 

5158 forward_return = dataset[forward_return_column] 

5159 valid = rank_deviation.notna() & forward_return.notna() 

5160 x = rank_deviation[valid].to_numpy() 

5161 y = forward_return[valid].to_numpy() 

5162 denominator = float((x * x).sum()) if len(x) >= 2 else 0.0 

5163 slope = float((x * y).sum() / denominator) if denominator > 0 else 0.0 

5164 calibrated_edge_bps = slope * 10_000.0 

5165 report["calibrated_edge_bps_per_rank_unit"] = calibrated_edge_bps 

5166 report["calibrated_edge_forward_return_column"] = forward_return_column 

5167 if not args.json: 

5168 print(f"Calibrated edge_bps_per_rank_unit ({forward_return_column}): {calibrated_edge_bps:.4f}") 

5169 print(f" Apply with: aq config set phase_v2.costs.edge_bps_per_rank_unit {calibrated_edge_bps:.4f}") 

5170 print(" Then enable the gate: aq config set phase_v2.costs.enabled true") 

5171 

5172 if run_calibrate_book_spread: 

5173 # V5.1 (development/Problems.md) - min_rank_confidence_spread was a 

5174 # guessed constant (0.2) never checked against this codebase's 

5175 # actual raw-score scale; evaluation/rank_book_simulator.py's own 

5176 # book simulation hardcodes min_rank_confidence_spread=0.0 (see 

5177 # that module's comment), so nothing ever exercised the real gate 

5178 # before it shipped live. This mirrors --calibrate-edge's own 

5179 # discipline: derive the number from data, don't guess it. 

5180 from evaluation import calibrate_book_confidence_spread, compute_blended_raw_scores 

5181 from evaluation.live_parity import build_candidate_metadata 

5182 from portfolio.rank_signal import resolve_rank_signal_policy 

5183 

5184 training_metrics_by_model: dict[str, dict | None] = {} 

5185 for model_name, metrics_filename in ( 

5186 ("sequence", "sequence_training_metrics.json"), 

5187 ("multitask", "multitask_training_metrics.json"), 

5188 ): 

5189 metrics_path = ML_DIR / metrics_filename 

5190 training_metrics_by_model[model_name] = ( 

5191 json.loads(metrics_path.read_text(encoding="utf-8")) if metrics_path.exists() else None 

5192 ) 

5193 policy = resolve_rank_signal_policy(training_metrics_by_model, config) 

5194 active_heads = [head_name for head_name, weight in policy["heads"].items() if weight > 0.0] 

5195 

5196 predictions_by_model_head: dict[str, dict[str, object]] = {} 

5197 for model_kind_for_head in policy["model_priority"]: 

5198 calib_model_filename, calib_schema_filename = _EVALUATE_MODEL_ARTIFACTS[model_kind_for_head] 

5199 calib_model_path = ML_DIR / calib_model_filename 

5200 calib_schema_path = ML_DIR / calib_schema_filename 

5201 if not calib_model_path.exists() or not calib_schema_path.exists(): 

5202 continue # best-effort - a missing model just means its heads fall through to the next model_priority entry 

5203 calib_model_export = json.loads(calib_model_path.read_text(encoding="utf-8")) 

5204 calib_feature_schema = json.loads(calib_schema_path.read_text(encoding="utf-8")) 

5205 calib_feature_names = calib_feature_schema["model_input_names"] 

5206 head_predictions = predict_heads( 

5207 dataset, calib_model_export, calib_feature_names, list(active_heads), 

5208 model_kind=model_kind_for_head, 

5209 sequence_feature_schema=calib_feature_schema if model_kind_for_head == "sequence" else None, 

5210 configured_window_size=int(sequence_window_default), 

5211 ) 

5212 predictions_by_model_head[model_kind_for_head] = head_predictions 

5213 

5214 dataset["raw_blended_score"] = compute_blended_raw_scores(dataset, predictions_by_model_head, policy) 

5215 

5216 book_config = config.get("phase_v2", {}).get("portfolio_book", {}) 

5217 strategy_mode = config.get("phase5", {}).get("backtest", {}).get("strategy_mode", "long_flat") 

5218 book_top_n = int(book_config.get("top_n", 6)) 

5219 book_bottom_n = int(book_config.get("bottom_n", 6)) if strategy_mode == "long_short" else 0 

5220 

5221 # V5.7.0: the pool live actually selects from (disabled asset classes and observation-only names are out), 

5222 # on equity-session dates only. 

5223 spread_asset_classes, spread_eligibility = _universe_asset_metadata(config) 

5224 book_spread_result = calibrate_book_confidence_spread( 

5225 dataset, 

5226 raw_score_column="raw_blended_score", 

5227 top_n=book_top_n, 

5228 bottom_n=book_bottom_n, 

5229 percentile=float(getattr(args, "book_spread_percentile", 0.10)), 

5230 candidate_metadata_by_ticker=build_candidate_metadata(spread_asset_classes, spread_eligibility), 

5231 session_asset_class="equity", 

5232 ) 

5233 report["book_spread_calibration"] = book_spread_result 

5234 _write_evaluation_json(evaluation_dir / "book_spread_calibration.json", book_spread_result) 

5235 if not args.json: 

5236 calibrated_spread = book_spread_result["calibrated_min_rank_confidence_spread"] 

5237 distribution = book_spread_result["spread_distribution"] 

5238 print( 

5239 f"Calibrated min_rank_confidence_spread (p{book_spread_result['percentile']*100:.0f}, " 

5240 f"{book_spread_result['num_dates_used']} dates used, " 

5241 f"{book_spread_result['num_dates_skipped_thin_universe']} skipped thin-universe): " 

5242 f"{calibrated_spread:.4f}" 

5243 ) 

5244 print( 

5245 f" Distribution: min={distribution['min']}, p10={distribution['p10']}, " 

5246 f"median={distribution['median']}, p75={distribution['p75']}, max={distribution['max']}" 

5247 ) 

5248 print(f" Apply with: aq config set phase_v2.portfolio_book.min_rank_confidence_spread {calibrated_spread:.4f}") 

5249 print( 

5250 " NOTE: this recalibrates the gate's threshold to this model's real achievable dispersion - " 

5251 "it does not certify the underlying rank heads are skillful. Check ml/*_training_metrics.json's " 

5252 "quality_status before trusting the resulting book." 

5253 ) 

5254 

5255 if run_calibrate_rolling_ic_floor: 

5256 # V5.3.5 (development/Problems.md #102) - min_rolling_mean_ic was 

5257 # about to be shipped as a guessed constant, the same 

5258 # "guessed-then-calibrated" gap min_rank_confidence_spread had 

5259 # (Problems.md #89) before --calibrate-book-spread fixed it. 

5260 # Mirrors that tool's exact structure, including recomputing the 

5261 # blended raw score fresh rather than reusing a value from a 

5262 # different block - see run_calibrate_book_spread above for why 

5263 # that duplication is this file's own established convention. 

5264 from evaluation import compute_blended_raw_scores 

5265 from evaluation.rolling_ic_gate_calibration import calibrate_rolling_ic_floor 

5266 from portfolio.rank_signal import resolve_rank_signal_policy 

5267 

5268 training_metrics_by_model: dict[str, dict | None] = {} 

5269 for model_name, metrics_filename in ( 

5270 ("sequence", "sequence_training_metrics.json"), 

5271 ("multitask", "multitask_training_metrics.json"), 

5272 ): 

5273 metrics_path = ML_DIR / metrics_filename 

5274 training_metrics_by_model[model_name] = ( 

5275 json.loads(metrics_path.read_text(encoding="utf-8")) if metrics_path.exists() else None 

5276 ) 

5277 policy = resolve_rank_signal_policy(training_metrics_by_model, config) 

5278 active_heads = [head_name for head_name, weight in policy["heads"].items() if weight > 0.0] 

5279 

5280 predictions_by_model_head: dict[str, dict[str, object]] = {} 

5281 for model_kind_for_head in policy["model_priority"]: 

5282 calib_model_filename, calib_schema_filename = _EVALUATE_MODEL_ARTIFACTS[model_kind_for_head] 

5283 calib_model_path = ML_DIR / calib_model_filename 

5284 calib_schema_path = ML_DIR / calib_schema_filename 

5285 if not calib_model_path.exists() or not calib_schema_path.exists(): 

5286 continue # best-effort - a missing model just means its heads fall through to the next model_priority entry 

5287 calib_model_export = json.loads(calib_model_path.read_text(encoding="utf-8")) 

5288 calib_feature_schema = json.loads(calib_schema_path.read_text(encoding="utf-8")) 

5289 calib_feature_names = calib_feature_schema["model_input_names"] 

5290 head_predictions = predict_heads( 

5291 dataset, calib_model_export, calib_feature_names, list(active_heads), 

5292 model_kind=model_kind_for_head, 

5293 sequence_feature_schema=calib_feature_schema if model_kind_for_head == "sequence" else None, 

5294 configured_window_size=int(sequence_window_default), 

5295 ) 

5296 predictions_by_model_head[model_kind_for_head] = head_predictions 

5297 

5298 dataset["raw_blended_score"] = compute_blended_raw_scores(dataset, predictions_by_model_head, policy) 

5299 

5300 rolling_ic_gate_config = config.get("phase_v2", {}).get("rolling_ic_gate", {}) 

5301 rolling_ic_result = calibrate_rolling_ic_floor( 

5302 dataset, 

5303 raw_score_column="raw_blended_score", 

5304 horizon_days=int(rolling_ic_gate_config.get("horizon_days", 20)), 

5305 rolling_window_days=int(rolling_ic_gate_config.get("rolling_window_days", 40)), 

5306 percentile=float(getattr(args, "rolling_ic_floor_percentile", 0.10)), 

5307 min_names_per_date=int(rolling_ic_gate_config.get("min_names_per_date", 10)), 

5308 ) 

5309 report["rolling_ic_floor_calibration"] = rolling_ic_result 

5310 _write_evaluation_json(evaluation_dir / "rolling_ic_floor_calibration.json", rolling_ic_result) 

5311 if not args.json: 

5312 calibrated_floor = rolling_ic_result["calibrated_min_rolling_mean_ic"] 

5313 distribution = rolling_ic_result["rolling_ic_distribution"] 

5314 print( 

5315 f"Calibrated min_rolling_mean_ic (p{rolling_ic_result['percentile']*100:.0f}, " 

5316 f"{rolling_ic_result['num_samples_used']} samples used, " 

5317 f"{rolling_ic_result['num_samples_skipped_insufficient_history']} skipped insufficient-history): " 

5318 f"{calibrated_floor:.4f}" 

5319 ) 

5320 print( 

5321 f" Distribution: min={distribution['min']}, p10={distribution['p10']}, " 

5322 f"median={distribution['median']}, p75={distribution['p75']}, max={distribution['max']}" 

5323 ) 

5324 print(f" Apply with: aq config set phase_v2.rolling_ic_gate.min_rolling_mean_ic {calibrated_floor:.4f}") 

5325 print( 

5326 " NOTE: only sets the threshold - phase_v2.rolling_ic_gate.enabled still defaults to false. " 

5327 "Check --replay-rolling-ic-gate's per-era breakdown before flipping it on live." 

5328 ) 

5329 

5330 if run_replay_rolling_ic_gate: 

5331 # V5.3.5 (development/Problems.md #102) - the critical pre-main.py 

5332 # checkpoint: recomputes the blended raw score fresh (same 

5333 # duplication convention as run_calibrate_rolling_ic_floor above), 

5334 # then replays the gate day-by-day at the same rebalance cadence 

5335 # phase_v2.portfolio_book.rebalance_every_bars uses live, and 

5336 # reports engagement broken down by the three known bad eras. 

5337 # 

5338 # Always evaluated as ENABLED regardless of 

5339 # phase_v2.rolling_ic_gate.enabled's live default (False) - this 

5340 # is a "what would happen IF this were live" diagnostic, the same 

5341 # relationship evaluation/kill_switch_replay.py's own replay has 

5342 # to the live kill switch (which has no master on/off flag to 

5343 # begin with). Everything else - crucially min_rolling_mean_ic - 

5344 # is read from config as-is, so this reports honestly against 

5345 # whatever floor is currently configured (the shipped -1e12 

5346 # sentinel gives a trivial always-engaged result until 

5347 # --calibrate-rolling-ic-floor's value has actually been applied 

5348 # with `aq config set`). 

5349 from evaluation import compute_blended_raw_scores 

5350 from evaluation.rolling_ic_gate_replay import ( 

5351 replay_rolling_ic_gate_over_dataset, 

5352 summarize_rolling_ic_gate_replay, 

5353 ) 

5354 from portfolio.rank_signal import resolve_rank_signal_policy 

5355 

5356 training_metrics_by_model: dict[str, dict | None] = {} 

5357 for model_name, metrics_filename in ( 

5358 ("sequence", "sequence_training_metrics.json"), 

5359 ("multitask", "multitask_training_metrics.json"), 

5360 ): 

5361 metrics_path = ML_DIR / metrics_filename 

5362 training_metrics_by_model[model_name] = ( 

5363 json.loads(metrics_path.read_text(encoding="utf-8")) if metrics_path.exists() else None 

5364 ) 

5365 policy = resolve_rank_signal_policy(training_metrics_by_model, config) 

5366 active_heads = [head_name for head_name, weight in policy["heads"].items() if weight > 0.0] 

5367 

5368 predictions_by_model_head: dict[str, dict[str, object]] = {} 

5369 for model_kind_for_head in policy["model_priority"]: 

5370 replay_model_filename, replay_schema_filename = _EVALUATE_MODEL_ARTIFACTS[model_kind_for_head] 

5371 replay_model_path = ML_DIR / replay_model_filename 

5372 replay_schema_path = ML_DIR / replay_schema_filename 

5373 if not replay_model_path.exists() or not replay_schema_path.exists(): 

5374 continue # best-effort - a missing model just means its heads fall through to the next model_priority entry 

5375 replay_model_export = json.loads(replay_model_path.read_text(encoding="utf-8")) 

5376 replay_feature_schema = json.loads(replay_schema_path.read_text(encoding="utf-8")) 

5377 replay_feature_names = replay_feature_schema["model_input_names"] 

5378 head_predictions = predict_heads( 

5379 dataset, replay_model_export, replay_feature_names, list(active_heads), 

5380 model_kind=model_kind_for_head, 

5381 sequence_feature_schema=replay_feature_schema if model_kind_for_head == "sequence" else None, 

5382 configured_window_size=int(sequence_window_default), 

5383 ) 

5384 predictions_by_model_head[model_kind_for_head] = head_predictions 

5385 

5386 dataset["raw_blended_score"] = compute_blended_raw_scores(dataset, predictions_by_model_head, policy) 

5387 

5388 rolling_ic_gate_config = dict(config.get("phase_v2", {}).get("rolling_ic_gate", {})) 

5389 rolling_ic_gate_config["enabled"] = True 

5390 rebalance_every_bars = int(config.get("phase_v2", {}).get("portfolio_book", {}).get("rebalance_every_bars", 10)) 

5391 rebalance_dates = sorted(dataset["date"].unique())[::max(1, rebalance_every_bars)] 

5392 

5393 replay_records = replay_rolling_ic_gate_over_dataset( 

5394 dataset, 

5395 raw_score_column="raw_blended_score", 

5396 rebalance_dates=rebalance_dates, 

5397 horizon_days=int(rolling_ic_gate_config.get("horizon_days", 20)), 

5398 rolling_window_days=int(rolling_ic_gate_config.get("rolling_window_days", 40)), 

5399 gate_config=rolling_ic_gate_config, 

5400 min_names_per_date=int(rolling_ic_gate_config.get("min_names_per_date", 10)), 

5401 ) 

5402 replay_summary = summarize_rolling_ic_gate_replay(replay_records) 

5403 report["rolling_ic_gate_replay"] = {"summary": replay_summary, "per_date": replay_records} 

5404 _write_evaluation_json(evaluation_dir / "rolling_ic_gate_replay.json", report["rolling_ic_gate_replay"]) 

5405 if not args.json: 

5406 overall = replay_summary["overall"] 

5407 print( 

5408 f"Rolling-IC gate replay (floor={rolling_ic_gate_config.get('min_rolling_mean_ic')}): " 

5409 f"{overall['disengaged_days']}/{overall['total_dates']} rebalance dates disengaged " 

5410 f"({overall['disengaged_day_fraction']:.2%})" 

5411 ) 

5412 for era_name, era_stats in replay_summary["by_era"].items(): 

5413 fraction = era_stats["disengaged_day_fraction"] 

5414 fraction_display = f"{fraction:.2%}" if fraction is not None else "n/a (no dates in era)" 

5415 print(f" {era_name}: {era_stats['disengaged_days']}/{era_stats['total_dates']} disengaged ({fraction_display})") 

5416 

5417 if run_calibrate_confidence_threshold: 

5418 # V5.2.6 (development/Problems.md) - min_confidence_to_trade was a 

5419 # guessed constant (0.12), never checked against this codebase's 

5420 # actual confidence-vs-forward-return relationship - the same 

5421 # "guessed constant, never calibrated" problem 

5422 # min_rank_confidence_spread had (Problems.md #89) before 

5423 # --calibrate-book-spread fixed it. Mirrors that tool's exact 

5424 # structure. 

5425 from evaluation import calibrate_confidence_threshold, compute_blended_raw_scores 

5426 from portfolio.rank_signal import resolve_rank_signal_policy 

5427 

5428 training_metrics_by_model: dict[str, dict | None] = {} 

5429 for model_name, metrics_filename in ( 

5430 ("sequence", "sequence_training_metrics.json"), 

5431 ("multitask", "multitask_training_metrics.json"), 

5432 ): 

5433 metrics_path = ML_DIR / metrics_filename 

5434 training_metrics_by_model[model_name] = ( 

5435 json.loads(metrics_path.read_text(encoding="utf-8")) if metrics_path.exists() else None 

5436 ) 

5437 policy = resolve_rank_signal_policy(training_metrics_by_model, config) 

5438 active_heads = [head_name for head_name, weight in policy["heads"].items() if weight > 0.0] 

5439 

5440 predictions_by_model_head: dict[str, dict[str, object]] = {} 

5441 for model_kind_for_head in policy["model_priority"]: 

5442 calib_model_filename, calib_schema_filename = _EVALUATE_MODEL_ARTIFACTS[model_kind_for_head] 

5443 calib_model_path = ML_DIR / calib_model_filename 

5444 calib_schema_path = ML_DIR / calib_schema_filename 

5445 if not calib_model_path.exists() or not calib_schema_path.exists(): 

5446 continue # best-effort - a missing model just means its heads fall through to the next model_priority entry 

5447 calib_model_export = json.loads(calib_model_path.read_text(encoding="utf-8")) 

5448 calib_feature_schema = json.loads(calib_schema_path.read_text(encoding="utf-8")) 

5449 calib_feature_names = calib_feature_schema["model_input_names"] 

5450 head_predictions = predict_heads( 

5451 dataset, calib_model_export, calib_feature_names, list(active_heads), 

5452 model_kind=model_kind_for_head, 

5453 sequence_feature_schema=calib_feature_schema if model_kind_for_head == "sequence" else None, 

5454 configured_window_size=int(sequence_window_default), 

5455 ) 

5456 predictions_by_model_head[model_kind_for_head] = head_predictions 

5457 

5458 dataset["raw_blended_score"] = compute_blended_raw_scores(dataset, predictions_by_model_head, policy) 

5459 

5460 book_config = config.get("phase_v2", {}).get("portfolio_book", {}) 

5461 strategy_mode = config.get("phase5", {}).get("backtest", {}).get("strategy_mode", "long_flat") 

5462 book_top_n = int(book_config.get("top_n", 6)) 

5463 book_bottom_n = int(book_config.get("bottom_n", 6)) if strategy_mode == "long_short" else 0 

5464 

5465 confidence_forward_return_column = "target_return_20d" 

5466 if confidence_forward_return_column not in dataset.columns: 

5467 print( 

5468 f"warning: {confidence_forward_return_column!r} not in dataset; falling back to " 

5469 "target_return_1d - the calibrated value will then represent a 1-day move, not the " 

5470 "20-day move predicted_rank_20d assumes.", 

5471 file=sys.stderr, 

5472 ) 

5473 confidence_forward_return_column = "target_return_1d" 

5474 

5475 confidence_result = calibrate_confidence_threshold( 

5476 dataset, 

5477 raw_score_column="raw_blended_score", 

5478 forward_return_column=confidence_forward_return_column, 

5479 top_n=book_top_n, 

5480 bottom_n=book_bottom_n, 

5481 round_trip_cost_fraction=float( 

5482 config.get("phase_v2", {}).get("liquidity", {}).get("max_round_trip_cost_fraction") or 0.001 

5483 ), 

5484 percentile=float(getattr(args, "confidence_threshold_percentile", 0.10)), 

5485 ) 

5486 report["confidence_threshold_calibration"] = confidence_result 

5487 _write_evaluation_json(evaluation_dir / "confidence_threshold_calibration.json", confidence_result) 

5488 if not args.json: 

5489 calibrated_general = confidence_result["calibrated_min_confidence_to_trade"] 

5490 calibrated_book_selected = confidence_result["calibrated_min_confidence_to_trade_book_selected"] 

5491 print( 

5492 f"Calibrated min_confidence_to_trade (p{confidence_result['percentile']*100:.0f}, " 

5493 f"{confidence_result['num_rows_used']} paying rows used, " 

5494 f"{confidence_result['num_dates_skipped_thin_universe']} dates skipped thin-universe): " 

5495 f"{calibrated_general:.4f}" 

5496 ) 

5497 print( 

5498 f"Calibrated min_confidence_to_trade_book_selected ({confidence_result['num_rows_used_book_selected']} " 

5499 f"paying book-selected rows used): {calibrated_book_selected:.4f}" 

5500 ) 

5501 print(f" Apply with: aq config set phase6.risk.min_confidence_to_trade {calibrated_general:.4f}") 

5502 print( 

5503 " Apply with: aq config set phase6.risk.min_confidence_to_trade_book_selected " 

5504 f"{calibrated_book_selected:.4f}" 

5505 ) 

5506 print( 

5507 " NOTE: this recalibrates the gate's threshold to this model's real achievable confidence " 

5508 "among historically-paying trades - it does not certify the underlying rank heads are " 

5509 "skillful. Check ml/*_training_metrics.json's quality_status before trusting the result." 

5510 ) 

5511 

5512 if run_ablation_flag: 

5513 from evaluation import run_ablation 

5514 

5515 ablation_config = config.get("phase_v2", {}).get("evaluation", {}).get("ablation", {}) 

5516 requested_variants = ( 

5517 [name.strip() for name in args.variants.split(",") if name.strip()] 

5518 if getattr(args, "variants", None) 

5519 else list(ablation_config.get("variants", ["static_baseline", "no_neutrality", "no_hysteresis", "no_cost_model"])) 

5520 ) 

5521 ablation_results = run_ablation(dataset, base_kwargs, requested_variants) 

5522 report["ablation"] = ablation_results 

5523 _write_evaluation_json( 

5524 ROOT_DIR / ablation_config.get("report_path", "ml/evaluation/ablation_report.json"), ablation_results 

5525 ) 

5526 if not args.json: 

5527 print(f"Ablation ({model_kind}/{head}, split={split}):") 

5528 for name, entry in ablation_results.items(): 

5529 if entry.get("status") in {"not_offline_measurable", "unknown_variant", "insufficient_windows"}: 

5530 print(f" {name}: [{entry['status']}] {entry.get('reason', '')}") 

5531 else: 

5532 print(f" {name}: net_sharpe={entry['net_sharpe']:.4f} delta_vs_static_baseline={entry['delta_vs_static_baseline']:+.4f}") 

5533 

5534 if args.json: 

5535 print(json.dumps(report, indent=2, default=str)) 

5536 

5537 _refresh_readme_evaluation_sections() 

5538 return 0 

5539 

5540 

5541def cmd_verify(args: argparse.Namespace) -> int: 

5542 """`aq verify` (V6.6.4): every way this project can be verified, in one table (evaluation/verification_matrix.py, development/verification.md).""" 

5543 from evaluation import verification_matrix as matrix 

5544 

5545 if args.write_doc: 

5546 path = ROOT_DIR / "development" / "verification.md" 

5547 text = path.read_text(encoding="utf-8") 

5548 start, end = "<!-- AQ:VERIFICATION_START -->", "<!-- AQ:VERIFICATION_END -->" 

5549 if start not in text or end not in text: 

5550 print("development/verification.md has no AQ:VERIFICATION markers", file=sys.stderr) 

5551 return 1 

5552 head, rest = text.split(start, 1) 

5553 _, tail = rest.split(end, 1) 

5554 path.write_text(f"{head}{start}\n{matrix.markdown()}\n{end}{tail}", encoding="utf-8", newline="\n") 

5555 print(f"wrote {path}") 

5556 return 0 

5557 if args.list or not (args.quick or args.record): 

5558 print(matrix.markdown()) 

5559 return 0 

5560 results = matrix.run_quick(ROOT_DIR) 

5561 if getattr(args, "json", False): 

5562 print(json.dumps(results, indent=2, default=str)) 

5563 if args.record: 

5564 matrix.record(Path(args.record), results) 

5565 print(f"recorded {args.record}") 

5566 return 0 if all(item["exit"] == 0 for item in results) else 1 

5567 

5568 

5569def cmd_docs_sync(args: argparse.Namespace) -> int: 

5570 import docs_facts 

5571 

5572 report = docs_facts.sync_docs(docs_facts.tracked_docs(ROOT_DIR), docs_facts.compute_facts(ROOT_DIR), check=args.check, 

5573 blocks=docs_facts.compute_blocks(ROOT_DIR)) 

5574 if getattr(args, "json", False): 

5575 print(json.dumps(report, indent=2)) 

5576 return 1 if report["unknown"] or (args.check and report["changed"]) else 0 

5577 for line in report["unknown"]: 

5578 print(f"unknown fact - {line}", file=sys.stderr) 

5579 for line in report["changed"]: 

5580 print(f"{'stale' if args.check else 'updated'} - {line}") 

5581 print(f"{len(report['changed'])} fact(s) {'stale' if args.check else 'updated'}, {len(report['unknown'])} unknown") 

5582 return 1 if report["unknown"] or (args.check and report["changed"]) else 0 

5583 

5584 

5585def cmd_models(args: argparse.Namespace, *, root: Path | None = None) -> int: 

5586 """`aq models` (V6.6.10): the example models published with each release, installed into a local cache and scored with the numpy 

5587 forward pass. The project's own trading models are not published.""" 

5588 import pandas as pd 

5589 

5590 from retraining import model_catalog as catalog 

5591 

5592 root = Path(root or catalog.DEFAULT_ROOT) 

5593 command = args.models_command 

5594 try: 

5595 if command == "list": 

5596 rows = [{**entry, "installed": (root / entry["name"]).is_dir()} for entry in catalog.catalog()] 

5597 rows += [{"name": folder.name, "kind": "lab", "summary": "installed from a zip", "installed": True} 

5598 for folder in sorted(root.iterdir()) if folder.is_dir() and not folder.name.startswith(".") and folder.name not in catalog.EXAMPLES] if root.is_dir() else [] 

5599 if getattr(args, "json", False): 

5600 print(json.dumps(rows, indent=2, default=str)) 

5601 return 0 

5602 for entry in rows: 

5603 state = "installed" if entry["installed"] else "not installed" 

5604 print(f"{entry['name']:<22} {entry['kind']:<10} {state:<14} {entry['summary']}") 

5605 return 0 

5606 if command == "remove": 

5607 folder = root / args.name 

5608 if not folder.is_dir(): 

5609 print(f"aq models remove: {args.name} is not installed", file=sys.stderr) 

5610 return 1 

5611 if getattr(args, "dry_run", False): 

5612 print(f"would remove {folder}") 

5613 return 0 

5614 shutil.rmtree(folder) 

5615 print(f"removed {folder}") 

5616 return 0 

5617 if command == "install": 

5618 if args.from_zip: 

5619 folder = catalog.install_zip(Path(args.from_zip), name=args.name, root=root, allow_unlisted=True) 

5620 else: 

5621 folder = catalog.install(args.name, version=args.version, root=root) 

5622 print(f"installed {args.name} into {folder}") 

5623 return 0 

5624 if command == "info": 

5625 loaded = catalog.load(args.name, root=root) 

5626 if getattr(args, "json", False): 

5627 print(json.dumps({"name": loaded["name"], "kind": loaded["kind"], "inputs": loaded["schema"].get("model_input_names"), "card": loaded["card"]}, indent=2)) 

5628 return 0 

5629 print(loaded["card"] or "(no model card)") 

5630 return 0 

5631 model = catalog.load(args.name, root=root) 

5632 if args.csv: 

5633 closes = pd.read_csv(args.csv, index_col=0) 

5634 closes.index = closes.index.astype(str) 

5635 else: 

5636 from aether_quant.samples import load_sample_prices 

5637 

5638 closes = load_sample_prices() 

5639 scores = catalog.score(model, closes, head=args.head) 

5640 if args.out: 

5641 scores.to_csv(args.out, index=False, lineterminator="\n") 

5642 print(f"{len(scores)} scores to {args.out}") 

5643 else: 

5644 last = scores[scores["date"] == scores["date"].max()].sort_values("score", ascending=False) 

5645 print(last.to_string(index=False)) 

5646 return 0 

5647 except (ValueError, FileNotFoundError, OSError) as error: 

5648 print(f"aq models {command}: {error}", file=sys.stderr) 

5649 return 1 

5650 

5651 

5652def cmd_init(args: argparse.Namespace) -> int: 

5653 """`aq init <dir>` (V6.6.10): a new signal project (signal, tests, pipeline, workflow) from the template in the wheel.""" 

5654 from evaluation.project_template import TEMPLATE, create_project, template_files 

5655 

5656 target = Path(args.directory) 

5657 if getattr(args, "dry_run", False): 

5658 print(f"would write into {target}: " + ", ".join(sorted(template_files(TEMPLATE)))) 

5659 return 0 

5660 if getattr(args, "force", False) and target.exists() and any(target.iterdir()): 

5661 clashes = [relative for relative in template_files(TEMPLATE) if (target / relative).exists()] 

5662 print(f"--force: overwriting {', '.join(clashes) or 'nothing'} in {target}") 

5663 import tempfile 

5664 

5665 with tempfile.TemporaryDirectory() as staging: 

5666 written = create_project(Path(staging) / "project", name=args.name or target.resolve().name, version=_installed_version()) 

5667 for relative in written: 

5668 destination = target / relative 

5669 destination.parent.mkdir(parents=True, exist_ok=True) 

5670 shutil.copy2(Path(staging) / "project" / relative, destination) 

5671 print(f"created {args.directory}: " + ", ".join(written)) 

5672 print(f"next: cd {args.directory} && pytest && aq pipeline run") 

5673 return 0 

5674 try: 

5675 written = create_project(target, name=args.name, version=_installed_version()) 

5676 except FileExistsError as error: 

5677 print(f"aq init: {error}", file=sys.stderr) 

5678 return 1 

5679 print(f"created {args.directory}: " + ", ".join(written)) 

5680 print(f"next: cd {args.directory} && pytest && aq pipeline run") 

5681 return 0 

5682 

5683 

5684def _installed_version() -> str: 

5685 from importlib.metadata import PackageNotFoundError, version 

5686 

5687 try: 

5688 return version("aether-quant") 

5689 except PackageNotFoundError: 

5690 return "0.0.0" 

5691 

5692 

5693def cmd_pipeline(args: argparse.Namespace) -> int: 

5694 """`aq pipeline run | status` (V6.6.10): data, signal, (train), evaluate, gate, report, resumable, in `runs/<id>/`.""" 

5695 import datetime as _datetime 

5696 

5697 from evaluation import pipeline 

5698 from retraining import run_resume 

5699 

5700 config = Path(args.config) if args.config else (Path("pipeline.toml") if Path("pipeline.toml").exists() else None) 

5701 runs = Path(args.runs_dir) 

5702 if args.pipeline_command == "validate": 

5703 try: 

5704 spec = pipeline.load_pipeline(config) 

5705 except (OSError, ValueError) as error: 

5706 print(f"aq pipeline validate: {error}", file=sys.stderr) 

5707 return 1 

5708 print(json.dumps(spec, indent=2, default=str) if getattr(args, "json", False) else f"{config or 'the defaults'}: valid ({spec['pipeline']['name']}, signal {spec['pipeline']['signal']})") 

5709 return 0 

5710 if args.pipeline_command == "list": 

5711 rows = [{"run": path.parent.name, "done": list(json.loads(path.read_text(encoding="utf-8"))["done"]), "stages": len(pipeline.STAGES)} 

5712 for path in sorted(runs.glob("*/state.json"), key=lambda item: item.stat().st_mtime)] 

5713 print(json.dumps(rows, indent=2) if args.json else "\n".join(f"{row['run']}: {len(row['done'])}/{row['stages']} stages" for row in rows) or "no pipeline runs yet: aq pipeline run") 

5714 return 0 

5715 if args.pipeline_command == "status": 

5716 candidates = [runs / args.run_id] if args.run_id else sorted(runs.glob("*/state.json"), key=lambda path: path.stat().st_mtime) 

5717 states = [path if path.name == "state.json" else path / "state.json" for path in candidates] 

5718 if not states or not states[-1].exists(): 

5719 print("no pipeline run yet: aq pipeline run") 

5720 return 1 

5721 chosen = states if getattr(args, "all", False) else states[-1:] 

5722 rows = [{"run": path.parent.name, "done": list(json.loads(path.read_text(encoding="utf-8"))["done"])} for path in chosen if path.exists()] 

5723 if getattr(args, "json", False): 

5724 print(json.dumps(rows, indent=2)) 

5725 return 0 

5726 for row in rows: 

5727 print(f"{row['run']}: " + ", ".join(f"{stage} done" for stage in row["done"]) + f" ({len(row['done'])}/{len(pipeline.STAGES)} stages)") 

5728 return 0 

5729 run_id = args.run_id 

5730 if getattr(args, "resume", False) and not run_id: 

5731 # V6.6.10: the newest run that has not reached its last stage, with the pipeline file it started with 

5732 stopped = run_resume.find_resumable(runs, "", last_step=pipeline.STAGES[-1]) 

5733 if stopped is None: 

5734 print("aq pipeline run --resume: no stopped run to continue", file=sys.stderr) 

5735 return 1 

5736 run_id = stopped.name 

5737 recorded = (run_resume.read_json(stopped / run_resume.RECORD, {}) or {}).get("config") 

5738 config = Path(recorded) if recorded and args.config is None else config 

5739 print(f"resuming run {run_id}: done {', '.join(run_resume.done_steps(stopped)) or 'nothing yet'}") 

5740 try: 

5741 spec = pipeline.load_pipeline(config) 

5742 except (OSError, ValueError) as error: 

5743 print(f"aq pipeline: {error}", file=sys.stderr) 

5744 return 1 

5745 run_id = run_id or _datetime.datetime.now(_datetime.timezone.utc).strftime("%Y%m%d_%H%M%S") 

5746 run_dir = runs / run_id 

5747 run_resume.start_record(run_dir, {"config": str(config.resolve()) if config is not None else None}) 

5748 print(f"pipeline {spec['pipeline']['name']} ({'defaults: the sample and 20-session momentum' if config is None else config}), run {run_id}") 

5749 state = pipeline.run_stages(pipeline.STAGES, pipeline.pipeline_actions(spec, run_dir=run_dir), state_path=run_dir / "state.json") 

5750 print((run_dir / "report.md").read_text(encoding="utf-8")) 

5751 return 0 if all(verdict["passed"] for verdict in state["done"]["gate"]["result"].values()) else 3 

5752 

5753 

5754def cmd_hello(args: argparse.Namespace) -> int: 

5755 """`aq hello`: real daily bars, the shipped rule, a cost-aware backtest and a clean report, in one command (V6.6.5, #343).""" 

5756 from data_pipeline.public_candles import DEFAULT_CACHE_DIR 

5757 from evaluation.hello_world import load_closes, render_html, render_text, run_hello 

5758 from json_safety import atomic_write_json, atomic_write_text 

5759 

5760 start = args.start 

5761 print("[1/4] Data: ", end="", flush=True) 

5762 closes, source, notice = load_closes(offline=args.offline, start=start, end=args.end, cache_dir=None if args.no_cache else DEFAULT_CACHE_DIR) 

5763 if notice: 

5764 print(f"{notice} ", end="") 

5765 print(f"{closes.shape[1]} coins, {closes.index.min()} to {closes.index.max()}, {source}") 

5766 print("[2/4] Rule: t3_crypto_trend_blend_x_eos, the shipped book (trend votes over 20/60/120 sessions)") 

5767 print("[3/4] Backtest: Coinbase taker fees and slippage, plus an 8-variant grid for the overfitting checks ...", flush=True) 

5768 report = run_hello(closes, start=start, end=args.end or None, data_source=source) 

5769 print("[4/4] Report") 

5770 print() 

5771 if args.json == "-": 

5772 from json_safety import sanitize_json_finite 

5773 

5774 print(json.dumps(sanitize_json_finite(report.to_dict()), indent=2, default=str)) 

5775 return 0 

5776 print(render_text(report)) 

5777 if args.json: 

5778 atomic_write_json(Path(args.json), report.to_dict(), indent=2) 

5779 print(f"wrote {args.json}") 

5780 if args.html: 

5781 atomic_write_text(Path(args.html), render_html(report)) 

5782 print(f"wrote {args.html}") 

5783 return 0 

5784 

5785 

5786def _json_config_parsers(subparsers, file_name: str) -> None: 

5787 get_parser = subparsers.add_parser("get", help=f"Print a {file_name} value") 

5788 get_parser.add_argument("dotted_path") 

5789 get_parser.add_argument("--json", action="store_true", help="Print the value as JSON") 

5790 keys_parser = subparsers.add_parser("keys", help="List leaf key paths (optionally scoped to a prefix)") 

5791 keys_parser.add_argument("dotted_prefix", nargs="?", default=None) 

5792 keys_parser.add_argument("--json", action="store_true", help="Print the paths as a JSON list") 

5793 set_parser = subparsers.add_parser("set", help=f"Set a {file_name} value (JSON-parsed, string fallback); a type change needs --force") 

5794 set_parser.add_argument("dotted_path") 

5795 set_parser.add_argument("value") 

5796 set_parser.add_argument("--dry-run", action="store_true", help="Print old -> new, write nothing") 

5797 set_parser.add_argument("--force", action="store_true", help="Allow the value to change type (bool to string, say)") 

5798 diff_parser = subparsers.add_parser("diff", help=f"Leaf keys added, removed and changed against {file_name} at a git ref (rule 9 review)") 

5799 diff_parser.add_argument("ref", nargs="?", default="HEAD", help="A commit or tag (default HEAD)") 

5800 diff_parser.add_argument("--json", action="store_true", help="Print JSON instead of text") 

5801 validate_parser = subparsers.add_parser("validate", help="Duplicate keys, NaN or inf, and (config.json) the sections main.py reads") 

5802 validate_parser.add_argument("--json", action="store_true", help="Print JSON instead of text") 

5803 

5804 

5805CLI_EXAMPLES: dict[str, tuple[str, ...]] = { 

5806 "hello": ("aq hello --offline", "aq hello --html report.html", "aq hello --json - > report.json"), 

5807 "models": ("aq models list", "aq models install example-crypto-mlp", "aq models score example-crypto-mlp --out scores.csv"), 

5808 "models list": ("aq models list --json",), "models install": ("aq models install example-crypto-mlp", "aq models install my-model --from mylab/my-model.zip"), 

5809 "models info": ("aq models info example-crypto-mlp",), "models score": ("aq models score example-crypto-mlp --csv closes.csv --out scores.csv",), 

5810 "models remove": ("aq models remove my-model --dry-run",), 

5811 "init": ("aq init my-signal", "aq init my-signal --name momentum --dry-run"), 

5812 "pipeline": ("aq pipeline run", "aq pipeline status --all"), "pipeline run": ("aq pipeline run --config pipeline.toml", "aq pipeline run --resume"), 

5813 "pipeline status": ("aq pipeline status --json",), "pipeline validate": ("aq pipeline validate --config pipeline.toml",), "pipeline list": ("aq pipeline list",), 

5814 "train": ("aq train --dataset-only", "aq train --multitask-only --seed 7 --memory-profile low", "aq train --walk-forward --step-days 90", "aq train --resume"), 

5815 "test": ("aq test --impacted", "aq test tests/test_kelly.py -k cap", "aq test --risk --coverage", "aq test new risk/my_rule.py", "aq test --repeat 5 tests/test_x.py"), 

5816 "backtest": ("aq backtest", "aq backtest --no-publish", "aq backtest --dry-run"), 

5817 "profile": ("aq profile", "aq profile --batched --iterations 2000", "aq profile --topology"), 

5818 "report": ("aq report", "aq report 2026-11-20_12-07-55"), 

5819 "research": ("aq research --signal my_signal.csv", "aq research --signal my_signal.csv --horizons 5,20,60 --json"), 

5820 "prove": ("aq prove --check-sorry", "aq prove --module BookNeutrality", "aq prove --list"), 

5821 "cycle": ("aq cycle status", "aq cycle retrain --host local --memory-profile low"), 

5822 "cycle research": ("aq cycle research rules --round rules.json --draft draft.json", "aq cycle research score --round rules.json"), 

5823 "cycle status": ("aq cycle status --json",), "cycle daily": ("aq cycle daily --dry-run",), 

5824 "cycle decide": ("aq cycle decide --generation g0007 --weights w.csv --ledger-file forward/decisions.jsonl --session 2026-11-20",), 

5825 "cycle retrain": ("aq cycle retrain --host local --memory-profile low", "aq cycle retrain --estimate", "aq cycle retrain --resume"), 

5826 "cycle promote": ("aq cycle promote --generation g0007 --to shadow",), "cycle schedule": ("aq cycle schedule show", "aq cycle schedule install --dry-run"), 

5827 "api": ("aq api", "aq api --port 8010 --no-reload", "aq api --check"), "webui": ("aq webui --open", "aq webui --docker --port 8080"), 

5828 "docker": ("aq docker up", "aq docker ps", "aq docker logs redis --tail 50"), "docker up": ("aq docker up --all",), "docker build": ("aq docker build --no-cache",), 

5829 "docker down": ("aq docker down",), "docker ps": ("aq docker ps",), "docker logs": ("aq docker logs audit-worker --follow",), 

5830 "config": ("aq config get phase_v2.runtime.mode", "aq config diff HEAD~1", "aq config validate"), 

5831 "config get": ("aq config get phase_v2.runtime.mode",), "config keys": ("aq config keys phase_v2.risk",), 

5832 "config set": ("aq config set phase_v2.ib.enabled true --dry-run",), "config preset": ("aq config preset --list", "aq config preset --apply moderate --dry-run"), 

5833 "config diff": ("aq config diff", "aq config diff v6.6.0 --json"), "config validate": ("aq config validate --json",), 

5834 "lean": ("aq lean get environments", "aq lean diff"), "lean get": ("aq lean get data-folder",), "lean keys": ("aq lean keys",), 

5835 "lean set": ("aq lean set data-folder data --dry-run",), "lean diff": ("aq lean diff HEAD~1",), "lean validate": ("aq lean validate",), 

5836 "retrain": ("aq retrain status", "aq retrain --dry-run plan"), "backfill": ("aq backfill fred --series DGS10", "aq backfill yfinance --tickers AAPL MSFT --apply"), 

5837 "paper-readiness": ("aq paper-readiness", "aq paper-readiness --json"), 

5838 "clean": ("aq clean ml", "aq clean ml --apply --yes", "aq clean caches --apply"), 

5839 "trade-lock": ("aq trade-lock --status", "aq trade-lock --on", "aq trade-lock --auto --yes"), 

5840 "kill-switch": ("aq kill-switch --status --json", "aq kill-switch --arm", "aq kill-switch --history --limit 10"), 

5841 "fetch": ("aq fetch stock --ticker AAPL --start 2020-01-01 --end 2024-12-31", "aq fetch crypto --ticker SOLUSD --start 2022-01-01 --end 2024-12-31 --apply"), 

5842 "ib": ("aq ib status",), "ib status": ("aq ib status --json",), "assets": ("aq assets status",), "assets status": ("aq assets status --json",), 

5843 "evaluate": ("aq evaluate --list", "aq evaluate --rank-book --json", "aq evaluate --lean-report --backtest-dir backtests/2026-11-20_12-07-55", 

5844 "aq evaluate --audit-leakage"), 

5845 "render-lean-config": ("aq render-lean-config --dry-run", "aq render-lean-config --account ibkr1", "aq render-lean-config --check"), 

5846 "users": ("aq users list", "aq users add ops --role operator"), "users add": ("aq users add viewer1 --role viewer --accounts default",), 

5847 "users list": ("aq users list --json",), "users remove": ("aq users remove viewer1",), "users rotate": ("aq users rotate ops",), 

5848 "live-readiness": ("aq live-readiness", "aq live-readiness --paper-check ml/evaluation/paper_check.json --markdown"), 

5849 "accounts": ("aq accounts list", "aq accounts validate"), "accounts list": ("aq accounts list --json",), "accounts validate": ("aq accounts validate --json",), 

5850 "accounts status": ("aq accounts status --json status.json",), 

5851 "live": ("aq live status", "aq live up --account paper --dry-run"), "live up": ("aq live up --account paper", "aq live up --account ibkr1 --yes"), 

5852 "live down": ("aq live down --account paper",), "live status": ("aq live status --account paper --json",), 

5853 "secrets": ("aq secrets status", "aq secrets set IB_PASSWORD"), "secrets status": ("aq secrets status --json secrets.json",), 

5854 "secrets set": ("aq secrets set COINBASE_API_SECRET",), "secrets delete": ("aq secrets delete COINBASE_API_SECRET",), 

5855 "secrets-check": ("aq secrets-check", "aq secrets-check --json"), 

5856 "audit-log": ("aq audit-log --verify", "aq audit-log --event-type order_placement --since 2026-11-01 --until 2026-11-20", "aq audit-log --export audit.jsonl"), 

5857 "docs": ("aq docs sync", "aq docs build --strict", "aq docs links"), "docs sync": ("aq docs sync --check",), "docs build": ("aq docs build --strict",), 

5858 "docs serve": ("aq docs serve --port 8000",), "docs cli": ("aq docs cli --check",), "docs links": ("aq docs links --external",), 

5859 "verify": ("aq verify", "aq verify --quick", "aq verify --quick --record verify.json"), 

5860} 

5861 

5862 

5863def _finish_parsers(parser: argparse.ArgumentParser, prefix: tuple[str, ...] = ()) -> None: 

5864 """Examples and a description for every command (from CLI_EXAMPLES where the parser has none), and aq evaluate's flags in 

5865 groups.""" 

5866 for action in parser._actions: 

5867 if not isinstance(action, argparse._SubParsersAction): 

5868 continue 

5869 for name, child in action.choices.items(): 

5870 key = " ".join((*prefix, name)) 

5871 if child.description is None: 

5872 child.description = next((choice.help for choice in action._choices_actions if choice.dest == name), None) 

5873 if not child.epilog and key in CLI_EXAMPLES: 

5874 child.epilog = "Examples:\n" + "\n".join(f" {example}" for example in CLI_EXAMPLES[key]) 

5875 child.formatter_class = argparse.RawDescriptionHelpFormatter 

5876 if key == "evaluate": 

5877 _group_evaluate_help(child) 

5878 _finish_parsers(child, (*prefix, name)) 

5879 

5880 

5881def _group_evaluate_help(parser: argparse.ArgumentParser) -> None: 

5882 """Move aq evaluate's flags into titled groups for its --help (parsing is unchanged).""" 

5883 by_option = {option: action for action in parser._actions for option in action.option_strings} 

5884 placed: set[int] = set() 

5885 inputs = ("--backtest-dir", "--period", "--reference-dir", "--start", "--end", "--interest-rate-file", "--trading-days", "--book-history-file", 

5886 "--book-run-index", "--max-open-sessions", "--data-dir", "--data-root", "--trial-returns", "--signal", "--calibration-file", "--symbol", 

5887 "--book-history-path", "--variants", "--run-id", "--ledger-branch", "--ledger-file", "--limit-fill-offset-sweep", 

5888 "--book-spread-percentile", "--confidence-threshold-percentile", "--rolling-ic-floor-percentile", "--volatility-threshold-percentile", 

5889 "--permutation", "--replay-hysteresis", "--hysteresis-survives-veto", "--reconcile-run-index", "--reconcile-all-runs") 

5890 for title, flags in (*EVALUATE_GROUPS, ("Inputs and options of the tools above", inputs), ("Output", ("--json", "--list"))): 

5891 group = parser.add_argument_group(title) 

5892 for flag in flags: 

5893 action = by_option.get(flag) 

5894 if action is None or id(action) in placed: 

5895 continue 

5896 placed.add(id(action)) 

5897 for container in parser._action_groups: 

5898 if action in container._group_actions and container is not group: 

5899 container._group_actions.remove(action) 

5900 group._group_actions.append(action) 

5901 

5902 

5903class _AqParser(argparse.ArgumentParser): 

5904 """argparse with a suggestion when a command or choice is mistyped.""" 

5905 

5906 def error(self, message: str): 

5907 match = re.search(r"invalid choice: '([^']*)' \(choose from (.*)\)", message) 

5908 if match: 

5909 choices = re.findall(r"'([^']*)'", match.group(2)) or [choice.strip() for choice in match.group(2).split(",")] 

5910 close = difflib.get_close_matches(match.group(1), choices, n=3) 

5911 if close: 

5912 message += f"\ndid you mean: {', '.join(close)}?" 

5913 super().error(message) 

5914 

5915 

5916def build_parser() -> argparse.ArgumentParser: 

5917 parser = _AqParser( 

5918 prog="aq", 

5919 description="Aether Quant: run the trading system, research signals and models, and maintain the project. Every command has --help with examples.", 

5920 epilog="Examples:\n aq hello --offline\n aq doctor\n aq help lab\n\nExit codes: 0 ok, 1 failure, 2 usage, 3 a gate failed or still running, 130 interrupted.", 

5921 formatter_class=argparse.RawDescriptionHelpFormatter, 

5922 ) 

5923 parser.add_argument("--version", action="store_true", help="Print the version and exit (aq version --json for details)") 

5924 parser.add_argument("--debug", action="store_true", help="Show the full traceback of an unexpected error (or set AQ_DEBUG=1)") 

5925 subparsers = parser.add_subparsers(dest="command", required=False, parser_class=_AqParser) 

5926 

5927 hello_parser = subparsers.add_parser("hello", help="Start here: download data, run the shipped rule, print a clean report (no key, no Docker)") 

5928 hello_parser.add_argument("--offline", action="store_true", help="Use the bundled sample instead of downloading") 

5929 hello_parser.add_argument("--start", default="2022-01-01", help="First decision date (YYYY-MM-DD)") 

5930 hello_parser.add_argument("--end", default=None, help="Last date (default: the last closed bar)") 

5931 hello_parser.add_argument("--json", default=None, metavar="FILE", help="Also write the report as JSON (- prints only the JSON)") 

5932 hello_parser.add_argument("--html", default=None, metavar="FILE", help="Also write a self-contained HTML page with the equity curve") 

5933 hello_parser.add_argument("--no-cache", action="store_true", help="Download again instead of reading ~/.cache/aether-quant") 

5934 hello_parser.set_defaults(func=cmd_hello) 

5935 

5936 models_parser = subparsers.add_parser("models", help="Example models from each GitHub release: list, install, info, score (no torch; the project's own models are not published)") 

5937 models_sub = models_parser.add_subparsers(dest="models_command", required=True) 

5938 models_list = models_sub.add_parser("list", help="The example models and whether each is installed") 

5939 models_list.add_argument("--json", action="store_true", help="Print JSON instead of text") 

5940 models_remove = models_sub.add_parser("remove", help="Delete an installed model from the cache") 

5941 models_remove.add_argument("name") 

5942 models_remove.add_argument("--dry-run", action="store_true", help="Print what would be removed") 

5943 models_install = models_sub.add_parser("install", help="Download an example from the release, check its sha256, unpack it into ~/.cache/aether-quant/models") 

5944 models_install.add_argument("name") 

5945 models_install.add_argument("--version", default=None, help="The release tag without its v (default: the latest release)") 

5946 models_install.add_argument("--from", dest="from_zip", default=None, metavar="ZIP", help="Install a local zip instead (checked the same way, against its own manifest)") 

5947 models_info = models_sub.add_parser("info", help="An installed example's model card") 

5948 models_info.add_argument("name") 

5949 models_info.add_argument("--json", action="store_true", help="Print JSON instead of text") 

5950 models_score = models_sub.add_parser("score", help="Score a close table (dates x tickers CSV) with an installed example or a model folder") 

5951 models_score.add_argument("name", help="An installed example, or a folder holding an exported model (your own ml/versions/<id>)") 

5952 models_score.add_argument("--csv", default=None, help="Wide closes: a date column then one column per ticker (default: the bundled sample)") 

5953 models_score.add_argument("--head", default="rank_20d", help="Which head to read (default rank_20d)") 

5954 models_score.add_argument("--out", default=None, help="Write date,ticker,score here instead of printing the last date's scores") 

5955 models_parser.set_defaults(func=cmd_models) 

5956 

5957 init_parser = subparsers.add_parser("init", help="Start your own signal project: signal, tests, a pipeline with a gate, a GitHub workflow") 

5958 init_parser.add_argument("directory", help="A new or empty folder") 

5959 init_parser.add_argument("--name", default=None, help="The project's name (default: the folder's)") 

5960 init_parser.add_argument("--force", action="store_true", help="Write into a folder that is not empty, overwriting the template's files") 

5961 init_parser.add_argument("--dry-run", action="store_true", help="Print the files it would write") 

5962 init_parser.set_defaults(func=cmd_init) 

5963 

5964 pipeline_parser = subparsers.add_parser("pipeline", help="Data, signal, evaluate, gate, report in one resumable command (pipeline.toml, or the sample with defaults)") 

5965 pipeline_sub = pipeline_parser.add_subparsers(dest="pipeline_command", required=True) 

5966 for name, help_text in (("run", "Run (or resume) a pipeline"), ("status", "The stages a run has finished"), ("validate", "Read and check the pipeline file, run nothing"), 

5967 ("list", "Every run and how far it got")): 

5968 command_parser = pipeline_sub.add_parser(name, help=help_text) 

5969 command_parser.add_argument("--config", default=None, help="The pipeline file (default: ./pipeline.toml, else the defaults)") 

5970 command_parser.add_argument("--run-id", default=None, help="Resume or read this run (default: a new one / the latest)") 

5971 command_parser.add_argument("--runs-dir", default="runs", help="Where runs live (default: ./runs)") 

5972 if name == "run": 

5973 command_parser.add_argument("--resume", action="store_true", help="Continue the newest stopped run with its own pipeline file (its finished stages are kept)") 

5974 else: 

5975 command_parser.add_argument("--json", action="store_true", help="Print JSON instead of text") 

5976 if name == "status": 

5977 command_parser.add_argument("--all", action="store_true", help="Every run, not only the latest") 

5978 pipeline_parser.set_defaults(func=cmd_pipeline) 

5979 

5980 train_parser = subparsers.add_parser("train", help="Run the training pipeline (wraps python train.py)") 

5981 train_group = train_parser.add_mutually_exclusive_group() 

5982 train_group.add_argument("--dataset-only", action="store_true", help="Build dataset/scaler/manifest only") 

5983 train_group.add_argument("--init-only", action="store_true", help="Refresh the data inventory only") 

5984 train_group.add_argument("--experts-only", action="store_true", help="Train the 4 expert models only") 

5985 train_group.add_argument( 

5986 "--candidate", action="store_true", 

5987 help="Train the baseline and experts into ml/versions/candidate-<uuid>/ without touching the active ml/ (wraps python train.py --candidate)", 

5988 ) 

5989 train_group.add_argument( 

5990 "--gating-only", action="store_true", help="Train the learned gating blend only (wraps python train_gating.py)" 

5991 ) 

5992 train_group.add_argument( 

5993 "--multitask-only", 

5994 action="store_true", 

5995 help="Train the joint direction+magnitude+volatility model only (wraps python train_multitask.py)", 

5996 ) 

5997 train_group.add_argument( 

5998 "--sequence-only", 

5999 action="store_true", 

6000 help="Train the Phase 2 causal-TCN sequence encoder only (wraps python train_sequence.py)", 

6001 ) 

6002 train_group.add_argument( 

6003 "--topology-only", 

6004 action="store_true", 

6005 help=( 

6006 "Train the learned topology overlay only (wraps python train_topology.py). Needs Postgres up " 

6007 "and enough accumulated realized-outcome events - see the command's own output if it skips." 

6008 ), 

6009 ) 

6010 train_group.add_argument( 

6011 "--strategy-selector-only", 

6012 action="store_true", 

6013 help=( 

6014 "Train the learned multi-leg strategy-selector model only (wraps python " 

6015 "train_strategy_selector.py). Needs real " 

6016 "option_strategy_outcome events (real option positions traded and closed) - expect this to " 

6017 "skip indefinitely in this environment, see the command's own output." 

6018 ), 

6019 ) 

6020 train_group.add_argument( 

6021 "--rl-sizing-only", 

6022 action="store_true", 

6023 help=( 

6024 "Train the offline contextual-bandit sizing overlay only (wraps python train_rl_sizing.py). Reads ml/datasets/*.csv, NOT Postgres - needs a completed " 

6025 "`aq train` and Component D's alt-data features in phase1.features.input_set." 

6026 ), 

6027 ) 

6028 train_group.add_argument( 

6029 "--walk-forward", 

6030 action="store_true", 

6031 help=( 

6032 "Run the dataset-build + training pipeline once per " 

6033 "walk-forward window (wraps python train.py --walk-forward). Never touches active ml/ - " 

6034 "diagnostic only, writes to ml/versions/<run-id>/window_<i>/." 

6035 ), 

6036 ) 

6037 train_parser.add_argument( 

6038 "--step-days", type=int, default=None, help="Walk-forward step size in days (only with --walk-forward)." 

6039 ) 

6040 train_parser.add_argument( 

6041 "--mode", 

6042 type=str, 

6043 choices=("rolling", "expanding"), 

6044 default=None, 

6045 help="Walk-forward mode: rolling or expanding (only with --walk-forward).", 

6046 ) 

6047 train_parser.add_argument( 

6048 "--include-multitask", 

6049 action="store_true", 

6050 help="Force multitask training per walk-forward window on for this run (only with --walk-forward).", 

6051 ) 

6052 train_parser.add_argument( 

6053 "--include-sequence", 

6054 action="store_true", 

6055 help="Force sequence training per walk-forward window on for this run (only with --walk-forward).", 

6056 ) 

6057 train_parser.add_argument( 

6058 "--resume-run-id", 

6059 type=str, 

6060 default=None, 

6061 help=( 

6062 "Continue an interrupted walk-forward run (only with --walk-forward): windows already finished " 

6063 "under ml/versions/<run-id>/window_<i>/window_result.json are loaded, not retrained." 

6064 ), 

6065 ) 

6066 train_parser.add_argument( 

6067 "--metrics", 

6068 type=str, 

6069 default=None, 

6070 help=( 

6071 "Comma-separated tracked-metric names to restrict walk-forward tracking to for this run " 

6072 "(only with --walk-forward)." 

6073 ), 

6074 ) 

6075 train_parser.add_argument( 

6076 "--seed", type=int, default=None, help="Override config.json's seed (only with --multitask-only/--sequence-only)" 

6077 ) 

6078 train_parser.add_argument( 

6079 "--ranking-objective", 

6080 type=str, 

6081 default=None, 

6082 choices=["mse", "soft_spearman", "listnet", "ic_pearson", "ls_sharpe", "class_balanced", "cost_aware"], 

6083 help="Override config.json's ranking_loss.objective for this run only (only with --multitask-only/--sequence-only)", 

6084 ) 

6085 train_parser.add_argument( 

6086 "--memory-profile", choices=["standard", "low"], default="standard", 

6087 help="low: train on a small machine (4 GB), slower: float32 reads, lazy sequence windows, a per-epoch checkpoint (passed to every trainer)", 

6088 ) 

6089 train_parser.add_argument( 

6090 "--resume", nargs="?", const="latest", default=None, metavar="RUN_ID", 

6091 help=( 

6092 "Continue a stopped `aq train` run with its own settings (the newest unfinished one, or RUN_ID): finished steps are skipped, " 

6093 "a walk-forward continues its windows (a window reuses its dataset and baseline when they were written completely), " 

6094 "the sequence trainer continues from its checkpoint" 

6095 ), 

6096 ) 

6097 train_parser.add_argument( 

6098 "--list-runs", action="store_true", help="List the `aq train` and `aq cycle retrain` runs with their finished steps, and stop", 

6099 ) 

6100 train_parser.add_argument("--dry-run", action="store_true", help="Print the mode and settings it would run with, and stop") 

6101 train_parser.add_argument("--json", action="store_true", help="With --list-runs: print JSON") 

6102 train_parser.set_defaults(func=cmd_train) 

6103 

6104 test_parser = subparsers.add_parser("test", help="Run the test suite (wraps pytest tests/), or a testing tool: new, where, slowest, clean-checkout, mutation, fuzz") 

6105 test_parser.add_argument("paths", nargs="*", help="Test files or node ids to run, or a tool: new MODULE, where MODULE, slowest, clean-checkout, mutation, fuzz") 

6106 test_parser.add_argument("-k", "--keyword", dest="k", default=None, metavar="EXPR", help="Only tests whose name matches EXPR (pytest -k)") 

6107 test_parser.add_argument("--lf", action="store_true", help="Only the tests that failed last time (pytest --lf)") 

6108 test_parser.add_argument("--impacted", action="store_true", help="Only the tests that name a module changed since HEAD, without coverage") 

6109 test_parser.add_argument("--watch", action="store_true", help="With --impacted or paths: rerun on every save (Ctrl-C stops)") 

6110 test_parser.add_argument("--repeat", type=int, default=None, metavar="N", help="Run the given tests N times and report the flaky ones (exit 3)") 

6111 test_parser.add_argument("--light-hypothesis", action="store_true", help="Fewer hypothesis examples, no too_slow health check (a 4 GB machine)") 

6112 test_parser.add_argument("--list-groups", action="store_true", help="Print the test groups and their sizes") 

6113 test_parser.add_argument("--group", default=None, help="With new: the test group (default: from the module's folder)") 

6114 test_parser.add_argument("--top", type=int, default=15, help="With slowest: how many (default 15)") 

6115 test_parser.add_argument("--target", default=None, help="With fuzz: one fuzz target") 

6116 test_parser.add_argument("--seconds", type=int, default=60, help="With fuzz: how long atheris runs (default 60)") 

6117 test_parser.add_argument("--json", action="store_true", help="With where, slowest, --repeat or --list-groups: print JSON") 

6118 test_parser.add_argument("--dry-run", action="store_true", help="Print the pytest command (or, with new, the files) and stop") 

6119 test_parser.add_argument( 

6120 "--lean", "--full", dest="lean", action="store_true", 

6121 help="Include the real `lean backtest .` integration test (tests/test_lean_backtest_ml_coverage.py, over an hour wall-clock) - excluded by default; --full is the same flag", 

6122 ) 

6123 test_parser.add_argument( 

6124 "--parallel", action="store_true", 

6125 help="Run via pytest-xdist (-n auto) - off by default, multiple workers importing torch risk OOM on memory-constrained machines", 

6126 ) 

6127 test_parser.add_argument( 

6128 "--coverage", action="store_true", 

6129 help="Every registered group (or the --<subsystem> groups given) in turn under coverage, appending, then the combined " 

6130 "report of every tracked module; fails under pyproject's fail_under (100). One process at a time, for a small PC.", 

6131 ) 

6132 test_parser.add_argument( 

6133 "--changed", action="store_true", 

6134 help="With --coverage, the fast gate before a commit: the tests that name each changed module (vs HEAD, new " 

6135 "files included) run under coverage and every changed file must reach 100%%; a fresh full coverage.json that already " 

6136 "shows them covered passes at once. AGENTS.md 'Coverage: 100%% after every commit'.", 

6137 ) 

6138 test_parser.add_argument( 

6139 "--ruff", action="store_true", 

6140 help="Run `ruff check .` BEFORE pytest - a lint failure fails fast without paying the full suite's wall-clock first (mirrors ci.yml's python-lint job).", 

6141 ) 

6142 for _subsystem_name in _SUBSYSTEM_TEST_FILES: 

6143 test_parser.add_argument( 

6144 f"--{_subsystem_name}", 

6145 action="store_true", 

6146 help=f"Run only the {_subsystem_name} subsystem's tests ({', '.join(_SUBSYSTEM_TEST_FILES[_subsystem_name][:2])}, ...)", 

6147 ) 

6148 test_parser.set_defaults(func=cmd_test) 

6149 

6150 backtest_parser = subparsers.add_parser("backtest", help="Run a Lean backtest (wraps lean backtest .)") 

6151 backtest_parser.add_argument( 

6152 "--image", 

6153 default=None, 

6154 help=f"Override the Lean engine Docker image (default: pinned {PINNED_LEAN_ENGINE_IMAGE}, " 

6155 "never the mutable :latest tag - see PINNED_LEAN_ENGINE_IMAGE's comment in aq_cli.py)", 

6156 ) 

6157 backtest_parser.add_argument("--no-publish", action="store_true", help="Leave the README, charts and evaluation reports alone (a research run)") 

6158 backtest_parser.add_argument("--dry-run", action="store_true", help="Print the Lean command and where the config is frozen, and stop") 

6159 backtest_parser.set_defaults(func=cmd_backtest) 

6160 

6161 profile_parser = subparsers.add_parser( 

6162 "profile", 

6163 help="Profile the per-bar hot path (wraps scripts/profile_inference.py / scripts/profile_subsystems.py)", 

6164 ) 

6165 # default=None (not 10_000/200) so cmd_profile() can tell "user didn't 

6166 # pass --iterations" apart from "user explicitly passed the same 

6167 # number" and let whichever script actually runs use ITS OWN default - 

6168 # profile_inference.py's 10,000 (cheap ~5ms/call) and 

6169 # profile_subsystems.py's 200 (build_market_topology() alone costs 

6170 # ~500-600ms/call at this project's real universe size - 10,000 there 

6171 # would take over an hour) are deliberately very different, and 

6172 # hardcoding either one here would silently override the other. 

6173 profile_parser.add_argument( 

6174 "--iterations", type=int, default=None, 

6175 help="Iterations to profile (default: 10000 for inference, 200 for --<subsystem> flags)", 

6176 ) 

6177 profile_parser.add_argument("--sort", default="cumulative", help="pstats sort key (default: cumulative)") 

6178 profile_parser.add_argument( 

6179 "--batched", action="store_true", 

6180 help="Use the batched expert-inference path (with its precomputed stack caches) instead of a per-expert loop", 

6181 ) 

6182 profile_parser.add_argument( 

6183 "--no-gc", action="store_true", 

6184 help="Disable the GC around the profiled region, to isolate whether GC pauses drive tail latency (inference only)", 

6185 ) 

6186 profile_parser.add_argument( 

6187 "--bucket-report", action="store_true", 

6188 help="Print a 10-bucket-by-iteration-index duration breakdown, to check for a warmup effect (inference only)", 

6189 ) 

6190 profile_parser.add_argument( 

6191 "--parallel", action="store_true", 

6192 help="Run the ProcessPoolExecutor IPC-overhead benchmark against run_symbol_inference() (inference only)", 

6193 ) 

6194 profile_parser.add_argument( 

6195 "--pool-workers", type=int, default=None, 

6196 help="Worker process count for --parallel (default: profile_inference.py's own default, 4)", 

6197 ) 

6198 profile_parser.add_argument( 

6199 "--symbols-per-bar", type=int, default=None, 

6200 help="Symbols-per-bar grouping for --batched's sequence-batching comparison and --parallel's benchmark (default: profile_inference.py's own default, 74)", 

6201 ) 

6202 for _profile_subsystem_name in _PROFILE_SUBSYSTEM_FLAGS: 

6203 profile_parser.add_argument( 

6204 f"--{_profile_subsystem_name}", 

6205 action="store_true", 

6206 help=f"Profile only the {_profile_subsystem_name} subsystem (scripts/profile_subsystems.py)", 

6207 ) 

6208 profile_parser.set_defaults(func=cmd_profile) 

6209 

6210 report_parser = subparsers.add_parser("report", help="Generate a Lean HTML report for a finished backtest") 

6211 report_parser.add_argument("backtest_dir", nargs="?", default=None, help="Folder name under backtests/, e.g. 2026-07-04_13-06-51 (omit to list the newest runs)") 

6212 report_parser.add_argument("result_id", nargs="?", default=None, help="Result JSON id, e.g. 1366365999 (default: the folder's only result)") 

6213 report_parser.set_defaults(func=cmd_report) 

6214 

6215 research_parser = subparsers.add_parser("research", help="Score any signal CSV (date,ticker,score) against the rank targets") 

6216 research_parser.add_argument("--signal", required=True, help="CSV with date, ticker, score columns") 

6217 research_parser.add_argument("--dataset", default=None, help="Dataset CSV (default: ml/datasets/full_dataset.csv)") 

6218 research_parser.add_argument("--horizons", default="5,20", help="Comma list of rank-target horizons (default: 5,20)") 

6219 research_parser.add_argument("--out", default=None, help="Report path (default: ml/evaluation/signal_report.json)") 

6220 research_parser.add_argument("--json", action="store_true", help="Print the report as JSON") 

6221 research_parser.set_defaults(func=cmd_research) 

6222 

6223 prove_parser = subparsers.add_parser("prove", help="Build the Lean 4 proofs in formal/ (needs elan + Mathlib cache)") 

6224 prove_parser.add_argument("--module", default=None, help="Build one spec only, e.g. BookNeutrality (default: all)") 

6225 prove_parser.add_argument("--regen-cases", action="store_true", 

6226 help="Also regenerate aether_quant/_formal_cases/ (the differential test inputs/outputs)") 

6227 prove_parser.add_argument("--check-sorry", action="store_true", 

6228 help="Only scan formal/AetherFormal/*.lean for sorry/admit (no Lean needed)") 

6229 prove_parser.add_argument("--list", action="store_true", help="List the specs and stop") 

6230 prove_parser.add_argument("--json", action="store_true", help="With --list or --check-sorry: print JSON") 

6231 prove_parser.set_defaults(func=cmd_prove) 

6232 

6233 cycle_parser = subparsers.add_parser("cycle", help="The research cycle: rounds, generations, retraining, handover") 

6234 cycle_subparsers = cycle_parser.add_subparsers(dest="cycle_command", required=True) 

6235 cycle_research_parser = cycle_subparsers.add_parser("research", help="One stage of a pre-registered research round") 

6236 cycle_research_parser.add_argument("stage", choices=["rules", "score", "placebo", "gate", "pbo", "freeze", "hold", "report"]) 

6237 cycle_research_parser.add_argument("--round", required=True, help="The round's rule file (written once, hash checked at every stage)") 

6238 cycle_research_parser.add_argument("--draft", default=None, help="rules only: the JSON to write as the round's rule file") 

6239 cycle_research_parser.add_argument("--only", nargs="*", default=None, help="score only: these trials") 

6240 cycle_research_parser.add_argument("--draws", type=int, default=100, help="placebo only: draws per null (default: 100)") 

6241 cycle_research_parser.add_argument("--force", action="store_true", help="Rescore a trial already scored") 

6242 cycle_research_parser.add_argument("--trial", default=None, help="freeze / hold: the candidate") 

6243 cycle_research_parser.add_argument("--digest", default=None, help="hold: the freeze's digest") 

6244 cycle_status_parser = cycle_subparsers.add_parser("status", help="Generations, shares, decay, and what is due (writes ml/generations/status.json)") 

6245 cycle_status_parser.add_argument("--ledger-file", default=None, help="Read this generations.jsonl instead of the forward-ledger branch") 

6246 cycle_status_parser.add_argument("--json", action="store_true", help="Print the status as JSON (the default output is JSON too)") 

6247 cycle_daily_parser = cycle_subparsers.add_parser("daily", help="Today's row for each generation, and the allocation (the scheduled Action's job)") 

6248 cycle_daily_parser.add_argument("--ledger-file", default=None, help="The generations.jsonl to append to (default: ml/cycle/generations.jsonl)") 

6249 cycle_daily_parser.add_argument("--dry-run", action="store_true", help="Compute on a temporary copy of the ledger") 

6250 cycle_decide_parser = cycle_subparsers.add_parser("decide", help="A host's dated decision for a generation that can't decide on a bare runner") 

6251 cycle_decide_parser.add_argument("--generation", required=True) 

6252 cycle_decide_parser.add_argument("--weights", required=True, help="CSV of ticker,weight") 

6253 cycle_decide_parser.add_argument("--ledger-file", required=True, help="forward/decisions.jsonl in a worktree of the branch") 

6254 cycle_decide_parser.add_argument("--session", required=True) 

6255 cycle_retrain_parser = cycle_subparsers.add_parser("retrain", help="Retrain on this machine or the training Codespace, resumable (RAM preflight; --smoke proves the plumbing anywhere)") 

6256 cycle_retrain_parser.add_argument("--host", choices=["local", "codespace"], default=None, help="Required, except with --resume or --estimate") 

6257 cycle_retrain_parser.add_argument("--procedure", default=None, help="A procedure in scripts/cycle_retrain.py: k06, k07, or stack (the model stack: multitask, sequence, gating and the walk-forward)") 

6258 cycle_retrain_parser.add_argument("--smoke", action="store_true", help="Every stage on a tiny synthetic panel") 

6259 cycle_retrain_parser.add_argument("--dry-run", action="store_true", help="Print the stages and the preflight, and stop") 

6260 cycle_retrain_parser.add_argument("--if-due", action="store_true", help="Do nothing unless `aq cycle status` says a retrain is due") 

6261 cycle_retrain_parser.add_argument("--memory-profile", choices=["standard", "low"], default="standard", 

6262 help="low: train the stack on a 4 GB machine (lazy sequence windows, chunked float32 reads, per-epoch checkpoints); slower") 

6263 cycle_retrain_parser.add_argument("--min-ram-gb", type=float, default=None, help="Override the profile's minimum RAM (standard 14, low 3.5)") 

6264 cycle_retrain_parser.add_argument("--score-end", default=None, help="A stack run: the last date of the walk-forward scores") 

6265 cycle_retrain_parser.add_argument("--estimate", action="store_true", help="Print each memory profile's estimated peak for the active dataset, and stop") 

6266 cycle_retrain_parser.add_argument("--resume", nargs="?", const="latest", default=None, metavar="RUN_ID", 

6267 help="Continue a stopped retrain with its own settings (the newest unfinished one, or RUN_ID): finished stages are skipped, the walk-forward and the sequence trainer continue where they stopped") 

6268 cycle_retrain_parser.add_argument("--list-runs", action="store_true", help="List the retrain and `aq train` runs with their finished stages, and stop") 

6269 cycle_retrain_parser.add_argument("--ledger-file", default=None, help=argparse.SUPPRESS) 

6270 cycle_promote_parser = cycle_subparsers.add_parser("promote", help="Change a generation's stage, by rule R-ADMIT1 (never touches broker settings)") 

6271 cycle_promote_parser.add_argument("--generation", required=True) 

6272 cycle_promote_parser.add_argument("--to", required=True, choices=["shadow", "ramping", "active", "fading", "winding_down", "retired", "rejected"]) 

6273 cycle_promote_parser.add_argument("--ledger-file", default=None, help="Read this generations.jsonl instead of the forward-ledger branch") 

6274 cycle_schedule_parser = cycle_subparsers.add_parser("schedule", help="Show or install a weekly retrain-if-due job on a machine with the RAM") 

6275 cycle_schedule_parser.add_argument("schedule_command", choices=["show", "install"]) 

6276 cycle_schedule_parser.add_argument("--platform", choices=["windows", "linux"], default=None) 

6277 cycle_schedule_parser.add_argument("--host", choices=["local", "codespace"], default="local") 

6278 cycle_schedule_parser.add_argument("--dry-run", action="store_true", help="install: print the job and register nothing") 

6279 cycle_parser.set_defaults(func=cmd_cycle) 

6280 

6281 api_parser = subparsers.add_parser("api", help="Start the FastAPI monitoring server (default 127.0.0.1:8001), or check one is answering") 

6282 api_parser.add_argument("--host", default="127.0.0.1", help="Bind address (default 127.0.0.1)") 

6283 api_parser.add_argument("--port", type=int, default=8001, help="Port (default 8001)") 

6284 api_parser.add_argument("--no-reload", dest="reload", action="store_false", help="Do not restart on code changes") 

6285 api_parser.add_argument("--check", action="store_true", help="GET /health on a running server (exit 1 if it does not answer)") 

6286 api_parser.set_defaults(func=cmd_api) 

6287 

6288 webui_parser = subparsers.add_parser("webui", help="Start the webui dev server (npm run dev), or the dashboard image with --docker") 

6289 webui_parser.add_argument("--docker", action="store_true", help="Run the dashboard image (demo data unless --data) instead of the dev server") 

6290 webui_parser.add_argument("--build", action="store_true", help="With --docker: build the image from this checkout first") 

6291 webui_parser.add_argument("--image", default=DASHBOARD_IMAGE, help="With --docker: the image to run") 

6292 webui_parser.add_argument("--port", type=int, default=8080, help="The port (default 8080), for the dev server and --docker") 

6293 webui_parser.add_argument("--open", action="store_true", help="Open the browser on it") 

6294 webui_parser.add_argument("--data", default=None, metavar="DIR", help="With --docker: serve this tree (visualization/, ml/) instead of the demo") 

6295 webui_parser.set_defaults(func=cmd_webui) 

6296 

6297 docker_parser = subparsers.add_parser("docker", help="Docker Compose shortcuts") 

6298 docker_subparsers = docker_parser.add_subparsers(dest="docker_command", required=True) 

6299 

6300 docker_up_parser = docker_subparsers.add_parser("up", help="Start infra services") 

6301 docker_up_group = docker_up_parser.add_mutually_exclusive_group() 

6302 docker_up_group.add_argument("--lean", action="store_true", help="Start via the lean Compose profile") 

6303 docker_up_group.add_argument("--all", action="store_true", help="Start the full stack, including all workers") 

6304 docker_up_parser.add_argument("--dry-run", action="store_true", help="Print the docker command") 

6305 docker_up_parser.set_defaults(func=cmd_docker_up) 

6306 

6307 docker_build_parser = docker_subparsers.add_parser( 

6308 "build", help="Rebuild the consolidated aether-quant-engine image (app + every worker)" 

6309 ) 

6310 docker_build_parser.add_argument("--no-cache", action="store_true", help="Build every layer again") 

6311 docker_build_parser.add_argument("--dry-run", action="store_true", help="Print the docker command") 

6312 docker_build_parser.set_defaults(func=cmd_docker_build) 

6313 docker_down_parser = docker_subparsers.add_parser("down", help="Stop and remove the Compose services") 

6314 docker_down_parser.add_argument("--dry-run", action="store_true", help="Print the docker command") 

6315 docker_down_parser.set_defaults(func=cmd_docker_down) 

6316 docker_ps_parser = docker_subparsers.add_parser("ps", help="The Compose services and their state") 

6317 docker_ps_parser.add_argument("--dry-run", action="store_true", help="Print the docker command") 

6318 docker_ps_parser.set_defaults(func=cmd_docker_ps) 

6319 docker_logs_parser = docker_subparsers.add_parser("logs", help="A service's recent logs (all services without one)") 

6320 docker_logs_parser.add_argument("service", nargs="?", default=None) 

6321 docker_logs_parser.add_argument("--tail", type=int, default=100, help="Lines per service (default 100)") 

6322 docker_logs_parser.add_argument("--follow", action="store_true", help="Keep printing new lines") 

6323 docker_logs_parser.add_argument("--dry-run", action="store_true", help="Print the docker command") 

6324 docker_logs_parser.set_defaults(func=cmd_docker_logs) 

6325 

6326 config_parser = subparsers.add_parser("config", help="Show or edit config.json") 

6327 config_parser.set_defaults(func=cmd_config) 

6328 config_subparsers = config_parser.add_subparsers(dest="config_command") 

6329 

6330 _json_config_parsers(config_subparsers, "config.json") 

6331 

6332 config_preset_parser = config_subparsers.add_parser( 

6333 "preset", help="List/show/apply a named config preset (phase_v2.presets)" 

6334 ) 

6335 config_preset_group = config_preset_parser.add_mutually_exclusive_group() 

6336 config_preset_group.add_argument("--list", dest="preset_list", action="store_true", help="List available presets") 

6337 config_preset_group.add_argument("--show", dest="preset_show", metavar="NAME", help="Print one preset's overrides") 

6338 config_preset_group.add_argument( 

6339 "--apply", dest="preset_apply", metavar="NAME", help="Apply one preset's overrides to config.json" 

6340 ) 

6341 config_preset_parser.add_argument( 

6342 "--dry-run", dest="preset_dry_run", action="store_true", help="With --apply: print old -> new, write nothing" 

6343 ) 

6344 

6345 lean_parser = subparsers.add_parser("lean", help="Show or edit lean.json (same shape as `aq config`)") 

6346 lean_parser.set_defaults(func=cmd_lean) 

6347 lean_subparsers = lean_parser.add_subparsers(dest="lean_command") 

6348 

6349 _json_config_parsers(lean_subparsers, "lean.json") 

6350 

6351 retrain_parser = subparsers.add_parser( 

6352 "retrain", help="Low-level orchestrator stage (python -m retraining.orchestrator STAGE); for a whole retrain use `aq cycle retrain`" 

6353 ) 

6354 retrain_parser.add_argument("--dry-run", action="store_true", help="Print the orchestrator command") 

6355 retrain_parser.add_argument( 

6356 "stage", 

6357 choices=[ 

6358 "plan", 

6359 "train", 

6360 "train_topology", 

6361 "train_gating", 

6362 "train_multitask", 

6363 "train_sequence", 

6364 "train_strategy_selector", 

6365 "validate", 

6366 "backtest", 

6367 "commit", 

6368 "promote", 

6369 "rollback", 

6370 "status", 

6371 "auto-rollback", 

6372 ], 

6373 ) 

6374 retrain_parser.add_argument("retrain_args", nargs=argparse.REMAINDER, help="Passed through verbatim, e.g. --version-id <uuid>") 

6375 retrain_parser.set_defaults(func=cmd_retrain) 

6376 

6377 backfill_parser = subparsers.add_parser( 

6378 "backfill", 

6379 help=( 

6380 "Whole-universe bulk backfills (python -m data_pipeline.<target>_backfill); each is a dry run unless given --apply. " 

6381 "For one ad-hoc ticker, use aq fetch." 

6382 ), 

6383 ) 

6384 backfill_parser.add_argument("target", choices=sorted(_BACKFILL_MODULE_BY_TARGET)) 

6385 backfill_parser.add_argument( 

6386 "backfill_args", 

6387 nargs=argparse.REMAINDER, 

6388 help="Passed through verbatim, e.g. --apply --tickers AAPL MSFT (dividends/yfinance), or --series DGS10 (fred)", 

6389 ) 

6390 backfill_parser.set_defaults(func=cmd_backfill) 

6391 

6392 paper_readiness_parser = subparsers.add_parser( 

6393 "paper-readiness", help="Is the system ready to run on paper (Postgres trading history, broker config)? live-readiness is the later paper-to-live scorecard" 

6394 ) 

6395 paper_readiness_parser.add_argument("--json", action="store_true", help="Print the checks as JSON") 

6396 paper_readiness_parser.set_defaults(func=cmd_paper_readiness) 

6397 

6398 clean_parser = subparsers.add_parser( 

6399 "clean", help="List (dry run by default) and delete regenerable ml/ artifacts: old candidate versions, " 

6400 "older backups, walk-forward window datasets", 

6401 ) 

6402 clean_parser.add_argument("target", choices=["ml", "coverage", "caches", "build"], help="ml: old versions and backups; coverage: coverage-report/; caches: __pycache__ and tool caches; build: build/ and dist/") 

6403 clean_parser.add_argument("--yes", action="store_true", help="With --apply: confirm without a prompt") 

6404 clean_parser.add_argument("--keep-versions", type=int, default=5, help="newest N ml/versions directories to keep (default 5)") 

6405 clean_parser.add_argument("--keep-backups", type=int, default=1, help="newest N ml/_backup_* directories to keep (default 1)") 

6406 clean_parser.add_argument( 

6407 "--strip-walk-forward-datasets", action="store_true", 

6408 help="also list the regenerable window_*/full_dataset.csv etc. inside kept walk-forward runs", 

6409 ) 

6410 clean_parser.add_argument("--apply", action="store_true", help="delete the listed items (default: dry run)") 

6411 clean_parser.add_argument("--json", action="store_true", help="Print JSON instead of text") 

6412 clean_parser.set_defaults(func=cmd_clean) 

6413 

6414 trade_lock_parser = subparsers.add_parser( 

6415 "trade-lock", help="Manually override the sticky total-drawdown trade lock" 

6416 ) 

6417 trade_lock_group = trade_lock_parser.add_mutually_exclusive_group(required=True) 

6418 trade_lock_group.add_argument("--on", action="store_true", help="Force trading paused") 

6419 trade_lock_group.add_argument("--off", action="store_true", help="Force trading resumed") 

6420 trade_lock_group.add_argument("--auto", action="store_true", help="Return to fully automatic behavior") 

6421 trade_lock_group.add_argument("--status", dest="status", action="store_true", help="Print the current override state") 

6422 trade_lock_parser.add_argument("--account", default=None, help="A named account's override (state/accounts/<id>/overrides.json) instead of config.json") 

6423 trade_lock_parser.add_argument("--yes", action="store_true", help="Confirm loosening the lock without a prompt") 

6424 trade_lock_parser.add_argument("--dry-run", action="store_true", help="Print old -> new and change nothing") 

6425 trade_lock_parser.add_argument("--json", action="store_true", help="With --status: print JSON") 

6426 trade_lock_parser.set_defaults(func=cmd_trade_lock) 

6427 

6428 kill_switch_parser = subparsers.add_parser( 

6429 "kill-switch", help="Manually override / inspect the automated production kill switch" 

6430 ) 

6431 kill_switch_group = kill_switch_parser.add_mutually_exclusive_group(required=True) 

6432 kill_switch_group.add_argument("--arm", action="store_true", help="Force kill-switch evaluation on") 

6433 kill_switch_group.add_argument("--disarm", action="store_true", help="Force kill-switch evaluation off") 

6434 kill_switch_group.add_argument("--auto", action="store_true", help="Defer to phase_v2.risk.kill_switch.enabled") 

6435 kill_switch_group.add_argument("--status", dest="status", action="store_true", help="Print the current override state") 

6436 kill_switch_group.add_argument("--history", action="store_true", help="List recorded kill-switch trips from the audit log") 

6437 kill_switch_parser.add_argument("--limit", type=int, default=50, help="Max --history rows (default 50)") 

6438 kill_switch_parser.add_argument("--account", default=None, help="A named account's override (state/accounts/<id>/overrides.json) instead of config.json") 

6439 kill_switch_parser.add_argument("--yes", action="store_true", help="Confirm disarming without a prompt") 

6440 kill_switch_parser.add_argument("--dry-run", action="store_true", help="Print old -> new and change nothing") 

6441 kill_switch_parser.add_argument("--json", action="store_true", help="With --status: print JSON") 

6442 kill_switch_parser.set_defaults(func=cmd_kill_switch) 

6443 

6444 fetch_parser = subparsers.add_parser( 

6445 "fetch", 

6446 help=( 

6447 "Ad-hoc fetch of historical OHLCV from Yahoo Finance for a ticker not yet in config.json. " 

6448 "For a whole-universe bulk refresh instead (dividends/FRED series/Yahoo gaps), see `aq backfill`." 

6449 ), 

6450 ) 

6451 fetch_parser.add_argument( 

6452 "asset_class", choices=list(_FETCH_ASSET_CLASSES), help="Asset class (picks the Lean data_path/market convention)" 

6453 ) 

6454 fetch_parser.add_argument("--ticker", required=True, help="Internal ticker, e.g. AAPL or BTCUSD") 

6455 fetch_parser.add_argument("--start", required=True, type=_iso_date, help="Start date, ISO 8601 YYYY-MM-DD") 

6456 fetch_parser.add_argument("--end", required=True, type=_iso_date, help="End date, ISO 8601 YYYY-MM-DD") 

6457 fetch_parser.add_argument( 

6458 "--apply", action="store_true", help="Actually write the zip file and update config.json (default: dry run, report only)" 

6459 ) 

6460 fetch_parser.add_argument( 

6461 "--expiry", default=None, help="Contract expiry, YYYY-MM-DD (required for asset_class futures/options; requires IB, see 'aq ib status')" 

6462 ) 

6463 fetch_parser.add_argument("--strike", type=float, default=None, help="Strike price (required for asset_class options)") 

6464 fetch_parser.add_argument("--right", choices=["call", "put"], default=None, help="Option right (required for asset_class options)") 

6465 fetch_parser.add_argument( 

6466 "--contract-month", default=None, 

6467 help="Futures only: YYYYMM - fetch a specific dated contract instead of the continuous front-month " 

6468 "(e.g. for building real historical term structure with a second, later --contract-month fetch under " 

6469 "the same --family-ticker)", 

6470 ) 

6471 fetch_parser.add_argument( 

6472 "--family-ticker", default=None, 

6473 help="Groups multiple fetched contracts under one root for offline training's derivatives-macro features " 

6474 "(train.py::build_derivatives_macro_features_by_date()) - e.g. two futures/options fetches sharing " 

6475 "--family-ticker ES. Defaults to --ticker itself (a single, ungrouped contract).", 

6476 ) 

6477 fetch_parser.add_argument("--json", action="store_true", help="Print the fetch report as JSON") 

6478 fetch_parser.set_defaults(func=cmd_fetch) 

6479 

6480 ib_parser = subparsers.add_parser("ib", help="Check Interactive Brokers configuration/connectivity") 

6481 ib_subparsers = ib_parser.add_subparsers(dest="ib_command", required=True) 

6482 ib_status_parser = ib_subparsers.add_parser("status", help="Report disabled / credentials-missing / reachable") 

6483 ib_status_parser.add_argument("--json", action="store_true", help="Print JSON instead of text") 

6484 ib_parser.set_defaults(func=cmd_ib) 

6485 

6486 assets_parser = subparsers.add_parser("assets", help="Report multi-asset-class (futures/options/FRED) readiness") 

6487 assets_subparsers = assets_parser.add_subparsers(dest="assets_command", required=True) 

6488 assets_status_parser = assets_subparsers.add_parser("status", help="Report IB/futures/options/FRED readiness at a glance") 

6489 assets_status_parser.add_argument("--json", action="store_true", help="Print JSON instead of text") 

6490 assets_parser.set_defaults(func=cmd_assets) 

6491 

6492 evaluate_parser = subparsers.add_parser( 

6493 "evaluate", 

6494 help="Offline, cost-aware evaluation of the cross-sectional rank book - net Sharpe/turnover/" 

6495 "capacity/cost-stress from the active model + dataset, without a Lean backtest", 

6496 ) 

6497 evaluate_parser.add_argument("--rank-book", action="store_true", help="Simulate the rank book net of costs") 

6498 evaluate_parser.add_argument("--account", default=None, help="Evaluate with one account's tightened limits (accounts.json), as its deployment runs") 

6499 evaluate_parser.add_argument("--capacity", action="store_true", help="Breadth (top_n sweep) + capacity estimate") 

6500 evaluate_parser.add_argument("--stress", action="store_true", help="Re-run at 1x/2x/3x the configured cost") 

6501 evaluate_parser.add_argument( 

6502 "--calibrate-edge", action="store_true", 

6503 help="Print an edge_bps_per_rank_unit calibrated from this split's realized rank-vs-return relationship", 

6504 ) 

6505 evaluate_parser.add_argument("--all", action="store_true", help="Run --rank-book, --capacity, --stress, --calibrate-edge, --benchmarks, --monte-carlo and --classification together") 

6506 evaluate_parser.add_argument( 

6507 "--walk-forward-summary", action="store_true", 

6508 help="Print an already-written ml/versions/walk-forward-*/walk_forward_summary.json - " 

6509 "never runs training itself; run `aq train --walk-forward` first.", 

6510 ) 

6511 evaluate_parser.add_argument( 

6512 "--run-id", default=None, 

6513 help="Specific walk-forward run-id to read with --walk-forward-summary (default: the most recent run).", 

6514 ) 

6515 evaluate_parser.add_argument( 

6516 "--ablation", action="store_true", 

6517 help="Run the adaptive-machinery ablation harness - runtime-only mechanisms " 

6518 "(gating, topology sizing, the net-edge gate, ...) honestly report not_offline_measurable " 

6519 "rather than a fabricated number. Not included in --all.", 

6520 ) 

6521 evaluate_parser.add_argument( 

6522 "--variants", default=None, 

6523 help="Comma-separated ablation variant names to run with --ablation (default: " 

6524 "phase_v2.evaluation.ablation.variants from config.json).", 

6525 ) 

6526 evaluate_parser.add_argument( 

6527 "--calibrate-book-spread", action="store_true", 

6528 help="Print a min_rank_confidence_spread calibrated from this split's actual raw-score dispersion " 

6529 "(the same resolved rank-signal blend and book top_n/bottom_n main.py uses live). Not included in " 

6530 "--all - loads both models' predictions, a heavier run like --ablation.", 

6531 ) 

6532 evaluate_parser.add_argument( 

6533 "--book-spread-percentile", type=float, default=0.10, 

6534 help="Percentile (0-1) of the per-date confidence-spread distribution to use as the calibrated " 

6535 "floor with --calibrate-book-spread (default: 0.10).", 

6536 ) 

6537 evaluate_parser.add_argument( 

6538 "--calibrate-confidence-threshold", action="store_true", 

6539 help="Print a min_confidence_to_trade (and, when book-selection data is available, a separate " 

6540 "min_confidence_to_trade_book_selected) calibrated from this split's real confidence-vs-forward-" 

6541 "return relationship, mirroring --calibrate-book-spread's discipline. Not included in --all.", 

6542 ) 

6543 evaluate_parser.add_argument( 

6544 "--confidence-threshold-percentile", type=float, default=0.10, 

6545 help="Percentile (0-1) of the paying-trade confidence distribution to use as the calibrated floor " 

6546 "with --calibrate-confidence-threshold (default: 0.10).", 

6547 ) 

6548 evaluate_parser.add_argument( 

6549 "--calibrate-rolling-ic-floor", action="store_true", 

6550 help="Print a phase_v2.rolling_ic_gate.min_rolling_mean_ic " 

6551 "calibrated from this split's real walk-forward rolling trailing-IC distribution (portfolio/" 

6552 "rolling_ic_gate.py's own aggregation, no-lookahead - see evaluation/rolling_ic_gate_calibration.py's " 

6553 "docstring), mirroring --calibrate-book-spread's discipline. Not included in --all - loads both " 

6554 "models' predictions, a heavier run like --ablation.", 

6555 ) 

6556 evaluate_parser.add_argument( 

6557 "--rolling-ic-floor-percentile", type=float, default=0.10, 

6558 help="Percentile (0-1) of the rolling-IC distribution to use as the calibrated floor with " 

6559 "--calibrate-rolling-ic-floor (default: 0.10).", 

6560 ) 

6561 evaluate_parser.add_argument( 

6562 "--reconcile-features", action="store_true", 

6563 help="Diff ONE symbol's logged live " 

6564 "feature values (book_history.jsonl's optional 'feature_snapshot' key, written when " 

6565 "phase_v2.diagnostics.book_history.include_feature_snapshot is on and the symbol is in " 

6566 "feature_snapshot_symbols) against full_dataset.csv's same (ticker, date) row - per-feature " 

6567 "deltas, worst offenders first. Requires --symbol. Not included in --all - investigation-only.", 

6568 ) 

6569 evaluate_parser.add_argument( 

6570 "--symbol", default=None, 

6571 help="Ticker to reconcile with --reconcile-features (e.g. --symbol XOM). Matched " 

6572 "case-insensitively against each record's feature_snapshot keys.", 

6573 ) 

6574 evaluate_parser.add_argument( 

6575 "--reconcile-book-history", action="store_true", 

6576 help="Compare a real Lean backtest's logged book selections " 

6577 "(phase_v2.diagnostics.book_history) against a fresh offline re-derivation of the same raw " 

6578 "scores on those same dates - true ground truth for diagnosing offline-vs-live divergence. " 

6579 "Not included in --all - loads both models' predictions like --calibrate-book-spread.", 

6580 ) 

6581 evaluate_parser.add_argument( 

6582 "--book-history-path", default=None, 

6583 help="Path to the book_history.jsonl log to reconcile with --reconcile-book-history " 

6584 "(default: phase_v2.diagnostics.book_history.output_path from config.json).", 

6585 ) 

6586 evaluate_parser.add_argument( 

6587 "--replay-hysteresis", action="store_true", 

6588 help="With --reconcile-book-history, replay offline's own hysteresis-aware selection " 

6589 "walk-forward across the log's dates (carrying held allocations forward, same as main.py's live " 

6590 "book) instead of reconciling each date independently - tells a real divergence apart from the " 

6591 "live book correctly holding an incumbent a from-scratch reselection wouldn't naturally pick.", 

6592 ) 

6593 reconcile_run_group = evaluate_parser.add_mutually_exclusive_group() 

6594 reconcile_run_group.add_argument( 

6595 "--reconcile-run-index", type=int, default=None, 

6596 help="With --reconcile-book-history, reconcile only the run at this 0-indexed position " 

6597 "within the log's own run-segmented history (negative indices count from the end, -1 == most " 

6598 "recent - the default). book_history.jsonl is a cumulative, never-rotated log - every historical " 

6599 "real backtest's records are appended forever - so reconciling without this flag defaults to the " 

6600 "LATEST run only, never a silent cross-run merge.", 

6601 ) 

6602 reconcile_run_group.add_argument( 

6603 "--reconcile-all-runs", action="store_true", 

6604 help="With --reconcile-book-history, reconcile EVERY run segment independently (each its " 

6605 "own held-allocations/summary, never merged across a run boundary) instead of just the most " 

6606 "recent - for investigating an older run's own numbers, not for combining them into one figure.", 

6607 ) 

6608 evaluate_parser.add_argument( 

6609 "--replay-kill-switch", action="store_true", 

6610 help="Day-by-day OFFLINE replay of the kill-switch + sticky trade-lock state machine " 

6611 "(evaluation/kill_switch_replay.py) against the rank book's own simulated return series - an " 

6612 "explicitly approximate estimate of how much of the run would have been locked out, without " 

6613 "needing a real Lean backtest. Not included in --all - investigation-only (an approximation: no intraday fills).", 

6614 ) 

6615 evaluate_parser.add_argument( 

6616 "--replay-rolling-ic-gate", action="store_true", 

6617 help="Day-by-day, no-lookahead OFFLINE replay of " 

6618 "portfolio/rolling_ic_gate.py's engagement decision (evaluation/rolling_ic_gate_replay.py) at " 

6619 "phase_v2.net_performance's rebalance cadence, with a per-era breakdown against the three known " 

6620 "bad eras this round's research found - the critical pre-main.py checkpoint before flipping " 

6621 "phase_v2.rolling_ic_gate.enabled live. Not included in --all - investigation-only.", 

6622 ) 

6623 evaluate_parser.add_argument( 

6624 "--simulate-limit-fills", action="store_true", 

6625 help="Offline counterfactual (evaluation/limit_fill_simulator.py) estimating how often a " 

6626 "real limit order would fill vs. time out, using the existing dataset's own high/low bars and " 

6627 "phase_v2.limit_orders' pricing/timeout config - without needing a real Lean backtest. Not " 

6628 "included in --all - investigation-only (an estimate from daily high/low bars).", 

6629 ) 

6630 evaluate_parser.add_argument( 

6631 "--limit-fill-offset-sweep", default=None, 

6632 help="Comma-separated offset_multiplier values to sweep with --simulate-limit-fills (default: a " 

6633 "single run at the configured phase_v2.limit_orders.offset_multiplier).", 

6634 ) 

6635 evaluate_parser.add_argument( 

6636 "--monte-carlo", action="store_true", 

6637 help="Monte Carlo simulation testing layer (evaluation/monte_carlo.py) - stationary-block " 

6638 "bootstraps the base rank-book run's daily net returns into --mc-runs alternative equity histories, " 

6639 "writing ml/evaluation/monte_carlo.json + monte_carlo_curves.npz and refreshing the README's Monte " 

6640 "Carlo section (curves chart + red average line + foldable deep stats). Requires/implies the base " 

6641 "--rank-book simulation. Included in --all.", 

6642 ) 

6643 evaluate_parser.add_argument("--mc-runs", type=int, default=1000, 

6644 help="Number of Monte Carlo resampled equity runs (default: 1000).") 

6645 evaluate_parser.add_argument("--mc-block-size", type=int, default=20, 

6646 help="Stationary block bootstrap block length in days (default: 20).") 

6647 evaluate_parser.add_argument("--mc-seed", type=int, default=42, 

6648 help="RNG seed - pinned by default so the README stays stable unless results change.") 

6649 evaluate_parser.add_argument("--mc-method", choices=["block", "iid"], default="block", 

6650 help="Resampling method (default: block = stationary block bootstrap).") 

6651 evaluate_parser.add_argument( 

6652 "--benchmarks", action="store_true", 

6653 help="Benchmark comparison (evaluation/benchmark_comparison.py + " 

6654 "evaluation/public_benchmarks.py) - runs the momentum/mean-reversion/random-entry strategy " 

6655 "baselines AND the SP500 buy-and-hold + daily-rebalanced 60/40 SPY-TLT public baselines over " 

6656 "the SAME dataset window/split as the rank book, writing ml/evaluation/benchmark_comparison.json " 

6657 "and refreshing the README's Benchmark Comparison section. Included in --all.", 

6658 ) 

6659 evaluate_parser.add_argument( 

6660 "--hysteresis-survives-veto", action="store_true", 

6661 help="With --reconcile-book-history --replay-hysteresis, keep offline's hysteresis anchor across a " 

6662 "date live VETOED. Default resets it, which replays logs from the older live code (where a veto wiped live's " 

6663 "memory); pass this flag for a newer run's log (the last formed book survives a veto).", 

6664 ) 

6665 evaluate_parser.add_argument( 

6666 "--as-live", action="store_true", 

6667 help="Also run the rank book AS-LIVE (evaluation/live_parity.py) - the blended rank head, " 

6668 "percentile hysteresis, the live confidence-spread and rolling-IC gates, hold-on-veto, confidence-weighted " 

6669 "sizing, one-day-stale forex/crypto features, a one-bar entry lag and the max-holding age exit - and report " 

6670 "it next to the idealized run (ml/evaluation/rank_book_simulation_as_live.json), with and without the " 

6671 "Almgren impact model. Opt-in, not included in --all.", 

6672 ) 

6673 evaluate_parser.add_argument( 

6674 "--audit-backtest", action="store_true", 

6675 help="Order-level audit of one finished Lean backtest folder (exposure per asset class, book-member " 

6676 "vs non-member entries, overlapping limit orders, holding periods, fees, Sharpe with and without a " 

6677 "risk-free rate, gate vetoes, engine-log teardown) -> ml/evaluation/backtest_audit.json. Needs no dataset " 

6678 "or model. Not included in --all.", 

6679 ) 

6680 evaluate_parser.add_argument( 

6681 "--backtest-dir", default=None, 

6682 help="With --audit-backtest or --audit-fills, the backtests/<timestamp> folder to audit (default: the newest).", 

6683 ) 

6684 evaluate_parser.add_argument( 

6685 "--period", action="append", default=None, metavar="START..END", 

6686 help="With --audit-backtest, also summarise this sub-period (ISO dates, repeatable): return, drawdown, Sharpe, " 

6687 "closed trades and realized P&L per class - BT2 spans the backtest split and the holdout and is judged on each.", 

6688 ) 

6689 evaluate_parser.add_argument( 

6690 "--attribute-lean", action="store_true", 

6691 help="One finished Lean run's daily P&L rebuilt per ticker from its order events and the data zips' closes, " 

6692 "split into main book / legacy signal / bond and forex sleeves / crypto core and graduates, fees per route, and " 

6693 "reconciled with Lean's equity curve (--backtest-dir, --period, --book-history-file) -> " 

6694 "ml/evaluation/lean_attribution.json. Needs no dataset or model.", 

6695 ) 

6696 evaluate_parser.add_argument( 

6697 "--lean-monte-carlo", action="store_true", 

6698 help="Block-bootstrap a finished Lean run's own daily equity returns (--backtest-dir, --mc-runs, " 

6699 "--mc-block-size, --mc-seed) -> ml/evaluation/monte_carlo_lean.json; the README Monte Carlo block shows it next to " 

6700 "the offline book. Needs no dataset or model.", 

6701 ) 

6702 evaluate_parser.add_argument( 

6703 "--lean-stats", action="store_true", 

6704 help="A finished Lean run's printed Sharpe / Sortino / PSR next to an exact replica of Lean's formulas on the " 

6705 "shipped and the older risk-free file, at 252 and 365 days a year (--backtest-dir, --interest-rate-file, " 

6706 "--trading-days) -> ml/evaluation/lean_stats_<run>.json. Needs no dataset or model.", 

6707 ) 

6708 evaluate_parser.add_argument( 

6709 "--forward-ledger", action="store_true", 

6710 help="Verify the forward ledger's hash chain and judge each frozen candidate (sessions, Sharpe, alpha t, what this many " 

6711 "sessions can show), read from the branch the scheduled Action writes (--ledger-branch) or a file (--ledger-file). Exit 1 on a broken chain.", 

6712 ) 

6713 evaluate_parser.add_argument("--ledger-branch", default=None, help="the forward ledger's branch (default forward-ledger)") 

6714 evaluate_parser.add_argument("--ledger-file", default=None, help="read the forward ledger from this file instead of its branch") 

6715 evaluate_parser.add_argument( 

6716 "--data-dir", default=None, 

6717 help="The Lean run's data root for --alpha-proof (data_wide, data_crypto_wide; default data): closes read from any other root come back empty.", 

6718 ) 

6719 evaluate_parser.add_argument( 

6720 "--alpha-proof", action="store_true", 

6721 help="Proof of alpha for one finished Lean run (--backtest-dir, default the README pin or the newest run): " 

6722 "the strategy without its T-bill sweep, per period (full / backtest / holdout / the fresh weeks after 2026-10-16) - " 

6723 "Sharpe with a bootstrap 95%% interval, alpha against SPY / AGG / BTC with a Newey-West t, PSR and the deflated " 

6724 "Sharpe over the trial registry - and the descriptive R-ALPHA1 verdict -> ml/evaluation/alpha_proof.json.", 

6725 ) 

6726 evaluate_parser.add_argument( 

6727 "--backtest-stats", action="store_true", 

6728 help="The README's Backtest Statistics for one finished Lean run (--backtest-dir, default the README pin or " 

6729 "the newest run): general characteristics, performance, runs and drawdowns, implementation shortfall, efficiency " 

6730 "(PSR, deflated Sharpe), classification scores and per-class attribution, for the portfolio and the strategy without " 

6731 "its T-bill sweep -> ml/evaluation/backtest_statistics.json. Needs no dataset or model.", 

6732 ) 

6733 evaluate_parser.add_argument( 

6734 "--lean-report", action="store_true", 

6735 help="Every run-folder tool for one finished Lean run in order (--lean-stats, --lean-monte-carlo, " 

6736 "--audit-backtest with the config's backtest and holdout periods, --attribute-lean, --audit-fills, --backtest-stats), " 

6737 "then the README. With --backtest-dir it also pins the README to that run. `aq backtest` runs it automatically.", 

6738 ) 

6739 evaluate_parser.add_argument( 

6740 "--classification", action="store_true", 

6741 help="Accuracy / precision / recall / F1 / negative log-loss of the --model's direction_20d head on --split " 

6742 "-> ml/evaluation/classification_scores_<model>.json (the Backtest Statistics' offline rows). Included in --all.", 

6743 ) 

6744 evaluate_parser.add_argument( 

6745 "--classification-parity", action="store_true", 

6746 help="A Lean run's logged book-call probabilities (diagnostics.book_history.include_probabilities) " 

6747 "against the same direction_20d head scored offline on the same rows, to a pre-registered tolerance " 

6748 "(--backtest-dir, --dataset) -> ml/evaluation/classification_parity.json. Needs the dataset and the model.", 

6749 ) 

6750 evaluate_parser.add_argument( 

6751 "--paper-check", action="store_true", 

6752 help="The paper-period checklist (veto rate, exposure, fills, slippage, fees, strategy vs sweep P&L, " 

6753 "turnover) of --backtest-dir (a paper or Lean run folder, optionally --start/--end) against the bands of the " 

6754 "contiguous 6-rebalance windows of --reference-dir (default: the README pin) -> ml/evaluation/paper_check.json.", 

6755 ) 

6756 evaluate_parser.add_argument("--reference-dir", default=None, help="With --paper-check, the reference Lean run (default: the README pin).") 

6757 evaluate_parser.add_argument("--start", default=None, help="With --paper-check, first date (YYYY-MM-DD) of the window to check.") 

6758 evaluate_parser.add_argument("--end", default=None, help="With --paper-check, last date (YYYY-MM-DD) of the window to check.") 

6759 evaluate_parser.add_argument( 

6760 "--interest-rate-file", default=None, 

6761 help="With --lean-stats, price the run on this risk-free file only (Lean's interest-rate.csv format).", 

6762 ) 

6763 evaluate_parser.add_argument( 

6764 "--trading-days", type=int, default=None, 

6765 help="With --lean-stats, annualise with this many days a year only (default: both 252 and 365).", 

6766 ) 

6767 evaluate_parser.add_argument( 

6768 "--book-history-file", default=None, 

6769 help="With --attribute-lean, the run's per-run book history (default: the visualization/book_history/*.jsonl " 

6770 "that started closest to the run folder's timestamp).", 

6771 ) 

6772 evaluate_parser.add_argument( 

6773 "--audit-fills", action="store_true", 

6774 help="Every fill of one finished Lean backtest against the dataset's open and the Lean zip's own open, per " 

6775 "asset class and order type, plus the dataset-vs-zip gap on the traded dates -> ml/evaluation/fill_price_audit.json. " 

6776 "Needs no model. Not included in --all.", 

6777 ) 

6778 evaluate_parser.add_argument( 

6779 "--book-run-index", type=int, default=-1, 

6780 help="With --audit-backtest: which run of the cumulative book_history.jsonl belongs to --backtest-dir " 

6781 "(-1 = the latest run, -2 = the one before it, ...). Older runs audited at the default pair the wrong book.", 

6782 ) 

6783 evaluate_parser.add_argument( 

6784 "--max-open-sessions", type=int, default=None, 

6785 help="With --audit-backtest, flag limit orders open longer than this many weekday sessions " 

6786 "(default: phase_v2.limit_orders.unfilled_timeout_bars + 1; the timeout is counted in equity bars, so calendar " 

6787 "days over a weekend made correct cancellations look stale).", 

6788 ) 

6789 evaluate_parser.add_argument( 

6790 "--factor-exposure", action="store_true", 

6791 help="Regress the rank book's daily net returns on SPY and a momentum factor (R2, loadings, " 

6792 "alpha Sharpe) -> ml/evaluation/factor_exposure.json. Opt-in, not included in --all.", 

6793 ) 

6794 evaluate_parser.add_argument( 

6795 "--calibrate-volatility-threshold", action="store_true", 

6796 help="Per-asset-class percentile of realized annualized volatility, with a suggested " 

6797 "phase_v2.topology.elevated_volatility_threshold (crypto sits structurally above the global 0.45 cutoff). " 

6798 "Opt-in, not included in --all.", 

6799 ) 

6800 evaluate_parser.add_argument( 

6801 "--volatility-threshold-percentile", type=float, default=0.80, 

6802 help="With --calibrate-volatility-threshold, the percentile used as the cutoff (default: 0.80).", 

6803 ) 

6804 evaluate_parser.add_argument( 

6805 "--ic-by-class", action="store_true", 

6806 help="Within- vs between-asset-class rank IC of the live blended score on --split " 

6807 "(-> ml/evaluation/class_ic_audit.json). Needs the model and dataset. Not included in --all.", 

6808 ) 

6809 evaluate_parser.add_argument( 

6810 "--audit-gates", action="store_true", 

6811 help="The rolling-IC gate's own reading vs the fully resolved IC on every date of --split, false-veto " 

6812 "share and lag (-> ml/evaluation/gate_audit.json). Not included in --all.", 

6813 ) 

6814 evaluate_parser.add_argument( 

6815 "--audit-data", action="store_true", 

6816 help="Audit every universe zip (coverage, gaps, suspicious moves, OHLC sanity, quote coverage, factor " 

6817 "files) and write a size+SHA-256 manifest of the data root (-> ml/evaluation/data_audit.json). No model.", 

6818 ) 

6819 evaluate_parser.add_argument( 

6820 "--data-root", default=None, help="With --audit-data, the Lean data root to audit (default: data).", 

6821 ) 

6822 evaluate_parser.add_argument( 

6823 "--audit-heads", action="store_true", 

6824 help="Every model head and submodel against its own promotion gate, marking what the live path reads " 

6825 "(-> ml/evaluation/head_audit.json). Reads only ml/*_training_metrics.json.", 

6826 ) 

6827 evaluate_parser.add_argument( 

6828 "--audit-leakage", action="store_true", 

6829 help="Label/feature leakage audit - tail NaN, label shuffle, single-feature IC, asset-identity prior " 

6830 "(-> ml/evaluation/leakage_audit.json).", 

6831 ) 

6832 evaluate_parser.add_argument( 

6833 "--overfit-report", action="store_true", 

6834 help="Train / validation / backtest rank IC per head and the gap (-> ml/evaluation/overfit_report.json).", 

6835 ) 

6836 evaluate_parser.add_argument( 

6837 "--pbo", action="store_true", 

6838 help="Probability of backtest overfitting (CSCV) over a trials' daily-returns table (-> ml/evaluation/pbo.json).", 

6839 ) 

6840 evaluate_parser.add_argument( 

6841 "--trial-returns", default=None, 

6842 help="With --pbo, a parquet/csv of daily returns, one column per trial (default: ml/evaluation/v643/trial_returns.parquet).", 

6843 ) 

6844 evaluate_parser.add_argument( 

6845 "--factor-spanning", action="store_true", 

6846 help="Regress a signal's long/short return on five factor baselines; needs --signal " 

6847 "(-> ml/evaluation/factor_spanning.json).", 

6848 ) 

6849 evaluate_parser.add_argument( 

6850 "--signal", default=None, help="With --factor-spanning, a CSV of date,ticker,score.", 

6851 ) 

6852 evaluate_parser.add_argument( 

6853 "--calibrate-sim-lean", action="store_true", 

6854 help="Decompose the offline-vs-Lean gap of a scripts/lean_calibration.py report rung by rung; needs " 

6855 "--calibration-file (-> ml/evaluation/sim_lean_gap.json).", 

6856 ) 

6857 evaluate_parser.add_argument( 

6858 "--calibration-file", default=None, help="With --calibrate-sim-lean, the lean_calibration.py JSON report.", 

6859 ) 

6860 evaluate_parser.add_argument( 

6861 "--audit-features", action="store_true", 

6862 help="Model-input feature quality - ticker-ID suspects, class-constant features, per-split IC sign " 

6863 "(-> ml/evaluation/feature_quality_audit.json).", 

6864 ) 

6865 evaluate_parser.add_argument( 

6866 "--permutation", action="store_true", 

6867 help="With --audit-features, also the multitask model's validation IC drop per shuffled feature (slow).", 

6868 ) 

6869 evaluate_parser.add_argument( 

6870 "--dataset", default=None, 

6871 help="With --ic-by-class / --audit-gates / --audit-features / --reconcile-features / --reconcile-book-history " 

6872 " (also --audit-fills and the rank-book runs), a dataset CSV other than ml/datasets/full_dataset.csv, which " 

6873 "holds all four splits (train / validation / backtest / holdout).", 

6874 ) 

6875 evaluate_parser.add_argument("--model", choices=["sequence", "multitask"], default=None, help="Default: sequence") 

6876 evaluate_parser.add_argument("--head", default=None, help="Model head to evaluate, e.g. rank_20d/rank_5d (default: rank_20d)") 

6877 evaluate_parser.add_argument("--split", default=None, help="Dataset split to evaluate: train/validation/backtest/all (default: backtest)") 

6878 evaluate_parser.add_argument( 

6879 "--preset", default=None, 

6880 help="Overlay phase_v2.presets.<name> in memory only (never writes config.json) - see `aq config preset --list`", 

6881 ) 

6882 evaluate_parser.add_argument("--json", action="store_true", help="Print the full report as JSON instead of a summary") 

6883 evaluate_parser.add_argument("--list", action="store_true", help="List the tool groups and their flags, and stop") 

6884 evaluate_parser.set_defaults(func=cmd_evaluate) 

6885 

6886 render_lean_parser = subparsers.add_parser( 

6887 "render-lean-config", 

6888 help="Render gitignored lean.live.json from .env.live / AETHER_* env vars (secrets for live/paper)", 

6889 ) 

6890 render_lean_parser.add_argument("--base", default=None, help="Empty tracked template (default: lean.json)") 

6891 render_lean_parser.add_argument("--out", default=None, help="Rendered secret-bearing output (default: lean.live.json)") 

6892 render_lean_parser.add_argument("--env-file", dest="env_file", default=None, help="Secrets file (default: .env.live)") 

6893 render_lean_parser.add_argument("--account", default=None, help="Render one account's secrets (AETHER_<ACCOUNT>_*) into lean.live.<account>.json") 

6894 render_lean_parser.add_argument("--dry-run", action="store_true", help="Print the field names that would be filled (never values), write nothing") 

6895 render_lean_parser.add_argument("--check", action="store_true", help="Exit 1 when the rendered file is missing or differs from what the secrets give") 

6896 render_lean_parser.set_defaults(func=cmd_render_lean_config) 

6897 

6898 users_parser = subparsers.add_parser("users", help="Dashboard and API users: viewer, operator (may lock an account), admin (may unlock)") 

6899 users_subparsers = users_parser.add_subparsers(dest="users_command", required=True) 

6900 users_add_parser = users_subparsers.add_parser("add", help="Add a user and print their token once") 

6901 users_add_parser.add_argument("name") 

6902 users_add_parser.add_argument("--role", default="viewer", help="viewer, operator or admin") 

6903 users_add_parser.add_argument("--accounts", default="*", help="Comma-separated account ids this user may act on (default: all)") 

6904 users_list_parser = users_subparsers.add_parser("list", help="Every user, role and account scope (no tokens)") 

6905 users_list_parser.add_argument("--json", action="store_true", help="Print JSON instead of text") 

6906 users_rotate_parser = users_subparsers.add_parser("rotate", help="Issue a user a new token (printed once); the old one stops working") 

6907 users_rotate_parser.add_argument("name") 

6908 users_rotate_parser.add_argument("--yes", action="store_true", help="Confirm without a prompt (needed without a terminal)") 

6909 users_remove_parser = users_subparsers.add_parser("remove", help="Remove a user (revokes their token)") 

6910 users_remove_parser.add_argument("name") 

6911 users_remove_parser.add_argument("--yes", action="store_true", help="Confirm without a prompt (needed without a terminal)") 

6912 users_parser.set_defaults(func=cmd_users) 

6913 

6914 live_readiness_parser = subparsers.add_parser("live-readiness", help="The paper-to-live scorecard: every condition for live capital, measured (exit 1 unless ready)") 

6915 live_readiness_parser.add_argument("--account", default=None, help="Score one account (accounts.json); default: the default account") 

6916 live_readiness_parser.add_argument("--paper-check", default=None, metavar="FILE", help="`aq evaluate --paper-check`'s JSON report, for the paper metrics") 

6917 live_readiness_parser.add_argument("--markdown", action="store_true", help="Print the scorecard as a Markdown table") 

6918 live_readiness_parser.add_argument("--json", default=None, metavar="FILE", help="Also write the scorecard here") 

6919 live_readiness_parser.add_argument("--no-write", action="store_true", help="Do not write visualization/grafana/live_readiness.json") 

6920 live_readiness_parser.add_argument("--docs", action="store_true", help="Also write the scorecard into docs/live/paper-to-live.md's generated block") 

6921 live_readiness_parser.set_defaults(func=cmd_live_readiness) 

6922 

6923 accounts_parser = subparsers.add_parser("accounts", help="The account registry (accounts.json): list, validate, status of each deployment") 

6924 accounts_subparsers = accounts_parser.add_subparsers(dest="accounts_command", required=True) 

6925 accounts_list_parser = accounts_subparsers.add_parser("list", help="Every account and its broker, environment and mode") 

6926 accounts_list_parser.add_argument("--json", dest="print_json", action="store_true", help="Print JSON instead of text") 

6927 accounts_validate_parser = accounts_subparsers.add_parser("validate", help="Parse accounts.json against config.json: ids, brokers, overrides that only tighten") 

6928 accounts_validate_parser.add_argument("--json", dest="print_json", action="store_true", help="Print JSON instead of text") 

6929 accounts_status_parser = accounts_subparsers.add_parser("status", help="Each account's secrets (resolved or not) and last state") 

6930 accounts_status_parser.add_argument("--json", default=None, metavar="FILE", help="Also write the rows") 

6931 accounts_parser.set_defaults(func=cmd_accounts) 

6932 

6933 live_parser = subparsers.add_parser("live", help="Start or stop one account's Lean live deployment (docker compose lean-live)") 

6934 live_subparsers = live_parser.add_subparsers(dest="live_command", required=True) 

6935 for _live_name, _live_help in (("up", "Start the account's live/paper deployment"), ("down", "Stop and remove it"), ("status", "Whether the account's container runs")): 

6936 _live_sub = live_subparsers.add_parser(_live_name, help=_live_help) 

6937 _live_sub.add_argument("--account", default="", help="The account id (default: the default account)") 

6938 if _live_name == "status": 

6939 _live_sub.add_argument("--json", action="store_true", help="Print JSON instead of text") 

6940 continue 

6941 _live_sub.add_argument("--dry-run", action="store_true", help="Print the commands instead of running them") 

6942 if _live_name == "up": 

6943 _live_sub.add_argument("--yes", action="store_true", help="Confirm a live (real-money) start without a prompt") 

6944 live_parser.set_defaults(func=cmd_live) 

6945 

6946 secrets_parser = subparsers.add_parser("secrets", help="Where each credential comes from (file, Docker secret, env, keyring), and keyring storage; never prints a value") 

6947 secrets_parser.add_argument("--account", default=None, help="One account's secrets (AETHER_<ACCOUNT>_*); default: the default account") 

6948 secrets_subparsers = secrets_parser.add_subparsers(dest="secrets_command", required=True) 

6949 secrets_status_parser = secrets_subparsers.add_parser("status", help="Each known secret: resolved or not, and from where") 

6950 secrets_status_parser.add_argument("--json", default=None, metavar="FILE", help="Also write the status (names and sources only)") 

6951 secrets_set_parser = secrets_subparsers.add_parser("set", help="Store a secret in the OS keyring (prompted, never echoed)") 

6952 secrets_set_parser.add_argument("name", help="e.g. IB_PASSWORD, COINBASE_API_SECRET") 

6953 secrets_delete_parser = secrets_subparsers.add_parser("delete", help="Remove a secret from the OS keyring") 

6954 secrets_delete_parser.add_argument("name") 

6955 secrets_delete_parser.add_argument("--yes", action="store_true", help="Confirm without a prompt (needed without a terminal)") 

6956 secrets_parser.set_defaults(func=cmd_secrets) 

6957 

6958 secrets_check_parser = subparsers.add_parser( 

6959 "secrets-check", 

6960 help="Fail if a populated secret field in lean.json or a tracked .env is about to be committed (backs the pre-commit hook)", 

6961 ) 

6962 secrets_check_parser.add_argument("--json", action="store_true", help="Print the findings as JSON (field names only, never values)") 

6963 secrets_check_parser.set_defaults(func=cmd_secrets_check) 

6964 

6965 audit_log_parser = subparsers.add_parser( 

6966 "audit-log", 

6967 help="Query the tamper-evident audit log (order placement, credential loads, live-mode transitions)", 

6968 ) 

6969 audit_log_parser.add_argument("--event-type", dest="event_type", default=None, 

6970 choices=["order_placement", "credential_load", "live_mode_transition"], 

6971 help="Filter to one event type (default: all)") 

6972 audit_log_parser.add_argument("--since", default=None, type=_iso_date, help="Only entries after this date, ISO 8601 YYYY-MM-DD") 

6973 audit_log_parser.add_argument("--limit", type=int, default=100, help="Max entries to show (default: 100)") 

6974 audit_log_parser.add_argument("--verify", action="store_true", help="Walk the whole hash chain and report the first break, if any") 

6975 audit_log_parser.add_argument("--until", default=None, type=_iso_date, help="Only entries on or before this date, ISO 8601 YYYY-MM-DD") 

6976 audit_log_parser.add_argument("--export", default=None, metavar="FILE", help="Write the matching entries as JSON lines") 

6977 audit_log_parser.add_argument("--json", action="store_true", help="Print the entries as JSON") 

6978 audit_log_parser.set_defaults(func=cmd_audit_log) 

6979 

6980 docs_parser = subparsers.add_parser("docs", help="Keep the numbers quoted in the docs true") 

6981 docs_subparsers = docs_parser.add_subparsers(dest="docs_command", required=True) 

6982 docs_sync_parser = docs_subparsers.add_parser("sync", help="Rewrite every <!--fact:key--> value and generated AQ block from its source") 

6983 docs_sync_parser.add_argument("--check", action="store_true", help="Change nothing; exit 1 if a value is stale") 

6984 docs_sync_parser.add_argument("--json", action="store_true", help="Print the stale and unknown keys as JSON") 

6985 docs_sync_parser.set_defaults(func=cmd_docs_sync) 

6986 import aq_devtools as _devtools 

6987 

6988 docs_build_parser = docs_subparsers.add_parser("build", help="Build the documentation site (scripts/build_docs.py, then mkdocs build)") 

6989 docs_build_parser.add_argument("--strict", action="store_true", help="Fail on any warning, as CI's docs job does") 

6990 docs_build_parser.set_defaults(func=_devtools.cmd_docs_extra) 

6991 docs_serve_parser = docs_subparsers.add_parser("serve", help="Serve the site locally with live reload") 

6992 docs_serve_parser.add_argument("--port", type=int, default=8000, help="Port (default 8000)") 

6993 docs_serve_parser.set_defaults(func=_devtools.cmd_docs_extra) 

6994 docs_cli_parser = docs_subparsers.add_parser("cli", help="Regenerate docs/reference/cli.md from the parser") 

6995 docs_cli_parser.add_argument("--check", action="store_true", help="Change nothing; exit 1 if the page is stale") 

6996 docs_cli_parser.set_defaults(func=_devtools.cmd_docs_extra) 

6997 docs_links_parser = docs_subparsers.add_parser("links", help="Every relative link and anchor in the docs resolves (exit 1 on a broken one)") 

6998 docs_links_parser.add_argument("--external", action="store_true", help="Also check http(s) links (network)") 

6999 docs_links_parser.add_argument("--json", action="store_true", help="Print the broken links as JSON") 

7000 docs_links_parser.set_defaults(func=_devtools.cmd_docs_extra) 

7001 

7002 verify_parser = subparsers.add_parser("verify", help="Every way to verify the project: the table, and the checks a small machine can run") 

7003 verify_parser.add_argument("--list", action="store_true", help="Print the table of verification surfaces (default)") 

7004 verify_parser.add_argument("--quick", action="store_true", help="Run the checks that fit a 4 GB machine: ruff, doc facts, the library gate, the sorry scan, secrets, the guard tests") 

7005 verify_parser.add_argument("--record", default=None, metavar="FILE", help="Run --quick and write the results as JSON") 

7006 verify_parser.add_argument("--write-doc", action="store_true", help="Regenerate the table in development/verification.md") 

7007 verify_parser.add_argument("--json", action="store_true", help="With --quick: print the results as JSON") 

7008 verify_parser.set_defaults(func=cmd_verify) 

7009 

7010 import aq_devtools 

7011 import aq_lab_cli 

7012 import aq_testtools 

7013 

7014 aq_devtools.register(subparsers) 

7015 aq_testtools.register(subparsers) 

7016 aq_lab_cli.register(subparsers) 

7017 _finish_parsers(parser) 

7018 return parser 

7019 

7020 

7021def run_command(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int: 

7022 """The command's exit code; Ctrl-C is 130, and an unexpected error is one line (the traceback with --debug or AQ_DEBUG=1).""" 

7023 if getattr(args, "version", False) and not getattr(args, "command", None): 

7024 import aq_devtools 

7025 

7026 print(aq_devtools._render_version(aq_devtools.version_info()).splitlines()[0]) 

7027 return 0 

7028 if not getattr(args, "command", None): 

7029 parser.print_help() 

7030 return 2 

7031 try: 

7032 return int(args.func(args) or 0) 

7033 except KeyboardInterrupt: 

7034 print("aq: interrupted", file=sys.stderr) 

7035 return 130 

7036 except Exception as error: # the top of the CLI: every command's unexpected failure ends here as one line 

7037 if getattr(args, "debug", False) or os.environ.get("AQ_DEBUG"): 

7038 raise 

7039 print(f"aq {args.command}: {type(error).__name__}: {error} (rerun with --debug for the traceback)", file=sys.stderr) 

7040 return 1 

7041 

7042 

7043def _safe_streams() -> None: 

7044 """A Windows console in cp1252 cannot print the status marks (✓, 🟢); replace what it cannot encode instead of crashing.""" 

7045 for stream in (sys.stdout, sys.stderr): 

7046 try: 

7047 stream.reconfigure(errors="replace") 

7048 except (AttributeError, ValueError): # a replaced stream (pytest's capture) has no reconfigure 

7049 pass 

7050 

7051 

7052def main(argv: list[str] | None = None) -> None: 

7053 _safe_streams() 

7054 parser = build_parser() 

7055 args = parser.parse_args(argv) 

7056 exit_code = run_command(args, parser) 

7057 if sys.stderr.isatty() and not getattr(args, "json", False): 

7058 check_for_update() 

7059 sys.exit(exit_code) 

7060 

7061 

7062if __name__ == "__main__": 

7063 main()