Coverage for scripts/v650_amendment2.py: 100%

219 statements  

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

1"""V6.5.0 amendments 2 and 3 (ml/evaluation/v650/rules_amendment_{2,3}.json): the corrected earnings trials and the pre-2013 read. 

2 

3 python scripts/v650_amendment2.py eps-score # R-SLEEVE2's Sharpe clauses and, for a pass, its placebos 

4 python scripts/v650_amendment2.py pbo # over all 42 selection trials, on the common window 

5 python scripts/v650_amendment2.py eps-pool # a survivor's R-LEAN19 runs, frozen first 

6 python scripts/v650_amendment2.py eps-judge --status <status file> 

7 python scripts/v650_amendment2.py pre2013-make # the frozen candidate on the pre-2013 root, and 20 placebos 

8 python scripts/v650_amendment2.py pre2013-judge --status <status file> 

9""" 

10 

11from __future__ import annotations 

12 

13import argparse 

14import json 

15import sys 

16from pathlib import Path 

17 

18import numpy as np 

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_lean import ( # noqa: E402 

26 E5_DRAWS, 

27 PHASES, 

28 SPECS, 

29 _base, 

30 candidate_rows, 

31 check_freeze, 

32 lean_statistics, 

33 make_run, 

34 pre2013_context, 

35) 

36from v650_research import DAILY, LEDGER, OUT, check_rules, load_context, read_json, write_json # noqa: E402 

37 

38from data_pipeline.edgar_facts import read_eps, read_splits, split_adjusted_eps, surprise_table # noqa: E402 

39from evaluation.premia_research import ( # noqa: E402 

40 annual_sharpe, 

41 nulls_for, 

42 passes_sharpe_clauses, 

43 placebo_p_value, 

44 placebo_sharpes, 

45 score_sleeve, 

46) 

47from evaluation.trial_ledger import append_trial # noqa: E402 

48from portfolio.premia_signals import XS, ResearchPanel, SleeveSpec # noqa: E402 

49 

50EPS_PATH = ROOT / "data" / "reference" / "edgar_eps.csv" 

51EPS_SPECS = [ 

52 SleeveSpec("t4_eps_sue_20", "T4", XS, "external_score", ("equity",), 5, {"table": "eps_20"}), 

53 SleeveSpec("t4_eps_sue_60", "T4", XS, "external_score", ("equity",), 5, {"table": "eps_60"}), 

54] 

55RESULT = OUT / "amendment3_eps.json" # amendment2_eps.json keeps the closed, defective variants' scores 

56 

57 

58def eps_context(): 

59 context = load_context() 

60 eps = split_adjusted_eps(read_eps(EPS_PATH), read_splits()) 

61 sessions = [str(day) for day in context.panel.known.index] 

62 columns = list(context.panel.known.columns) 

63 extras = dict(context.panel.extras) 

64 extras["eps_20"] = surprise_table(eps, sessions, columns, hold_sessions=20) 

65 extras["eps_60"] = surprise_table(eps, sessions, columns, hold_sessions=60) 

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

67 return context, eps 

68 

69 

70def stage_eps_score(args) -> int: 

71 rules = check_rules() 

72 context, eps = eps_context() 

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

74 out = {"tickers": int(eps["ticker"].nunique()), "quarters": int(len(eps)), "first_filed": str(eps["filed"].min()), "scores": {}, "placebos": {}} 

75 frames = pd.read_parquet(DAILY) 

76 for spec in EPS_SPECS: 

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

78 daily = score.pop("daily") 

79 series = daily[min(daily)] 

80 frames[spec.id] = series.reindex(frames.index) 

81 out["scores"][spec.id] = score 

82 append_trial(LEDGER, trial_id=spec.id, track="T4", window="selection", role="candidate", annualised_sharpe=score["sharpe"], n_obs=len(series), engine="offline") 

83 print(f"{spec.id}: sharpe {score['sharpe']} h1 {score['sharpe_first_half']} h2 {score['sharpe_second_half']} dd {score['max_drawdown']} gross {score['mean_gross']}", flush=True) 

84 if passes_sharpe_clauses(score): 

85 tests = {} 

86 for mode in nulls_for(spec): 

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

88 tests[mode] = {"p": placebo_p_value(score["sharpe"], sharpes), "draws": len(sharpes), "median": float(np.median(sharpes)) if sharpes else None} 

89 print(f" {mode}: p {tests[mode]['p']:.4f} median {tests[mode]['median']}", flush=True) 

90 out["placebos"][spec.id] = tests 

91 frames.to_parquet(DAILY) 

92 out["survivors"] = [ 

93 spec.id for spec in EPS_SPECS 

94 if spec.id in out["placebos"] and all(test["p"] < 0.05 for test in out["placebos"][spec.id].values()) 

95 ] 

96 write_json(RESULT, out) 

97 print("survivors:", out["survivors"], flush=True) 

98 return 0 

99 

100 

101def stage_pbo(args) -> int: 

102 from evaluation.pbo import probability_of_backtest_overfitting 

103 

104 daily = pd.read_parquet(DAILY).sort_index() 

105 common = daily[(daily.index >= "2019-01-01") & (daily.index <= "2023-06-30")].fillna(0.0) 

106 report = probability_of_backtest_overfitting(common.to_numpy(), blocks=16, periods_per_year=365) 

107 result = {key: report.get(key) for key in ("pbo", "num_trials", "num_combinations", "prob_oos_loss")} 

108 result["window"] = "2019-01-01..2023-06-30, the basis fixed in pbo_verdict.json" 

109 write_json(OUT / "amendment3_pbo.json", result) 

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

111 return 0 

112 

113 

114def stage_pre2013_make(args) -> int: 

115 rules = check_rules() 

116 definition = check_freeze() 

117 base = _base() 

118 context, config = pre2013_context(base) 

119 window = tuple(rules["windows"]["pre2013"]) 

120 available = [name for name in definition["survivors"] if SPECS[name].universe != ("crypto",)] 

121 early = {"survivors": available, "method": None if len(available) == 1 else definition["method"]} 

122 runs = {"v650_e5": make_run("v650_e5", candidate_rows(early, context, start=window[0], end=window[1], phase_index=0), window, config, data_root="data_pre2013", sweep=False)} 

123 rng = np.random.default_rng(2013) 

124 for draw in range(E5_DRAWS): 

125 name = f"v650_e5_null_{draw:02d}" 

126 rows = candidate_rows(early, context, start=window[0], end=window[1], phase_index=int(rng.integers(PHASES)), null_mode="time_shift", seed=2_000 + draw) 

127 runs[name] = make_run(name, rows, window, config, data_root="data_pre2013", sweep=False) 

128 write_json(OUT / "pre2013_runs.json", {"definition": early, "runs": runs}) 

129 (OUT / "pre2013_run_list.txt").write_text(" ".join(f"ml/evaluation/run_configs/{name}.json" for name in runs) + "\n", encoding="utf-8", newline="\n") 

130 print(f"{len(runs)} runs; sleeves {available}") 

131 return 0 

132 

133 

134def _nav_returns(run_dir: Path) -> pd.Series: 

135 from evaluation.backtest_audit import daily_equity_from_chart, load_backtest_run 

136 

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

138 return pd.Series(dict(points), dtype=float).sort_index().pct_change().dropna() 

139 

140 

141def per_year(series: pd.Series) -> float: 

142 """Observations per year: this root has no crypto, so a run may sample weekdays only, and a fixed 365 would inflate its Sharpe.""" 

143 days = (pd.Timestamp(series.index.max()) - pd.Timestamp(series.index.min())).days 

144 return len(series) / max(days / 365.25, 1e-9) 

145 

146 

147def sharpe_on_observations(series: pd.Series) -> float | None: 

148 values = series.to_numpy(dtype=float) 

149 if len(values) < 20 or values.std(ddof=1) <= 0.0: 

150 return None 

151 return float(values.mean() / values.std(ddof=1) * np.sqrt(per_year(series))) 

152 

153 

154def stage_pre2013_judge(args) -> int: 

155 from evaluation.alpha_proof import alpha_regression, benchmark_daily_returns, to_sessions 

156 from evaluation.backtest_audit import load_backtest_run 

157 from evaluation.lean_attribution import fills_from_order_events 

158 

159 done = {} 

160 for line in Path(args.status).read_text(encoding="utf-8-sig").splitlines(): 

161 parts = line.split() 

162 if len(parts) == 3 and parts[0] == "LEAN_DONE": 

163 done[parts[1]] = ROOT / parts[2] 

164 main_dir = done["v650_e5"] 

165 series = _nav_returns(main_dir) 

166 manifest_config = json.loads((ROOT / "ml" / "evaluation" / "run_configs" / "v650_e5.json").read_text(encoding="utf-8")) 

167 benchmarks = benchmark_daily_returns(ROOT, manifest_config, tickers=("SPY", "AGG"), start=str(series.index.min()), end=str(series.index.max()), data_dir="data_pre2013") 

168 alpha = alpha_regression(to_sessions(series, benchmarks.index), benchmarks) 

169 placebos = [value for name, path in done.items() if name.startswith("v650_e5_null_") and (value := sharpe_on_observations(_nav_returns(path))) is not None] 

170 fills = fills_from_order_events(load_backtest_run(main_dir).get("order_events", [])) 

171 observed = sharpe_on_observations(series) 

172 result = { 

173 "run": main_dir.name, "n": int(len(series)), "observations_per_year": per_year(series), 

174 "sharpe": observed, "sharpe_at_fixed_365": annual_sharpe(series), "lean": lean_statistics(main_dir), 

175 "alpha_annual": alpha.get("alpha_annual"), "alpha_t": alpha.get("t_hac"), "betas": alpha.get("betas"), 

176 "first_fill": fills[0].date if fills else None, "last_fill": fills[-1].date if fills else None, "fills": len(fills), 

177 "placebo_sharpes": sorted(placebos), "placebos_at_or_above": sum(value >= observed for value in placebos) if observed is not None else None, 

178 "placebo_median": float(np.median(placebos)) if placebos else None, 

179 } 

180 write_json(OUT / "pre2013_result.json", result) 

181 append_trial(LEDGER, trial_id="t3_trend_blend", track="pre2013", window="pre2013", role="verification", annualised_sharpe=observed, n_obs=len(series), engine="lean", detail={"run": main_dir.name}) 

182 print(json.dumps({key: value for key, value in result.items() if key != "placebo_sharpes"}, indent=1, default=str)) 

183 return 0 

184 

185 

186def eps_rows(spec: SleeveSpec, context, *, start: str, end: str, phase_index: int, null_mode: str | None = None, seed: int = 0) -> dict: 

187 from evaluation.premia_research import phase_offsets, weights_for 

188 from portfolio.premia_signals import null_signal, sleeve_signal 

189 

190 signal = sleeve_signal(spec, context.panel) 

191 if null_mode: 

192 signal = null_signal(signal, null_mode, seed=seed, asset_class=context.panel.asset_class) 

193 offsets = phase_offsets(spec.rebalance_every, PHASES) 

194 return weights_for(spec, context, signal, start=start, end=end, phase_offset=offsets[phase_index % len(offsets)]) 

195 

196 

197def apply_correlation_clause(survivors: list[str], scores: dict, daily: pd.DataFrame, max_correlation: float = 0.7) -> list[str]: 

198 """R-SLEEVE2: among survivors, a daily correlation above the limit drops the lower Sharpe.""" 

199 kept: list[str] = [] 

200 for name in sorted(survivors, key=lambda item: scores[item]["sharpe"], reverse=True): 

201 if all(daily[[name, other]].dropna().corr().iloc[0, 1] <= max_correlation for other in kept): 

202 kept.append(name) 

203 return kept 

204 

205 

206def stage_eps_pool(args) -> int: 

207 """R-LEAN19's runs for the surviving earnings sleeves. Recorded in the vault before any row after the selection window exists.""" 

208 import hashlib 

209 

210 from vault_record import record 

211 

212 rules = check_rules() 

213 result = read_json(RESULT, {}) 

214 survivors = apply_correlation_clause(result.get("survivors") or [], result.get("scores") or {}, pd.read_parquet(DAILY)) 

215 result["survivors_after_correlation"] = survivors 

216 write_json(RESULT, result) 

217 if not survivors: 

218 print("no earnings sleeve survived: nothing changes") 

219 return 0 

220 code = ["scripts/v650_amendment2.py", "data_pipeline/edgar_facts.py", "portfolio/premia_signals.py", "portfolio/target_weights.py", "main.py"] 

221 write_json(OUT / "amendment2_freeze.json", {"survivors": survivors, "code": {path: hashlib.sha256((ROOT / path).read_bytes()).hexdigest() for path in code}}) 

222 recorded = record("amendment2_freeze", ["ml/evaluation/v650/amendment2_freeze.json", "ml/evaluation/v650/amendment2_eps.json"], {"survivors": float(len(survivors))}) 

223 if not recorded["ok"]: 

224 raise SystemExit(f"could not record the freeze: {recorded}") 

225 context, _ = eps_context() 

226 specs = {spec.id: spec for spec in EPS_SPECS} 

227 base = _base() 

228 window, long_window = tuple(rules["windows"]["verification"]), tuple(rules["windows"]["long"]) 

229 runs = {} 

230 for name in survivors: 

231 for phase in range(PHASES): 

232 run = f"v650_pool_{name}_p{phase}" 

233 runs[run] = make_run(run, eps_rows(specs[name], context, start=window[0], end=window[1], phase_index=phase), window, base) 

234 run = f"v650_pool_{name}_long" 

235 runs[run] = make_run(run, eps_rows(specs[name], context, start=long_window[0], end=long_window[1], phase_index=0), long_window, base) 

236 write_json(OUT / "eps_pool_runs.json", runs) 

237 (OUT / "eps_pool_run_list.txt").write_text(" ".join(f"ml/evaluation/run_configs/{name}.json" for name in runs) + "\n", encoding="utf-8", newline="\n") 

238 print(f"{len(runs)} runs; frozen in vault commit {recorded['commit']}") 

239 return 0 

240 

241 

242def describe_run(run_dir: Path) -> dict: 

243 from v650_instrument import RUN_CONFIGS 

244 from v650_lean import ANNUALIZATION, strategy_series 

245 

246 from evaluation.alpha_proof import alpha_regression, benchmark_daily_returns, sharpe, to_sessions 

247 from evaluation.backtest_audit import load_backtest_run 

248 from evaluation.lean_attribution import fills_from_order_events 

249 

250 config = json.loads((RUN_CONFIGS / f"{run_dir.name}.json").read_text(encoding="utf-8")) 

251 series = strategy_series(run_dir, config) 

252 stats = lean_statistics(run_dir) 

253 stats["strategy_sharpe"] = sharpe(series.to_numpy(dtype=float), ANNUALIZATION) 

254 log = (run_dir / "log.txt").read_text(encoding="utf-8", errors="replace") 

255 stats["complete"] = "PythonInitializer.Shutdown(): start" in log and "Runtime Error" not in log 

256 benchmarks = benchmark_daily_returns(ROOT, config, start=str(series.index.min()), end=str(series.index.max())) 

257 alpha = alpha_regression(to_sessions(series, benchmarks.index), benchmarks) 

258 fills = [fill for fill in fills_from_order_events(load_backtest_run(run_dir).get("order_events", [])) if fill.ticker != "BIL"] 

259 stats.update(alpha_annual=alpha.get("alpha_annual"), alpha_t=alpha.get("t_hac"), betas=alpha.get("betas"), run=run_dir.name, 

260 last_fill=fills[-1].date if fills else None) 

261 return stats 

262 

263 

264def stage_eps_judge(args) -> int: 

265 from v650_lean import judge_fallback 

266 

267 done = {} 

268 for line in Path(args.status).read_text(encoding="utf-8-sig").splitlines(): 

269 parts = line.split() 

270 if len(parts) == 3 and parts[0] == "LEAN_DONE" and parts[1].startswith("v650_pool_"): 

271 done[parts[1]] = ROOT / parts[2] 

272 previous = read_json(OUT / "r_lean19.json", {}) 

273 pool = dict(previous["pool"]) 

274 detail: dict[str, dict] = {} 

275 for name in read_json(RESULT, {}).get("survivors_after_correlation") or []: 

276 phases = {f"p{phase}": describe_run(done[f"v650_pool_{name}_p{phase}"]) for phase in range(PHASES)} 

277 long_run = describe_run(done[f"v650_pool_{name}_long"]) 

278 detail[name] = {"phases": phases, "long": long_run} 

279 

280 def median(key: str, phases: dict = phases) -> float | None: 

281 values = [entry[key] for entry in phases.values() if entry.get(key) is not None] 

282 return float(np.median(values)) if values else None 

283 

284 pool[name] = {key: median(key) for key in ("lean_sharpe", "strategy_sharpe", "annual_std", "drawdown_pct", "alpha_annual", "alpha_t")} 

285 pool[name].update(complete=all(entry["complete"] for entry in phases.values()), long_strategy_sharpe=long_run["strategy_sharpe"]) 

286 append_trial(LEDGER, trial_id=name, track="pool", window="verification", role="verification", annualised_sharpe=pool[name]["strategy_sharpe"], n_obs=0, engine="lean", 

287 detail={"lean_sharpe": pool[name]["lean_sharpe"]}) 

288 verdict = judge_fallback(pool, previous["baseline"]) 

289 write_json(OUT / "r_lean19_amended.json", {"baseline": previous["baseline"], "pool": pool, "verdict": verdict, "detail": detail}) 

290 print(json.dumps({"best": verdict["best"], "install": verdict["install"], "pool_top": {name: pool[name] for name in sorted(pool, key=lambda n: -(pool[n]["strategy_sharpe"] or -9))[:3]}, 

291 "detail": detail}, indent=1, default=str)) 

292 return 0 

293 

294 

295def main() -> int: 

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

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

298 score = commands.add_parser("eps-score") 

299 score.add_argument("--draws", type=int, default=200) 

300 commands.add_parser("pbo") 

301 commands.add_parser("eps-pool") 

302 eps_judge = commands.add_parser("eps-judge") 

303 eps_judge.add_argument("--status", required=True) 

304 commands.add_parser("pre2013-make") 

305 judge = commands.add_parser("pre2013-judge") 

306 judge.add_argument("--status", required=True) 

307 args = parser.parse_args() 

308 return {"eps-score": stage_eps_score, "pbo": stage_pbo, "eps-pool": stage_eps_pool, "eps-judge": stage_eps_judge, 

309 "pre2013-make": stage_pre2013_make, "pre2013-judge": stage_pre2013_judge}[args.command](args) 

310 

311 

312if __name__ == "__main__": 

313 raise SystemExit(main())