Spaces:
Sleeping
Sleeping
File size: 10,469 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 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 | """Data provider router with automatic fallback.
Provides:
- Primary provider: Alpha Vantage (premium quality, rate limited)
- Fallback provider: Yahoo Finance (unlimited, free)
- Automatic fallback on rate limit or failure
- Unified interface for all data operations
Usage:
router = DataProviderRouter()
quote = router.get_quote("AAPL") # Tries Alpha Vantage, falls back to Yahoo if needed
history = router.get_historical("AAPL", period="1y")
"""
import logging
from typing import Dict, Any, Optional, List
from enum import Enum
from quantlib_pro.data.alpha_vantage_client import AlphaVantageClient
from quantlib_pro.data.yahoo_client import YahooFinanceClient
logger = logging.getLogger(__name__)
class ProviderStatus(Enum):
"""Data provider status."""
ACTIVE = "active"
RATE_LIMITED = "rate_limited"
FAILED = "failed"
UNAVAILABLE = "unavailable"
class DataProviderRouter:
"""Router for market data with automatic provider fallback.
Fallback chain:
1. Alpha Vantage (if API key available and not rate limited)
2. Yahoo Finance (unlimited free tier)
"""
def __init__(
self,
alpha_vantage_api_key: Optional[str] = None,
alpha_vantage_tier: str = "free",
prefer_alpha_vantage: bool = True,
timeout: int = 10
):
"""Initialize data provider router.
Args:
alpha_vantage_api_key: Alpha Vantage API key (optional)
alpha_vantage_tier: Alpha Vantage tier (free, basic, premium)
prefer_alpha_vantage: Prefer Alpha Vantage over Yahoo Finance
timeout: Request timeout in seconds
"""
self.prefer_alpha_vantage = prefer_alpha_vantage
self.timeout = timeout
# Initialize providers
self.alpha_vantage: Optional[AlphaVantageClient] = None
self.yahoo: YahooFinanceClient = YahooFinanceClient(timeout=timeout)
# Try to initialize Alpha Vantage
try:
self.alpha_vantage = AlphaVantageClient(
api_key=alpha_vantage_api_key,
tier=alpha_vantage_tier,
timeout=timeout
)
logger.info("✓ Alpha Vantage client initialized")
except ValueError as e:
logger.warning(f"Alpha Vantage not available: {e}")
self.alpha_vantage = None
# Provider status tracking
self.alpha_vantage_status = ProviderStatus.ACTIVE if self.alpha_vantage else ProviderStatus.UNAVAILABLE
self.yahoo_status = ProviderStatus.ACTIVE
def _try_providers(
self,
operation: str,
*args,
**kwargs
) -> Dict[str, Any]:
"""Try operation with providers in order, falling back on failure.
Args:
operation: Method name (e.g., "get_quote")
*args: Positional arguments for the operation
**kwargs: Keyword arguments for the operation
Returns:
Result from the first successful provider
Raises:
Exception if all providers fail
"""
providers = []
# Build provider list based on preference
if self.prefer_alpha_vantage and self.alpha_vantage:
providers.append(("Alpha Vantage", self.alpha_vantage, self.alpha_vantage_status))
providers.append(("Yahoo Finance", self.yahoo, self.yahoo_status))
if not self.prefer_alpha_vantage and self.alpha_vantage:
providers.append(("Alpha Vantage", self.alpha_vantage, self.alpha_vantage_status))
errors = []
for provider_name, provider, status in providers:
# Skip unavailable providers
if status == ProviderStatus.UNAVAILABLE:
continue
try:
# Get the method from the provider
method = getattr(provider, operation)
logger.debug(f"Trying {provider_name}.{operation}({args[0] if args else ''})")
result = method(*args, **kwargs)
# Add metadata
result["_provider"] = provider_name
result["_timestamp"] = result.get("timestamp", "")
logger.info(f"✓ {provider_name} {operation} succeeded")
return result
except Exception as e:
error_msg = str(e)
logger.warning(f"✗ {provider_name} {operation} failed: {error_msg}")
errors.append((provider_name, error_msg))
# Update provider status
if "rate limit" in error_msg.lower() or "429" in error_msg:
if provider_name == "Alpha Vantage":
self.alpha_vantage_status = ProviderStatus.RATE_LIMITED
elif "circuit breaker" in error_msg.lower():
if provider_name == "Alpha Vantage":
self.alpha_vantage_status = ProviderStatus.FAILED
continue
# All providers failed
error_summary = "; ".join([f"{name}: {msg}" for name, msg in errors])
raise Exception(f"All providers failed for {operation}: {error_summary}")
def get_quote(self, symbol: str) -> Dict[str, Any]:
"""Get real-time quote for a symbol.
Args:
symbol: Stock ticker (e.g., "AAPL")
Returns:
Dict with quote data and provider info
"""
return self._try_providers("get_quote", symbol)
def get_historical(
self,
symbol: str,
period: str = "1y",
adjusted: bool = True
) -> Dict[str, Any]:
"""Get historical daily prices for a symbol.
Args:
symbol: Stock ticker
period: Data period for Yahoo Finance (1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max)
adjusted: Include adjusted close (for dividends/splits)
Returns:
Dict with time-series data and provider info
"""
# Alpha Vantage uses outputsize instead of period
if self.prefer_alpha_vantage and self.alpha_vantage:
try:
# Map period to Alpha Vantage outputsize
outputsize = "full" if period in ["5y", "10y", "max"] else "compact"
result = self.alpha_vantage.get_historical(
symbol,
outputsize=outputsize,
adjusted=adjusted
)
result["_provider"] = "Alpha Vantage"
return result
except Exception as e:
logger.warning(f"Alpha Vantage failed: {e}, falling back to Yahoo Finance")
# Yahoo Finance fallback
return self._try_providers("get_historical", symbol, period=period, adjusted=adjusted)
def get_intraday(
self,
symbol: str,
interval: str = "5m"
) -> Dict[str, Any]:
"""Get intraday prices.
Args:
symbol: Stock ticker
interval: Time interval (1m, 5m, 15m, 30m, 60m)
Returns:
Dict with intraday time-series data and provider info
Note:
Intraday data may only be available with premium Alpha Vantage or
for limited periods on Yahoo Finance (1m data: 7 days only)
"""
return self._try_providers("get_intraday", symbol, interval=interval)
def get_batch_quotes(self, symbols: List[str]) -> Dict[str, Dict[str, Any]]:
"""Get quotes for multiple symbols.
Args:
symbols: List of stock tickers
Returns:
Dict mapping symbol to quote data: {
"AAPL": {...},
"MSFT": {...},
...
}
"""
results = {}
errors = {}
for symbol in symbols:
try:
results[symbol] = self.get_quote(symbol)
except Exception as e:
logger.error(f"Failed to get quote for {symbol}: {e}")
errors[symbol] = str(e)
if errors:
logger.warning(f"Batch quote errors: {errors}")
return results
def get_batch_historical(
self,
symbols: List[str],
period: str = "1y",
adjusted: bool = True
) -> Dict[str, Dict[str, Any]]:
"""Get historical data for multiple symbols.
Args:
symbols: List of stock tickers
period: Data period
adjusted: Include adjusted close
Returns:
Dict mapping symbol to historical data
"""
results = {}
errors = {}
for symbol in symbols:
try:
results[symbol] = self.get_historical(symbol, period=period, adjusted=adjusted)
except Exception as e:
logger.error(f"Failed to get historical data for {symbol}: {e}")
errors[symbol] = str(e)
if errors:
logger.warning(f"Batch historical errors: {errors}")
return results
def get_provider_status(self) -> Dict[str, str]:
"""Get status of all providers.
Returns:
Dict with provider statuses: {
"alpha_vantage": "active",
"yahoo_finance": "active"
}
"""
return {
"alpha_vantage": self.alpha_vantage_status.value,
"yahoo_finance": self.yahoo_status.value
}
def reset_alpha_vantage_status(self):
"""Reset Alpha Vantage status (for manual recovery)."""
if self.alpha_vantage:
self.alpha_vantage_status = ProviderStatus.ACTIVE
logger.info("Alpha Vantage status reset to ACTIVE")
def close(self):
"""Close all provider connections."""
if self.alpha_vantage:
self.alpha_vantage.close()
# Yahoo Finance client doesn't need explicit close
def __enter__(self):
"""Context manager entry."""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Context manager exit."""
self.close()
|