Coverage for data_pipeline/yfinance_backfill.py: 100%
270 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"""Yahoo Finance historical data backfill (Phase V2-19.5).
3Manual, offline maintenance script — never runs inside the Lean container or
4any always-on Docker worker (mirrors train_topology.py's "never runs in the
5Lean container" status, not performance/trigger_worker.py's continuous-worker
6one). Fills gaps in thin local Lean zips (e.g. ETHUSD/LTCUSD, which only have
7a few scattered days of real Coinbase minute data — see
8train.py::ensure_derived_crypto_daily_series() and development/Changelog.md's
9Phase-9 entry) using `yfinance`.
11Two independent safety boundaries, both requiring an explicit human step:
121. Writing/overwriting zip files is gated by --apply (default: dry run only).
132. config.json's available_from/available_to are NEVER edited by this
14 script, --apply or not — train.py::build_asset_quality() only counts rows
15 inside those configured windows (config.json phase9.asset_quality), so
16 widening the zip alone does nothing until a human widens the window too.
17 This script only prints the suggested new values.
19Usage:
20 python -m data_pipeline.yfinance_backfill [--tickers ETHUSD LTCUSD] [--apply]
21"""
23from __future__ import annotations
25import argparse
26import json
27import logging
28import math
29from collections.abc import Callable
30from datetime import date, datetime, timedelta
31from pathlib import Path
32from zipfile import ZipFile
34import pandas as pd
36logger = logging.getLogger(__name__)
38ROOT = Path(__file__).resolve().parents[1]
39CONFIG_PATH = ROOT / "config.json"
41# Internal ticker -> Yahoo symbol, used only when the asset's own
42# config.json "backfill" block doesn't set an explicit "symbol".
43YAHOO_TICKER_OVERRIDES = {
44 "ETHUSD": "ETH-USD",
45 "BTCUSD": "BTC-USD",
46 "LTCUSD": "LTC-USD",
47}
50# ---------------------------------------------------------------------------
51# Pure helpers
52# ---------------------------------------------------------------------------
55def yahoo_symbol_for(ticker: str, backfill_config: dict) -> str:
56 """backfill_config["symbol"] wins if present, else YAHOO_TICKER_OVERRIDES,
57 else the internal ticker unchanged (equities: AAPL -> AAPL)."""
58 explicit = backfill_config.get("symbol")
59 if explicit:
60 return str(explicit)
61 return YAHOO_TICKER_OVERRIDES.get(ticker, ticker)
64def detect_gap(asset: dict, existing_rows: list[dict]) -> dict:
65 """Pure: compares the asset's configured backfill_from/backfill_to
66 against the dates already present in its Lean zip (existing_rows, each a
67 dict with a "date" key holding a datetime.date). Returns whether a real
68 gap exists and the date range that should actually be fetched.
69 """
70 backfill_config = asset.get("backfill") or {}
71 if not backfill_config:
72 return {"needs_backfill": False, "missing_before": None, "missing_after": None, "fetch_start": None, "fetch_end": None}
74 fetch_start = date.fromisoformat(backfill_config["backfill_from"])
75 fetch_end = date.fromisoformat(backfill_config["backfill_to"])
77 existing_dates = [row["date"] for row in existing_rows]
78 existing_min = min(existing_dates) if existing_dates else None
79 existing_max = max(existing_dates) if existing_dates else None
81 missing_before = fetch_start if (existing_min is None or fetch_start < existing_min) else None
82 missing_after = fetch_end if (existing_max is None or fetch_end > existing_max) else None
84 return {
85 "needs_backfill": missing_before is not None or missing_after is not None,
86 "missing_before": missing_before,
87 "missing_after": missing_after,
88 "fetch_start": fetch_start,
89 "fetch_end": fetch_end,
90 }
93def apply_price_overrides(rows: list[dict], overrides: list[dict] | None) -> tuple[list[dict], int]:
94 """V5.8.0: applies verified single-bar corrections ({"date": "YYYY-MM-DD", "set": {field: value}}, from
95 data_pipeline/price_overrides.json) to unscaled Yahoo rows. Returns (rows, number of rows changed)."""
96 by_date = {str(entry["date"])[:10]: dict(entry.get("set") or {}) for entry in (overrides or [])}
97 if not by_date:
98 return rows, 0
99 out, changed = [], 0
100 for row in rows:
101 fields = by_date.get(row["date"].isoformat() if hasattr(row["date"], "isoformat") else str(row["date"])[:10])
102 if fields:
103 row = {**row, **{key: float(value) for key, value in fields.items()}}
104 changed += 1
105 out.append(row)
106 return out, changed
109def sanitize_ohlc(rows: list[dict]) -> tuple[list[dict], int]:
110 """V5.8.0: Yahoo's forex bars often carry a high below max(open, close) or a low above min(open, close) (57-226 rows
111 per pair over 2013-2026). Lean and every range feature (ATR, Corwin-Schultz spread) assume low <= open/close <= high,
112 so the high/low are widened to contain the open and close. Returns (rows, number of rows changed); consistent rows
113 pass through untouched."""
114 cleaned, changed = [], 0
115 for row in rows:
116 high = max(row["high"], row["open"], row["close"])
117 low = min(row["low"], row["open"], row["close"])
118 if high != row["high"] or low != row["low"]:
119 changed += 1
120 row = {**row, "high": high, "low": low}
121 cleaned.append(row)
122 return cleaned, changed
125def scale_for_lean(rows: list[dict], security_type: str) -> list[dict]:
126 """Applies train.py's x10000 integer convention for equities (Lean's
127 deflated-price format — see train.py::load_lean_bars()); crypto rows
128 pass through unscaled, matching
129 train.py::ensure_derived_crypto_daily_series(). Pure — no I/O.
130 """
131 if security_type != "equity":
132 return [dict(row) for row in rows]
134 scaled = []
135 for row in rows:
136 scaled.append(
137 {
138 "date": row["date"],
139 "open": round(row["open"] * 10000),
140 "high": round(row["high"] * 10000),
141 "low": round(row["low"] * 10000),
142 "close": round(row["close"] * 10000),
143 "volume": row["volume"],
144 }
145 )
146 return scaled
149def rows_to_lean_csv(rows: list[dict]) -> str:
150 """Exact row format train.py::ensure_derived_crypto_daily_series() writes:
151 f"{date:%Y%m%d} 00:00,{open},{high},{low},{close},{volume}", one row per
152 line, sorted by date.
153 """
154 ordered = sorted(rows, key=lambda row: row["date"])
155 lines = [
156 f"{row['date'].strftime('%Y%m%d')} 00:00,{row['open']},{row['high']},{row['low']},{row['close']},{row['volume']}"
157 for row in ordered
158 ]
159 return "\n".join(lines) + ("\n" if lines else "")
162def _numeric(value: str):
163 try:
164 return int(value)
165 except ValueError:
166 return float(value)
169def _read_existing_lean_rows(path: Path) -> list[dict]:
170 """Reads a Lean daily zip's rows back into the same dict shape
171 scale_for_lean()/rows_to_lean_csv() use, preserving whatever numeric
172 representation (int or float) is already stored — no rescaling."""
173 rows: list[dict] = []
174 with ZipFile(path) as archive:
175 member = archive.namelist()[0]
176 with archive.open(member) as handle:
177 text = handle.read().decode("utf-8")
179 for line in text.splitlines():
180 if not line.strip():
181 continue
182 date_field, open_v, high_v, low_v, close_v, volume_v = line.split(",")
183 row_date = datetime.strptime(date_field.split()[0], "%Y%m%d").date()
184 rows.append(
185 {
186 "date": row_date,
187 "open": _numeric(open_v),
188 "high": _numeric(high_v),
189 "low": _numeric(low_v),
190 "close": _numeric(close_v),
191 "volume": _numeric(volume_v),
192 }
193 )
194 return rows
197def write_lean_zip(output_zip: Path, ticker: str, new_rows: list[dict], *, merge_with_existing: bool = True) -> None:
198 """Mirrors train.py::ensure_derived_crypto_daily_series()'s
199 ZipFile(output_zip, 'w') pattern, member name f'{ticker.lower()}.csv'.
201 When merge_with_existing, reads the existing zip's rows first and keys
202 the merge by date — existing (real Lean) rows always win on overlap;
203 new_rows only fill dates that were genuinely missing.
204 """
205 merged_by_date: dict[date, dict] = {}
206 if merge_with_existing and output_zip.exists():
207 for row in _read_existing_lean_rows(output_zip):
208 merged_by_date[row["date"]] = row
210 for row in new_rows:
211 merged_by_date.setdefault(row["date"], row)
213 csv_text = rows_to_lean_csv(list(merged_by_date.values()))
215 output_zip.parent.mkdir(parents=True, exist_ok=True)
216 member_name = f"{ticker.lower()}.csv"
217 with ZipFile(output_zip, "w") as archive:
218 archive.writestr(member_name, csv_text)
221# ---------------------------------------------------------------------------
222# V4.10 — forex sibling of the 5-column mid-price OHLCV functions above.
223# Lean's real forex daily CSV is a 10-column bid/ask format (confirmed
224# directly against the real local sample zips under
225# data/forex/{oanda,fxcm}/daily/ - see data/forex/readme.md), not the flat
226# OHLCV shape equity/crypto use. Yahoo Finance's own FX data is mid/last
227# OHLC only (no real bid/ask spread), so synthesize_forex_bid_ask_row()
228# below is an honest, documented zero-spread APPROXIMATION for backtest/
229# training purposes only, never a live spread feed (development/
230# Problems.md #66). The real local sample data (2007+) DOES carry genuine
231# historical bid != ask spread, so the merge path here preserves full
232# 10-field rows on overlap, never collapsing existing real rows to a
233# synthesized mid — same "existing/real rows always win" convention as
234# write_lean_zip() above.
235# ---------------------------------------------------------------------------
238def synthesize_forex_bid_ask_row(row: dict) -> dict:
239 """Yahoo Finance's FX data is mid/last OHLC only, no real bid/ask
240 spread — this is a documented, honest zero-spread APPROXIMATION for
241 backtest/training purposes only, never a live spread feed (see
242 development/Problems.md #66). Duplicates the same OHLC values into
243 both the bid and ask column groups, volume 0 in both — matches the
244 real Lean forex daily CSV shape (data/forex/readme.md) without
245 inventing a fake spread number."""
246 return {
247 "date": row["date"],
248 "bid_open": row["open"],
249 "bid_high": row["high"],
250 "bid_low": row["low"],
251 "bid_close": row["close"],
252 "bid_volume": 0,
253 "ask_open": row["open"],
254 "ask_high": row["high"],
255 "ask_low": row["low"],
256 "ask_close": row["close"],
257 "ask_volume": 0,
258 }
261def forex_rows_to_lean_csv(rows: list[dict]) -> str:
262 """10-column bid/ask Lean forex daily CSV — the FX sibling of
263 rows_to_lean_csv(). Rows already carry all 10 value fields (see
264 synthesize_forex_bid_ask_row()/_read_existing_lean_forex_rows() below)
265 — this function only formats and sorts, never synthesizes."""
266 ordered = sorted(rows, key=lambda row: row["date"])
267 lines = [
268 f"{row['date'].strftime('%Y%m%d')} 00:00,"
269 f"{row['bid_open']},{row['bid_high']},{row['bid_low']},{row['bid_close']},{row['bid_volume']},"
270 f"{row['ask_open']},{row['ask_high']},{row['ask_low']},{row['ask_close']},{row['ask_volume']}"
271 for row in ordered
272 ]
273 return "\n".join(lines) + ("\n" if lines else "")
276def _read_existing_lean_forex_rows(path: Path) -> list[dict]:
277 """Forex sibling of _read_existing_lean_rows() — 11-field split (date
278 + 10 bid/ask values), preserves real bid/ask exactly as stored, no
279 collapsing to mid."""
280 rows: list[dict] = []
281 with ZipFile(path) as archive:
282 member = archive.namelist()[0]
283 with archive.open(member) as handle:
284 text = handle.read().decode("utf-8")
286 for line in text.splitlines():
287 if not line.strip():
288 continue
289 (
290 date_field, bid_open, bid_high, bid_low, bid_close, bid_volume,
291 ask_open, ask_high, ask_low, ask_close, ask_volume,
292 ) = line.split(",")
293 row_date = datetime.strptime(date_field.split()[0], "%Y%m%d").date()
294 rows.append(
295 {
296 "date": row_date,
297 "bid_open": _numeric(bid_open), "bid_high": _numeric(bid_high),
298 "bid_low": _numeric(bid_low), "bid_close": _numeric(bid_close),
299 "bid_volume": _numeric(bid_volume),
300 "ask_open": _numeric(ask_open), "ask_high": _numeric(ask_high),
301 "ask_low": _numeric(ask_low), "ask_close": _numeric(ask_close),
302 "ask_volume": _numeric(ask_volume),
303 }
304 )
305 return rows
308def write_lean_forex_zip(output_zip: Path, ticker: str, new_ohlcv_rows: list[dict], *, merge_with_existing: bool = True) -> None:
309 """Forex sibling of write_lean_zip() — same call signature (plain
310 5-field OHLCV rows, the exact shape fetch_adhoc_asset() already
311 produces via scale_for_lean()), so data_pipeline/fetch.py's
312 ASSET_CLASS_CONFIG write_fn swap needs no caller changes. Synthesizes
313 each NEW row via synthesize_forex_bid_ask_row(), merges by date
314 against _read_existing_lean_forex_rows() (existing REAL rows always
315 win — identical convention to write_lean_zip()), writes via
316 forex_rows_to_lean_csv()."""
317 merged_by_date: dict[date, dict] = {}
318 if merge_with_existing and output_zip.exists():
319 for row in _read_existing_lean_forex_rows(output_zip):
320 merged_by_date[row["date"]] = row
322 for row in new_ohlcv_rows:
323 merged_by_date.setdefault(row["date"], synthesize_forex_bid_ask_row(row))
325 csv_text = forex_rows_to_lean_csv(list(merged_by_date.values()))
327 output_zip.parent.mkdir(parents=True, exist_ok=True)
328 member_name = f"{ticker.lower()}.csv"
329 with ZipFile(output_zip, "w") as archive:
330 archive.writestr(member_name, csv_text)
333# ---------------------------------------------------------------------------
334# V5.4.10 — crypto sibling of the forex synthesis above. Lean's crypto daily
335# subscription adds BOTH a trade and a quote feed (the quote is used by
336# Lean's default fill-path bookkeeping), so a real LEAN backtest requests
337# `data/crypto/coinbase/daily/<ticker>_quote.zip` even though this
338# algorithm's own logic only ever consumes TRADE bars for crypto (main.py
339# only reads Slice.quote_bars for forex — see on_data()/V4.6). The pipeline
340# only ever generated *_trade.zip, so every non-BTC crypto asset's quote
341# request failed (BTC's quote zip had been produced by an external manual
342# step with real bid/ask). Functionally benign — Lean falls back to trade
343# data and fills are already governed by main.py's own slippage model — but
344# it left traded assets (LTCUSD) with a permanently failing quote
345# subscription in the data-monitor report. Like the forex synthesize path
346# (development/Problems.md #66), Yahoo gives no genuine bid/ask for
347# crypto, so this is an honest, documented ZERO-SPREAD APPROXIMATION -
348# bid and ask mirror the trade OHLC (never a live spread feed), trade
349# volume is carried into both volume columns to satisfy Lean's 11-field
350# crypto quote CSV shape (confirmed against btcusd_quote.zip).
351# ---------------------------------------------------------------------------
354def synthesize_crypto_bid_ask_row(row: dict) -> dict:
355 """Yahoo Finance crypto data is trade OHLCV only, no genuine bid/ask —
356 documented ZERO-SPREAD APPROXIMATION for backtest data-completeness only
357 (this algorithm never reads crypto quote bars; see the block comment
358 above). Duplicates trade OHLC into both bid and ask groups, carries the
359 trade volume into both volume columns — matches Lean's real crypto
360 quote CSV shape (data/crypto/coinbase/daily/btcusd_quote.zip), no fake
361 spread invented."""
362 return {
363 "date": row["date"],
364 "bid_open": row["open"], "bid_high": row["high"],
365 "bid_low": row["low"], "bid_close": row["close"],
366 "bid_volume": row["volume"],
367 "ask_open": row["open"], "ask_high": row["high"],
368 "ask_low": row["low"], "ask_close": row["close"],
369 "ask_volume": row["volume"],
370 }
373def crypto_rows_to_lean_csv(rows: list[dict]) -> str:
374 """11-column bid/ask Lean crypto daily CSV — the crypto sibling of
375 forex_rows_to_lean_csv(). Rows already carry all 10 value fields (see
376 synthesize_crypto_bid_ask_row()); this only formats and sorts, never
377 synthesizes."""
378 ordered = sorted(rows, key=lambda row: row["date"])
379 lines = [
380 f"{row['date'].strftime('%Y%m%d')} 00:00,"
381 f"{row['bid_open']},{row['bid_high']},{row['bid_low']},{row['bid_close']},{row['bid_volume']},"
382 f"{row['ask_open']},{row['ask_high']},{row['ask_low']},{row['ask_close']},{row['ask_volume']}"
383 for row in ordered
384 ]
385 return "\n".join(lines) + ("\n" if lines else "")
388def _read_existing_lean_crypto_quote_rows(path: Path) -> list[dict]:
389 """Crypto sibling of _read_existing_lean_forex_rows() — 11-field split
390 (date + 10 bid/ask values), preserves whatever is already stored."""
391 rows: list[dict] = []
392 with ZipFile(path) as archive:
393 member = archive.namelist()[0]
394 with archive.open(member) as handle:
395 text = handle.read().decode("utf-8")
396 for line in text.splitlines():
397 if not line.strip():
398 continue
399 (
400 date_field, bid_open, bid_high, bid_low, bid_close, bid_volume,
401 ask_open, ask_high, ask_low, ask_close, ask_volume,
402 ) = line.split(",")
403 row_date = datetime.strptime(date_field.split()[0], "%Y%m%d").date()
404 rows.append(
405 {
406 "date": row_date,
407 "bid_open": _numeric(bid_open), "bid_high": _numeric(bid_high),
408 "bid_low": _numeric(bid_low), "bid_close": _numeric(bid_close),
409 "bid_volume": _numeric(bid_volume),
410 "ask_open": _numeric(ask_open), "ask_high": _numeric(ask_high),
411 "ask_low": _numeric(ask_low), "ask_close": _numeric(ask_close),
412 "ask_volume": _numeric(ask_volume),
413 }
414 )
415 return rows
418def write_lean_crypto_quote_zip(
419 trade_zip: Path, quote_zip: Path, ticker: str, *, merge_with_existing: bool = True
420) -> int:
421 """Derives a Lean crypto QUOTE zip from an existing TRADE zip — the
422 data-completeness fix for the missing *_quote.zip files (see block
423 comment above). Reads the trade zip's OHLCV rows via
424 _read_existing_lean_rows(), synthesizes each into a zero-spread bid/ask
425 row, merges by date against an existing quote zip if present (existing
426 REAL rows always win — same convention as write_lean_zip()), writes via
427 crypto_rows_to_lean_csv(). Returns the number of rows written. Raises
428 FileNotFoundError if the trade zip is absent."""
429 if not trade_zip.exists():
430 raise FileNotFoundError(f"trade zip not found: {trade_zip}")
432 trade_rows = _read_existing_lean_rows(trade_zip)
434 merged_by_date: dict[date, dict] = {}
435 if merge_with_existing and quote_zip.exists():
436 for row in _read_existing_lean_crypto_quote_rows(quote_zip):
437 merged_by_date[row["date"]] = row
438 for row in trade_rows:
439 merged_by_date.setdefault(row["date"], synthesize_crypto_bid_ask_row(row))
441 csv_text = crypto_rows_to_lean_csv(list(merged_by_date.values()))
443 quote_zip.parent.mkdir(parents=True, exist_ok=True)
444 member_name = f"{ticker.lower()}.csv"
445 with ZipFile(quote_zip, "w") as archive:
446 archive.writestr(member_name, csv_text)
447 return len(merged_by_date)
450# ---------------------------------------------------------------------------
451# The only function that imports yfinance — deferred, mirrors
452# experience/redis_queue.py's deferred `import redis`.
453# ---------------------------------------------------------------------------
456def fetch_yahoo_ohlcv(symbol: str, start: str, end: str) -> list[dict]:
457 """Real dollar/crypto prices, unscaled. Returns [] on any failure or
458 empty response — never raises, so one bad symbol never aborts a
459 multi-asset run."""
460 try:
461 import yfinance as yf # deferred — dev-only dependency, never in requirements.txt
463 # auto_adjust=True: Yahoo applies its own split/dividend adjustment
464 # before this ever reaches a Lean zip. This module today only ever
465 # backfills crypto gaps (no splits/dividends), but train.py reading
466 # its own equity Lean zips unadjusted was a real, separate bug (see
467 # train.py::apply_split_adjustments()/development/Problems.md) -
468 # this flag stays correct here so a future equity backfill (this
469 # module's docstring already anticipates non-crypto assets) doesn't
470 # reintroduce the same class of unadjusted-price corruption.
471 frame = yf.download(symbol, start=start, end=end, auto_adjust=True, progress=False)
472 except Exception as exc:
473 logger.warning("fetch_yahoo_ohlcv(%s): fetch failed — %s", symbol, exc)
474 return []
476 if frame is None or frame.empty:
477 logger.warning("fetch_yahoo_ohlcv(%s): no data returned for %s..%s", symbol, start, end)
478 return []
480 # Newer yfinance always returns MultiIndex columns (price field, ticker),
481 # even for a single-ticker download — `record["Open"]` on that shape
482 # returns a length-1 Series instead of a scalar, and `float(...)` on it
483 # only works today via a deprecated pandas fallback (FutureWarning: will
484 # raise TypeError in a future pandas). Flattening to the price-field
485 # level here keeps `record["Open"]` a plain scalar regardless of which
486 # yfinance/pandas version is installed.
487 if isinstance(frame.columns, pd.MultiIndex):
488 frame.columns = frame.columns.get_level_values(0)
490 # V5.4.7 (development/Problems.md #123): rate-limiting / delisted
491 # responses often return a NON-empty frame whose rows are all NaN -
492 # `float(record["Open"])` happily produced nan and write_lean_zip
493 # persisted it as genuine OHLCV. Rows without a finite OHLC set are
494 # now dropped; a frame that is ALL such rows degrades to [] (the same
495 # honest "no data" path as the empty-frame case above).
496 rows = []
497 skipped_non_finite = 0
498 for index, record in frame.iterrows():
499 row_date = index.date() if hasattr(index, "date") else index
500 try:
501 open_p = float(record["Open"])
502 high = float(record["High"])
503 low = float(record["Low"])
504 close_p = float(record["Close"])
505 volume = float(record["Volume"])
506 except (TypeError, ValueError, KeyError):
507 skipped_non_finite += 1
508 continue
509 if not all(math.isfinite(v) for v in (open_p, high, low, close_p)):
510 skipped_non_finite += 1
511 continue
512 rows.append(
513 {
514 "date": row_date,
515 "open": open_p,
516 "high": high,
517 "low": low,
518 "close": close_p,
519 "volume": volume,
520 }
521 )
522 if skipped_non_finite:
523 logger.warning(
524 "fetch_yahoo_ohlcv(%s): skipped %d non-finite row(s) from %s..%s",
525 symbol, skipped_non_finite, start, end,
526 )
527 return rows
530# ---------------------------------------------------------------------------
531# Orchestration
532# ---------------------------------------------------------------------------
535def plan_backfill(config: dict, *, tickers: list[str] | None = None) -> list[dict]:
536 """Orchestrates over config["phase1"]["universe"]["assets"] entries that
537 carry an optional "backfill" sub-block. Reads existing zip rows (if the
538 zip already exists) purely to compute the gap — no network I/O here."""
539 plans = []
540 for asset in config["phase1"]["universe"]["assets"]:
541 backfill_config = asset.get("backfill")
542 if not backfill_config:
543 continue
544 if tickers and asset["ticker"] not in tickers:
545 continue
547 output_zip = ROOT / asset["data_path"]
548 existing_rows = _read_existing_lean_rows(output_zip) if output_zip.exists() else []
549 gap = detect_gap(asset, existing_rows)
551 plans.append(
552 {
553 "ticker": asset["ticker"],
554 "security_type": asset["security_type"],
555 "yahoo_symbol": yahoo_symbol_for(asset["ticker"], backfill_config),
556 "data_path": str(output_zip),
557 "gap": gap,
558 }
559 )
560 return plans
563def run_backfill(config: dict, plan: list[dict], *, apply: bool, fetch_fn: Callable = fetch_yahoo_ohlcv) -> dict:
564 """apply=False (default): dry run — fetches nothing written to disk.
565 apply=True: writes merged zips via write_lean_zip(). fetch_fn is the
566 injection point for tests (never real yfinance in tests)."""
567 entries = []
568 for plan_entry in plan:
569 gap = plan_entry["gap"]
570 if not gap["needs_backfill"]:
571 entries.append({**plan_entry, "action": "skipped_no_gap", "rows_fetched": 0})
572 continue
574 # V5.4.7 (development/Problems.md #123): yf.download's `end` is
575 # EXCLUSIVE while backfill_to/fetch_end is inclusive - without the
576 # +1 day, the configured end date could never be fetched, so
577 # needs_backfill stayed True forever and every run refetched.
578 fetch_end_exclusive = gap["fetch_end"] + timedelta(days=1)
579 rows = fetch_fn(
580 plan_entry["yahoo_symbol"],
581 gap["fetch_start"].isoformat(),
582 fetch_end_exclusive.isoformat(),
583 )
584 scaled_rows = scale_for_lean(rows, plan_entry["security_type"])
586 if not scaled_rows:
587 action = "no_data_returned"
588 elif apply:
589 write_lean_zip(Path(plan_entry["data_path"]), plan_entry["ticker"], scaled_rows, merge_with_existing=True)
590 action = "written"
591 else:
592 action = "dry_run"
594 dates = [row["date"] for row in rows]
595 entries.append(
596 {
597 **plan_entry,
598 "action": action,
599 "rows_fetched": len(rows),
600 "suggested_available_from": min(dates) if dates else None,
601 "suggested_available_to": max(dates) if dates else None,
602 }
603 )
604 return {"apply": apply, "entries": entries}
607# ---------------------------------------------------------------------------
608# CLI
609# ---------------------------------------------------------------------------
612def main() -> None:
613 logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s — %(message)s")
614 parser = argparse.ArgumentParser(
615 description="Aether Quant Yahoo Finance historical data backfill (V2-19.5) — "
616 "offline/manual only, never run inside Lean or a Docker worker."
617 )
618 parser.add_argument("--tickers", nargs="*", default=None, help="Restrict to these tickers (default: all assets with a 'backfill' block)")
619 parser.add_argument("--apply", action="store_true", help="Actually write zip files (default: dry run, report only)")
620 parser.add_argument("--config-path", type=Path, default=CONFIG_PATH)
621 parser.add_argument(
622 "--quotes",
623 action="store_true",
624 help="Crypto only: derive missing *_quote.zip files from each crypto "
625 "asset's existing *_trade.zip (zero-spread synthesis — see "
626 "write_lean_crypto_quote_zip()). --apply writes the zips, "
627 "otherwise a dry run.",
628 )
629 args = parser.parse_args()
631 with args.config_path.open("r", encoding="utf-8") as f:
632 config = json.load(f)
634 if args.quotes:
635 crypto_assets = [
636 asset
637 for asset in config["phase1"]["universe"]["assets"]
638 if asset.get("security_type") == "crypto"
639 and (not args.tickers or asset["ticker"] in args.tickers)
640 ]
641 if not crypto_assets:
642 print("No crypto assets found (nothing to do).")
643 return
644 print(f"{'APPLY' if args.apply else 'DRY RUN'} — crypto quote-zip synthesis:\n")
645 for asset in crypto_assets:
646 trade_path = ROOT / asset["data_path"]
647 quote_path = trade_path.with_name(trade_path.name.replace("_trade.zip", "_quote.zip"))
648 if not trade_path.exists():
649 print(f"- {asset['ticker']}: SKIPPED (trade zip missing: {trade_path})")
650 continue
651 if not args.apply:
652 exists = "exists (would merge)" if quote_path.exists() else "missing (would create)"
653 print(f"- {asset['ticker']}: dry_run, quote={exists}")
654 continue
655 rows = write_lean_crypto_quote_zip(trade_path, quote_path, asset["ticker"])
656 print(f"- {asset['ticker']}: written {rows} row(s) -> {quote_path.name}")
657 if not args.apply:
658 print("\nDry run only — no files were written. Re-run with --apply to write zip files.")
659 return
661 plan = plan_backfill(config, tickers=args.tickers)
662 if not plan:
663 print("No assets with a 'backfill' config block found (nothing to do).")
664 return
666 report = run_backfill(config, plan, apply=args.apply)
667 print(f"{'APPLY' if args.apply else 'DRY RUN'} — {len(report['entries'])} asset(s) evaluated:\n")
668 for entry in report["entries"]:
669 print(f"- {entry['ticker']} ({entry['yahoo_symbol']}): {entry['action']}, rows_fetched={entry['rows_fetched']}")
670 if entry.get("suggested_available_from"):
671 print(
672 f" If this widens coverage, update config.json manually: "
673 f"available_from={entry['suggested_available_from'].isoformat()}"
674 )
676 if not args.apply:
677 print("\nDry run only — no files were written. Re-run with --apply to write zip files.")
678 print(
679 "\nNote: config.json's available_from/available_to are never edited automatically. "
680 "Update them by hand for the wider history to actually affect training/backtesting."
681 )
684if __name__ == "__main__":
685 main()