Coverage for data_pipeline/factor_file_backfill.py: 100%
193 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"""Lean-format split/dividend factor-file backfill for equity tickers
2missing a local factor file (development/Problems.md #91/#97/#99).
4train.py::apply_split_adjustments() backward-adjusts each ticker's raw
5OHLCV using data/equity/usa/factor_files/<ticker>.csv - the same
6adjustment DataNormalizationMode.Adjusted already applies to main.py's
7live/backtest data feed at runtime (Lean's default for
8self.add_equity(ticker, self.resolution)). When that local file is
9missing, load_factor_file() returns None and apply_split_adjustments()
10silently no-ops - offline trains on RAW, unadjusted prices while live
11never has this problem. Of 104 configured assets (77 equities), only 22
12have a local factor file; the other 63 don't - this whole data/ tree is
13gitignored, so this is a local/incomplete data pull, not a deliberate
14scope decision anywhere in the code.
16This module derives real Lean-format factor files for the missing
17tickers from yfinance's own dividend/split history (dev-only dependency,
18deferred import - mirrors dividend_backfill.py's/yfinance_backfill.py's
19own convention), computing each row's CUMULATIVE backward-adjustment
20factor the same way Lean's own factor files do (confirmed by reading a
21real one, data/equity/usa/factor_files/aapl.csv, directly: earliest row
22carries the largest cumulative adjustment, format is
23date(YYYYMMDD),price_factor,split_factor,reference_price, no header,
24terminal sentinel row 20501231,1,1,0).
26No changes to train.py are needed or made here - load_factor_file()/
27apply_split_adjustments() already do the right thing the moment a file
28exists at the expected path; this module is purely a data-generation
29task.
31Same two-safety-boundary shape as dividend_backfill.py/fred_backfill.py/
32yfinance_backfill.py:
331. Writing factor files is gated by --apply (default: dry run only).
342. Never touches config.json - this module's only output is
35 data/equity/usa/factor_files/*.csv, read back by train.py's own
36 dataset-build pipeline (`aq train --dataset-only`), not at Lean
37 runtime (main.py never reads these).
39V5.5.0 (development/Problems.md #130) - DOUBLE-ADJUSTMENT FIX. The 63 files
40this module generated in V5.3.3 were applied on top of zips that
41yfinance_backfill.py had ALREADY written with `auto_adjust=True`, i.e. prices
42that are split- AND dividend-adjusted as of fetch time. Both train.py and
43Lean then multiplied them by the factor file again:
44 - prices carried the cumulative split factor a second time (AMZN $84.63 in
45 2019 became $4.23, NVDA ~$0.02-0.3), so per-share IB commissions on a
46 share count 20-480x too large cost 16-49 bps a side instead of ~1;
47 - every ex-dividend date gained an extra +dividend-yield return (the series
48 already contained it), flattering dividend payers' longs and penalizing
49 their shorts.
50Evidence, reproducible with `--audit`: for each generated file the zip's close
51on an event date equals reference_price x (the cumulative factor of the events
52AFTER that date) - the signature of an already-adjusted series - while the 22
53genuine QuantConnect files have zip == reference_price (raw). A second,
54independent fingerprint of the writer: yfinance_backfill writes volume as a
55float ("98898000.0"), QuantConnect's own zips as an integer.
57A zip written by yfinance_backfill needs NO factor adjustment, so
58`--repair-adjusted-zips` REMOVES such tickers' files (backing the originals up
59first) and generation now skips them. Remove, do not "neutralize": a
60sentinel-only identity file (`20501231,1,1,0`) is NOT equivalent to a missing
61file for Lean - its zero reference price trips Lean's numerical-precision check
62and it logs "data for the following symbols was adjust to a later starting
63date: [EMB, 12/30/2050] ...", i.e. the symbol has no data until 2050. That
64exact trap sank V5.5.0's first backtest attempt (it was caught in the engine
65log of a run that had already crashed for another reason). A missing file is
66what every run before #100 used, and works in both Lean and train.py.
68Usage:
69 python -m data_pipeline.factor_file_backfill [--tickers NVDA GE] [--apply]
70 python -m data_pipeline.factor_file_backfill --audit
71 python -m data_pipeline.factor_file_backfill --repair-adjusted-zips [--tickers T ...] [--apply]
72"""
74from __future__ import annotations
76import argparse
77import json
78import logging
79import shutil
80import statistics
81from pathlib import Path
82from zipfile import ZipFile
84logger = logging.getLogger(__name__)
86ROOT = Path(__file__).resolve().parents[1]
87CONFIG_PATH = ROOT / "config.json"
88FACTOR_FILES_DIR = ROOT / "data" / "equity" / "usa" / "factor_files"
90TERMINAL_SENTINEL_ROW = {"factor_date": "20501231", "price_factor": 1.0, "split_factor": 1.0, "reference_price": 0.0}
93# ---------------------------------------------------------------------------
94# Pure helpers
95# ---------------------------------------------------------------------------
98def configured_equity_tickers(config: dict) -> list[str]:
99 """Every phase1.universe.assets entry with security_type == "equity",
100 de-duplicated, order-preserving. Deliberately broader than
101 dividend_backfill.option_underlying_tickers() (which only resolves
102 option underlyings) - factor files are needed for every directly-
103 tradeable equity/ETF asset, including bond ETFs (SHY/IEF/TLT/AGG/...),
104 which also pay real distributions and are also security_type "equity".
105 Never raises on a malformed asset entry - missing keys are skipped."""
106 tickers: list[str] = []
107 seen: set[str] = set()
108 for asset in config.get("phase1", {}).get("universe", {}).get("assets", []):
109 if asset.get("security_type") != "equity":
110 continue
111 ticker = asset.get("ticker")
112 if ticker and ticker not in seen:
113 seen.add(ticker)
114 tickers.append(ticker)
115 return tickers
118def tickers_missing_factor_file(tickers: list[str], factor_files_dir: Path = FACTOR_FILES_DIR) -> list[str]:
119 """Filters `tickers` down to those with no local
120 data/equity/usa/factor_files/<ticker-lower>.csv yet - the default CLI
121 scope, same "no flag = sane default" pattern as dividend_backfill.py's
122 --tickers default."""
123 return [ticker for ticker in tickers if not (factor_files_dir / f"{ticker.lower()}.csv").exists()]
126def compute_lean_factor_rows(history) -> list[dict]:
127 """Pure. `history` is a pandas DataFrame with a DatetimeIndex plus
128 Close/Dividends/Stock Splits columns - fetch_corporate_actions()'s
129 exact return shape (matches yfinance's own Ticker.history(actions=True)
130 column names).
132 Walks real events (Dividends != 0 or Stock Splits != 0) newest-to-
133 oldest, accumulating:
134 - price_factor *= (1 - dividend_amount / close_on_prior_session)
135 per dividend event (a cash dividend doesn't change share count,
136 only the ex-date price drop needs correcting)
137 - split_factor *= 1 / split_ratio per split event
138 emitting one row per event date carrying the CUMULATIVE factor as of
139 that date - Lean's own convention (confirmed against the real
140 data/equity/usa/factor_files/aapl.csv: earliest row carries the
141 largest cumulative adjustment, converging to ~1.0 near the most
142 recent event). `reference_price` is the raw Close on that event's own
143 date (matches the real file's 4th column, an audit reference, never
144 consumed by the adjustment formula itself).
146 Returns [] when `history` has zero real dividend/split events - no
147 row is fabricated for a ticker that never needed adjusting.
149 Always appends TERMINAL_SENTINEL_ROW last (Lean's own far-future
150 sentinel, matching every real factor file's last row) - EXCEPT when
151 there are zero real events, in which case [] is returned instead of a
152 sentinel-only file (see this module's docstring / write_factor_file()
153 callers: a missing file and a sentinel-only file resolve identically
154 through train.py's merge_asof(direction="forward") + .fillna(1.0), so
155 skipping is lower-risk than writing a file that isn't needed)."""
156 events = []
157 for event_date, row in history.iterrows():
158 dividend = float(row.get("Dividends", 0.0) or 0.0)
159 split = float(row.get("Stock Splits", 0.0) or 0.0)
160 if dividend == 0.0 and split == 0.0:
161 continue
162 events.append(
163 {
164 "date": event_date,
165 "dividend": dividend,
166 "split_ratio": split,
167 "close": float(row["Close"]),
168 "prior_close": None,
169 }
170 )
172 if not events:
173 return []
175 close_series = history["Close"]
176 for event in events:
177 prior_close = close_series.loc[:event["date"]].iloc[:-1]
178 event["prior_close"] = float(prior_close.iloc[-1]) if not prior_close.empty else float(event["close"])
180 events.sort(key=lambda event: event["date"], reverse=True)
182 # Cumulative factors are computed walking newest-to-oldest (each older
183 # event's factor must already include every later event's adjustment),
184 # but the OUTPUT is written oldest-first with the terminal sentinel
185 # last - matching every real Lean factor file's own on-disk order
186 # (confirmed against data/equity/usa/factor_files/aapl.csv). Not
187 # strictly required for correctness (train.py::load_factor_file()
188 # re-sorts by date on read regardless), but keeps a generated file
189 # directly diffable against a real one.
190 rows: list[dict] = []
191 price_factor = 1.0
192 split_factor = 1.0
193 for event in events:
194 if event["dividend"] != 0.0 and event["prior_close"] > 0.0:
195 price_factor *= 1.0 - (event["dividend"] / event["prior_close"])
196 if event["split_ratio"] != 0.0:
197 split_factor *= 1.0 / event["split_ratio"]
198 event_date = event["date"]
199 rows.append(
200 {
201 "factor_date": event_date.strftime("%Y%m%d") if hasattr(event_date, "strftime") else str(event_date),
202 "price_factor": price_factor,
203 "split_factor": split_factor,
204 "reference_price": event["close"],
205 }
206 )
208 rows.reverse()
209 rows.append(dict(TERMINAL_SENTINEL_ROW))
210 return rows
213# ---------------------------------------------------------------------------
214# V5.5.0 - already-adjusted zip detection and repair (see module docstring)
215# ---------------------------------------------------------------------------
217# Outside factor_files/ on purpose: nothing in the directory Lean reads should be a stray subfolder.
218BACKUP_DIR_NAME = "factor_files_backup_pre_v550"
221def read_zip_daily_rows(zip_path: Path) -> list[list[str]]:
222 """Raw Lean daily CSV rows (`YYYYMMDD 00:00,open,high,low,close,volume`)
223 as split string fields. [] for a missing/unreadable zip - never raises."""
224 try:
225 with ZipFile(zip_path) as archive:
226 member = archive.namelist()[0]
227 text = archive.read(member).decode("utf-8", errors="replace")
228 except (OSError, IndexError, ValueError, KeyError):
229 return []
230 return [line.split(",") for line in text.splitlines() if line.strip()]
233def zip_written_by_yfinance_backfill(rows: list[list[str]], sample_size: int = 50) -> bool:
234 """True when the zip's volume column is float-formatted ("98898000.0").
235 yfinance_backfill.rows_to_lean_csv() writes a float; QuantConnect's own
236 daily zips write an integer ("44109029"). yfinance_backfill fetches with
237 auto_adjust=True, so such a zip is split- AND dividend-adjusted already.
238 Looks at the first/last `sample_size` rows; any integer-formatted volume
239 in the sample means NOT written by the backfill (a merged zip keeps real
240 QC rows verbatim - "existing rows always win")."""
241 if not rows:
242 return False
243 sample = rows[:sample_size] + rows[-sample_size:]
244 volumes = [row[5] for row in sample if len(row) >= 6]
245 return bool(volumes) and all("." in volume for volume in volumes)
248def reference_ratio_median(zip_rows: list[list[str]], factor_rows: list[dict], max_events: int = 40) -> float | None:
249 """Median of zip_close / reference_price over factor-file event dates that
250 exist in the zip. ~1.0 -> the zip is on the factor file's own (raw) scale;
251 clearly below 1.0 -> the zip already includes later dividend adjustments.
252 None when no event date can be matched."""
253 close_by_date = {}
254 for row in zip_rows:
255 try:
256 close_by_date[row[0][:8]] = float(row[4]) / 10000.0
257 except (IndexError, ValueError):
258 continue
259 ratios = []
260 for factor_row in factor_rows:
261 reference = float(factor_row.get("reference_price") or 0.0)
262 close = close_by_date.get(str(factor_row.get("factor_date")))
263 if reference > 0.0 and close is not None:
264 ratios.append(close / reference)
265 return statistics.median(ratios[-max_events:]) if ratios else None
268def read_factor_file_rows(path: Path) -> list[dict]:
269 rows = []
270 for line in path.read_text(encoding="utf-8").splitlines():
271 parts = line.strip().split(",")
272 if len(parts) < 4:
273 continue
274 rows.append(
275 {
276 "factor_date": parts[0],
277 "price_factor": float(parts[1]),
278 "split_factor": float(parts[2]),
279 "reference_price": float(parts[3]),
280 }
281 )
282 return rows
285def factor_file_is_identity(factor_rows: list[dict]) -> bool:
286 return all(row["price_factor"] == 1.0 and row["split_factor"] == 1.0 for row in factor_rows)
289def audit_factor_file(zip_rows: list[list[str]], factor_rows: list[dict]) -> dict:
290 """Does a factor file exist for a ticker whose zip is already adjusted?
291 ANY such file is wrong: a real one double-adjusts (train.py and Lean both
292 re-apply it), and a sentinel-only "identity" one makes Lean start the
293 symbol's data in 2050. So `needs_repair` is simply "backfill-written zip
294 AND a factor file is present" - the only correct state is no file."""
295 from_backfill = zip_written_by_yfinance_backfill(zip_rows)
296 event_rows = [row for row in factor_rows if row["factor_date"] != "20501231"]
297 identity = factor_file_is_identity(event_rows)
298 ratio = reference_ratio_median(zip_rows, event_rows)
299 if not from_backfill:
300 reason = "zip is not backfill-written (raw QuantConnect data): its factor file is legitimate"
301 elif identity and not event_rows:
302 reason = "sentinel-only factor file on an adjusted zip: Lean pushes the symbol's data start to 12/30/2050"
303 else:
304 reason = "yfinance auto_adjust=True zip (already split+dividend adjusted) + a factor file = double adjustment"
305 return {
306 "zip_written_by_yfinance_backfill": from_backfill,
307 "factor_file_is_identity": identity,
308 "zip_to_reference_ratio_median": None if ratio is None else round(ratio, 4),
309 "needs_repair": bool(from_backfill),
310 "reason": reason,
311 }
314def repair_factor_file(factor_dir: Path, ticker: str, *, apply: bool) -> Path | None:
315 """Removes <ticker>.csv after copying it to <factor_dir>/../factor_files_backup_pre_v550/
316 (never overwriting an existing backup - the first backup is the true
317 original, so repairing an already-neutralized file cannot lose it).
318 Returns the backup path when applied, else None."""
319 path = factor_dir / f"{ticker.lower()}.csv"
320 if not apply:
321 return None
322 backup_dir = factor_dir.parent / BACKUP_DIR_NAME
323 backup_dir.mkdir(parents=True, exist_ok=True)
324 backup_path = backup_dir / path.name
325 if not backup_path.exists():
326 shutil.copy2(path, backup_path)
327 path.unlink()
328 return backup_path
331# ---------------------------------------------------------------------------
332# The only function that imports yfinance - deferred, mirrors
333# dividend_backfill.py's/yfinance_backfill.py's own convention.
334# ---------------------------------------------------------------------------
337def fetch_corporate_actions(yahoo_symbol: str):
338 """Real historical Close/Dividends/Stock Splits via ONE yfinance call
339 (Ticker.history(period="max", auto_adjust=False, actions=True)) - the
340 raw close series and the corporate-action events come back aligned by
341 date in a single round-trip, so compute_lean_factor_rows() never needs
342 a second network call for "close on the session before the ex-date".
343 Returns None on any fetch failure (network, delisted, no history) -
344 never raises, same fail-open convention as
345 dividend_backfill.fetch_dividend_history()."""
346 try:
347 import yfinance as yf # deferred - dev-only dependency, never in requirements.txt
349 history = yf.Ticker(yahoo_symbol).history(period="max", auto_adjust=False, actions=True)
350 except Exception as exc:
351 logger.warning("fetch_corporate_actions(%s): fetch failed — %s", yahoo_symbol, exc)
352 return None
354 if history is None or history.empty:
355 logger.warning("fetch_corporate_actions(%s): no history returned", yahoo_symbol)
356 return None
357 return history
360# ---------------------------------------------------------------------------
361# Orchestration
362# ---------------------------------------------------------------------------
365def write_factor_file(output_dir: Path, ticker: str, rows: list[dict]) -> Path:
366 """Writes data/equity/usa/factor_files/<ticker-lower>.csv, no header,
367 Lean's exact column order (date,price_factor,split_factor,
368 reference_price) - matches train.py::load_factor_file()'s own read
369 shape (names=["factor_date", "price_factor", "split_factor",
370 "reference_price"]) column-for-column."""
371 output_dir.mkdir(parents=True, exist_ok=True)
372 output_path = output_dir / f"{ticker.lower()}.csv"
373 lines = [
374 f"{row['factor_date']},{row['price_factor']},{row['split_factor']},{row['reference_price']}"
375 for row in rows
376 ]
377 output_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
378 return output_path
381# ---------------------------------------------------------------------------
382# CLI
383# ---------------------------------------------------------------------------
386def _audit_or_repair(config: dict, args: argparse.Namespace) -> int:
387 """--audit / --repair-adjusted-zips, both local-only (no network)."""
388 zip_paths = {
389 asset["ticker"]: ROOT / asset["data_path"]
390 for asset in config.get("phase1", {}).get("universe", {}).get("assets", [])
391 if asset.get("security_type") == "equity" and asset.get("data_path")
392 }
393 tickers = args.tickers if args.tickers else sorted(zip_paths)
394 repaired = flagged = 0
395 for ticker in tickers:
396 factor_path = args.output_dir / f"{ticker.lower()}.csv"
397 if not factor_path.exists() or ticker not in zip_paths:
398 continue
399 verdict = audit_factor_file(read_zip_daily_rows(zip_paths[ticker]), read_factor_file_rows(factor_path))
400 if verdict["needs_repair"]:
401 flagged += 1
402 if args.repair_adjusted_zips and verdict["needs_repair"]:
403 backup = repair_factor_file(args.output_dir, ticker, apply=args.apply)
404 repaired += 1 if args.apply else 0
405 status = f"repaired (backup: {backup})" if args.apply else "would_repair"
406 else:
407 status = "DOUBLE-ADJUSTED" if verdict["needs_repair"] else "ok"
408 print(f"- {ticker}: {status} ratio={verdict['zip_to_reference_ratio_median']} {verdict['reason']}")
409 print(f"\n{flagged} double-adjusted factor file(s) found; {repaired} repaired.")
410 if args.repair_adjusted_zips and not args.apply and flagged:
411 print("Dry run only - re-run with --apply to rewrite them (originals are backed up first).")
412 return 0 if (args.repair_adjusted_zips or not flagged) else 1
415def main() -> int:
416 logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s — %(message)s")
417 parser = argparse.ArgumentParser(
418 description="Aether Quant Lean factor-file backfill - offline/manual only, "
419 "no API key required, never run inside Lean or a Docker worker."
420 )
421 parser.add_argument(
422 "--tickers", nargs="*", default=None,
423 help="Restrict to these tickers (default: every configured equity ticker missing a local factor file)",
424 )
425 parser.add_argument("--apply", action="store_true", help="Actually write factor files (default: dry run, report only)")
426 parser.add_argument("--config-path", type=Path, default=CONFIG_PATH)
427 parser.add_argument("--output-dir", type=Path, default=FACTOR_FILES_DIR)
428 parser.add_argument(
429 "--audit", action="store_true",
430 help="V5.5.0: report, per configured equity with a factor file, whether it sits on top of an "
431 "already-adjusted (yfinance auto_adjust=True) zip - the double-adjustment / 2050-start trap of Problems.md #130. Read-only; exit 1 on a finding.",
432 )
433 parser.add_argument(
434 "--repair-adjusted-zips", action="store_true",
435 help="V5.5.0: remove the factor file of every ticker whose zip is already split+dividend adjusted "
436 "(originals backed up to <output-dir>/../factor_files_backup_pre_v550/). Dry run unless --apply.",
437 )
438 args = parser.parse_args()
440 with args.config_path.open("r", encoding="utf-8") as f:
441 config = json.load(f)
443 if args.audit or args.repair_adjusted_zips:
444 return _audit_or_repair(config, args)
446 tickers = args.tickers if args.tickers else tickers_missing_factor_file(configured_equity_tickers(config), args.output_dir)
448 zip_paths = {
449 asset["ticker"]: ROOT / asset["data_path"]
450 for asset in config.get("phase1", {}).get("universe", {}).get("assets", [])
451 if asset.get("data_path")
452 }
453 print(f"{'APPLY' if args.apply else 'DRY RUN'} — checking corporate-action history for {len(tickers)} ticker(s):\n")
454 for ticker in tickers:
455 # V5.5.0: a yfinance_backfill-written zip is already split+dividend adjusted; generating a
456 # factor file for it re-applies every correction (Problems.md #130).
457 zip_rows = read_zip_daily_rows(zip_paths[ticker]) if ticker in zip_paths else []
458 if zip_written_by_yfinance_backfill(zip_rows):
459 print(f"- {ticker}: skipped_zip_already_adjusted (yfinance auto_adjust=True zip needs no factor file)")
460 continue
461 history = fetch_corporate_actions(ticker)
462 if history is None:
463 print(f"- {ticker}: no_data_returned")
464 continue
465 rows = compute_lean_factor_rows(history)
466 if not rows:
467 print(f"- {ticker}: skipped_no_corporate_actions (identity fallback is already correct, no file needed)")
468 continue
469 if args.apply:
470 write_factor_file(args.output_dir, ticker, rows)
471 action = "written"
472 else:
473 action = "dry_run"
474 print(f"- {ticker}: {action}, factor_rows={len(rows) - 1} (+ terminal sentinel)")
476 if not args.apply:
477 print("\nDry run only — no factor files were written. Re-run with --apply to write them.")
478 return 0
481if __name__ == "__main__":
482 raise SystemExit(main())