Coverage for scripts/v644_rcal5.py: 100%

90 statements  

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

1"""R-CAL5 (V6.4.4, rule in ml/evaluation/v644/r_cal5_rule.json, the #249 lead): re-derive the simulator's live-gate replicas 

2from the engine's own trades. 

3 

4 audit for BT5 / BT7 / BT8: classify Lean's main-book trades (from the fills) and the calibrated simulator's (from its 

5 weights) into entries, exits, flips and resizes on and off live's rebalance dates 

6 (evaluation/gate_replica_audit.py) -> ml/evaluation/v644/gate_replica_audit.json 

7 score run each candidate rung (a `simulate_rank_book` keyword set on top of the calibrated rung) through 

8 scripts/lean_calibration.run_window on the three runs and decide it by R-CAL5 -> r_cal5_result.json 

9 

10 python scripts/v644_rcal5.py audit 

11 python scripts/v644_rcal5.py score --candidate '<name>={"key": value, ...}' [...] 

12""" 

13 

14from __future__ import annotations 

15 

16import argparse 

17import json 

18import sys 

19from pathlib import Path 

20 

21ROOT_DIR = Path(__file__).resolve().parents[1] 

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

23sys.path.insert(0, str(ROOT_DIR / "scripts")) 

24 

25OUT_DIR = ROOT_DIR / "ml" / "evaluation" / "v644" 

26WINDOWS = { 

27 "bt5": "bt5=backtests/2026-10-22_10-56-13@2023-07-01..2026-10-16:backtest+holdout", 

28 "bt7": "bt7=backtests/2026-10-24_05-28-07@2023-07-01..2026-10-16:backtest+holdout", 

29 "bt8": "bt8=backtests/2026-10-24_18-50-22@2023-07-01..2026-10-16:backtest+holdout", 

30} 

31MIN_GAIN = 0.05 

32BRANCH_A = 0.9 

33 

34 

35def main_book_tickers(config: dict) -> set[str]: 

36 """Tickers the main book trades: equities that are not bond ETFs, and crypto (the T-bill sweep and sleeves excluded).""" 

37 sweep = str((config["phase_v2"].get("cash_sweep") or {}).get("ticker", "BIL")).upper() 

38 out = set() 

39 for asset in config["phase1"]["universe"]["assets"]: 

40 kind = str(asset.get("asset_class") or asset.get("security_type")) 

41 if kind in ("equity", "crypto") and str(asset["ticker"]).upper() != sweep: 

42 out.add(str(asset["ticker"]).upper()) 

43 return out 

44 

45 

46def audit_window(text: str, dataset: Path, config: dict) -> dict: 

47 from as_live_levers import AsLiveHarness 

48 from lean_calibration import live_decisions, parse_window, rebalance_phase, topology_inputs_fn_for, window_config 

49 

50 from evaluation.backtest_audit import load_backtest_run 

51 from evaluation.gate_replica_audit import compare_profiles, lean_trades, offline_trades, trade_profile 

52 from evaluation.lean_attribution import fills_from_order_events, find_book_history_for_run 

53 

54 window = parse_window(text) 

55 config = window_config(window, config) 

56 run_dir = ROOT_DIR / window["run_dir"] 

57 run = load_backtest_run(run_dir) 

58 history_path = find_book_history_for_run(run_dir, ROOT_DIR / "visualization" / "book_history") 

59 history = [json.loads(line) for line in history_path.read_text(encoding="utf-8").splitlines() if line.strip()] 

60 live = live_decisions(history, window["start"], window["end"]) 

61 harness = AsLiveHarness(window["splits"], dataset_path=dataset, config=config) 

62 sessions = sorted(harness.session_dates) 

63 in_window = [date for date in sessions if window["start"] <= date <= window["end"]] 

64 phase = rebalance_phase(min(live) if live else None, sessions, int(config["phase_v2"]["portfolio_book"]["rebalance_every_bars"])) 

65 harness.topology_inputs_fn = topology_inputs_fn_for(harness, config) 

66 harness._mechanisms.clear() 

67 from lean_calibration import ANALYZER_INCLUDE 

68 

69 # the research default (scripts/v643_research.Chain.as_live): the calibrated rung plus the V6.1.0 mechanisms 

70 mechanisms = harness.v610_mechanisms(config, legacy=False) 

71 result = harness.as_live(log_weights=True, rebalance_counter_start=phase, intraday_next_return_column="next_intraday_return", 

72 min_commission_usd_by_ticker=harness.min_commission_usd_by_ticker, 

73 assumed_portfolio_value_usd=harness.initial_cash, include=ANALYZER_INCLUDE, **mechanisms) 

74 keep = [i for i, date in enumerate(result.per_date) if window["start"] <= date <= window["end"]] 

75 offline = offline_trades([result.per_date[i] for i in keep], [result.weights_log[i] for i in keep]) 

76 tickers = main_book_tickers(config) 

77 lean = [trade for trade in lean_trades(fills_from_order_events(run["order_events"]), tickers) 

78 if window["start"] <= trade["date"] <= window["end"]] 

79 rebalance_dates = sorted(live) 

80 lean_profile = trade_profile(lean, rebalance_dates, in_window, lag_sessions=1) 

81 offline_profile = trade_profile(offline, rebalance_dates, in_window) 

82 return {"window": window["name"], "lean": lean_profile, "offline": offline_profile, 

83 "compare": compare_profiles(lean_profile, offline_profile), "live_rebalance_dates": len(rebalance_dates)} 

84 

85 

86def verdict(name: str, base: dict, cand: dict) -> dict: 

87 gains = {w: (cand[w] - base[w]) if cand.get(w) is not None and base.get(w) is not None else None for w in base} 

88 checks = { 

89 "bt5_gain_ge_0.05": gains["bt5"] is not None and gains["bt5"] >= MIN_GAIN, 

90 "bt7_not_lower": gains["bt7"] is not None and gains["bt7"] >= 0.0, 

91 "bt8_not_lower": gains["bt8"] is not None and gains["bt8"] >= 0.0, 

92 } 

93 adopted = all(checks.values()) 

94 best = cand if adopted else base 

95 return {"candidate": name, "base_correlation": base, "candidate_correlation": cand, "gains": gains, "checks": checks, 

96 "adopted": adopted, "branch": "A" if all(v is not None and v >= BRANCH_A for v in best.values()) else "B"} 

97 

98 

99def main() -> int: 

100 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 

101 parser.add_argument("mode", choices=["audit", "score"]) 

102 parser.add_argument("--dataset", default=str(ROOT_DIR / "ml" / "datasets" / "full_dataset.csv")) 

103 parser.add_argument("--candidate", action="append", default=[], help='name={"simulate_rank_book keyword": value, ...}') 

104 parser.add_argument("--windows", nargs="*", default=list(WINDOWS)) 

105 args = parser.parse_args() 

106 config = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8")) 

107 if args.mode == "audit": 

108 out = {name: audit_window(WINDOWS[name], Path(args.dataset), config) for name in args.windows} 

109 (OUT_DIR / "gate_replica_audit.json").write_text(json.dumps(out, indent=1), encoding="utf-8") 

110 for name, entry in out.items(): 

111 print(name, json.dumps({k: entry["compare"]["rows"][k] for k in entry["compare"]["ranked"][:4]}), 

112 entry["compare"]["median_sessions_between_trades"], flush=True) 

113 return 0 

114 from lean_calibration import BOOK_COMPONENTS, parse_window, run_window 

115 

116 candidates = {} 

117 for text in args.candidate: 

118 name, _, payload = text.partition("=") 

119 candidates[name] = {"base": "v610_mechanisms", **json.loads(payload)} 

120 results, rows = {}, {} 

121 base = {} 

122 for window in args.windows: 

123 report = run_window(parse_window(WINDOWS[window]), Path(args.dataset), config, BOOK_COMPONENTS, extra_ladder=candidates, 

124 rcal2=True) 

125 base[window] = report["variants"]["v610_mechanisms"].get("daily_correlation") 

126 rows[window] = {name: {k: v for k, v in report["variants"][name].items() if k != "disagreement"} for name in candidates} 

127 for name in candidates: 

128 cand = {window: rows[window][name].get("daily_correlation") for window in args.windows} 

129 results[name] = verdict(name, base, cand) 

130 out = {"results": results, "rows": rows} 

131 (OUT_DIR / "r_cal5_result.json").write_text(json.dumps(out, indent=1, default=str), encoding="utf-8") 

132 print("R-CAL5:", json.dumps({n: {k: r[k] for k in ("gains", "adopted")} for n, r in results.items()}, default=str)) 

133 return 0 

134 

135 

136if __name__ == "__main__": 

137 raise SystemExit(main())