Coverage for scripts/v650_research.py: 100%

161 statements  

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

1"""V6.5.0 selection on the offline engine: scores, placebos, the gate (rule R-SLEEVE2), the combination (T6). 

2 

3 python scripts/v650_research.py score --tracks T3 T4 

4 python scripts/v650_research.py placebo --draws 200 

5 python scripts/v650_research.py gate 

6 

7Every stage refuses to run when rules.json no longer matches its hash, and nothing here reads past the selection window 

8(`assert_selection_only`). Scores go to selection_scores.json (never `research.json`: the trial registry globs that name). 

9""" 

10 

11from __future__ import annotations 

12 

13import argparse 

14import hashlib 

15import json 

16import sys 

17from pathlib import Path 

18 

19import pandas as pd 

20 

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

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

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

24 

25from v650_trials import ALL_SPECS, COMBINATION_IDS # noqa: E402 

26 

27from evaluation.premia_research import ( # noqa: E402 

28 annual_sharpe, 

29 build_context, 

30 max_drawdown, 

31 nulls_for, 

32 passes_sharpe_clauses, 

33 phase_offsets, 

34 placebo_p_value, 

35 placebo_sharpes, 

36 score_sleeve, 

37 selection_gate, 

38 weights_for, 

39) 

40from evaluation.trial_ledger import append_trial # noqa: E402 

41from portfolio.premia_signals import ResearchPanel, combine_sleeves, sleeve_signal # noqa: E402 

42 

43OUT = ROOT / "ml" / "evaluation" / "v650" 

44SCORES = OUT / "selection_scores.json" 

45DAILY = OUT / "selection_daily.parquet" 

46PLACEBOS = OUT / "selection_placebos.json" 

47GATE = OUT / "selection_gate.json" 

48LEDGER = OUT / "trial_ledger.jsonl" 

49ML_SCORES = OUT / "scores" 

50SELECTION_END = "2023-06-30" 

51 

52 

53def check_rules() -> dict: 

54 text = (OUT / "rules.json").read_text(encoding="utf-8") 

55 expected = (OUT / "rules.sha256").read_text(encoding="utf-8").strip() 

56 actual = hashlib.sha256(text.encode("utf-8")).hexdigest() 

57 if actual != expected: 

58 raise SystemExit(f"rules.json changed: {actual} is not the recorded {expected}") 

59 return json.loads(text) 

60 

61 

62def assert_selection_only(end: str) -> None: 

63 if end > SELECTION_END: 

64 raise SystemExit(f"{end} is past the selection window ({SELECTION_END})") 

65 

66 

67def window_of(spec, rules: dict) -> tuple[str, str, str]: 

68 key = "ml_sleeves" if spec.track in ("T2", "T5") else "rule_sleeves" 

69 start, split, end = rules["selection_windows"][key] 

70 assert_selection_only(end) 

71 return start, split, end 

72 

73 

74def load_context(): 

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

76 context = build_context(ROOT, config) 

77 extras = dict(context.panel.extras) 

78 sessions = context.panel.known.index 

79 if ML_SCORES.exists(): 

80 for path in sorted(ML_SCORES.glob("*.csv")): 

81 table = pd.read_csv(path, dtype={"date": str, "ticker": str}) 

82 table = table[table["date"] <= SELECTION_END] 

83 extras[path.stem] = table.pivot_table(index="date", columns="ticker", values="score", aggfunc="last").reindex(sessions) 

84 context.panel = ResearchPanel(context.panel.known, context.panel.asset_class, context.panel.fred, extras) 

85 return context 

86 

87 

88def read_json(path: Path, default): 

89 return json.loads(path.read_text(encoding="utf-8")) if path.exists() else default 

90 

91 

92def write_json(path: Path, payload) -> None: 

93 path.write_text(json.dumps(payload, indent=1), encoding="utf-8", newline="\n") 

94 

95 

96def stage_score(args) -> int: 

97 rules = check_rules() 

98 context = load_context() 

99 scores = read_json(SCORES, {}) 

100 frames = {} 

101 if DAILY.exists(): 

102 stored = pd.read_parquet(DAILY) 

103 frames = {column: stored[column].dropna() for column in stored.columns} 

104 for spec in ALL_SPECS: 

105 if spec.track not in args.tracks or (spec.id in scores and not args.force): 

106 continue 

107 table = spec.params.get("table") 

108 if table is not None and table not in context.panel.extras: 

109 print(f"{spec.id}: no table {table} yet", flush=True) 

110 continue 

111 start, split, end = window_of(spec, rules) 

112 score = score_sleeve(spec, context, start=start, split=split, end=end) 

113 daily = score.pop("daily") 

114 frames[spec.id] = daily[min(daily)] 

115 scores[spec.id] = score 

116 append_trial(LEDGER, trial_id=spec.id, track=spec.track, window="selection", role="candidate", annualised_sharpe=score["sharpe"], 

117 n_obs=len(frames[spec.id]), engine="offline") 

118 print(f"{spec.id:28s} sharpe {_show(score['sharpe'])} h1 {_show(score['sharpe_first_half'])} h2 {_show(score['sharpe_second_half'])} " 

119 f"dd {score['max_drawdown']:.3f} turn {score['turnover']:.1f} gross {score['mean_gross']:.2f}", flush=True) 

120 write_json(SCORES, scores) 

121 pd.DataFrame(frames).sort_index().to_parquet(DAILY) 

122 return 0 

123 

124 

125def _show(value) -> str: 

126 return " n/a" if value is None else f"{value:5.2f}" 

127 

128 

129def stage_placebo(args) -> int: 

130 rules = check_rules() 

131 context = load_context() 

132 scores = read_json(SCORES, {}) 

133 placebos_path = PLACEBOS.with_name(f"selection_placebos{args.suffix}.json") 

134 ledger_path = LEDGER.with_name(f"trial_ledger{args.suffix}.jsonl") 

135 done = read_json(placebos_path, {}) 

136 for spec in ALL_SPECS: 

137 score = scores.get(spec.id) 

138 if score is None or not passes_sharpe_clauses(score) or (spec.id in done and not args.force): 

139 continue 

140 if args.only and spec.id not in args.only: 

141 continue 

142 start, _, end = window_of(spec, rules) 

143 out = {} 

144 for mode in nulls_for(spec): 

145 sharpes = placebo_sharpes(spec, context, mode, start=start, end=end, draws=args.draws) 

146 out[mode] = {"p": placebo_p_value(score["sharpe"], sharpes), "draws": len(sharpes), 

147 "median": float(pd.Series(sharpes).median()) if sharpes else None, 

148 "q95": float(pd.Series(sharpes).quantile(0.95)) if sharpes else None} 

149 print(f"{spec.id:28s} {mode:12s} p {out[mode]['p']:.3f} placebo median {_show(out[mode]['median'])} q95 {_show(out[mode]['q95'])}", flush=True) 

150 for sharpe in sharpes: 

151 append_trial(ledger_path, trial_id=f"{spec.id}:{mode}", track=spec.track, window="selection", role="placebo", 

152 annualised_sharpe=sharpe, n_obs=0, engine="offline") 

153 done[spec.id] = out 

154 write_json(placebos_path, done) 

155 return 0 

156 

157 

158def stage_gate(args) -> int: 

159 check_rules() 

160 scores = read_json(SCORES, {}) 

161 placebos = {} 

162 for path in sorted(OUT.glob("selection_placebos*.json")): 

163 placebos.update(read_json(path, {})) 

164 daily = pd.read_parquet(DAILY) 

165 rows = [{**score, "daily": {0: daily[name].dropna()}} for name, score in scores.items() if name in daily] 

166 p_values = {name: {mode: entry["p"] for mode, entry in tests.items()} for name, tests in placebos.items()} 

167 gate = selection_gate(rows, p_values) 

168 unscored = [spec.id for spec in ALL_SPECS if spec.id not in scores] 

169 gate["unscored"] = unscored 

170 write_json(GATE, gate) 

171 print(json.dumps(gate, indent=1)) 

172 return 0 

173 

174 

175def stage_combine(args) -> int: 

176 """T6 over the survivors, on the selection window. A single survivor is its own combination.""" 

177 rules = check_rules() 

178 gate = read_json(GATE, {}) 

179 survivors = gate.get("survivors") or [] 

180 if not survivors: 

181 print("no survivor: R-LEAN19 directly") 

182 return 0 

183 context = load_context() 

184 specs = {spec.id: spec for spec in ALL_SPECS} 

185 start, split, end = rules["selection_windows"]["rule_sleeves"] 

186 assert_selection_only(end) 

187 sleeves = {} 

188 for name in survivors: 

189 spec = specs[name] 

190 signal = sleeve_signal(spec, context.panel) 

191 sleeves[name] = weights_for(spec, context, signal, start=start, end=end, phase_offset=phase_offsets(spec.rebalance_every)[0]) 

192 results = {} 

193 for name, method in zip(COMBINATION_IDS, ("inverse_vol", "hrp"), strict=False): 

194 rows = combine_sleeves(sleeves, context.panel, method=method, settings=context.settings, start=start, end=end) 

195 strategy = context.simulate(rows, start, end)["strategy"] 

196 results[name] = {"sharpe": annual_sharpe(strategy), "first_half": annual_sharpe(strategy[strategy.index < split]), 

197 "second_half": annual_sharpe(strategy[strategy.index >= split]), "max_drawdown": max_drawdown(strategy)} 

198 append_trial(LEDGER, trial_id=name, track="T6", window="selection", role="candidate", annualised_sharpe=results[name]["sharpe"], 

199 n_obs=len(strategy), engine="offline") 

200 print(name, results[name], flush=True) 

201 write_json(OUT / "selection_combination.json", {"survivors": survivors, "results": results}) 

202 return 0 

203 

204 

205def main() -> int: 

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

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

208 score = commands.add_parser("score") 

209 score.add_argument("--tracks", nargs="+", default=["T3", "T4"]) 

210 score.add_argument("--force", action="store_true") 

211 placebo = commands.add_parser("placebo") 

212 placebo.add_argument("--draws", type=int, default=200) 

213 placebo.add_argument("--force", action="store_true") 

214 placebo.add_argument("--only", nargs="*", default=None, help="sleeve ids, to split the work across hosts") 

215 placebo.add_argument("--suffix", default="", help="output file suffix of this host's part; `gate` merges every part") 

216 commands.add_parser("gate") 

217 commands.add_parser("combine") 

218 args = parser.parse_args() 

219 return {"score": stage_score, "placebo": stage_placebo, "gate": stage_gate, "combine": stage_combine}[args.command](args) 

220 

221 

222if __name__ == "__main__": 

223 raise SystemExit(main())