Coverage for scripts/book_variant_research.py: 100%

150 statements  

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

1"""R-BOOK (V6.0.0, todo lead 1): can any single change to the main equity book beat its costs? Pre-registered rule. 

2 

3The V5.8.0 stack shows a pooled rank IC of +0.05 that does not pay a top-6 / bottom-6 book's costs (BT2: main-book members 

4+$1,184 net of fees over 3.25 years, legacy -$834). This runs each candidate change ALONE against the current config on the 

5Lean-calibrated simulator (`scripts/lean_calibration.py`'s calibrated rung: next-open fills, the broker's per-order floor, 

6live's resize / cooldown / trailing stop, the learned-topology sizing), on the validation and backtest splits: 

7 

8 B0 current config B6 sector-neutral rank head (watchlist heads only to adopt) 

9 B1 rebalance 20 bars, max hold 40 B7 residual rank head 

10 B2a hysteresis margin 0.10 B8a/b 4/4 and 10/10 names 

11 B2b hysteresis margin 0.15 B9 60-day rank head (`v8_rank60`, candidate version dirs) 

12 B3 rank_20d only (no rank_5d) 

13 B4 class slots {equity 5/5, crypto 1/1} 

14 B5 class slots {equity 6/6} (crypto leaves the main book) 

15 

16Decision (R-CAL branch from `ml/evaluation/v600/calibration.json`): a variant is ADOPTED iff, against B0 on the same rows, 

17 1. its UNGATED net Sharpe improves by >= +0.10 on the backtest split and is not worse by more than 0.02 on validation, 

18 2. its ungated net Sharpe is > 0 on both splits, 

19 3. branch A only: the as-live (gated) book passes the margins of clause 1 as well, 

20 4. its max drawdown is not worse by more than 1.0 pp on either split, 

21and a head variant must be at least `watchlist` on its promotion gate (R-HEAD). Passing variants are combined greedily in 

22order of validation Sharpe, each addition tested against the running best. The holdout is reported, never used. 

23 

24 python scripts/book_variant_research.py --dataset ml/datasets/full_dataset.csv [--branch B] [--only B1 B2a] 

25 -> ml/evaluation/v600/book_research.json 

26""" 

27 

28from __future__ import annotations 

29 

30import argparse 

31import copy 

32import json 

33import sys 

34from pathlib import Path 

35 

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

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

38sys.path.insert(0, str(Path(__file__).resolve().parent)) 

39 

40MIN_BACKTEST_GAIN = 0.10 

41MAX_VALIDATION_LOSS = 0.02 

42MAX_DRAWDOWN_WORSENING = 0.01 

43 

44# id -> {"config": {phase_v2 dotted key: value}, "heads": {head: weight} | None, "ml_dir": version dir | None, "dataset": str | None} 

45VARIANTS: dict[str, dict] = { 

46 "B0": {}, 

47 "B1": {"config": {"portfolio_book.rebalance_every_bars": 20, "exits.max_holding_bars": 40}}, 

48 "B2a": {"config": {"portfolio_book.hysteresis_rank_margin": 0.10}}, 

49 "B2b": {"config": {"portfolio_book.hysteresis_rank_margin": 0.15}}, 

50 "B3": {"heads": {"rank_20d": 1.0}}, 

51 "B4": {"config": {"portfolio_book.per_asset_class_slots": {"equity": [5, 5], "crypto": [1, 1]}}}, 

52 "B5": {"config": {"portfolio_book.per_asset_class_slots": {"equity": [6, 6]}}}, 

53 "B6": {"heads": {"sector_neutral_rank_20d": 1.0}}, 

54 "B7": {"heads": {"residual_rank_20d": 1.0}}, 

55 "B8a": {"config": {"portfolio_book.top_n": 4, "portfolio_book.bottom_n": 4}}, 

56 "B8b": {"config": {"portfolio_book.top_n": 10, "portfolio_book.bottom_n": 10}}, 

57 "B9": {"heads": {"rank_60d": 1.0}, "config": {"portfolio_book.rebalance_every_bars": 20}, 

58 "ml_dir": "ml/versions/v600cs20261015_mt_v8_rank60_s1", "dataset": "ml/datasets/v600_rank60_dataset.csv"}, 

59} 

60 

61 

62def passes_margins(base: dict, variant: dict) -> dict: 

63 """R-BOOK clauses 1, 2 and 4 on one scoring mode. `base` / `variant` = {split: {"net_sharpe", "net_max_drawdown"}}.""" 

64 gain_backtest = variant["backtest"]["net_sharpe"] - base["backtest"]["net_sharpe"] 

65 change_validation = variant["validation"]["net_sharpe"] - base["validation"]["net_sharpe"] 

66 drawdown_ok = all( 

67 variant[split]["net_max_drawdown"] - base[split]["net_max_drawdown"] >= -MAX_DRAWDOWN_WORSENING for split in ("validation", "backtest") 

68 ) 

69 checks = { 

70 "backtest_gain_ge_0.10": gain_backtest >= MIN_BACKTEST_GAIN, 

71 "validation_not_worse_than_0.02": change_validation >= -MAX_VALIDATION_LOSS, 

72 "positive_on_both_splits": variant["validation"]["net_sharpe"] > 0.0 and variant["backtest"]["net_sharpe"] > 0.0, 

73 "drawdown_within_1pp": drawdown_ok, 

74 } 

75 return {"checks": checks, "backtest_gain": gain_backtest, "validation_change": change_validation, "passes": all(checks.values())} 

76 

77 

78def decide(base: dict, variant: dict, branch: str, *, head_status_ok: bool = True) -> dict: 

79 """base / variant = {"ungated": {...}, "as_live": {...}}. Branch A also requires the as-live margins (clause 3); the 

80 positivity clause is judged on the ungated book only.""" 

81 ungated = passes_margins(base["ungated"], variant["ungated"]) 

82 verdict = {"ungated": ungated, "head_status_ok": head_status_ok} 

83 adopted = ungated["passes"] and head_status_ok 

84 if branch == "A": 

85 as_live = passes_margins(base["as_live"], variant["as_live"]) 

86 as_live["checks"].pop("positive_on_both_splits", None) 

87 as_live["passes"] = all(as_live["checks"].values()) 

88 verdict["as_live"] = as_live 

89 adopted = adopted and as_live["passes"] 

90 verdict["adopted"] = bool(adopted) 

91 return verdict 

92 

93 

94def merge_variants(chosen: list[str]) -> dict: 

95 """The combined spec of several variants; None when two of them set the same key or the head blend (no silent winner).""" 

96 merged: dict = {"config": {}, "heads": None, "ml_dir": None, "dataset": None} 

97 for name in chosen: 

98 spec = VARIANTS[name] 

99 for key, value in (spec.get("config") or {}).items(): 

100 if key in merged["config"] and merged["config"][key] != value: 

101 return {} 

102 merged["config"][key] = value 

103 for field in ("heads", "ml_dir", "dataset"): 

104 if spec.get(field): 

105 if merged[field] and merged[field] != spec[field]: 

106 return {} 

107 merged[field] = spec[field] 

108 return merged 

109 

110 

111def greedy_combination(passing: list[str], validation_sharpe: dict[str, float], evaluate, base: dict, branch: str, 

112 head_ok) -> tuple[list[str], list[dict]]: 

113 """Add passing variants in order of ungated validation Sharpe; each must pass against the running best.""" 

114 chosen: list[str] = [] 

115 running = base 

116 log = [] 

117 for name in sorted(passing, key=lambda item: -validation_sharpe[item]): 

118 spec = merge_variants(chosen + [name]) 

119 if not spec: 

120 log.append({"variant": name, "skipped": "conflicts with an adopted variant"}) 

121 continue 

122 result = evaluate(spec) 

123 verdict = decide(running, result, branch, head_status_ok=head_ok(spec)) 

124 log.append({"variant": name, "combined": chosen + [name], "verdict": verdict}) 

125 if verdict["adopted"]: 

126 chosen.append(name) 

127 running = result 

128 return chosen, log 

129 

130 

131# The owner kept the four rank heads of the installed multitask / sequence models as watchlist on 2026-10-13 (R-MODEL8, Problems 

132# #162) although the single-split gate calls them not_promotable; a variant that only re-weights them inherits that decision. 

133OWNER_WATCHLIST_HEADS = frozenset({"rank_5d", "rank_20d", "residual_rank_5d", "residual_rank_20d"}) 

134 

135 

136def head_status_ok(spec: dict, config: dict, version_metrics: dict | None) -> bool: 

137 """R-HEAD for a head variant: every head it blends must be `watchlist` or better on its backtest promotion gate (the 

138 owner's watchlist decision covers the installed model's rank heads, never a new candidate's).""" 

139 heads = (spec or {}).get("heads") 

140 if not heads: 

141 return True 

142 allowed = set(config["phase_v2"]["rank_signal"].get("min_promotion_status", ["promotable", "watchlist"])) 

143 metrics = version_metrics or {} 

144 for head in heads: 

145 if not spec.get("ml_dir") and head in OWNER_WATCHLIST_HEADS: 

146 continue 

147 quality = (metrics.get("backtest", {}) or {}).get(f"{head}_ranking_quality") or {} 

148 if quality.get("quality_status") not in allowed: 

149 return False 

150 return True 

151 

152 

153def main() -> int: 

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

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

156 parser.add_argument("--branch", choices=("A", "B"), default=None, help="default: read ml/evaluation/v600/calibration.json") 

157 parser.add_argument("--only", nargs="*", default=None, help="variant ids (B0 always runs)") 

158 parser.add_argument("--out", default=str(ROOT_DIR / "ml" / "evaluation" / "v600" / "book_research.json")) 

159 args = parser.parse_args() 

160 

161 from as_live_levers import AsLiveHarness, summarize 

162 from lean_calibration import calibrated_overrides, topology_inputs_fn_for, use_topology 

163 

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

165 branch = args.branch 

166 if branch is None: 

167 branch = json.loads((ROOT_DIR / "ml" / "evaluation" / "v600" / "calibration.json").read_text(encoding="utf-8"))["verdict"]["branch"] 

168 cache: dict = {} 

169 current_group: list = [None] 

170 

171 def harness_for(spec: dict, split: str): 

172 dataset = spec.get("dataset") or args.dataset 

173 group = (json.dumps(spec.get("heads"), sort_keys=True), spec.get("ml_dir"), dataset) 

174 if current_group[0] != group: # one scoring group resident at a time (each frame is 100-200 MB) 

175 cache.clear() 

176 current_group[0] = group 

177 key = (split, *group) 

178 if key not in cache: 

179 cfg = copy.deepcopy(config) 

180 if spec.get("heads"): 

181 cfg["phase_v2"]["rank_signal"]["heads"] = dict(spec["heads"]) 

182 cfg["phase_v2"]["rank_signal"]["demote_not_promotable_heads"] = False # R-HEAD is judged separately 

183 ml_dir = ROOT_DIR / spec["ml_dir"] if spec.get("ml_dir") else None 

184 harness = AsLiveHarness(split, dataset_path=ROOT_DIR / dataset, config=cfg, ml_dir=ml_dir) 

185 cache[key] = (harness, topology_inputs_fn_for(harness, cfg)) 

186 return cache[key] 

187 

188 def run(spec: dict, split: str, *, gated: bool) -> dict: 

189 harness, topology_fn = harness_for(spec, split) 

190 use_topology(harness, topology_fn) 

191 kwargs = calibrated_overrides(harness) 

192 if not gated: 

193 kwargs.update(gate="off", min_rank_confidence_spread=0.0) 

194 result = harness.as_live(config_overrides={f"{k}": v for k, v in (spec.get("config") or {}).items()} or None, **kwargs) 

195 return summarize(result) 

196 

197 def evaluate(spec: dict, which=("validation", "backtest")) -> dict: 

198 return {mode: {split: run(spec, split, gated=(mode == "as_live")) for split in which} for mode in ("ungated", "as_live")} 

199 

200 selected = [name for name in VARIANTS if name != "B0" and (not args.only or name in args.only)] 

201 # config-only variants share B0's scoring, so they run first; each head variant then loads its own scores 

202 chosen_ids = ["B0"] + sorted(selected, key=lambda name: bool(VARIANTS[name].get("heads") or VARIANTS[name].get("dataset"))) 

203 results: dict[str, dict] = {} 

204 for name in chosen_ids: 

205 spec = VARIANTS[name] 

206 results[name] = evaluate(spec) 

207 print(f"{name:4s} ungated v/b {results[name]['ungated']['validation']['net_sharpe']:+.3f}/{results[name]['ungated']['backtest']['net_sharpe']:+.3f}" 

208 f" as-live v/b {results[name]['as_live']['validation']['net_sharpe']:+.3f}/{results[name]['as_live']['backtest']['net_sharpe']:+.3f}", flush=True) 

209 

210 version_metrics = {} 

211 for name in chosen_ids: 

212 ml_dir = VARIANTS[name].get("ml_dir") 

213 metrics_path = ROOT_DIR / (ml_dir or "ml") / "multitask_training_metrics.json" 

214 version_metrics[name] = json.loads(metrics_path.read_text(encoding="utf-8")) if metrics_path.exists() else None 

215 

216 verdicts = {} 

217 for name in chosen_ids[1:]: 

218 base = results["B0"] 

219 if VARIANTS[name].get("dataset"): # a different row set (60-day purge): compare with B0 on the SAME rows 

220 base = evaluate({"dataset": VARIANTS[name]["dataset"]}) 

221 results[f"B0@{name}"] = base 

222 verdicts[name] = decide(base, results[name], branch, head_status_ok=head_status_ok(VARIANTS[name], config, version_metrics[name])) 

223 print(f"{name:4s} adopted={verdicts[name]['adopted']} ungated gain {verdicts[name]['ungated']['backtest_gain']:+.3f} " 

224 f"validation {verdicts[name]['ungated']['validation_change']:+.3f} checks {verdicts[name]['ungated']['checks']}", flush=True) 

225 

226 passing = [name for name, verdict in verdicts.items() if verdict["adopted"] and not VARIANTS[name].get("dataset")] 

227 validation_sharpe = {name: results[name]["ungated"]["validation"]["net_sharpe"] for name in passing} 

228 chosen, combination_log = greedy_combination( 

229 passing, validation_sharpe, evaluate, results["B0"], branch, 

230 head_ok=lambda spec: head_status_ok(spec, config, version_metrics.get("B0")), 

231 ) 

232 final = {"adopted": chosen, "spec": merge_variants(chosen) if chosen else {}} 

233 if chosen: 

234 final["holdout_seen"] = { 

235 "b0": {mode: run({}, "holdout", gated=(mode == "as_live")) for mode in ("ungated", "as_live")}, 

236 "final": {mode: run(final["spec"], "holdout", gated=(mode == "as_live")) for mode in ("ungated", "as_live")}, 

237 } 

238 else: 

239 final["holdout_seen"] = {"b0": {mode: run({}, "holdout", gated=(mode == "as_live")) for mode in ("ungated", "as_live")}} 

240 print("R-BOOK adopted:", chosen or "none (no variant beats costs)") 

241 Path(args.out).parent.mkdir(parents=True, exist_ok=True) 

242 Path(args.out).write_text( 

243 json.dumps({"branch": branch, "results": results, "verdicts": verdicts, "combination": combination_log, "final": final}, indent=1, default=float), 

244 encoding="utf-8", 

245 ) 

246 print(f"written {args.out}") 

247 return 0 

248 

249 

250if __name__ == "__main__": 

251 raise SystemExit(main())