Coverage for scripts/data_append_refresh.py: 100%

100 statements  

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

1"""Append the latest daily bars to the shipped data without touching a stored row (V6.4.0, Problems.md #215). 

2 

3V5.8.0 rewrote `data/` in full from ONE Yahoo vintage (`auto_adjust=True`), because adjusted bars appended to rows adjusted 

4as of an earlier date put a step at every later dividend or split. This refresh keeps that vintage: for each asset it 

5fetches a little before the last stored date, computes the factor that puts today's vintage back on the stored rows' basis 

6(old close / new close at the latest common date; 1.0 unless a dividend or split happened since), scales ONLY the new rows 

7by it, and merges them behind the existing rows (the writers' "existing rows win" merge). FRED caches are appended the same 

8way. `scripts/data_append_guard.py` proves afterwards that no row up to the cutoff changed. 

9 

10 python scripts/data_append_refresh.py [--end 2026-10-17] [--cutoff 2026-09-30] [--tickers AAPL ...] [--apply] 

11 

12Dry run by default (fetches and reports the factor and the new rows per asset, writes nothing). 

13""" 

14 

15from __future__ import annotations 

16 

17import argparse 

18import json 

19import sys 

20from datetime import date, timedelta 

21from pathlib import Path 

22 

23ROOT_DIR = Path(__file__).resolve().parents[1] 

24sys.path.insert(0, str(ROOT_DIR)) 

25sys.path.insert(0, str(Path(__file__).resolve().parent)) 

26 

27from build_holdout_data import CLASS_KEY_BY_SECURITY_TYPE, yahoo_symbol # noqa: E402 

28from data_append_guard import merge_csv_append_only, scale_new_rows, splice_ratio # noqa: E402 

29 

30from data_pipeline.fetch import ASSET_CLASS_CONFIG # noqa: E402 

31from data_pipeline.fred_backfill import fetch_fred_series, reference_series, rows_to_cache_csv # noqa: E402 

32from data_pipeline.yfinance_backfill import ( # noqa: E402 

33 _read_existing_lean_forex_rows, 

34 _read_existing_lean_rows, 

35 apply_price_overrides, 

36 fetch_yahoo_ohlcv, 

37 sanitize_ohlc, 

38 scale_for_lean, 

39 write_lean_crypto_quote_zip, 

40 write_lean_zip, 

41) 

42 

43OVERLAP_DAYS = 14 

44EXTRA_EQUITY = {"BIL": "data/equity/usa/daily/bil.zip", "SPY": "data/equity/usa/daily/spy.zip"} # outside the universe 

45SUSPICIOUS_RATIO = 0.05 # a splice factor further from 1 than this is a split or a bad print: reported, not hidden 

46 

47 

48def stored_closes(path: Path, security_type: str) -> tuple[dict[str, float], date | None]: 

49 """({date: close in real units}, newest stored date) of one Lean zip.""" 

50 if security_type == "forex": 

51 rows = _read_existing_lean_forex_rows(path) 

52 closes = {row["date"].isoformat(): float(row["bid_close"]) for row in rows} 

53 else: 

54 rows = _read_existing_lean_rows(path) 

55 scale = 10000.0 if security_type == "equity" else 1.0 

56 closes = {row["date"].isoformat(): float(row["close"]) / scale for row in rows} 

57 return closes, (max(row["date"] for row in rows) if rows else None) 

58 

59 

60def refresh_asset(asset: dict, root: Path, end: str, overrides: dict, *, apply: bool) -> dict: 

61 ticker, security_type = asset["ticker"], asset["security_type"] 

62 path = root / asset["data_path"] 

63 if not path.exists(): 

64 return {"status": "no_stored_file"} 

65 old_close, last_stored = stored_closes(path, security_type) 

66 if last_stored is None: 

67 return {"status": "empty_stored_file"} 

68 symbol = yahoo_symbol(asset) 

69 start = (last_stored - timedelta(days=OVERLAP_DAYS)).isoformat() 

70 rows, _overridden = apply_price_overrides(fetch_yahoo_ohlcv(symbol, start, end), overrides.get(ticker)) 

71 rows, _widened = sanitize_ohlc(rows) 

72 if not rows: 

73 return {"status": "no_data", "yahoo_symbol": symbol} 

74 new_close = {row["date"].isoformat(): float(row["close"]) for row in rows} 

75 ratio, anchor = splice_ratio(old_close, new_close) 

76 fresh = scale_new_rows(rows, ratio, last_stored.isoformat()) 

77 report = {"status": "ok", "yahoo_symbol": symbol, "last_stored": last_stored.isoformat(), "ratio": ratio, "ratio_anchor": anchor, 

78 "new_rows": len(fresh), "last_new": fresh[-1]["date"].isoformat() if fresh else None, 

79 "suspicious_ratio": abs(ratio - 1.0) > SUSPICIOUS_RATIO, "no_overlap": anchor is None} 

80 if apply and fresh: 

81 write_fn = ASSET_CLASS_CONFIG[CLASS_KEY_BY_SECURITY_TYPE[security_type]].get("write_fn", write_lean_zip) 

82 write_fn(path, ticker, scale_for_lean(fresh, security_type), merge_with_existing=True) 

83 if security_type == "crypto" and path.name.endswith("_trade.zip"): 

84 write_lean_crypto_quote_zip(path, path.with_name(path.name.replace("_trade.zip", "_quote.zip")), ticker, merge_with_existing=True) 

85 return report 

86 

87 

88def refresh_fred(config: dict, root: Path, end: str, cutoff: str, *, apply: bool) -> dict[str, dict]: 

89 report = {} 

90 cache = root / "data" / "reference" / "fred_series" 

91 for key, series_id in reference_series(config, "all").items(): 

92 path = cache / f"{key}.csv" 

93 if not path.exists(): 

94 report[key] = {"status": "no_stored_file"} 

95 continue 

96 rows = fetch_fred_series(series_id, "1990-01-01", end) 

97 if not rows: 

98 report[key] = {"status": "no_data"} 

99 continue 

100 merged = merge_csv_append_only(path.read_text(encoding="utf-8"), rows_to_cache_csv(rows), cutoff) 

101 added = merged.count("\n") - path.read_text(encoding="utf-8").count("\n") 

102 report[key] = {"status": "ok", "rows_added": added} 

103 if apply: 

104 path.write_text(merged, encoding="utf-8", newline="\n") 

105 return report 

106 

107 

108def main() -> int: 

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

110 parser.add_argument("--end", default=(date.today() + timedelta(days=1)).isoformat(), help="Yahoo end date (exclusive)") 

111 parser.add_argument("--cutoff", default="2026-09-30", help="rows up to this date must stay byte-identical (FRED rule)") 

112 parser.add_argument("--tickers", nargs="*", default=None) 

113 parser.add_argument("--skip-fred", action="store_true") 

114 parser.add_argument("--report", default=str(ROOT_DIR / "ml" / "evaluation" / "v640" / "data_refresh.json")) 

115 parser.add_argument("--apply", action="store_true") 

116 args = parser.parse_args() 

117 

118 config = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8")) 

119 overrides_path = ROOT_DIR / "data_pipeline" / "price_overrides.json" 

120 overrides = json.loads(overrides_path.read_text(encoding="utf-8")) if overrides_path.exists() else {} 

121 assets = list(config["phase1"]["universe"]["assets"]) 

122 known = {asset["ticker"] for asset in assets} 

123 assets += [{"ticker": ticker, "security_type": "equity", "data_path": path} for ticker, path in EXTRA_EQUITY.items() if ticker not in known] 

124 report: dict[str, dict] = {} 

125 for asset in assets: 

126 if args.tickers and asset["ticker"] not in args.tickers: 

127 continue 

128 if asset["security_type"] not in CLASS_KEY_BY_SECURITY_TYPE: 

129 continue 

130 report[asset["ticker"]] = refresh_asset(asset, ROOT_DIR, args.end, overrides, apply=args.apply) 

131 entry = report[asset["ticker"]] 

132 print(f"{asset['ticker']:10s} {entry['status']:8s} " + ( 

133 f"+{entry['new_rows']:3d} rows to {entry['last_new']} ratio {entry['ratio']:.6f}" + (" SUSPICIOUS" if entry["suspicious_ratio"] else "") 

134 if entry["status"] == "ok" else ""), flush=True) 

135 fred = {} if args.skip_fred else refresh_fred(config, ROOT_DIR, args.end, args.cutoff, apply=args.apply) 

136 flagged = sorted(t for t, e in report.items() if e["status"] != "ok" or e.get("suspicious_ratio") or e.get("no_overlap")) 

137 print(f"{len(report)} assets, {len(flagged)} flagged: {flagged}; FRED: {sum(1 for e in fred.values() if e['status'] == 'ok')} series") 

138 if args.apply: 

139 Path(args.report).parent.mkdir(parents=True, exist_ok=True) 

140 Path(args.report).write_text(json.dumps({"end": args.end, "assets": report, "fred": fred}, indent=1), encoding="utf-8") 

141 return 0 

142 

143 

144if __name__ == "__main__": 

145 raise SystemExit(main())