Coverage for scripts/splice_holdout_dataset.py: 100%
145 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"""Refresh the holdout rows of `ml/datasets/full_dataset.csv` on the 4 GB dev PC (V6.4.2), instead of the ~8 GB `--full-splits` build.
3A data refresh only appends bars (`scripts/data_append_refresh.py`), so every row before the holdout is unchanged and only the
4holdout window needs building. `build_holdout_dataset.py` still builds the train and validation rows of its windows config, so
5this tool hands it a windows config whose train / validation windows are one month each in 2014-15: the builder then holds
6little more than the build window. The build starts a sensitivity lookback (252 rows) plus a month before the splice, because
7the `sens_*` betas regress on the rows the builder kept (a build that started in 2025-03 left them at 0.0, which the guard
8caught). The new rows replace the old file's rows from `--splice-from` on, streamed line by line.
10The overlap guard proves the narrow build equals the full one before anything is written: every old row dated
11`--splice-from`..`--compare-until` must exist in the new build with the same features (within 1e-9) and the same labels
12(`--compare-until` sits a label horizon before the old data end, so those labels were resolved in both), except the four
13`SAMPLE_DEPENDENT_LABELS`, whose whole-history beta moves with any rebuild; the result counts how many of their cells moved. Rows outside the
14holdout (`train` / `validation` / `backtest`) are copied verbatim, so the per-split files stay valid and are not rewritten.
16 python scripts/splice_holdout_dataset.py --build [--build-start 2024-05-31] [--build-end 2026-10-16]
17 python scripts/splice_holdout_dataset.py --splice --splice-from 2025-07-01 --compare-until 2026-08-28
18"""
20from __future__ import annotations
22import argparse
23import csv
24import json
25import math
26import subprocess
27import sys
28from pathlib import Path
30ROOT_DIR = Path(__file__).resolve().parents[1]
31DATASETS = ROOT_DIR / "ml" / "datasets"
32DEFAULT_OLD = DATASETS / "full_dataset.csv"
33DEFAULT_WINDOW = DATASETS / "v642_holdout_window.csv"
34DEFAULT_WINDOWS_CONFIG = ROOT_DIR / "ml" / "evaluation" / "v642" / "splice_windows.json"
35KEPT_SPLITS = ("train", "validation", "backtest")
36# labels built on ONE whole-history beta per asset (train.build_cross_sectional_rank_targets' beta-neutral block,
37# train.build_residual_rank_targets): they move with the build's sample, so no partial build can reproduce them, and a full
38# rebuild changes them on every row too. Neither head is on the shipped path (beta-neutral disabled, residual demoted, #226).
39SAMPLE_DEPENDENT_LABELS = frozenset({
40 "target_beta_neutral_rank_5d", "target_beta_neutral_rank_20d", "target_residual_rank_5d", "target_residual_rank_20d",
41})
42TOLERANCE = 1e-9
43NARROW_TRAINING = {"start": "2014-12-01", "end": "2014-12-31"}
44NARROW_VALIDATION = {"start": "2015-01-02", "end": "2015-01-30"}
46csv.field_size_limit(min(sys.maxsize, 2**31 - 1))
49def default_build_start(config: dict, splice_from: str) -> str:
50 """A build start that leaves every trailing per-row window whole by `splice_from`: the sensitivity betas regress on the
51 last `lookback_days` ROWS the builder kept (a narrow build drops 2015..build start), so it needs that many equity sessions
52 (~1.45 calendar days each) plus a month before the splice."""
53 from datetime import date, timedelta
55 sensitivity = config.get("phase1", {}).get("features", {}).get("cross_asset_sensitivity", {}) or {}
56 lookback = int(sensitivity.get("lookback_days", 252) or 252)
57 return (date.fromisoformat(splice_from) - timedelta(days=int(lookback * 1.45) + 31)).isoformat()
60def narrow_windows_config(config: dict, build_start: str, build_end: str) -> dict:
61 """A `--windows-config` for build_holdout_dataset.py: tiny train / validation windows, the build window as holdout."""
62 windows = dict(config["phase1"]["windows"])
63 windows.update(training=dict(NARROW_TRAINING), validation=dict(NARROW_VALIDATION),
64 holdout={"start": build_start, "end": build_end})
65 return {"phase1": {"windows": windows}}
68def values_equal(old: str, new: str, tolerance: float = TOLERANCE) -> bool:
69 """CSV cells equal as text, or as finite numbers within `tolerance`, or both empty / both NaN."""
70 if old == new:
71 return True
72 try:
73 a, b = float(old), float(new)
74 except ValueError:
75 return False
76 if math.isnan(a) and math.isnan(b):
77 return True
78 return math.isfinite(a) and math.isfinite(b) and abs(a - b) <= tolerance * max(1.0, abs(a), abs(b))
81def overlap_mismatches(old_rows, new_rows, header: list[str], ignore: set[str], limit: int = 20) -> dict:
82 """Merge-join of two (date, ticker)-sorted row streams: {"missing": old keys absent from the new stream, "cells":
83 [(key, column, old, new)], "compared": n}. Streams, so the 4 GB PC never holds the overlap in memory."""
84 index = [position for position, name in enumerate(header) if name not in ignore]
85 date_col, ticker_col = header.index("date"), header.index("ticker")
86 missing, cells, compared = [], [], 0
87 new_iter = iter(new_rows)
88 new = next(new_iter, None)
89 for old in old_rows:
90 key = (old[date_col], old[ticker_col])
91 while new is not None and (new[date_col], new[ticker_col]) < key:
92 new = next(new_iter, None)
93 compared += 1
94 if new is None or (new[date_col], new[ticker_col]) != key:
95 missing.append(key)
96 continue
97 for position in index:
98 if len(cells) < limit and not values_equal(old[position], new[position]):
99 cells.append((key, header[position], old[position], new[position]))
100 return {"missing": missing, "cells": cells, "compared": compared}
103def _rows(path: Path):
104 with path.open(newline="", encoding="utf-8") as handle:
105 reader = csv.reader(handle)
106 header = next(reader)
107 yield header
108 yield from reader
111def dated(path: Path, date_from: str, date_to: str, date_col: int):
112 """Rows dated date_from..date_to (ISO strings compare as dates) of a date-sorted dataset, streamed."""
113 rows = _rows(path)
114 next(rows)
115 for row in rows:
116 if row[date_col] > date_to:
117 return
118 if row[date_col] >= date_from:
119 yield row
122def splice(old_path: Path, window_path: Path, out_path: Path, splice_from: str, compare_until: str) -> dict:
123 old_iter = _rows(old_path)
124 header = next(old_iter)
125 window_header = next(_rows(window_path))
126 if window_header != header:
127 raise ValueError("the window build's columns differ from the old dataset's: rebuild it with the same config")
128 date_col, split_col = header.index("date"), header.index("split")
130 check = overlap_mismatches(dated(old_path, splice_from, compare_until, date_col),
131 dated(window_path, splice_from, compare_until, date_col), header,
132 ignore={"split", *SAMPLE_DEPENDENT_LABELS})
133 if check["missing"] or check["cells"]:
134 raise ValueError(f"overlap guard failed ({check['compared']} rows compared): {len(check['missing'])} rows missing, "
135 f"first cell differences {check['cells'][:5]}")
136 moved = overlap_mismatches(dated(old_path, splice_from, compare_until, date_col),
137 dated(window_path, splice_from, compare_until, date_col), header,
138 ignore=set(header) - SAMPLE_DEPENDENT_LABELS, limit=10**9)
140 tmp_path = out_path.with_suffix(".splice.tmp")
141 counts = {"kept": 0, "dropped_old_holdout": 0, "new_holdout": 0}
142 try:
143 last_new_date = _write_spliced(tmp_path, header, old_iter, window_path, splice_from, date_col, split_col, counts)
144 except BaseException:
145 tmp_path.unlink(missing_ok=True)
146 raise
147 tmp_path.replace(out_path)
148 return dict(counts, compared=check["compared"], last_date=last_new_date,
149 sample_dependent_cells_moved=len(moved["cells"]))
152def _write_spliced(tmp_path: Path, header: list[str], old_iter, window_path: Path, splice_from: str, date_col: int,
153 split_col: int, counts: dict) -> str | None:
154 last_new_date = None
155 with tmp_path.open("w", newline="", encoding="utf-8") as handle:
156 writer = csv.writer(handle, lineterminator="\n")
157 writer.writerow(header)
158 for row in old_iter:
159 if row[date_col] < splice_from:
160 writer.writerow(row)
161 counts["kept"] += 1
162 elif row[split_col] in KEPT_SPLITS:
163 raise ValueError(f"a {row[split_col]} row dated {row[date_col]} sits after --splice-from; pick an earlier date")
164 else:
165 counts["dropped_old_holdout"] += 1
166 window = _rows(window_path)
167 next(window)
168 for row in window:
169 if row[date_col] >= splice_from and row[split_col] == "backtest":
170 row[split_col] = "holdout"
171 writer.writerow(row)
172 counts["new_holdout"] += 1
173 last_new_date = max(last_new_date or row[date_col], row[date_col])
174 return last_new_date
177def main() -> int:
178 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
179 parser.add_argument("--build", action="store_true", help="build the holdout window with narrow train / validation windows")
180 parser.add_argument("--build-start", default=None,
181 help="default: a sensitivity lookback (252 sessions) plus a month before --splice-from")
182 parser.add_argument("--build-end", default=None, help="default: phase1.windows.holdout.end of config.json")
183 parser.add_argument("--splice", action="store_true", help="check the overlap, then replace the old holdout rows")
184 parser.add_argument("--splice-from", default=None, help="default: phase1.windows.holdout.start of config.json")
185 parser.add_argument("--compare-until", default=None, help="last date whose labels both builds resolved")
186 parser.add_argument("--old", type=Path, default=DEFAULT_OLD)
187 parser.add_argument("--window", type=Path, default=DEFAULT_WINDOW)
188 parser.add_argument("--out", type=Path, default=None, help="default: --old (written through a temp file)")
189 parser.add_argument("--scaler-stats", default=None, help="with --build: the scaler to apply (default: the active one; V6.6.10, a retrained candidate's own)")
190 parser.add_argument("--manifest", default=None, help="with --build: the asset-quality flags to apply (default: the active ones)")
191 args = parser.parse_args()
192 config = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8"))
193 holdout = config["phase1"]["windows"]["holdout"]
194 splice_from = args.splice_from or holdout["start"]
195 if args.build:
196 build_start = args.build_start or default_build_start(config, splice_from)
197 windows_config = narrow_windows_config(config, build_start, args.build_end or holdout["end"])
198 DEFAULT_WINDOWS_CONFIG.parent.mkdir(parents=True, exist_ok=True)
199 DEFAULT_WINDOWS_CONFIG.write_text(json.dumps(windows_config, indent=2), encoding="utf-8")
200 command = [sys.executable, str(ROOT_DIR / "scripts" / "build_holdout_dataset.py"), "--windows-config", str(DEFAULT_WINDOWS_CONFIG),
201 "--start", build_start, "--end", args.build_end or holdout["end"], "--output", str(args.window),
202 *(["--scaler-stats", args.scaler_stats] if args.scaler_stats else []), *(["--manifest", args.manifest] if args.manifest else [])]
203 print(" ".join(command))
204 if subprocess.call(command) != 0:
205 return 1
206 if args.splice:
207 if not args.compare_until:
208 parser.error("--splice needs --compare-until (a label horizon before the old data end)")
209 result = splice(args.old, args.window, args.out or args.old, splice_from, args.compare_until)
210 print(json.dumps(result, indent=2))
211 return 0
214if __name__ == "__main__":
215 raise SystemExit(main())