Coverage for scripts/v650_instrument.py: 100%

178 statements  

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

1"""V6.5.0 instrument batch: the run configs that test the target-weights path against the offline engine, and the comparison. 

2 

3 python scripts/v650_instrument.py make # weight files and run configs of BT12-BT23 

4 python scripts/v650_instrument.py compare <name> <backtests/run> # R-INSTR1 for one run 

5 python scripts/v650_instrument.py orders <backtests/a> <backtests/b> # are two runs the same, order for order? 

6 

7The plumbing weights are random on purpose. They carry no signal and cannot be selected, so running them on any window 

8reads nothing about any candidate. The window predates the verification data and spans a crypto fee change and March 2020. 

9""" 

10 

11from __future__ import annotations 

12 

13import argparse 

14import copy 

15import datetime 

16import hashlib 

17import json 

18import sys 

19from pathlib import Path 

20 

21import numpy as np 

22 

23ROOT = Path(__file__).resolve().parents[1] 

24sys.path.insert(0, str(ROOT)) 

25sys.path.insert(0, str(ROOT / "scripts")) 

26 

27from evaluation.target_weights_engine import MarketPanel, load_market_panel, simulate_target_weights # noqa: E402 

28from portfolio.financing import load_rate_series # noqa: E402 

29from portfolio.target_weights import load_weight_file, resolve_target_weights_config, write_weight_file # noqa: E402 

30 

31V650 = ROOT / "ml" / "evaluation" / "v650" 

32WEIGHTS = V650 / "weights" 

33RUN_CONFIGS = ROOT / "ml" / "evaluation" / "run_configs" 

34PLUMBING_WINDOW = ("2019-01-01", "2020-12-31") 

35VERIFICATION_WINDOW = ("2023-07-01", "2026-11-02") 

36RATE_CSV = ROOT / "data" / "alternative" / "interest-rate" / "usa" / "interest-rate.csv" 

37 

38 

39def target_path_config(base: dict, *, weights_path: str, weights_sha256: str, window: tuple[str, str], locks: bool = True) -> dict: 

40 """A run of the target-weights path under the risk settings of the plan's §3.4. `locks=False` is for plumbing 

41 weights, whose purpose is to compare the two engines over the whole window: they are random, not risk-controlled.""" 

42 config = copy.deepcopy(base) 

43 config["phase_v2"]["target_weights"].update({"enabled": True, "weights_path": weights_path, "weights_sha256": weights_sha256}) 

44 config["runtime"]["lean_window_override"] = {"start": window[0], "end": window[1]} 

45 config["phase6"]["risk"]["max_total_drawdown_pct"] = 0.15 if locks else 0.95 

46 config["phase6"]["risk"]["max_daily_drawdown_pct"] = 0.05 if locks else 0.95 

47 config["phase_v2"]["backtest"]["bypass_sticky_trade_lock"] = False 

48 kill = config["phase_v2"]["risk"]["kill_switch"] 

49 # off (rules_amendment_1.json): sticky at 3 x 7% / sqrt(252), one ordinary bad crypto day ended every run within months 

50 kill["max_drawdown_velocity_pct_per_bar"] = 1.0 

51 kill["min_rolling_sharpe"] = -100.0 

52 kill["min_live_rank_ic"] = -100.0 

53 kill["max_consecutive_losses"] = 100000 

54 kill["max_slippage_divergence_bps"] = 100000 

55 return config 

56 

57 

58def random_weights(panel: MarketPanel, tickers: list[str], *, seed: int, start: str, end: str, every: int, gross: float, neutral: bool) -> dict: 

59 rng = np.random.default_rng(seed) 

60 sessions = [date for date in panel.dates if date in panel.sessions and start <= date <= end] 

61 index = panel.index() 

62 rows: dict[str, dict[str, float]] = {} 

63 for position, date in enumerate(sessions): 

64 if position % every: 

65 continue 

66 row = panel.dates.index(date) 

67 live = [ticker for ticker in tickers if np.isfinite(panel.closes[max(0, row - 3):row + 1, index[ticker]]).any()] 

68 if not live: 

69 rows[date] = {} 

70 continue 

71 raw = rng.normal(size=len(live)) 

72 if neutral: 

73 raw -= raw.mean() 

74 else: 

75 raw = np.abs(raw) 

76 scale = gross / np.abs(raw).sum() 

77 rows[date] = {ticker: float(value * scale) for ticker, value in zip(live, raw, strict=False)} 

78 return rows 

79 

80 

81def oracle_weights(panel: MarketPanel, tickers: list[str], *, start: str, end: str, every: int, gross: float) -> dict: 

82 """Long the next period's winners and short its losers, using the future. A test of the machinery: what a perfect 

83 signal earns through this path, as a ceiling. Never selectable.""" 

84 index = panel.index() 

85 sessions = [date for date in panel.dates if date in panel.sessions and start <= date <= end] 

86 rows: dict[str, dict[str, float]] = {} 

87 for position in range(0, len(sessions) - every - 1, every): 

88 now = panel.dates.index(sessions[position + 1]) 

89 later = panel.dates.index(sessions[position + 1 + every]) 

90 moves = {} 

91 for ticker in tickers: 

92 first, last = panel.opens[now, index[ticker]], panel.opens[later, index[ticker]] 

93 if np.isfinite(first) and np.isfinite(last) and first > 0.0: 

94 moves[ticker] = last / first - 1.0 

95 ranked = sorted(moves, key=moves.get) 

96 count = min(6, len(ranked) // 2) 

97 if count == 0: 

98 continue 

99 weight = gross / (2 * count) 

100 rows[sessions[position]] = {**dict.fromkeys(ranked[-count:], weight), **dict.fromkeys(ranked[:count], -weight)} 

101 return rows 

102 

103 

104def _write_config(name: str, config: dict) -> str: 

105 text = json.dumps(config, indent=4) 

106 path = RUN_CONFIGS / f"{name}.json" 

107 path.write_text(text, encoding="utf-8", newline="\n") 

108 return hashlib.sha256(text.encode("utf-8")).hexdigest() 

109 

110 

111def make() -> dict: 

112 from v610_research import apply_dotted 

113 

114 base = json.loads((ROOT / "config.json").read_text(encoding="utf-8")) 

115 panel = load_market_panel(ROOT, base) 

116 WEIGHTS.mkdir(parents=True, exist_ok=True) 

117 classes = panel.asset_class 

118 equities = [t for t in panel.tickers if classes[t] == "equity"] 

119 bonds = [t for t in panel.tickers if classes[t] == "bond"] 

120 forex = [t for t in panel.tickers if classes[t] == "forex"] 

121 crypto = [t for t in ("BTCUSD", "ETHUSD", "LTCUSD") if t in classes] 

122 start, end = PLUMBING_WINDOW 

123 

124 files = { 

125 "plumbing_equity": random_weights(panel, equities, seed=11, start=start, end=end, every=5, gross=1.0, neutral=True), 

126 "plumbing_crypto": random_weights(panel, crypto, seed=12, start=start, end=end, every=5, gross=0.3, neutral=False), 

127 "plumbing_oracle": oracle_weights(panel, equities, start=start, end=end, every=5, gross=1.0), 

128 } 

129 mixed = random_weights(panel, equities + bonds, seed=13, start=start, end=end, every=5, gross=0.8, neutral=True) 

130 mixed_fx = random_weights(panel, forex, seed=14, start=start, end=end, every=5, gross=0.4, neutral=True) 

131 mixed_crypto = random_weights(panel, crypto, seed=15, start=start, end=end, every=5, gross=0.1, neutral=False) 

132 files["plumbing_mixed"] = {date: {**mixed[date], **mixed_fx.get(date, {}), **mixed_crypto.get(date, {})} for date in mixed} 

133 

134 manifest: dict[str, dict] = {} 

135 runs = {"v650_bt13": "plumbing_equity", "v650_bt14": "plumbing_crypto", "v650_bt15": "plumbing_mixed", 

136 "v650_bt16": "plumbing_equity", "v650_bt17": "plumbing_oracle"} 

137 hashes = {name: write_weight_file(rows, WEIGHTS / f"{name}.csv") for name, rows in files.items()} 

138 for run, name in runs.items(): 

139 config = target_path_config(base, weights_path=f"ml/evaluation/v650/weights/{name}.csv", weights_sha256=hashes[name], 

140 window=PLUMBING_WINDOW, locks=name == "plumbing_oracle") 

141 manifest[run] = {"weights": name, "weights_sha": hashes[name], "config_sha": _write_config(run, config), "role": "plumbing"} 

142 

143 # BT11's window, not the root config's (whose default window stops at the end of the backtest split) 

144 gated = copy.deepcopy(base) 

145 gated["runtime"]["lean_window_override"] = {"start": VERIFICATION_WINDOW[0], "end": VERIFICATION_WINDOW[1]} 

146 manifest["v650_bt12"] = {"role": "plumbing", "config_sha": _write_config("v650_bt12", gated), "is": "BT11's book on the new code, flag off"} 

147 

148 ablations = { 

149 "v650_bt18": ("rolling IC gate off", {"rolling_ic_gate.enabled": False}), 

150 "v650_bt19": ("risk-off override off", {"regime_detection.risk_off_override_min_severity": 2.0}), 

151 "v650_bt20": ("spread floor 0", {"portfolio_book.min_rank_confidence_spread": 0.0}), 

152 "v650_bt21": ("non-model exits off", {"exits.enabled": False}), 

153 "v650_bt22": ("cost sizing off", {"costs.cost_sizing_enabled": False}), 

154 } 

155 everything: dict = {} 

156 for run, (label, changes) in ablations.items(): 

157 everything.update(changes) 

158 manifest[run] = {"role": "candidate", "is": label, "config_sha": _write_config(run, apply_dotted(gated, changes))} 

159 manifest["v650_bt23"] = {"role": "candidate", "is": "all five off", "config_sha": _write_config("v650_bt23", apply_dotted(gated, everything))} 

160 (V650 / "instrument_manifest.json").write_text(json.dumps(manifest, indent=1), encoding="utf-8", newline="\n") 

161 return manifest 

162 

163 

164def _engine_for(run_config: dict, panel: MarketPanel) -> dict: 

165 target = run_config["phase_v2"]["target_weights"] 

166 config = resolve_target_weights_config(target) 

167 weights = load_weight_file(ROOT / target["weights_path"], target["weights_sha256"]) 

168 window = run_config["runtime"]["lean_window_override"] 

169 rf_dates, rf_rates = load_rate_series(RATE_CSV) 

170 from data_pipeline.fred_backfill import load_cached_fred_series 

171 from features.fx_carry import fx_carry_3m 

172 

173 fred = load_cached_fred_series() 

174 kill = run_config["phase_v2"]["risk"]["kill_switch"] 

175 return simulate_target_weights( 

176 weights, panel, config, start=window["start"], end=window["end"], sweep_config=run_config["phase_v2"]["cash_sweep"], 

177 rf_dates=rf_dates, rf_rates=rf_rates, 

178 carry_fn=lambda ticker, date: fx_carry_3m(ticker, "forex", datetime.date.fromisoformat(date), fred), 

179 max_total_drawdown=run_config["phase6"]["risk"]["max_total_drawdown_pct"], 

180 max_drawdown_velocity=kill["max_drawdown_velocity_pct_per_bar"], 

181 ) 

182 

183 

184def compare(name: str, run_dir: Path) -> dict: 

185 """Daily correlation and annual return gap of the engine against one finished Lean run (rule R-INSTR1).""" 

186 import pandas as pd 

187 

188 from evaluation.backtest_audit import daily_equity_from_chart, load_backtest_run 

189 

190 run_config = json.loads((RUN_CONFIGS / f"{name}.json").read_text(encoding="utf-8")) 

191 panel = load_market_panel(ROOT, run_config) 

192 engine = _engine_for(run_config, panel) 

193 points = daily_equity_from_chart(load_backtest_run(run_dir)["result"]) 

194 lean_nav = pd.Series(dict(points), dtype=float).sort_index() 

195 window = run_config["runtime"]["lean_window_override"] 

196 lean_nav = lean_nav[(lean_nav.index >= window["start"]) & (lean_nav.index <= window["end"])] 

197 lean = lean_nav.pct_change().dropna() 

198 report: dict = {"name": name, "run": str(run_dir), "lean_days": int(len(lean)), "engine_days": int(len(engine["total"]))} 

199 for lag in (-1, 0, 1): 

200 joined = pd.concat([lean, engine["total"].shift(lag)], axis=1, join="inner").dropna() 

201 report[f"corr_lag{lag}"] = float(joined.corr().iloc[0, 1]) if len(joined) > 10 else None 

202 weekly = pd.concat([(1 + lean).groupby(pd.to_datetime(lean.index).to_period("W")).prod() - 1, 

203 (1 + engine["total"]).groupby(pd.to_datetime(engine["total"].index).to_period("W")).prod() - 1], 

204 axis=1, join="inner").dropna() 

205 report["corr_weekly"] = float(weekly.corr().iloc[0, 1]) if len(weekly) > 5 else None 

206 years = max(len(lean) / 365.25, 1e-9) 

207 report["lean_total_return"] = float(lean_nav.iloc[-1] / lean_nav.iloc[0] - 1.0) 

208 report["engine_total_return"] = float(engine["nav"].iloc[-1] / engine["nav"].iloc[0] - 1.0) 

209 report["annual_gap_bps"] = float((report["engine_total_return"] - report["lean_total_return"]) / years * 1e4) 

210 report["engine_fees"] = engine["fees"] 

211 report["engine_financing"] = engine["financing"] 

212 report["engine_fills"] = engine["fills"] 

213 report["engine_locked_on"] = engine["locked_on"] 

214 return report 

215 

216 

217def orders(first: Path, second: Path) -> dict: 

218 """Are two runs the same, order for order?""" 

219 from evaluation.backtest_audit import load_backtest_run 

220 from evaluation.lean_attribution import fills_from_order_events 

221 

222 def fills(run_dir: Path) -> list[tuple]: 

223 run = load_backtest_run(run_dir) 

224 return [(fill.date, fill.ticker, round(fill.quantity, 6), round(fill.price, 6)) for fill in fills_from_order_events(run.get("order_events", []))] 

225 

226 a, b = fills(first), fills(second) 

227 only_a, only_b = sorted(set(a) - set(b)), sorted(set(b) - set(a)) 

228 return {"first": len(a), "second": len(b), "identical": a == b, "only_first": only_a[:10], "only_second": only_b[:10]} 

229 

230 

231def main() -> int: 

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

233 commands = parser.add_subparsers(dest="command", required=True) 

234 commands.add_parser("make") 

235 compare_parser = commands.add_parser("compare") 

236 compare_parser.add_argument("name") 

237 compare_parser.add_argument("run_dir") 

238 orders_parser = commands.add_parser("orders") 

239 orders_parser.add_argument("first") 

240 orders_parser.add_argument("second") 

241 args = parser.parse_args() 

242 if args.command == "make": 

243 result = make() 

244 elif args.command == "compare": 

245 result = compare(args.name, ROOT / args.run_dir) 

246 else: 

247 result = orders(ROOT / args.first, ROOT / args.second) 

248 print(json.dumps(result, indent=1)) 

249 return 0 

250 

251 

252if __name__ == "__main__": 

253 raise SystemExit(main())