Coverage for scripts/v660_lean.py: 100%

166 statements  

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

1"""V6.6.0's Lean runs: the instrument batch (BT24-BT27) and R-INSTR2. 

2 

3 python scripts/v660_lean.py instrument # writes run configs; every run stays inside free cells 

4 python scripts/v660_lean.py compare <name> <backtests/run> 

5 python scripts/v660_lean.py orders <backtests/a> <backtests/b> # order-for-order, for BT24 against the pin 

6""" 

7 

8from __future__ import annotations 

9 

10import argparse 

11import copy 

12import hashlib 

13import json 

14import sys 

15from pathlib import Path 

16 

17import numpy as np 

18import pandas as pd 

19 

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

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

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

23 

24from v650_instrument import oracle_weights, random_weights, target_path_config # noqa: E402 

25 

26from evaluation.research_cells import coin_side, name_side # noqa: E402 

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

28from evaluation.wide_context import SECTOR_ETFS, project_tickers, wide_config_for # noqa: E402 

29from portfolio.financing import load_rate_series # noqa: E402 

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

31 

32OUT = ROOT / "ml" / "evaluation" / "v660" 

33WEIGHTS = OUT / "weights" 

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

35PIN = "backtests/2026-11-04_18-10-49" 

36# Inside free cells: side A names, inside S; side A coins, inside CS. Oracle weights read the future, which a plumbing run may. 

37WIDE_WINDOW = ("2014-01-02", "2015-12-31") 

38CRYPTO_WINDOW = ("2020-01-02", "2021-12-31") 

39WIDE_PATH = {"min_weight_change": 0.001, "no_bar_exit": True, "no_bar_exit_after": 2, "financing_enabled": True} 

40 

41 

42def write_run(name: str, config: dict, *, data_root: str | None = None) -> dict: 

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

44 (RUN_CONFIGS / f"{name}.json").write_text(text, encoding="utf-8", newline="\n") 

45 dataroot = RUN_CONFIGS / f"{name}.dataroot" 

46 if data_root: 

47 dataroot.write_text(data_root + "\n", encoding="utf-8", newline="\n") 

48 elif dataroot.exists(): 

49 dataroot.unlink() 

50 return {"name": name, "config_sha": hashlib.sha256(text.encode("utf-8")).hexdigest(), "data_root": data_root or "data"} 

51 

52 

53def wide_run(name: str, rows: dict, window: tuple[str, str], base: dict, tickers: set[str], *, data_root: str, locks: bool = False, config_for=None) -> dict: 

54 """A target-path run on a wide root. The run's universe is only the names its weight file holds, which keeps Lean's memory bounded.""" 

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

56 sha = write_weight_file(rows, WEIGHTS / f"{name}.csv") 

57 universe = config_for(base, tickers) if config_for else wide_config_for(base, ROOT, tickers, data_dir=data_root) 

58 config = target_path_config(universe, weights_path=f"ml/evaluation/v660/weights/{name}.csv", weights_sha256=sha, window=window, locks=locks) 

59 config["phase_v2"]["target_weights"].update(WIDE_PATH) 

60 return {**write_run(name, config, data_root=data_root), "weights_sha": sha, "rows": len(rows)} 

61 

62 

63def stopping_name(panel, side_names: list[str], window: tuple[str, str]) -> str | None: 

64 """A side-A name whose bars stop inside the window, to prove `no_bar_exit` in Lean. None if the window has no such name.""" 

65 index = panel.index() 

66 first, last = np.searchsorted(panel.dates, window[0]), np.searchsorted(panel.dates, window[1]) 

67 for ticker in sorted(side_names): 

68 column = panel.closes[:, index[ticker]] 

69 if np.isfinite(column[first]) and not np.isfinite(column[last]): 

70 return ticker 

71 return None 

72 

73 

74def synthetic_stop(root: Path, ticker: str, stop_date: str, data_dir: str) -> dict: 

75 """Cuts one side-A name's bars at `stop_date` in a copy under its own ticker: a stock that stops, when the window's real data holds none.""" 

76 from data_pipeline.data_audit import read_lean_daily_zip 

77 from data_pipeline.yfinance_backfill import scale_for_lean, write_lean_zip 

78 

79 source = root / data_dir / "equity" / "usa" / "daily" / f"{ticker.lower()}.zip" 

80 frame = read_lean_daily_zip(source, "equity") 

81 frame = frame[frame["date"] <= pd.Timestamp(stop_date)] 

82 rows = [{"date": row.date.date(), "open": row.open, "high": row.high, "low": row.low, "close": row.close, "volume": row.volume} for row in frame.itertuples()] 

83 name = "ZZSTOP" 

84 write_lean_zip(root / data_dir / "equity" / "usa" / "daily" / f"{name.lower()}.zip", name, scale_for_lean(rows, "equity"), merge_with_existing=False) 

85 return {"ticker": name, "first": frame["date"].iloc[0].strftime("%Y-%m-%d"), "last": frame["date"].iloc[-1].strftime("%Y-%m-%d")} 

86 

87 

88def make_instrument() -> dict: 

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

90 project = project_tickers(base, "equity") 

91 manifest = json.loads((ROOT / "data_wide" / "wide_manifest.json").read_text(encoding="utf-8")) 

92 side_a = sorted(ticker for ticker, entry in manifest["tickers"].items() if entry.get("member") and name_side(ticker, [*project, *SECTOR_ETFS]) == "A") 

93 usable = [ticker for ticker in side_a if manifest["tickers"][ticker]["first"] < WIDE_WINDOW[0] and manifest["tickers"][ticker]["last"] > WIDE_WINDOW[1]] 

94 runs: dict[str, dict] = {} 

95 

96 # BT24: the installed config on the phase's code, order for order with the pin 

97 gated = copy.deepcopy(base) 

98 gated["runtime"]["lean_window_override"] = {"start": "2023-07-01", "end": "2026-11-02"} 

99 runs["v660_bt24"] = {**write_run("v660_bt24", gated), "role": "plumbing", "is": f"equals {PIN}, order for order"} 

100 

101 # BT25: random long/short ranks across 250 side-A names, and one that stops trading 

102 stop = synthetic_stop(ROOT, sorted(usable)[0], "2015-03-31", "data_wide") 

103 names = sorted(usable)[1:250] 

104 universe = {*names, stop["ticker"]} 

105 wide_tickers = dict(manifest["tickers"]) 

106 wide_tickers[stop["ticker"]] = {"first": stop["first"], "last": stop["last"], "member": True} 

107 

108 def config_for(config_base: dict, tickers: set[str]) -> dict: 

109 from build_wide_root import wide_config 

110 

111 return wide_config(config_base, {"tickers": wide_tickers}, tickers=tickers, keep_project_crypto=False) 

112 

113 panel = load_market_panel(ROOT, config_for(base, universe), data_dir="data_wide") 

114 rows = random_weights(panel, sorted(universe), seed=25, start=WIDE_WINDOW[0], end=WIDE_WINDOW[1], every=20, gross=1.2, neutral=True) 

115 runs["v660_bt25"] = {**wide_run("v660_bt25", rows, WIDE_WINDOW, base, universe, data_root="data_wide", config_for=config_for), "role": "plumbing", "stops": stop} 

116 

117 # BT26: BT25 with locks low enough to trip, proving liquidation on the equity path 

118 sha = write_weight_file(rows, WEIGHTS / "v660_bt26.csv") 

119 locked = target_path_config(config_for(base, universe), weights_path="ml/evaluation/v660/weights/v660_bt26.csv", weights_sha256=sha, window=WIDE_WINDOW, locks=True) 

120 locked["phase_v2"]["target_weights"].update(WIDE_PATH) 

121 locked["phase6"]["risk"]["max_total_drawdown_pct"] = 0.02 

122 runs["v660_bt26"] = {**write_run("v660_bt26", locked, data_root="data_wide"), "role": "plumbing", "is": "a lock at 2% must close the book"} 

123 

124 # BT27: oracle on side-A coins inside CS, including a coin that later delisted 

125 crypto = json.loads((ROOT / "data_crypto_wide" / "crypto_wide_manifest.json").read_text(encoding="utf-8")) 

126 project_coins = project_tickers(base, "crypto") 

127 side_a_coins = sorted(entry["ticker"] for entry in crypto["coins"].values() if coin_side(entry["ticker"], project_coins) == "A") 

128 alive = [coin["ticker"] for coin in crypto["coins"].values() if coin["ticker"] in side_a_coins and coin["first"] < CRYPTO_WINDOW[0] and coin["last"] >= CRYPTO_WINDOW[1]] 

129 died = [coin["ticker"] for coin in crypto["coins"].values() if coin["ticker"] in side_a_coins and coin["first"] < "2020-06-30" and CRYPTO_WINDOW[0] < coin["last"] < "2021-09-30"] 

130 coins = sorted({*alive[:12], *died[:2], "BTCUSD"}) 

131 

132 def crypto_config(config_base: dict, tickers: set[str]) -> dict: 

133 config = copy.deepcopy(config_base) 

134 config["phase1"]["universe"]["assets"] = [ 

135 {"ticker": coin, "security_type": "crypto", "market": "coinbase", "data_path": f"data/crypto/coinbase/daily/{coin.lower()}_trade.zip"} for coin in sorted(tickers) 

136 ] + [{"ticker": ticker, "security_type": "equity", "market": "usa", "data_path": f"data/equity/usa/daily/{ticker.lower()}.zip"} for ticker in ("SPY", "AGG")] 

137 return config 

138 

139 crypto_panel = load_market_panel(ROOT, crypto_config(base, set(coins)), data_dir="data_crypto_wide") 

140 oracle = oracle_weights(crypto_panel, coins, start=CRYPTO_WINDOW[0], end=CRYPTO_WINDOW[1], every=20, gross=0.3) 

141 # crypto is long-only on this path; the book keeps the winners' half 

142 oracle = {date: {ticker: weight for ticker, weight in row.items() if weight > 0.0} for date, row in oracle.items()} 

143 # hold a dead coin across its last bar, or nothing here tests the exit: an oracle reads its label, so it would never buy one that is about to stop 

144 dead = died[0] 

145 dead_last = next(coin["last"] for coin in crypto["coins"].values() if coin["ticker"] == dead) 

146 last_row = max(date for date in oracle if date < dead_last) 

147 oracle[last_row] = {**oracle[last_row], dead: 0.02} 

148 runs["v660_bt27"] = {**wide_run("v660_bt27", oracle, CRYPTO_WINDOW, base, set(coins), data_root="data_crypto_wide", config_for=crypto_config), "role": "plumbing", "died": died[:2]} 

149 

150 (OUT / "instrument_manifest.json").write_text(json.dumps(runs, indent=1), encoding="utf-8", newline="\n") 

151 return runs 

152 

153 

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

155 """R-INSTR2 for one finished run: daily correlation and annual gap of the engine against Lean, and fees.""" 

156 from evaluation.backtest_audit import daily_equity_from_chart, load_backtest_run 

157 

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

159 dataroot = RUN_CONFIGS / f"{name}.dataroot" 

160 data_dir = dataroot.read_text(encoding="utf-8").strip() if dataroot.exists() else "data" 

161 panel = load_market_panel(ROOT, run_config, data_dir=data_dir) 

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

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

164 rf_dates, rf_rates = load_rate_series(ROOT / data_dir / "alternative" / "interest-rate" / "usa" / "interest-rate.csv") 

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

166 engine = simulate_target_weights( 

167 load_weight_file(ROOT / target["weights_path"], target["weights_sha256"]), panel, resolve_target_weights_config(target), start=window["start"], end=window["end"], 

168 sweep_config=run_config["phase_v2"]["cash_sweep"], rf_dates=rf_dates, rf_rates=rf_rates, carry_fn=lambda ticker, date: 0.0, 

169 max_total_drawdown=run_config["phase6"]["risk"]["max_total_drawdown_pct"], max_drawdown_velocity=kill["max_drawdown_velocity_pct_per_bar"], 

170 ) 

171 run = load_backtest_run(run_dir) 

172 points = daily_equity_from_chart(run["result"]) 

173 nav = pd.Series(dict(points), dtype=float).sort_index() 

174 nav = nav[(nav.index >= window["start"]) & (nav.index <= window["end"])] 

175 lean = nav.pct_change().dropna() 

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

177 joined.columns = ["lean", "engine"] 

178 years = max(len(nav) / 365.25, 1e-9) 

179 lean_annual = float((nav.iloc[-1] / nav.iloc[0]) ** (1.0 / years) - 1.0) 

180 engine_annual = float((1.0 + engine["total"]).prod() ** (1.0 / years) - 1.0) 

181 stats = (run["result"].get("statistics") or run["result"].get("Statistics") or {}) 

182 fees_text = str(stats.get("Total Fees", "") or "").replace("$", "").replace(",", "") 

183 lean_fees = float(fees_text) if fees_text else None 

184 report = { 

185 "name": name, "run": str(run_dir), "days": len(joined), "correlation": float(joined.corr().iloc[0, 1]) if len(joined) > 2 else None, 

186 "lean_annual": lean_annual, "engine_annual": engine_annual, "annual_gap_bps": abs(lean_annual - engine_annual) * 1e4, "lean_fees": lean_fees, "engine_fees": float(engine["fees"]), 

187 "fees_within_2pct": None if not lean_fees else abs(lean_fees - float(engine["fees"])) / lean_fees <= 0.02, "no_bar_exits": engine["no_bar_exits"], "locked_on": engine.get("locked_on"), 

188 } 

189 report["passes_r_instr2"] = bool(report["correlation"] is not None and report["correlation"] >= 0.99 and report["annual_gap_bps"] <= 100.0 and report["fees_within_2pct"] in (True, None)) 

190 results_path = OUT / "instrument_result.json" 

191 results = json.loads(results_path.read_text(encoding="utf-8")) if results_path.exists() else {} 

192 results[name] = report 

193 results_path.write_text(json.dumps(results, indent=1), encoding="utf-8", newline="\n") 

194 return report 

195 

196 

197def compare_orders(first: Path, second: Path) -> dict: 

198 """Are two runs the same order for order? Time, symbol and quantity of every fill.""" 

199 from evaluation.backtest_audit import load_backtest_run 

200 from evaluation.lean_attribution import fills_from_order_events 

201 

202 def fills(path: Path) -> list[tuple]: 

203 return sorted((str(fill.date), fill.ticker, round(float(fill.quantity), 8)) for fill in fills_from_order_events(load_backtest_run(path).get("order_events", []))) 

204 

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

206 report = {"first": str(first), "second": str(second), "fills_first": len(a), "fills_second": len(b), "equal": a == b} 

207 if a != b: 

208 report["only_first"] = sorted(set(a) - set(b))[:10] 

209 report["only_second"] = sorted(set(b) - set(a))[:10] 

210 return report 

211 

212 

213def main() -> int: 

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

215 commands = parser.add_subparsers(dest="stage", required=True) 

216 commands.add_parser("instrument") 

217 one = commands.add_parser("compare") 

218 one.add_argument("name") 

219 one.add_argument("run") 

220 orders = commands.add_parser("orders") 

221 orders.add_argument("first") 

222 orders.add_argument("second") 

223 args = parser.parse_args() 

224 if args.stage == "instrument": 

225 print(json.dumps(make_instrument(), indent=1)) 

226 elif args.stage == "compare": 

227 print(json.dumps(compare(args.name, Path(args.run)), indent=1)) 

228 else: 

229 print(json.dumps(compare_orders(Path(args.first), Path(args.second)), indent=1)) 

230 return 0 

231 

232 

233if __name__ == "__main__": 

234 raise SystemExit(main())