"""Pre-warm EODHD OHLCV cache for every ticker in the latest global universe. Run once per monthly cycle (or whenever the universe parquet is rebuilt) to ensure the signal-generation pipeline reads from cache exclusively (no live fetches during scoring). Tickers already cached are skipped. Usage: python scripts/live/warm_ohlcv_cache.py # actually fetch python scripts/live/warm_ohlcv_cache.py --dry-run # show scope, don't fetch python scripts/live/warm_ohlcv_cache.py --extend-to-today """ from __future__ import annotations import argparse import logging import sys import time from datetime import date from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[2])) import pandas as pd from src.data.eodhd_client import EODHDClient, EODHDError logger = logging.getLogger(__name__) def _latest_universe_parquet(universe_dir: Path) -> Path: files = sorted(universe_dir.glob("global_msci_world_imi_*.parquet")) if not files: raise FileNotFoundError( f"No universe parquet in {universe_dir} — run build_global_universe.py first" ) return files[-1] def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--dry-run", action="store_true", help="Report what would be fetched without making any API calls", ) parser.add_argument( "--extend-to-today", action="store_true", help="Force re-fetch for cached tickers whose cache max-date is before today", ) parser.add_argument( "--max-tickers", type=int, default=None, help="Stop after N tickers (testing/throttling)", ) parser.add_argument( "--universe-dir", default="data/universe", help="Directory containing global_msci_world_imi_*.parquet (default: data/universe)", ) args = parser.parse_args() logging.basicConfig(level=logging.WARNING, format="%(asctime)s %(levelname)s %(message)s") universe_path = _latest_universe_parquet(Path(args.universe_dir)) universe = pd.read_parquet(universe_path) tickers = sorted(universe["eodhd_ticker"].dropna().unique().tolist()) cache_dir = Path("data/raw/eodhd/eod") cached = {p.stem for p in cache_dir.glob("*.json")} if cache_dir.is_dir() else set() to_fetch = [t for t in tickers if t not in cached] today_iso = date.today().isoformat() print("=" * 80) print(f"OHLCV cache warmer — {today_iso}") print("=" * 80) print(f"Universe parquet: {universe_path.name}") print(f"Universe size: {len(tickers):,}") print(f"Already cached: {len(cached & set(tickers)):,}") print(f"To fetch: {len(to_fetch):,}") if args.extend_to_today: print(f"Extend-to-today: enabled (cached tickers will refresh to {today_iso})") if args.max_tickers is not None: print(f"Max tickers cap: {args.max_tickers:,}") to_fetch = to_fetch[: args.max_tickers] estimated_minutes = len(to_fetch) / 15 / 60 print(f"Estimated runtime (at ~15/sec rate limit): {estimated_minutes:.1f} min") print(f"API quota cost: ~{len(to_fetch):,} calls " f"({len(to_fetch) / 1000:.1f}% of 100k monthly quota)") if args.dry_run: print("\n[DRY RUN] — exiting without fetching") return if not to_fetch and not args.extend_to_today: print("\nNothing to do — cache is up to date.") return client = EODHDClient() n_ok = 0 n_fail = 0 failed: list[tuple[str, str]] = [] start = time.monotonic() # This loop fetches data for new tickers. for i, ticker in enumerate(to_fetch, 1): try: df = client.get_eod_prices(ticker) if len(df) == 0: logger.warning("Empty EOD for %s — kept cache slot but no data", ticker) n_ok += 1 except EODHDError as exc: n_fail += 1 failed.append((ticker, f"{exc.status_code} {exc.reason[:60]}")) logger.warning("Failed %s: %s", ticker, exc) if i % 100 == 0: elapsed = time.monotonic() - start rate = i / elapsed eta = (len(to_fetch) - i) / rate / 60 print(f" [{i:>5}/{len(to_fetch):>5}] {rate:.1f}/sec ETA {eta:.1f} min") # This loop refreshes cached tickers through today's date. n_extended = 0 if args.extend_to_today: already = sorted(cached & set(tickers)) if args.max_tickers is not None: already = already[: args.max_tickers] print(f"\nExtending {len(already):,} cached tickers to {today_iso} ...") for i, ticker in enumerate(already, 1): try: client.get_eod_prices(ticker, extend_cache_to=today_iso) n_extended += 1 except EODHDError as exc: n_fail += 1 failed.append((ticker, f"extend: {exc.status_code} {exc.reason[:60]}")) if i % 200 == 0: print(f" [{i:>5}/{len(already):>5}] extended") total_elapsed = time.monotonic() - start print() print(f"Done in {total_elapsed/60:.1f} min") print(f" Newly fetched: {n_ok:,}") print(f" Extended: {n_extended:,}") print(f" Failed: {n_fail:,}") if failed: print("\nFirst 20 failures:") for t, reason in failed[:20]: print(f" {t:<15} {reason}") # Save the complete failure list for review. fail_path = Path("data/universe") / f"ohlcv_fetch_failures_{date.today().strftime('%Y%m%d')}.csv" pd.DataFrame(failed, columns=["eodhd_ticker", "failure_reason"]).to_csv(fail_path, index=False) print(f"Full failure list: {fail_path}") if __name__ == "__main__": main()