""" FVG-Delta Forex Signal Engine v6.0 — Hardened Data Feed ======================================================= WHY THIS MODULE EXISTS ---------------------- The original engine called ``yfinance.download(...)`` directly. On Hugging Face (and any datacentre IP) Yahoo now frequently answers a scraper request with an empty body, an HTML consent page, or an HTTP 429 instead of JSON. yfinance then raises:: JSONDecodeError('Expecting value: line 1 column 1 (char 0)') ...for EVERY symbol, so the whole scan returns no data (exactly the forex "scans don't work" symptom). THE FIX (all free, no API key) ------------------------------ 1. Use a ``curl_cffi`` session that *impersonates a real Chrome browser* (TLS + HTTP/2 fingerprint). Modern yfinance uses curl_cffi internally; giving it an impersonating session is the documented way past Yahoo's bot wall. 2. Try ONE batched download for the whole chunk (fast, few requests). For any symbol the batch failed to return, retry it individually with exponential backoff + jitter — a single bad symbol no longer blanks the whole batch. 3. Never raise to the caller. Return whatever succeeded; the caller keeps the previous good bars for anything missing (last-good cache in app.py). PUBLIC API ---------- ``fetch_ohlc(yahoo_syms, period, interval, bars_per_symbol, ...) -> Dict[str, List[OHLC]]`` Returns a dict keyed by YAHOO symbol. Each value is a list of OHLC tuples ``(ts_epoch_seconds_utc, open, high, low, close, volume)`` sorted oldest→newest. The last tuple is the still-forming candle. app.py converts these to Candle objects, so this module stays free of any app.py import (no circular import). ``feed_health() -> Dict`` Lightweight counters for the dashboard / diagnostics. """ from __future__ import annotations import logging import random import time from typing import Dict, List, Tuple log = logging.getLogger("fvg.data_feed") # (ts_epoch_seconds_utc, open, high, low, close, volume) OHLC = Tuple[int, float, float, float, float, float] # Module-level singletons / counters ----------------------------------------- _SESSION = None _SESSION_KIND = "none" # "curl_cffi" | "requests" | "none" _HEALTH = { "batch_calls": 0, "batch_ok": 0, "single_calls": 0, "single_ok": 0, "symbols_returned": 0, "last_error": "", "last_ok_ts": 0, "session_kind": "none", } def _make_session(): """Build (once) a browser-impersonating HTTP session for yfinance. Prefers curl_cffi (TLS fingerprint of real Chrome — beats Yahoo's bot wall). Falls back to a plain requests session with a browser User-Agent, then to None (yfinance uses its own default client).""" global _SESSION, _SESSION_KIND if _SESSION is not None or _SESSION_KIND != "none": return _SESSION # 1) curl_cffi — the real fix. try: from curl_cffi import requests as creq # type: ignore _SESSION = creq.Session(impersonate="chrome") _SESSION_KIND = "curl_cffi" _HEALTH["session_kind"] = _SESSION_KIND log.info("data_feed: using curl_cffi (impersonate=chrome) session") return _SESSION except Exception as e: # pragma: no cover - import/runtime guard log.warning("data_feed: curl_cffi unavailable (%s); trying requests", e) # 2) plain requests with a browser UA — weaker but sometimes enough. try: import requests # type: ignore s = requests.Session() s.headers.update({ "User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/124.0 Safari/537.36"), "Accept": "application/json,text/plain,*/*", }) _SESSION = s _SESSION_KIND = "requests" _HEALTH["session_kind"] = _SESSION_KIND log.info("data_feed: using plain requests session (no curl_cffi)") return _SESSION except Exception: _SESSION_KIND = "none" _HEALTH["session_kind"] = _SESSION_KIND return None def _df_to_ohlc(sub, bars_per_symbol: int) -> List[OHLC]: """Convert a per-symbol OHLC DataFrame slice to a trimmed OHLC tuple list.""" rows: List[OHLC] = [] try: sub = sub.dropna(how="any") except Exception: return rows for ts, r in sub.iterrows(): try: epoch = int(ts.timestamp()) # pandas Timestamp -> UTC epoch seconds vol = r["Volume"] if "Volume" in r else 0.0 try: vol = float(vol) if vol != vol: # NaN vol = 0.0 except Exception: vol = 0.0 rows.append((epoch, float(r["Open"]), float(r["High"]), float(r["Low"]), float(r["Close"]), vol)) except Exception: continue if bars_per_symbol > 0: rows = rows[-bars_per_symbol:] return rows def _download(yf, syms: List[str], period: str, interval: str, session): """Call yfinance.download once. Handles the session kwarg being unsupported on some versions by retrying without it.""" kw = dict(period=period, interval=interval, progress=False, auto_adjust=False, group_by="ticker", threads=True) if session is not None: try: return yf.download(syms, session=session, **kw) except TypeError: # Older/newer yfinance signatures may not accept session= here. pass except Exception: # Network/parse failure with the session — fall through to default. pass return yf.download(syms, **kw) def _extract(df, syms: List[str], bars_per_symbol: int, out: Dict[str, List[OHLC]]) -> None: """Pull every symbol we can out of a (possibly multi-ticker) DataFrame.""" if df is None: return single = len(syms) == 1 for ys in syms: if ys in out: continue try: sub = df if single else df[ys] except Exception: continue rows = _df_to_ohlc(sub, bars_per_symbol) if rows: out[ys] = rows def fetch_ohlc(yahoo_syms: List[str], period: str = "8d", interval: str = "15m", bars_per_symbol: int = 260, retries: int = 3, batch_size: int = 50) -> Dict[str, List[OHLC]]: """Robustly fetch 15m OHLC for many Yahoo symbols. Never raises. Strategy: batched download per ``batch_size`` chunk; any symbol the batch failed to return is retried individually with exponential backoff. Returns only what succeeded — the caller keeps last-good bars for the rest. """ out: Dict[str, List[OHLC]] = {} if not yahoo_syms: return out try: import yfinance as yf # local import: keeps module import cheap except Exception as e: _HEALTH["last_error"] = f"yfinance import failed: {e}" log.error("data_feed: yfinance import failed: %s", e) return out session = _make_session() # ---- 1) Batched passes ------------------------------------------------- for i in range(0, len(yahoo_syms), max(1, batch_size)): chunk = yahoo_syms[i:i + max(1, batch_size)] _HEALTH["batch_calls"] += 1 try: df = _download(yf, chunk, period, interval, session) _extract(df, chunk, bars_per_symbol, out) _HEALTH["batch_ok"] += 1 except Exception as e: _HEALTH["last_error"] = str(e)[:200] log.warning("data_feed: batch failed (%d syms): %s", len(chunk), e) # ---- 2) Per-symbol retry for whatever is still missing ----------------- missing = [y for y in yahoo_syms if y not in out] for ys in missing: for attempt in range(max(1, retries)): _HEALTH["single_calls"] += 1 try: df = _download(yf, [ys], period, interval, session) _extract(df, [ys], bars_per_symbol, out) if ys in out: _HEALTH["single_ok"] += 1 break except Exception as e: _HEALTH["last_error"] = str(e)[:200] # exponential backoff + jitter before the next attempt time.sleep(min(4.0, 0.5 * (2 ** attempt)) + random.uniform(0, 0.4)) if out: _HEALTH["symbols_returned"] = len(out) _HEALTH["last_ok_ts"] = int(time.time()) return out def feed_health() -> Dict: """Snapshot of feed counters for the dashboard / /health endpoint.""" return dict(_HEALTH)