Spaces:
Sleeping
Sleeping
File size: 5,997 Bytes
72fc0ee | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 | """
ResilientDataFetcher — 6-level fallback chain for market data.
Level Label Description
----- --------------- -------------------------------------------------
1 memory_cache In-process LRU dict (sub-ms)
2 redis_cache Redis (1-5 ms)
3 file_cache Parquet files (10-50 ms)
4 yfinance Yahoo Finance HTTP (300-2000 ms)
5 alternative_api Placeholder for a secondary data provider
"""
from __future__ import annotations
import logging
import time
from datetime import datetime, timedelta
from typing import Any, Optional
import numpy as np
import pandas as pd
from quantlib_pro.resilience import CircuitBreakerOpenError, registry
from quantlib_pro.utils.types import DataSource, PriceData
from quantlib_pro.utils.validation import require_ticker
from .cache import get_dataframe, set_dataframe
log = logging.getLogger(__name__)
class DataFetchError(RuntimeError):
"""Raised only when all 6 levels fail."""
class ResilientDataFetcher:
"""
Fetch OHLCV price history for a ticker using a 6-level fallback chain.
Parameters
----------
redis_client:
Optional pre-built redis.Redis instance. If None, Redis levels
are silently skipped.
cache_ttl:
Seconds to keep cached data in memory / Redis.
alt_api_fn:
Optional callable ``(ticker, start, end) -> pd.DataFrame`` for
the alternative data provider (Level 5).
"""
def __init__(
self,
redis_client: Any = None,
cache_ttl: int = 3600,
alt_api_fn: Optional[Any] = None,
) -> None:
self._redis = redis_client
self._ttl = cache_ttl
self._alt_api_fn = alt_api_fn
# ------------------------------------------------------------------ public
def fetch(
self,
ticker: str,
start: Optional[str] = None,
end: Optional[str] = None,
period: str = "1y",
) -> PriceData:
"""
Fetch OHLCV data for *ticker*.
Returns a :class:`~quantlib_pro.utils.types.PriceData` whose
``source`` field describes which level was used.
Raises
------
DataFetchError
If all 6 levels fail.
"""
ticker = require_ticker(ticker)
cache_key = self._build_key(ticker, start, end, period)
methods = [
("cache", self._try_cache, DataSource.MEMORY_CACHE),
("yfinance", self._try_yfinance, DataSource.YFINANCE),
("alternative", self._try_alt_api, DataSource.ALTERNATIVE_API),
]
for level_name, method, source in methods:
t0 = time.perf_counter()
try:
df = method(ticker, cache_key, start, end, period)
except Exception as exc:
log.warning("Level %s failed for %s: %s", level_name, ticker, exc)
continue
if df is None or df.empty:
log.debug("Level %s returned empty for %s", level_name, ticker)
continue
elapsed_ms = (time.perf_counter() - t0) * 1000
log.info(
"Fetched %s from %s in %.0f ms (%d rows)",
ticker,
source.value,
elapsed_ms,
len(df),
)
# Cache the data
self._prime_cache(cache_key, df)
return PriceData(
ticker=ticker,
df=df,
source=source,
fetched_at=datetime.utcnow(),
)
raise DataFetchError(
f"All data sources exhausted for '{ticker}'. "
"Check network connectivity and retry."
)
# ----------------------------------------------------------------- levels
def _try_cache(
self,
ticker: str,
cache_key: str,
start: Optional[str],
end: Optional[str],
period: str,
) -> Optional[pd.DataFrame]:
df, source_label = get_dataframe(cache_key, redis_client=self._redis)
if df is not None and not df.empty:
log.debug("Cache HIT [%s] for %s", source_label, ticker)
return df
return None
def _try_yfinance(
self,
ticker: str,
cache_key: str,
start: Optional[str],
end: Optional[str],
period: str,
) -> Optional[pd.DataFrame]:
def _download() -> pd.DataFrame:
import yfinance as yf # type: ignore[import]
t = yf.Ticker(ticker)
if start and end:
df = t.history(start=start, end=end, auto_adjust=True)
else:
df = t.history(period=period, auto_adjust=True)
return df
cb = registry.get("yfinance", failure_threshold=3, recovery_timeout=120)
return cb.call(_download)
def _try_alt_api(
self,
ticker: str,
cache_key: str,
start: Optional[str],
end: Optional[str],
period: str,
) -> Optional[pd.DataFrame]:
if self._alt_api_fn is None:
return None
def _call() -> pd.DataFrame:
return self._alt_api_fn(ticker, start, end)
cb = registry.get("alternative_api", failure_threshold=3, recovery_timeout=300)
return cb.call(_call)
# ----------------------------------------------------------------- helpers
@staticmethod
def _build_key(
ticker: str,
start: Optional[str],
end: Optional[str],
period: str,
) -> str:
parts = [ticker]
if start:
parts.append(f"s{start}")
if end:
parts.append(f"e{end}")
if not (start or end):
parts.append(f"p{period}")
return ":".join(parts)
def _prime_cache(self, cache_key: str, df: pd.DataFrame) -> None:
set_dataframe(cache_key, df, redis_client=self._redis, ttl_seconds=self._ttl)
|