Coverage for scripts/v660_round2.py: 100%
259 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""V6.6.0 addendum: a second, small selection round on the free cell S, and the report-only analyses round 1 left undone.
3Round 2 exists because round 1's evidence says where the cost goes: eight sleeves earn a positive no-cost Sharpe that costs then take away. Its eight
4trials (rules_r2.json, hashed and recorded in the vault before any score) test two standard remedies, a no-trade band and a wider book, and one fixed
5composite of the lowest-turnover signals. They are counted in the trial ledger (so in the deflated Sharpe's N), judged by round 1's unchanged bar,
6and read only cell S on side-A names. Nothing here opens V1, V2, V3, P or CV.
8 python scripts/v660_round2.py rules
9 python scripts/v660_round2.py score
10 python scripts/v660_round2.py placebo [--draws 100]
11 python scripts/v660_round2.py gate
12 python scripts/v660_round2.py pbo
13 python scripts/v660_round2.py report # rank IC by year, sector and liquidity; costs at 2x and NAV 25k (no gate reads these)
14 python scripts/v660_round2.py ib_subset # the installed sleeve on the coins IB lists, at IB's fees
15 python scripts/v660_round2.py kraken_subset # the same on the 11 coins Kraken lists, at Kraken's taker fee
16"""
18from __future__ import annotations
20import argparse
21import dataclasses
22import hashlib
23import json
24import sys
25from pathlib import Path
27import numpy as np
28import pandas as pd
30ROOT = Path(__file__).resolve().parents[1]
31sys.path.insert(0, str(ROOT))
32sys.path.insert(0, str(ROOT / "scripts"))
34from v660_research import ( # noqa: E402
35 DAILY,
36 LEDGER,
37 OUT,
38 WINDOW_LABEL,
39 _ic_clause,
40 _show,
41 assert_selection_only,
42 base_config,
43 check_rules,
44 load_cells,
45 passes_earlier_clauses,
46 read_json,
47 write_json,
48)
49from v660_trials import PBO_COLUMNS, SECTORS, TOP_K, W, min_live_names # noqa: E402
51from evaluation.premia_research import ( # noqa: E402
52 annual_sharpe,
53 nulls_for,
54 placebo_p_value,
55 placebo_sharpes,
56 score_sleeve,
57 selection_gate,
58 weights_for,
59)
60from evaluation.target_weights_engine import simulate_target_weights # noqa: E402
61from evaluation.trial_ledger import append_trial # noqa: E402
62from portfolio.premia_signals import XS, SleeveSpec # noqa: E402
63from portfolio.wide_signals import live_names_per_rebalance, rank_mean # noqa: E402
65RULES_R2 = OUT / "rules_r2.json"
66RULES_R2_SHA = OUT / "rules_r2.sha256"
67SCORES_R2 = OUT / "selection_scores_r2.json"
68DAILY_R2 = OUT / "selection_daily_r2.parquet"
69GATE_R2 = OUT / "selection_gate_r2.json"
70PBO_R2 = OUT / "selection_pbo_r2.json"
71REPORT_R2 = OUT / "report_only_r2.json"
72IB_SUBSET = OUT / "ib_subset.json"
74# id: (what it tests, base table(s), rebalance days, names per sector, no-trade band as a share of NAV, why)
75TRIALS = {
76 "r01": ("a wider book", ("w04",), 20, 10, 0.001, "w04 had the best net score and the nearest miss; twice the names per sector halves the single-name noise"),
77 "r02": ("a fixed composite", ("w03", "w04"), 20, TOP_K, 0.001, "asset growth and accruals: the two lowest-turnover signals with a positive net score; equal rank mean, never fitted"),
78 "r03": ("a fixed composite", ("w03", "w04", "w06"), 20, TOP_K, 0.001, "r02 plus the quality composite, the third lowest-turnover signal with a positive net score"),
79 "r04": ("a no-trade band", ("w14",), 5, TOP_K, 0.01, "residual reversal earned 0.63 before costs and paid them out at a turnover of 97; skip trades under 1% of NAV"),
80 "r05": ("a no-trade band", ("w14",), 10, TOP_K, 0.01, "r04 at half the rebalance frequency"),
81 "r06": ("a no-trade band", ("w11",), 20, TOP_K, 0.005, "52-week high: 0.39 before costs, 0.26 after, turnover 19"),
82 "r07": ("a no-trade band", ("w09",), 20, TOP_K, 0.005, "residual momentum: 0.33 before costs, 0.13 after, turnover 12"),
83 "r08": ("a no-trade band", ("w10",), 20, TOP_K, 0.005, "overnight momentum: 0.36 before costs, 0.19 after, turnover 9.6"),
84}
85IB_COINS = ("BTCUSD", "ETHUSD", "LTCUSD", "BCHUSD", "LINKUSD", "XRPUSD", "ADAUSD", "DOGEUSD")
86# Cost-sensitivity set: every sleeve whose no-cost Sharpe was positive in round 1, plus round 2's.
87SENSITIVITY = ("w03", "w04", "w06", "w09", "w10", "w11", "w14", "w15")
90def spec_of(trial: str) -> SleeveSpec:
91 _, _, every, top_k, _, _ = TRIALS[trial]
92 return SleeveSpec(trial, "W", XS, "external_score", SECTORS, every, {"table": trial, "top_k": top_k})
95def band_of(trial: str) -> float:
96 return TRIALS[trial][4]
99def check_rules_r2() -> dict:
100 check_rules()
101 payload = RULES_R2.read_bytes()
102 if hashlib.sha256(payload).hexdigest() != RULES_R2_SHA.read_text(encoding="utf-8").strip():
103 raise SystemExit("rules_r2.json is not the recorded hash")
104 return json.loads(payload)
107def stage_rules(args) -> int:
108 if RULES_R2.exists():
109 raise SystemExit("rules_r2.json is already written and is never overwritten")
110 rules = json.loads((OUT / "rules.json").read_text(encoding="utf-8"))
111 payload = {
112 "written": "before any round-2 score",
113 "parent": {"file": "rules.json", "sha256": hashlib.sha256((OUT / "rules.json").read_bytes()).hexdigest()},
114 "why_a_second_round": (
115 "Round 1 found 0 of 28 survivors on cell S. Eight sleeves had a positive no-cost Sharpe that costs removed (w03 .31, w04 .68, w06 .32, w09 .33, "
116 "w10 .36, w11 .39, w14 .63, w15 .19 gross; net 0.10, 0.45, 0.13, 0.13, 0.19, 0.26, -2.06, -0.11). The owner asked for research to improve the model before committing."
117 ),
118 "honest_limits": [
119 "Cell S has now been read by 28 trials; these eight are chosen with that knowledge, so a pass here is weaker than a round-1 pass.",
120 "The deflated Sharpe's N counts them (the same ledger), and the bar is round 1's, unchanged: R-SLEEVE3 and PBO below 0.5 over round 1's columns plus these.",
121 "A survivor would go to a freeze and the unread holdouts V1-V3 and P once. None of them is read in this round.",
122 ],
123 "bar": rules.get("rules", {}).get("R-SLEEVE3") or "round 1's R-SLEEVE3, unchanged",
124 "cell": "S", "side": "A",
125 "trials": {
126 trial: {"tests": tests, "tables": list(tables), "rebalance_every": every, "top_k": top_k, "min_weight_change": band, "why": why}
127 for trial, (tests, tables, every, top_k, band, why) in TRIALS.items()
128 },
129 "report_only": [
130 "rank IC by year, sector and dollar-volume tercile for m1-m5 and w04",
131 f"net Sharpe at 2x costs and at NAV $25k for {', '.join(SENSITIVITY)} and r01-r08",
132 f"the installed crypto sleeve on {', '.join(IB_COINS)} at IB's fee schedule (0.15% with a $1.75 minimum, the middle of its 0.12-0.18%)",
133 ],
134 }
135 RULES_R2.write_text(json.dumps(payload, indent=1), encoding="utf-8", newline="\n")
136 RULES_R2_SHA.write_text(hashlib.sha256(RULES_R2.read_bytes()).hexdigest() + "\n", encoding="utf-8", newline="\n")
137 print(RULES_R2_SHA.read_text().strip())
138 return 0
141def prepared_cell():
142 """Cell S with round 2's tables added and one context per trial (the no-trade band lives in the config)."""
143 cell = load_cells([W[0]])["S"]
144 panel, member = cell.context.panel, cell.member
145 for trial, (_, tables, _, _, _, _) in TRIALS.items():
146 parts = [panel.extras[name] for name in tables]
147 table = parts[0] if len(parts) == 1 else rank_mean(parts, minimum=len(parts))
148 panel.extras[trial] = table.where(member)
149 contexts = {trial: dataclasses.replace(cell.context, config=dataclasses.replace(cell.context.config, min_weight_change=band_of(trial))) for trial in TRIALS}
150 return cell, contexts
153def stage_score(args) -> int:
154 check_rules_r2()
155 cell, contexts = prepared_cell()
156 assert_selection_only(cell.cell.end)
157 scores = read_json(SCORES_R2, {})
158 frames = pd.read_parquet(DAILY_R2).to_dict("series") if DAILY_R2.exists() else {}
159 for trial in TRIALS:
160 if (args.only and trial not in args.only) or (trial in scores and not args.force):
161 continue
162 spec = spec_of(trial)
163 signal = cell.context.panel.extras[trial]
164 live = live_names_per_rebalance(signal.loc[signal.index >= cell.cell.start], spec.rebalance_every)
165 score = score_sleeve(spec, contexts[trial], start=cell.cell.start, split=cell.cell.split, end=cell.cell.end, signal=signal)
166 daily = score.pop("daily")
167 middle = daily[min(daily)]
168 frames[trial] = middle
169 ic = _ic_clause(spec, cell, signal)
170 scores[trial] = {**score, "cell": "S", "live_names": live, "ic": ic, "round": 2}
171 append_trial(LEDGER, trial_id=trial, track="W", window=WINDOW_LABEL, role="candidate", annualised_sharpe=score["sharpe"], n_obs=len(middle), engine="offline",
172 detail={"cell": "S", "round": 2})
173 write_json(SCORES_R2, scores)
174 pd.DataFrame(frames).sort_index().to_parquet(DAILY_R2)
175 first, second, t = _show(score["sharpe_first_half"]), _show(score["sharpe_second_half"]), _show((ic or {}).get("nonoverlap_t"))
176 print(f"{trial} Sharpe {_show(score['sharpe'])} ({first}, {second}) IC t {t} live {live['median']:.0f} turnover {score['turnover']:.1f}", flush=True)
177 return 0
180def stage_placebo(args) -> int:
181 check_rules_r2()
182 scores = read_json(SCORES_R2, {})
183 eligible = [trial for trial in TRIALS if trial in scores and passes_earlier_clauses(trial, "W", scores[trial])]
184 print("reach the placebo clause:", eligible or "none", flush=True)
185 if not eligible:
186 return 0
187 cell, contexts = prepared_cell()
188 path = OUT / "selection_placebos_r2.json"
189 done = read_json(path, {})
190 for trial in eligible:
191 if trial in done and not args.force:
192 continue
193 spec = spec_of(trial)
194 out = {}
195 for mode in nulls_for(spec):
196 sharpes = placebo_sharpes(spec, contexts[trial], mode, start=cell.cell.start, end=cell.cell.end, draws=args.draws)
197 out[mode] = {"p": placebo_p_value(scores[trial]["sharpe"], sharpes), "draws": len(sharpes), "median": float(pd.Series(sharpes).median()) if sharpes else None}
198 print(f"{trial} {mode:12s} p {out[mode]['p']:.3f} median {_show(out[mode]['median'])}", flush=True)
199 done[trial] = out
200 write_json(path, done)
201 return 0
204def stage_gate(args) -> int:
205 check_rules_r2()
206 scores = read_json(SCORES_R2, {})
207 placebos = read_json(OUT / "selection_placebos_r2.json", {})
208 daily = pd.read_parquet(DAILY_R2)
209 eligible = {name: score for name, score in scores.items() if passes_earlier_clauses(name, "W", score)}
210 rows = [{**score, "id": name, "daily": {0: daily[name].dropna()}} for name, score in eligible.items()]
211 p_values = {name: {mode: entry["p"] for mode, entry in tests.items()} for name, tests in placebos.items()}
212 gate = selection_gate(rows, p_values)
213 failed_early = {}
214 for name, score in scores.items():
215 if name in eligible:
216 continue
217 if (score.get("live_names") or {}).get("median", 0.0) < min_live_names(name, "W"):
218 failed_early[name] = "live_names"
219 elif not (score["sharpe"] is not None and score["sharpe"] >= 0.5 and score["sharpe_first_half"] >= 0.4 and score["sharpe_second_half"] >= 0.4):
220 failed_early[name] = "sharpe"
221 else:
222 failed_early[name] = "ic"
223 gate["failed_earlier_clauses"] = failed_early
224 gate["unscored"] = [trial for trial in TRIALS if trial not in scores]
225 write_json(GATE_R2, gate)
226 print(json.dumps({key: gate[key] for key in ("survivors", "failed", "failed_earlier_clauses", "unscored")}, indent=1))
227 return 0
230def stage_pbo(args) -> int:
231 from evaluation.pbo import probability_of_backtest_overfitting
233 check_rules_r2()
234 both = pd.concat([pd.read_parquet(DAILY), pd.read_parquet(DAILY_R2)], axis=1)
235 columns = [name for name in (*PBO_COLUMNS, *TRIALS) if name in both.columns]
236 window = ("2011-01-01", "2018-12-31")
237 matrix = both[columns]
238 matrix = matrix[(matrix.index >= window[0]) & (matrix.index <= window[1])].dropna(how="all").fillna(0.0)
239 result = probability_of_backtest_overfitting(matrix.to_numpy(dtype=float), blocks=16, periods_per_year=252)
240 report = {"pbo": result.get("pbo"), "num_trials": len(columns), "window": "..".join(window), "round_1_columns": len(PBO_COLUMNS), "round_2_columns": len(TRIALS)}
241 write_json(PBO_R2, report)
242 print(json.dumps(report, indent=1))
243 return 0
246def ic_by_group(table: pd.DataFrame, label: pd.DataFrame, groups: dict[str, pd.DataFrame | pd.Series], *, start: str, end: str, step: int = 20) -> dict:
247 """Mean Spearman IC over every `step`th session, overall and within each group. `groups` maps a name to a ticker->group Series (static) or a
248 session x ticker frame of group labels (dynamic)."""
249 dates = [date for date in table.index if start <= date <= end][::step]
250 rows: dict[str, dict[str, list[float]]] = {name: {} for name in groups}
251 rows["year"] = {}
252 for date in dates:
253 pair = pd.concat([table.loc[date], label.loc[date]], axis=1, keys=["s", "y"]).dropna()
254 if len(pair) < 30:
255 continue
256 rows["year"].setdefault(date[:4], []).append(float(pair["s"].rank().corr(pair["y"].rank())))
257 for name, grouping in groups.items():
258 membership = grouping.loc[date] if isinstance(grouping, pd.DataFrame) else grouping
259 for group, part in pair.groupby(membership.reindex(pair.index), observed=True):
260 if len(part) >= 12:
261 rows[name].setdefault(str(group), []).append(float(part["s"].rank().corr(part["y"].rank())))
262 return {name: {group: {"ic": float(np.mean(values)), "dates": len(values)} for group, values in sorted(by.items())} for name, by in rows.items()}
265def cost_variants(context, trial_spec, signal, *, start: str, end: str, split: str) -> dict:
266 """Median-phase net Sharpe at today's costs, 2x costs, NAV $25k, and both."""
267 base = context.config
268 doubled = dataclasses.replace(
269 base, equity_fee_bps=base.equity_fee_bps * 2.0, equity_min_fee_usd=base.equity_min_fee_usd * 2.0,
270 slippage_bps_by_class={name: value * 2.0 for name, value in base.slippage_bps_by_class.items()},
271 )
272 out = {}
273 for label, config, nav in (("as_is", base, 100_000.0), ("costs_2x", doubled, 100_000.0), ("nav_25k", base, 25_000.0), ("nav_25k_costs_2x", doubled, 25_000.0)):
274 values = []
275 for offset in range(0, trial_spec.rebalance_every, max(1, trial_spec.rebalance_every // 5)):
276 weights = weights_for(trial_spec, context, signal, start=start, end=end, phase_offset=offset)
277 result = simulate_target_weights(
278 weights, context.market, config, start=start, end=end, nav=nav, sweep_config=context.sweep, rf_dates=context.rf_dates, rf_rates=context.rf_rates,
279 carry_fn=context.carry,
280 )
281 values.append(annual_sharpe(result["strategy_excess"], sessions=context.market.sessions))
282 finite = [value for value in values if value is not None]
283 out[label] = float(np.median(finite)) if finite else None
284 return out
287def stage_report(args) -> int:
288 check_rules_r2()
289 cell, contexts = prepared_cell()
290 window = cell.cell
291 bars = cell.bars
292 dollar_volume = (bars.raw_close * bars.volume).rolling(60, min_periods=30).median().shift(1)
293 tercile = dollar_volume.rank(axis=1, pct=True).apply(lambda column: pd.cut(column, [0, 1 / 3, 2 / 3, 1.0], labels=["low", "mid", "high"], include_lowest=True))
294 sector = pd.Series(cell.sectors)
295 report: dict = {"ic": {}, "costs": {}}
296 for name in ("m1", "m2", "m3", "m4", "m5", "w04"):
297 table = cell.context.panel.extras.get(name)
298 if table is None:
299 continue
300 report["ic"][name] = ic_by_group(table, cell.label, {"sector": sector, "liquidity": tercile}, start=window.start, end=window.end)
301 print(name, "IC by year", {year: round(value["ic"], 4) for year, value in report["ic"][name]["year"].items()}, flush=True)
302 for trial in (*SENSITIVITY, *TRIALS):
303 if trial in TRIALS:
304 spec, context, signal = spec_of(trial), contexts[trial], cell.context.panel.extras[trial]
305 else:
306 spec = next(item for item in W if item.id == trial)
307 context, signal = cell.context, cell.context.panel.extras[trial]
308 report["costs"][trial] = cost_variants(context, spec, signal, start=window.start, end=window.end, split=window.split)
309 print(trial, report["costs"][trial], flush=True)
310 write_json(REPORT_R2, report)
311 return 0
314def stage_ib_subset(args) -> int:
315 from v660_verdict import INSTALLED
317 from evaluation.premia_research import build_context
318 from portfolio.premia_signals import signal_to_weights, sleeve_signal
320 check_rules_r2()
321 base = base_config()
322 context = build_context(ROOT, base)
323 panel = context.panel
324 signal = sleeve_signal(INSTALLED, panel)
325 crypto = [column for column in signal.columns if panel.asset_class.get(column) == "crypto"]
326 ib_signal = signal.copy()
327 ib_signal[[column for column in crypto if column not in IB_COINS]] = np.nan
328 no_eos = signal.copy()
329 no_eos["EOSUSD"] = np.nan # Coinbase lists EOS-USD as delisted (status "delisted", trading disabled)
331 def ib_fee(asset_class, notional, date, config):
332 return max(1.75, abs(notional) * 15.0 / 1e4) if asset_class == "crypto" else 0.0
334 from evaluation.target_weights_engine import default_fee_usd
336 out = {}
337 for label, window in (("2014-12..2026-11", ("2014-12-01", "2026-11-02")), ("2023-07..2026-11", ("2023-07-01", "2026-11-02")), ("2025-07..2026-11", ("2025-07-01", "2026-11-02"))):
338 for name, table, fee in (
339 ("12_coins_coinbase_fees", signal, default_fee_usd), ("11_coins_without_eos_coinbase_fees", no_eos, default_fee_usd),
340 ("8_ib_coins_coinbase_fees", ib_signal, default_fee_usd), ("8_ib_coins_ib_fees", ib_signal, ib_fee),
341 ):
342 weights = signal_to_weights(table, panel, kind=INSTALLED.kind, rebalance_every=INSTALLED.rebalance_every, settings=context.settings, start=window[0], end=window[1])
343 result = simulate_target_weights(
344 weights, context.market, context.config, start=window[0], end=window[1], sweep_config=context.sweep, rf_dates=context.rf_dates, rf_rates=context.rf_rates,
345 carry_fn=context.carry, fee_fn=fee,
346 )
347 strategy = result["strategy_excess"]
348 out.setdefault(label, {})[name] = {"sharpe": annual_sharpe(strategy), "fees_usd": float(result["fees"]), "mean_gross": float(result["gross"].mean())}
349 print(label, name, out[label][name], flush=True)
350 out["added_after_the_rules_were_hashed"] = "the 11-coins-without-EOS rows: Coinbase's product API says EOS-USD is delisted, found while checking venues. Report only."
351 out["note"] = (
352 "Diagnostic only. The 12 coins were picked with hindsight and the IB list is from press reports, not IB's own page: BTC, ETH, LTC, BCH (Paxos since 2021), "
353 "LINK, XRP, ADA, DOGE (2025-26 additions). XLM, EOS, ETC and ZEC were not found on any IB list."
354 )
355 write_json(IB_SUBSET, out)
356 return 0
359def stage_kraken_subset(args) -> int:
360 """The installed sleeve on the 11 coins Kraken lists (all but EOS) at Kraken's spot taker fee. Its schedule is disputed between sources (0.25%/0.40%
361 maker/taker at the lowest volume tier on one, 0.40%/0.80% on another), so both takers are run. Report only."""
362 from v660_verdict import INSTALLED
364 from evaluation.premia_research import build_context
365 from portfolio.premia_signals import signal_to_weights, sleeve_signal
367 base = base_config()
368 context = build_context(ROOT, base)
369 panel = context.panel
370 signal = sleeve_signal(INSTALLED, panel)
371 signal["EOSUSD"] = np.nan
373 def taker(bps: float):
374 return lambda asset_class, notional, date, config: abs(notional) * bps / 1e4 if asset_class == "crypto" else 0.0
376 out = {}
377 for label, window in (("2014-12..2026-11", ("2014-12-01", "2026-11-02")), ("2023-07..2026-11", ("2023-07-01", "2026-11-02")), ("2025-07..2026-11", ("2025-07-01", "2026-11-02"))):
378 weights = signal_to_weights(signal, panel, kind=INSTALLED.kind, rebalance_every=INSTALLED.rebalance_every, settings=context.settings, start=window[0], end=window[1])
379 for name, fee in (("kraken_taker_40bps", taker(40.0)), ("kraken_taker_80bps", taker(80.0))):
380 result = simulate_target_weights(
381 weights, context.market, context.config, start=window[0], end=window[1], sweep_config=context.sweep, rf_dates=context.rf_dates, rf_rates=context.rf_rates,
382 carry_fn=context.carry, fee_fn=fee,
383 )
384 out.setdefault(label, {})[name] = {"sharpe": annual_sharpe(result["strategy_excess"]), "fees_usd": float(result["fees"])}
385 print(label, name, out[label][name], flush=True)
386 out["note"] = "Diagnostic only, hindsight coins. Coinbase's date-effective schedule on the same 11 coins is in ib_subset.json (11_coins_without_eos_coinbase_fees)."
387 write_json(OUT / "kraken_subset.json", out)
388 return 0
391def main() -> int:
392 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
393 commands = parser.add_subparsers(dest="stage", required=True)
394 commands.add_parser("rules")
395 score = commands.add_parser("score")
396 score.add_argument("--only", nargs="*", default=None)
397 score.add_argument("--force", action="store_true")
398 placebo = commands.add_parser("placebo")
399 placebo.add_argument("--draws", type=int, default=100)
400 placebo.add_argument("--force", action="store_true")
401 for name in ("gate", "pbo", "report", "ib_subset", "kraken_subset"):
402 commands.add_parser(name)
403 args = parser.parse_args()
404 return {"rules": stage_rules, "score": stage_score, "placebo": stage_placebo, "gate": stage_gate, "pbo": stage_pbo, "report": stage_report, "ib_subset": stage_ib_subset, "kraken_subset": stage_kraken_subset}[args.stage](args)
407if __name__ == "__main__":
408 raise SystemExit(main())