Coverage for data_pipeline/fred_backfill.py: 100%
169 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"""FRED (Federal Reserve Economic Data) historical series backfill.
3Powers features/bond_features.py's real yield-curve/credit-spread signals -
4distinct from macro_features.py's existing yield_curve_slope_proxy/
5credit_spread_proxy, which derive a *proxy* from bond-ETF price momentum.
6This module fetches the *actual* Treasury yield/credit-spread series FRED
7publishes, no API key required (FRED's public graph CSV endpoint).
9Uses `httpx` over HTTP/2, NOT stdlib urllib (V5.1 Phase 2, CODESPACE RUN 1
10diagnosis, development/Problems.md). FRED's graph-export endpoint
11(fredgraph.csv) was directly confirmed - via curl and Python urllib, from
12two independent networks - to hang/reset on plain HTTP/1.1 while
13responding in ~1-2s over HTTP/2; stdlib's urllib has no HTTP/2 support, so
14this is a real, load-bearing dependency, not a convenience one. See
15fetch_fred_series()'s own docstring for the full diagnosis, including why
16the User-Agent matters here in a non-obvious way.
18Same two-safety-boundary shape as yfinance_backfill.py:
191. Writing the local cache is gated by --apply (default: dry run only).
202. Never touches config.json - this module's only output is
21 data/reference/fred_series/*.csv, read back by
22 load_cached_fred_series() at train/backtest time (Lean backtests are
23 date-bounded and must never make a live HTTP call mid-run).
25Usage:
26 python -m data_pipeline.fred_backfill [--series DGS10 DGS2] [--apply]
27"""
29from __future__ import annotations
31import argparse
32import bisect
33import csv
34import json
35import logging
36from datetime import date, timedelta
37from pathlib import Path
39from json_safety import atomic_write_text
41logger = logging.getLogger(__name__)
43ROOT = Path(__file__).resolve().parents[1]
44CONFIG_PATH = ROOT / "config.json"
45FRED_SERIES_CACHE_DIR = ROOT / "data" / "reference" / "fred_series"
47FRED_CSV_URL = "https://fred.stlouisfed.org/graph/fredgraph.csv?id={series_id}"
49DEFAULT_BOND_REFERENCE_SERIES = {
50 "treasury_3mo": "DGS3MO",
51 "treasury_2yr": "DGS2",
52 "treasury_5yr": "DGS5",
53 "treasury_10yr": "DGS10",
54 "treasury_30yr": "DGS30",
55 "credit_spread_baa10y": "BAA10Y",
56}
58# Phase 4.12 (development/Problems.md #71): the alternative-data trio
59# feeding features/alt_data_features.py. Chosen from a wider candidate list
60# (VIX/VXV/NFCI/STLFSI4/UMCSENT/TEDRATE/SOFR/BAMLH0A0HYM2/DTWEXBGS) after
61# live-fetching each one and checking (a) real coverage across
62# phase1.universe.common_window (2014-12-01..2021-03-31) and (b)
63# collinearity against the 8 existing bond_* features and against each
64# other. STLFSI4/NFCI-level/BAA10Y overlap too much (rho 0.67-0.88) to add
65# both; UMCSENT/TEDRATE/SOFR fail on coverage or lag; BAMLH0A0HYM2 has NO
66# usable history before 2023-07-25 through FRED's keyless endpoint (ICE
67# BofA series are license-restricted beyond a short trailing window) - do
68# not re-add it without a paid FRED API key. DTWEXBGS was in this same
69# candidate list and cleared both checks even then - it simply wasn't
70# needed for the original 3-series alt-data trio above (a broadcast LEVEL
71# feature; VIX/VXV/NFCI already covered vol/conditions). V5.1 Phase 2 (item
72# 8 / F2, development/Problems.md) re-adds it below as a cross-asset
73# SENSITIVITY DRIVER instead - a per-asset beta against dollar-index daily
74# CHANGE varies across the cross-section (usable by a ranker) in a way a
75# broadcast dollar-index LEVEL never would have. treasury_10yr_real
76# (DFII10) and breakeven_inflation_10y (T10YIE) are new for the same
77# purpose - real-rate and inflation-expectation sensitivity drivers,
78# neither previously evaluated as a candidate here. GUARDRAIL (plan): FRED
79# coverage for all 3 must be reverified on the Codespace before the first
80# real training run - assume nothing until `aq backfill fred` confirms it;
81# if any lacks 2014-12 -> 2021-03 coverage, drop it and its 2 sensitivity
82# columns (features/cross_asset_sensitivity.py) rather than shipping a
83# constant.
84DEFAULT_ALT_DATA_REFERENCE_SERIES = {
85 "implied_volatility_vix": "VIXCLS",
86 "implied_volatility_3m": "VXVCLS",
87 "financial_conditions_nfci": "NFCI",
88 "treasury_10yr_real": "DFII10",
89 "breakeven_inflation_10y": "T10YIE",
90 "dollar_index": "DTWEXBGS",
91}
93# V5.7.0: the foreign 3-month rates behind features/fx_carry.py (OECD 3-month interbank, monthly, dated the 1st);
94# the US leg is the daily `treasury_3mo` bill already in the bond group. Publication lags live in
95# features/fx_carry.py (FX_RATE_PUBLICATION_LAG_DAYS) because that module is the only consumer.
96DEFAULT_FX_RATE_REFERENCE_SERIES = {
97 "interbank_3m_eur": "IR3TIB01EZM156N",
98 "interbank_3m_gbp": "IR3TIB01GBM156N",
99 "interbank_3m_jpy": "IR3TIB01JPM156N",
100 "interbank_3m_aud": "IR3TIB01AUM156N",
101 "interbank_3m_cad": "IR3TIB01CAM156N",
102 "interbank_3m_chf": "IR3TIB01CHM156N",
103 "interbank_3m_nzd": "IR3TIB01NZM156N",
104}
106# Days to subtract from the decision date before doing the as-of lookup
107# (see series_value_asof()) - i.e. how many days after a series' own date
108# column the observation is actually PUBLISHED. VIX/VXV are same-day CBOE
109# closes (0 lag, identical convention to the Treasury/BAA10Y series
110# above). NFCI observations are Friday-dated but released the FOLLOWING
111# Wednesday (+5 calendar days); 7 is a deliberately conservative superset
112# that survives a holiday-shifted release. Verified this session: every
113# cached NFCI row falls on a Friday. DFII10/T10YIE are same-day Treasury-
114# desk marks (0 lag, same convention as the nominal DGS* series).
115# DTWEXBGS (H.10 trade-weighted dollar index) is a Federal Reserve Board
116# release published the following business day (1 lag) - unlike the
117# CBOE/Treasury series above, it is NOT a same-day mark.
118ALT_DATA_PUBLICATION_LAG_DAYS = {
119 "implied_volatility_vix": 0,
120 "implied_volatility_3m": 0,
121 "financial_conditions_nfci": 7,
122 "treasury_10yr_real": 0,
123 "breakeven_inflation_10y": 0,
124 "dollar_index": 1,
125}
128# ---------------------------------------------------------------------------
129# Pure helpers
130# ---------------------------------------------------------------------------
133def parse_fred_csv(text: str, series_id: str, start: str, end: str) -> list[dict]:
134 """Parses FRED's two-column CSV. The date column header has varied
135 across FRED API versions ("DATE" historically, "observation_date" as
136 of this module's writing) - read positionally (fieldnames[0]/[1])
137 rather than by a hardcoded name so a future FRED header rename doesn't
138 silently zero out every row. FRED marks holiday/no-observation rows
139 with either an empty string or a literal "." in the value column -
140 both are dropped, not coerced to 0.0 (a missing yield observation must
141 never look like "yield is exactly 0%"). Clipped to [start, end]
142 inclusive. Never raises on malformed rows - skips them, matching
143 fetch_yahoo_ohlcv()'s "never abort the whole fetch over one bad row"
144 convention."""
145 start_date = date.fromisoformat(start)
146 end_date = date.fromisoformat(end)
148 rows: list[dict] = []
149 reader = csv.DictReader(text.splitlines())
150 if not reader.fieldnames or len(reader.fieldnames) < 2:
151 return rows
152 date_column, value_column = reader.fieldnames[0], reader.fieldnames[1]
153 for record in reader:
154 raw_date = record.get(date_column)
155 raw_value = record.get(value_column)
156 if not raw_date or raw_value is None or raw_value.strip() in ("", "."):
157 continue
158 try:
159 row_date = date.fromisoformat(raw_date.strip())
160 value = float(raw_value.strip())
161 except ValueError:
162 continue
163 if row_date < start_date or row_date > end_date:
164 continue
165 rows.append({"date": row_date, "value": value})
166 return rows
169def rows_to_cache_csv(rows: list[dict]) -> str:
170 """date.isoformat(),value - one row per line, sorted by date. Mirrors
171 yfinance_backfill.rows_to_lean_csv()'s "pure formatting, sorted" shape."""
172 ordered = sorted(rows, key=lambda row: row["date"])
173 lines = [f"{row['date'].isoformat()},{row['value']}" for row in ordered]
174 return "\n".join(lines) + ("\n" if lines else "")
177def cache_csv_to_rows(text: str) -> list[dict]:
178 """Inverse of rows_to_cache_csv() - reads the local cache format back."""
179 rows: list[dict] = []
180 for line in text.splitlines():
181 if not line.strip():
182 continue
183 raw_date, raw_value = line.split(",")
184 rows.append({"date": date.fromisoformat(raw_date), "value": float(raw_value)})
185 return rows
188# V6.0.0 (latency): the as-of lookups re-sorted the whole series (~8,000 daily rows) on every call, several times per tick.
189# The sorted (dates, values) of a list is built once and reused while the list is unchanged. The cache keeps the list itself
190# alive, so its id cannot be reused by another list, and a changed length rebuilds the entry.
191_SORTED_INDEX_CACHE: dict[int, tuple[list[dict], int, list, list]] = {}
192_SORTED_INDEX_CACHE_MAX = 256
195def _sorted_index(rows: list[dict]) -> tuple[list, list]:
196 entry = _SORTED_INDEX_CACHE.get(id(rows))
197 if entry is not None and entry[0] is rows and entry[1] == len(rows):
198 return entry[2], entry[3]
199 ordered = sorted(rows, key=lambda row: row["date"])
200 dates = [row["date"] for row in ordered]
201 values = [row["value"] for row in ordered]
202 if len(_SORTED_INDEX_CACHE) >= _SORTED_INDEX_CACHE_MAX:
203 _SORTED_INDEX_CACHE.clear()
204 _SORTED_INDEX_CACHE[id(rows)] = (rows, len(rows), dates, values)
205 return dates, values
208def series_value_asof(rows: list[dict], current_date, publication_lag_days: int = 0) -> float | None:
209 """Most recent observation whose value was PUBLISHED on or before
210 current_date - the shared, publication-lag-aware as-of lookup for
211 BOTH train.py::build_alt_data_features_by_date() and
212 main.py::_build_alt_data_payload(), so the lookahead rule below cannot
213 drift between the two callers the way build_bond_features_by_date()'s
214 inline _series_asof_lookup() and main.py::_fred_series_asof() already
215 have (both correct for a same-day series, since publication_lag_days
216 is implicitly 0 there - but that helper has no lag parameter at all,
217 so it must never be reused for a lagged series).
219 The lookahead this guards against: FRED dates every observation by its
220 REFERENCE period, not its release date. DGS10's 2020-03-16 row is that
221 day's close, known that evening (lag 0, safe). NFCI's 2020-03-20 row
222 is the week ENDING Friday 2020-03-20, not released until Wednesday
223 2020-03-25 (lag ~5-7 days) - a bare bisect_right(dates, current_date)
224 would hand a 2020-03-23 decision a number that did not exist for two
225 more days. effective_date = current_date - publication_lag_days
226 reproduces the exact bisect every existing 0-lag caller already does
227 when publication_lag_days=0 (see
228 test_series_value_asof_zero_lag_matches_existing_bisect_behavior).
230 `rows` is one series' [{"date": date, "value": float}, ...] - the same
231 per-series list load_cached_fred_series() returns. Returns None (never
232 raises) if `rows` is empty or every observation postdates
233 effective_date."""
234 if not rows:
235 return None
236 target = current_date.date() if hasattr(current_date, "date") else current_date
237 effective_date = target - timedelta(days=publication_lag_days)
238 dates, values = _sorted_index(rows)
239 position = bisect.bisect_right(dates, effective_date)
240 if position == 0:
241 return None
242 return values[position - 1]
245def series_change_asof(
246 rows: list[dict],
247 current_date,
248 publication_lag_days: int = 0,
249 periods_back: int = 4,
250) -> float | None:
251 """value_asof(current_date) minus the observation `periods_back`
252 OBSERVATIONS (not calendar days) earlier in the same series - e.g.
253 periods_back=4 on a weekly series is a 4-week change. Both endpoints
254 are read from the same lag-adjusted, sorted index position, so the
255 change inherits series_value_asof()'s publication guard by
256 construction - there is no code path where the more-recent endpoint is
257 unpublished as of current_date.
259 Returns None (never 0.0 - a missing change must not look like "no
260 change") when `rows` is empty, current_date predates every
261 observation, or fewer than periods_back+1 observations precede
262 effective_date."""
263 if not rows:
264 return None
265 target = current_date.date() if hasattr(current_date, "date") else current_date
266 effective_date = target - timedelta(days=publication_lag_days)
267 dates, values = _sorted_index(rows)
268 position = bisect.bisect_right(dates, effective_date)
269 prior_index = position - 1 - periods_back
270 if position == 0 or prior_index < 0:
271 return None
272 return values[position - 1] - values[prior_index]
275# ---------------------------------------------------------------------------
276# The only function that performs network I/O.
277# ---------------------------------------------------------------------------
280def fetch_fred_series(series_id: str, start: str, end: str) -> list[dict]:
281 """GET FRED's public graph CSV endpoint for series_id, clipped to
282 [start, end]. Returns [] on any HTTP/parse failure - never raises, so
283 one bad/renamed series id never aborts a multi-series backfill run,
284 matching fetch_yahoo_ohlcv()'s convention exactly.
286 MUST use HTTP/2 (http2=True below) - confirmed by direct diagnosis
287 (V5.1 Phase 2, CODESPACE RUN 1) that FRED's graph-export endpoint
288 hangs/RST_STREAMs on plain HTTP/1.1 requests (reproduced with both
289 curl --http1.1 and stdlib urllib, from two independent networks) while
290 responding in ~1-2s over HTTP/2. This is why the module now depends on
291 httpx instead of stdlib urllib, which cannot speak HTTP/2 at all.
293 Do NOT set a browser-spoofing User-Agent here (a prior version of this
294 function did, believing FRED required one - that belief was never
295 re-verified and turned out backwards). Under HTTP/2 specifically, a
296 "Mozilla/5.0..." User-Agent paired with httpx's own (non-browser) TLS
297 fingerprint gets an IMMEDIATE RST_STREAM from FRED's edge - a
298 mismatched UA/TLS-fingerprint pair reads as automated traffic
299 disguising itself, which is worse than not disguising it at all.
300 httpx's own honest default User-Agent (python-httpx/x.y) was verified
301 working reliably; leave headers unset."""
302 import httpx # the research extra; a top-level import broke four facades on a lite install (#342)
304 url = FRED_CSV_URL.format(series_id=series_id)
305 try:
306 with httpx.Client(http2=True, timeout=15.0) as client:
307 response = client.get(url)
308 response.raise_for_status()
309 text = response.text
310 except httpx.HTTPError as exc:
311 logger.warning("fetch_fred_series(%s): fetch failed — %s", series_id, exc)
312 return []
314 rows = parse_fred_csv(text, series_id, start, end)
315 if not rows:
316 logger.warning("fetch_fred_series(%s): no data returned for %s..%s", series_id, start, end)
317 return rows
320# ---------------------------------------------------------------------------
321# Orchestration
322# ---------------------------------------------------------------------------
325def bond_reference_series(config: dict) -> dict[str, str]:
326 """config["phase1"]["features"]["bond_reference_series"], falling back
327 to DEFAULT_BOND_REFERENCE_SERIES so this module works standalone even
328 against an older config.json."""
329 return {
330 **DEFAULT_BOND_REFERENCE_SERIES,
331 **config.get("phase1", {}).get("features", {}).get("bond_reference_series", {}),
332 }
335def fetch_all_bond_reference_series(config: dict, start: str, end: str) -> dict[str, list[dict]]:
336 """One independent fetch per series - a single bad/rate-limited FRED
337 series never aborts the others, same convention as
338 yfinance_backfill.run_backfill()'s per-asset loop."""
339 return {
340 series_key: fetch_fred_series(series_id, start, end)
341 for series_key, series_id in bond_reference_series(config).items()
342 }
345def alt_data_reference_series(config: dict) -> dict[str, str]:
346 """Phase 4.12 (development/Problems.md #71) sibling of
347 bond_reference_series(): config["phase1"]["features"]["alt_data_reference_series"],
348 falling back to DEFAULT_ALT_DATA_REFERENCE_SERIES."""
349 return {
350 **DEFAULT_ALT_DATA_REFERENCE_SERIES,
351 **config.get("phase1", {}).get("features", {}).get("alt_data_reference_series", {}),
352 }
355def fx_rate_reference_series(config: dict) -> dict[str, str]:
356 """V5.7.0 sibling of bond_reference_series(): the foreign 3-month rates for the FX carry feature,
357 config["phase1"]["features"]["fx_rate_reference_series"] over DEFAULT_FX_RATE_REFERENCE_SERIES."""
358 return {
359 **DEFAULT_FX_RATE_REFERENCE_SERIES,
360 **config.get("phase1", {}).get("features", {}).get("fx_rate_reference_series", {}),
361 }
364def reference_series(config: dict, group: str = "all") -> dict[str, str]:
365 """Merged view over bond_reference_series()/alt_data_reference_series()/fx_rate_reference_series()
366 for the CLI's --group flag. group="bond", "alt" or "fx" returns just that
367 one map unchanged (bond_reference_series() itself is deliberately left
368 untouched by this addition - see test_bond_reference_series_unchanged_by_alt_addition);
369 "all" (default) merges all three, later groups taking precedence only in
370 the pathological case of an actual name collision (none exist today -
371 the dicts' keys are disjoint by construction)."""
372 if group == "bond":
373 return bond_reference_series(config)
374 if group == "alt":
375 return alt_data_reference_series(config)
376 if group == "fx":
377 return fx_rate_reference_series(config)
378 return {**bond_reference_series(config), **alt_data_reference_series(config), **fx_rate_reference_series(config)}
381def write_fred_series_cache(cache_dir: Path, series_key: str, rows: list[dict]) -> None:
382 """Writes data/reference/fred_series/{series_key}.csv - a local,
383 offline-readable cache (never committed as real market data the way
384 Lean zips are; refreshed by re-running this module with --apply).
386 V5.4.7 (development/Problems.md #123): the write now MERGES with any
387 existing cache file instead of replacing it - the CLI's --start/--end
388 clip a narrow refetch (e.g. one series, one recent year), and a full
389 replacement silently destroyed every cached observation outside that
390 window, degrading bond/macro features via series_value_asof() ever
391 after. New rows win on date collisions (fresh fetch is authoritative
392 for its own window); dates only in the existing cache are preserved."""
393 cache_dir.mkdir(parents=True, exist_ok=True)
394 output_path = cache_dir / f"{series_key}.csv"
395 merged: dict = {row["date"]: row["value"] for row in rows}
396 if output_path.exists():
397 try:
398 for existing_row in cache_csv_to_rows(output_path.read_text(encoding="utf-8")):
399 merged.setdefault(existing_row["date"], existing_row["value"])
400 except Exception as exc:
401 # An unreadable old cache must not block a fresh write - the
402 # new rows alone are still strictly better than no cache.
403 logger.warning("write_fred_series_cache(%s): unreadable old cache (%s) - replacing.", series_key, exc)
404 merged_rows = [{"date": day, "value": value} for day, value in sorted(merged.items())]
405 atomic_write_text(output_path, rows_to_cache_csv(merged_rows))
408def load_cached_fred_series(cache_dir: Path = FRED_SERIES_CACHE_DIR) -> dict[str, list[dict]]:
409 """Reads back whatever *.csv files exist under cache_dir. Returns {} if
410 the directory doesn't exist yet (fresh clone, backfill never run) -
411 every caller of this (train.py/main.py) must treat a missing/empty
412 series as "neutral-default the corresponding bond feature", never a
413 crash, same as macro_features.py's own missing-reference convention."""
414 if not cache_dir.exists():
415 return {}
416 series: dict[str, list[dict]] = {}
417 for path in sorted(cache_dir.glob("*.csv")):
418 try:
419 series[path.stem] = cache_csv_to_rows(path.read_text(encoding="utf-8"))
420 except (ValueError, OSError) as exc:
421 logger.warning("load_cached_fred_series(%s): unreadable cache file — %s", path, exc)
422 return series
425# ---------------------------------------------------------------------------
426# CLI
427# ---------------------------------------------------------------------------
430def main() -> None:
431 logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s — %(message)s")
432 parser = argparse.ArgumentParser(
433 description="Aether Quant FRED historical series backfill - offline/manual only, "
434 "no API key required, never run inside Lean or a Docker worker."
435 )
436 parser.add_argument("--series", nargs="*", default=None, help="Restrict to these series keys (default: all of --group's reference series)")
437 parser.add_argument(
438 "--group",
439 choices=["bond", "alt", "fx", "all"],
440 default="all",
441 help="Which reference-series map to fetch: bond (phase1.features.bond_reference_series), "
442 "alt (phase1.features.alt_data_reference_series, Problems.md #71), fx (the foreign 3-month rates of the "
443 "FX carry feature, V5.7.0), or all (default, all three merged)",
444 )
445 parser.add_argument("--start", default="1990-01-01")
446 parser.add_argument("--end", default=date.today().isoformat())
447 parser.add_argument("--apply", action="store_true", help="Actually write the local cache (default: dry run, report only)")
448 parser.add_argument("--config-path", type=Path, default=CONFIG_PATH)
449 parser.add_argument("--cache-dir", type=Path, default=FRED_SERIES_CACHE_DIR)
450 args = parser.parse_args()
452 with args.config_path.open("r", encoding="utf-8") as f:
453 config = json.load(f)
455 series_map = reference_series(config, args.group)
456 if args.series:
457 series_map = {key: value for key, value in series_map.items() if key in args.series}
459 print(f"{'APPLY' if args.apply else 'DRY RUN'} — fetching {len(series_map)} FRED series ({args.start}..{args.end}):\n")
460 for series_key, series_id in series_map.items():
461 rows = fetch_fred_series(series_id, args.start, args.end)
462 if args.apply and rows:
463 write_fred_series_cache(args.cache_dir, series_key, rows)
464 action = "written"
465 elif not rows:
466 action = "no_data_returned"
467 else:
468 action = "dry_run"
469 print(f"- {series_key} ({series_id}): {action}, rows_fetched={len(rows)}")
471 if not args.apply:
472 print("\nDry run only — no cache files were written. Re-run with --apply to write the cache.")
475if __name__ == "__main__":
476 main()