Coverage for scripts/data_append_guard.py: 100%
102 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"""Append-only guard for the data refresh (V6.4.0, Problems.md #215). stdlib only.
3The shipped data is one consistent Yahoo vintage (`auto_adjust=True`); every trained model and every Lean run read it. A
4refresh to a later date must therefore only ADD rows after the cutoff: any change to a row dated on or before it (a
5revised dividend adjustment, a corrected print) would move the dataset, the models' inputs and the Lean paths that the
6BT5 = BT4 check relies on. This module hashes the rows up to the cutoff before the refresh and verifies them after, and
7holds the splice that puts the new rows on the old rows' price basis.
9 python scripts/data_append_guard.py snapshot --out ml/evaluation/v640/data_before.json [--cutoff 2026-09-30]
10 python scripts/data_append_guard.py verify --before ml/evaluation/v640/data_before.json --out ml/evaluation/v640/data_append_guard.json
11"""
13from __future__ import annotations
15import argparse
16import hashlib
17import json
18import re
19import sys
20import zipfile
21from pathlib import Path
23ROOT_DIR = Path(__file__).resolve().parents[1]
25# relative to data/: the files the models and Lean read as dated rows
26PATTERNS = ("equity/usa/daily/*.zip", "crypto/coinbase/daily/*.zip", "forex/oanda/daily/*.zip", "reference/fred_series/*.csv")
27_LEAN_DATE = re.compile(r"^(\d{4})(\d{2})(\d{2})[ ,]")
28_ISO_DATE = re.compile(r"^(\d{4})-(\d{2})-(\d{2})\b")
29PRICE_FIELDS = ("open", "high", "low", "close")
32def row_date(line: str) -> str | None:
33 """YYYY-MM-DD of a Lean row ("20260930 00:00,...") or a FRED cache row ("2026-09-30,2.35"); None for anything else."""
34 match = _LEAN_DATE.match(line) or _ISO_DATE.match(line)
35 return f"{match.group(1)}-{match.group(2)}-{match.group(3)}" if match else None
38def file_lines(path: Path) -> list[str]:
39 """The file's data lines (first member of a zip, or the text of a csv), no blank lines, CRs stripped."""
40 if path.suffix == ".zip":
41 with zipfile.ZipFile(path) as archive:
42 text = archive.read(archive.namelist()[0]).decode("utf-8")
43 else:
44 text = path.read_text(encoding="utf-8")
45 return [line.rstrip("\r") for line in text.split("\n") if line.strip()]
48def rows_up_to(lines: list[str], cutoff: str) -> list[str]:
49 return [line for line in lines if (row_date(line) or "9999-99-99") <= cutoff]
52def digest(lines: list[str]) -> str:
53 return hashlib.sha256("\n".join(lines).encode("utf-8")).hexdigest()
56def snapshot(data_dir: Path, cutoff: str, patterns=PATTERNS) -> dict[str, dict]:
57 """{relative path: {"sha256": digest of the rows dated <= cutoff, "rows": their count, "last": newest date}}."""
58 out = {}
59 for pattern in patterns:
60 for path in sorted(Path(data_dir).glob(pattern)):
61 lines = file_lines(path)
62 kept = rows_up_to(lines, cutoff)
63 dates = [row_date(line) for line in lines if row_date(line)]
64 out[path.relative_to(data_dir).as_posix()] = {"sha256": digest(kept), "rows": len(kept), "last": max(dates) if dates else None}
65 return out
68def verify(before: dict[str, dict], after: dict[str, dict]) -> list[dict]:
69 """The files whose pre-cutoff rows changed or vanished: [{"path", "reason"}]. A file that is new after the refresh is
70 not a violation."""
71 problems = []
72 for path, entry in before.items():
73 now = after.get(path)
74 if now is None:
75 problems.append({"path": path, "reason": "missing_after_refresh"})
76 elif now["sha256"] != entry["sha256"]:
77 problems.append({"path": path, "reason": "rows_up_to_the_cutoff_changed", "rows_before": entry["rows"], "rows_after": now["rows"]})
78 return problems
81# ---------------------------------------------------------------- the splice: new rows on the old rows' basis
84def splice_ratio(old_close: dict[str, float], new_close: dict[str, float]) -> tuple[float, str | None]:
85 """old / new close at the LATEST date both series have: the factor that puts a fresher Yahoo vintage (adjusted for
86 dividends and splits up to today) back on the basis of the rows already stored. (1.0, None) with no common date."""
87 common = sorted(set(old_close) & set(new_close))
88 for day in reversed(common):
89 if new_close[day] > 0.0 and old_close[day] > 0.0:
90 ratio = old_close[day] / new_close[day]
91 return (1.0 if abs(ratio - 1.0) < 1e-9 else ratio), day
92 return 1.0, None
95def scale_new_rows(rows: list[dict], ratio: float, after: str, fields=PRICE_FIELDS) -> list[dict]:
96 """The rows dated after `after` with their price fields multiplied by `ratio` (volume untouched); older rows dropped."""
97 out = []
98 for row in rows:
99 if str(row["date"])[:10] > after:
100 scaled = dict(row)
101 for field in fields:
102 if field in scaled:
103 scaled[field] = scaled[field] * ratio
104 out.append(scaled)
105 return out
108def merge_csv_append_only(old_text: str, new_text: str, cutoff: str) -> str:
109 """A dated csv (FRED cache) where the rows dated <= cutoff are exactly the stored ones (no revision, no late addition)
110 and rows after it come from the fresh fetch, sorted by date, header preserved."""
111 old_lines = [line.rstrip("\r") for line in old_text.split("\n")]
112 header = [line for line in old_lines if line.strip() and row_date(line) is None]
113 kept = {row_date(line): line for line in old_lines if row_date(line)}
114 merged = {day: line for day, line in kept.items() if day <= cutoff}
115 for line in (line.rstrip("\r") for line in new_text.split("\n")):
116 day = row_date(line)
117 if day and day > cutoff:
118 merged[day] = line
119 # a date <= cutoff the stored file lacks (a monthly rate published late) stays out: a dataset row of that day
120 # never saw it, and adding it would move the feature values read as-of that day
121 return "\n".join(header + [merged[day] for day in sorted(merged)]) + "\n"
124def main() -> int:
125 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
126 sub = parser.add_subparsers(dest="command", required=True)
127 snap = sub.add_parser("snapshot")
128 snap.add_argument("--data-dir", default=str(ROOT_DIR / "data"))
129 snap.add_argument("--cutoff", default="2026-09-30")
130 snap.add_argument("--out", required=True)
131 check = sub.add_parser("verify")
132 check.add_argument("--data-dir", default=str(ROOT_DIR / "data"))
133 check.add_argument("--before", required=True)
134 check.add_argument("--out", default=None)
135 args = parser.parse_args()
136 if args.command == "snapshot":
137 payload = {"cutoff": args.cutoff, "files": snapshot(Path(args.data_dir), args.cutoff)}
138 Path(args.out).parent.mkdir(parents=True, exist_ok=True)
139 Path(args.out).write_text(json.dumps(payload, indent=1), encoding="utf-8")
140 print(f"snapshot of {len(payload['files'])} files up to {args.cutoff} -> {args.out}")
141 return 0
142 before = json.loads(Path(args.before).read_text(encoding="utf-8"))
143 cutoff = before["cutoff"]
144 problems = verify(before["files"], snapshot(Path(args.data_dir), cutoff))
145 report = {"cutoff": cutoff, "files_checked": len(before["files"]), "violations": problems}
146 if args.out:
147 Path(args.out).parent.mkdir(parents=True, exist_ok=True)
148 Path(args.out).write_text(json.dumps(report, indent=1), encoding="utf-8")
149 print(f"{report['files_checked']} files checked, {len(problems)} with changed rows up to {cutoff}")
150 for problem in problems[:20]:
151 print(" ", problem)
152 return 1 if problems else 0
155if __name__ == "__main__":
156 sys.exit(main())