Coverage for data_pipeline/dividend_backfill.py: 100%
98 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"""Dividend ex-date/amount history backfill + forward cadence-based
2projection - powers portfolio/options_assignment_risk.py's early-
3call-assignment signal (development/Problems.md - early-assignment
4probability/pricing modeling).
6No dividend $ amounts/ex-div dates/schedule exist anywhere else in this
7codebase - data_pipeline/fred_backfill.py only pulls Treasury yield/credit-
8spread series, and data_pipeline/yfinance_backfill.py's auto_adjust=True
9OHLCV downloads discard raw dividend events before they ever reach a Lean
10zip. This module fetches actual historical ex-dividend dates/amounts via
11yfinance (dev-only dependency, deferred import - mirrors
12yfinance_backfill.py's own convention) and derives a best-effort FORWARD
13projection from historical cadence - NOT yfinance's own forward
14Ticker.calendar/get_earnings_dates fields, which are scraped from Yahoo's
15UI and empirically unreliable/frequently stale or absent for less-followed
16tickers. This is a deliberate accuracy-over-completeness choice; every
17consumer must treat the projection as a best-effort estimate, never a
18confirmed date (see estimate_next_ex_dividend_date()'s own
19"confidence"/"method" fields).
21Same two-safety-boundary shape as fred_backfill.py/yfinance_backfill.py:
221. Writing the local cache is gated by --apply (default: dry run only).
232. Never touches config.json - this module's only output is
24 data/reference/dividend_schedule/*.json, read back once at main.py
25 init (Lean backtests are date-bounded and must never make a live HTTP
26 call mid-run) - refreshed by re-running this module with --apply, not
27 intraday.
29Usage:
30 python -m data_pipeline.dividend_backfill [--tickers AAPL MSFT] [--apply]
31"""
33from __future__ import annotations
35import argparse
36import json
37import logging
38import statistics
39from datetime import date
40from pathlib import Path
42logger = logging.getLogger(__name__)
44ROOT = Path(__file__).resolve().parents[1]
45CONFIG_PATH = ROOT / "config.json"
46DIVIDEND_SCHEDULE_CACHE_DIR = ROOT / "data" / "reference" / "dividend_schedule"
48MIN_HISTORY_EVENTS_FOR_ESTIMATE = 2
49CADENCE_LOOKBACK_EVENTS = 8
52# ---------------------------------------------------------------------------
53# Pure helpers
54# ---------------------------------------------------------------------------
57def estimate_next_ex_dividend_date(history: list[dict], as_of: date) -> dict:
58 """Pure. Projects the next ex-div date from historical CADENCE (median
59 days between consecutive ex_dates over the trailing
60 CADENCE_LOOKBACK_EVENTS events), rolled forward from the most recent
61 ex_date <= as_of - NOT a yfinance forward-calendar call (see module
62 docstring). Returns {"estimated_next_ex_date": iso-date | None,
63 "estimated_amount": float | None, "cadence_days": int | None,
64 "confidence": "low"|"medium"|"none", "method": str}.
66 "none" confidence (every numeric field None) when fewer than
67 MIN_HISTORY_EVENTS_FOR_ESTIMATE events are available as-of as_of - an
68 unknown schedule must never be indistinguishable from a genuinely "no
69 dividend expected" signal, the same None-vs-neutral-default
70 distinction every other pure signal function in this codebase draws.
71 "medium" only with a reasonably regular cadence over enough lookback
72 events; "low" otherwise. Never raises."""
73 past_events = sorted(
74 (event for event in history if event.get("ex_date") is not None and event["ex_date"] <= as_of),
75 key=lambda event: event["ex_date"],
76 )
77 if len(past_events) < MIN_HISTORY_EVENTS_FOR_ESTIMATE:
78 return {
79 "estimated_next_ex_date": None,
80 "estimated_amount": None,
81 "cadence_days": None,
82 "confidence": "none",
83 "method": "insufficient_history",
84 }
86 lookback = past_events[-CADENCE_LOOKBACK_EVENTS:]
87 gaps = [(lookback[i]["ex_date"] - lookback[i - 1]["ex_date"]).days for i in range(1, len(lookback))]
88 cadence_days = max(round(statistics.median(gaps)), 1)
89 most_recent = lookback[-1]
90 estimated_next = most_recent["ex_date"]
91 # Roll forward past `as_of` by whole cadence steps - handles a stale
92 # cache (as_of well past the last known event) without ever guessing a
93 # date already in the past.
94 while estimated_next <= as_of:
95 estimated_next = date.fromordinal(estimated_next.toordinal() + cadence_days)
97 spread = (max(gaps) - min(gaps)) if len(gaps) > 1 else 0
98 confidence = "medium" if len(gaps) >= 3 and spread <= 15 else "low"
100 return {
101 "estimated_next_ex_date": estimated_next.isoformat(),
102 "estimated_amount": most_recent["amount"],
103 "cadence_days": cadence_days,
104 "confidence": confidence,
105 "method": "historical_cadence_projection - not a confirmed forward date",
106 }
109def dividend_schedule_payload(ticker: str, history: list[dict], as_of: date) -> dict:
110 """Composes fetch_dividend_history()'s raw history +
111 estimate_next_ex_dividend_date()'s projection into the exact shape
112 write_dividend_schedule() persists / main.py reads back."""
113 estimate = estimate_next_ex_dividend_date(history, as_of)
114 return {
115 "ticker": ticker,
116 "fetched_at": as_of.isoformat(),
117 "history": [{"ex_date": event["ex_date"].isoformat(), "amount": event["amount"]} for event in history],
118 "next_ex_dividend_estimate": estimate,
119 }
122def option_underlying_tickers(config: dict) -> list[str]:
123 """Every ticker this module is actually useful for: an option asset's
124 underlying_ticker, or an equity asset's own ticker directly. Pure,
125 de-duplicated, order-preserving, never raises on a malformed asset
126 entry (missing keys just get skipped)."""
127 tickers: list[str] = []
128 seen: set[str] = set()
129 for asset in config.get("phase1", {}).get("universe", {}).get("assets", []):
130 security_type = asset.get("security_type")
131 ticker = asset.get("underlying_ticker") if security_type == "option" else asset.get("ticker")
132 if ticker and ticker not in seen:
133 seen.add(ticker)
134 tickers.append(ticker)
135 return tickers
138# ---------------------------------------------------------------------------
139# The only function that imports yfinance - deferred, mirrors
140# yfinance_backfill.py's own convention.
141# ---------------------------------------------------------------------------
144def fetch_dividend_history(yahoo_symbol: str) -> list[dict]:
145 """Real historical ex-dividend dates + per-share amounts via
146 yfinance.Ticker(yahoo_symbol).dividends. Returns [] on any fetch
147 failure (network, delisted, no dividend history) - never raises, same
148 fail-open convention as yfinance_backfill.fetch_yahoo_ohlcv()."""
149 try:
150 import yfinance as yf # deferred - dev-only dependency, never in requirements.txt
152 series = yf.Ticker(yahoo_symbol).dividends
153 except Exception as exc:
154 logger.warning("fetch_dividend_history(%s): fetch failed — %s", yahoo_symbol, exc)
155 return []
157 if series is None or series.empty:
158 logger.warning("fetch_dividend_history(%s): no dividend history returned", yahoo_symbol)
159 return []
161 rows = []
162 for index, amount in series.items():
163 row_date = index.date() if hasattr(index, "date") else index
164 rows.append({"ex_date": row_date, "amount": float(amount)})
165 return sorted(rows, key=lambda row: row["ex_date"])
168# ---------------------------------------------------------------------------
169# Orchestration
170# ---------------------------------------------------------------------------
173def write_dividend_schedule(cache_dir: Path, ticker: str, history: list[dict], as_of: date) -> dict:
174 """Writes data/reference/dividend_schedule/<ticker>.json. Returns the
175 payload written (for CLI reporting)."""
176 payload = dividend_schedule_payload(ticker, history, as_of)
177 cache_dir.mkdir(parents=True, exist_ok=True)
178 output_path = cache_dir / f"{ticker}.json"
179 output_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
180 return payload
183def load_cached_dividend_schedule(ticker: str, cache_dir: Path = DIVIDEND_SCHEDULE_CACHE_DIR) -> dict:
184 """Reads back data/reference/dividend_schedule/<ticker>.json. Returns
185 {} when missing/unreadable (fresh clone, backfill never run for this
186 ticker) - callers (main.py) must treat an empty dict as "no dividend
187 schedule known", never a crash, same convention as
188 fred_backfill.load_cached_fred_series()."""
189 path = cache_dir / f"{ticker}.json"
190 if not path.exists():
191 return {}
192 try:
193 return json.loads(path.read_text(encoding="utf-8"))
194 except (ValueError, OSError) as exc:
195 logger.warning("load_cached_dividend_schedule(%s): unreadable cache file — %s", ticker, exc)
196 return {}
199# ---------------------------------------------------------------------------
200# CLI
201# ---------------------------------------------------------------------------
204def main() -> None:
205 logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s — %(message)s")
206 parser = argparse.ArgumentParser(
207 description="Aether Quant dividend history backfill - offline/manual only, "
208 "no API key required, never run inside Lean or a Docker worker."
209 )
210 parser.add_argument(
211 "--tickers", nargs="*", default=None, help="Restrict to these tickers (default: every option underlying/equity in phase1.universe.assets)"
212 )
213 parser.add_argument("--apply", action="store_true", help="Actually write the local cache (default: dry run, report only)")
214 parser.add_argument("--config-path", type=Path, default=CONFIG_PATH)
215 parser.add_argument("--cache-dir", type=Path, default=DIVIDEND_SCHEDULE_CACHE_DIR)
216 args = parser.parse_args()
218 with args.config_path.open("r", encoding="utf-8") as f:
219 config = json.load(f)
221 tickers = args.tickers if args.tickers else option_underlying_tickers(config)
222 as_of = date.today()
224 print(f"{'APPLY' if args.apply else 'DRY RUN'} — fetching dividend history for {len(tickers)} ticker(s):\n")
225 for ticker in tickers:
226 history = fetch_dividend_history(ticker)
227 if not history:
228 print(f"- {ticker}: no_data_returned, events_fetched=0")
229 continue
230 payload = dividend_schedule_payload(ticker, history, as_of)
231 if args.apply:
232 write_dividend_schedule(args.cache_dir, ticker, history, as_of)
233 action = "written"
234 else:
235 action = "dry_run"
236 print(f"- {ticker}: {action}, events_fetched={len(history)}, next_ex_estimate={payload['next_ex_dividend_estimate']}")
238 if not args.apply:
239 print("\nDry run only — no cache files were written. Re-run with --apply to write the cache.")
242if __name__ == "__main__":
243 main()