Spaces:
Sleeping
Sleeping
File size: 11,901 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 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 | """Enhanced Redis cache manager for market data.
Features:
- Automatic cache key generation
- TTL management by data type
- Cache invalidation strategies
- Cache warming
- Cache statistics
- Integration with data router
Cache Key Schema:
- quote:{symbol} β Real-time quote (TTL: 60s)
- historical:{symbol}:{period} β Historical data (TTL: 24h)
- intraday:{symbol}:{interval} β Intraday data (TTL: 5min)
- correlation_matrix:{symbols}:{days} β Correlation matrix (TTL: 1h)
- vol_surface:{symbol} β Volatility surface (TTL: 1h)
"""
import os
import json
import logging
import hashlib
from typing import Any, Dict, Optional, List
from datetime import datetime, timedelta
import redis
import pandas as pd
logger = logging.getLogger(__name__)
class CacheManager:
"""Redis cache manager for market data."""
# Default TTLs by data type (in seconds)
TTL_DEFAULTS = {
"quote": 60, # Real-time quotes: 1 minute
"historical": 86400, # Historical data: 24 hours
"intraday": 300, # Intraday data: 5 minutes
"correlation_matrix": 3600, # Correlation: 1 hour
"vol_surface": 3600, # Volatility surface: 1 hour
"portfolio": 300, # Portfolio data: 5 minutes
"backtest": 7200, # Backtest results: 2 hours
"regime_state": 1800, # Regime state: 30 minutes
}
def __init__(
self,
redis_url: Optional[str] = None,
key_prefix: str = "quantlib:",
enabled: bool = True
):
"""Initialize cache manager.
Args:
redis_url: Redis connection URL (default: from REDIS_URL env)
key_prefix: Prefix for all cache keys
enabled: Enable/disable caching (useful for testing)
"""
self.key_prefix = key_prefix
self.enabled = enabled
# Initialize Redis connection
self.redis_client: Optional[redis.Redis] = None
if enabled:
try:
redis_url = redis_url or os.getenv(
"REDIS_URL",
"redis://localhost:6379/0"
)
self.redis_client = redis.from_url(
redis_url,
decode_responses=True,
socket_connect_timeout=2,
socket_timeout=2,
max_connections=20
)
# Test connection
self.redis_client.ping()
logger.info(f"β Redis cache connected: {redis_url}")
except Exception as e:
logger.warning(f"Redis cache unavailable: {e}. Caching disabled.")
self.redis_client = None
self.enabled = False
def _build_key(self, data_type: str, *args) -> str:
"""Build cache key from data type and arguments.
Args:
data_type: Type of data (quote, historical, etc.)
*args: Arguments to include in key (symbol, period, etc.)
Returns:
Cache key: "quantlib:quote:AAPL"
"""
parts = [data_type] + [str(arg) for arg in args]
key = ":".join(parts)
return f"{self.key_prefix}{key}"
def _hash_key(self, data: str) -> str:
"""Generate hash for data (for complex keys)."""
return hashlib.md5(data.encode()).hexdigest()[:16]
def get(self, data_type: str, *args) -> Optional[Any]:
"""Get data from cache.
Args:
data_type: Type of data
*args: Key components
Returns:
Cached data or None if not found
"""
if not self.enabled or not self.redis_client:
return None
key = self._build_key(data_type, *args)
try:
raw_data = self.redis_client.get(key)
if raw_data is None:
logger.debug(f"Cache MISS: {key}")
return None
# Parse JSON
data = json.loads(raw_data)
logger.debug(f"Cache HIT: {key}")
return data
except Exception as e:
logger.warning(f"Cache GET error for {key}: {e}")
return None
def set(
self,
data_type: str,
data: Any,
*args,
ttl: Optional[int] = None
) -> bool:
"""Set data in cache.
Args:
data_type: Type of data
data: Data to cache (must be JSON-serializable)
*args: Key components
ttl: Time to live in seconds (default: from TTL_DEFAULTS)
Returns:
True if cached successfully
"""
if not self.enabled or not self.redis_client:
return False
key = self._build_key(data_type, *args)
ttl = ttl or self.TTL_DEFAULTS.get(data_type, 3600)
try:
# Serialize to JSON
raw_data = json.dumps(data)
# Set with TTL
self.redis_client.setex(key, ttl, raw_data)
logger.debug(f"Cache SET: {key} (TTL: {ttl}s)")
return True
except Exception as e:
logger.warning(f"Cache SET error for {key}: {e}")
return False
def get_dataframe(self, data_type: str, *args) -> Optional[pd.DataFrame]:
"""Get DataFrame from cache.
Args:
data_type: Type of data
*args: Key components
Returns:
Cached DataFrame or None
"""
data = self.get(data_type, *args)
if data is None:
return None
try:
return pd.DataFrame(data)
except Exception as e:
logger.warning(f"Failed to convert cached data to DataFrame: {e}")
return None
def set_dataframe(
self,
data_type: str,
df: pd.DataFrame,
*args,
ttl: Optional[int] = None
) -> bool:
"""Set DataFrame in cache.
Args:
data_type: Type of data
df: DataFrame to cache
*args: Key components
ttl: Time to live in seconds
Returns:
True if cached successfully
"""
try:
# Convert DataFrame to dict (records format for efficiency)
data = df.to_dict('records') if not df.empty else []
return self.set(data_type, data, *args, ttl=ttl)
except Exception as e:
logger.warning(f"Failed to cache DataFrame: {e}")
return False
def delete(self, data_type: str, *args) -> bool:
"""Delete data from cache.
Args:
data_type: Type of data
*args: Key components
Returns:
True if deleted successfully
"""
if not self.enabled or not self.redis_client:
return False
key = self._build_key(data_type, *args)
try:
self.redis_client.delete(key)
logger.debug(f"Cache DELETE: {key}")
return True
except Exception as e:
logger.warning(f"Cache DELETE error for {key}: {e}")
return False
def invalidate_pattern(self, pattern: str) -> int:
"""Invalidate all keys matching a pattern.
Args:
pattern: Redis pattern (e.g., "quote:*")
Returns:
Number of keys deleted
"""
if not self.enabled or not self.redis_client:
return 0
full_pattern = f"{self.key_prefix}{pattern}"
try:
keys = list(self.redis_client.scan_iter(match=full_pattern, count=100))
if keys:
deleted = self.redis_client.delete(*keys)
logger.info(f"Invalidated {deleted} keys matching {full_pattern}")
return deleted
return 0
except Exception as e:
logger.warning(f"Pattern invalidation error: {e}")
return 0
def invalidate_symbol(self, symbol: str) -> int:
"""Invalidate all cached data for a symbol.
Args:
symbol: Stock ticker
Returns:
Number of keys deleted
"""
return self.invalidate_pattern(f"*:{symbol}*")
def get_stats(self) -> Dict[str, Any]:
"""Get cache statistics.
Returns:
Dict with cache stats: {
"connected": True,
"keys": 1234,
"memory_used": "10.5 MB",
"hit_rate": 0.85
}
"""
if not self.enabled or not self.redis_client:
return {"connected": False}
try:
info = self.redis_client.info()
keyspace = self.redis_client.info("keyspace")
# Extract stats
db0 = keyspace.get("db0", {})
keys = db0.get("keys", 0)
return {
"connected": True,
"keys": keys,
"memory_used": info.get("used_memory_human", "N/A"),
"hit_rate": info.get("keyspace_hit_rate", 0),
"uptime_seconds": info.get("uptime_in_seconds", 0),
"connected_clients": info.get("connected_clients", 0),
}
except Exception as e:
logger.warning(f"Failed to get cache stats: {e}")
return {"connected": False, "error": str(e)}
def flush_all(self) -> bool:
"""Flush all keys from cache (DANGEROUS - use only in dev/test).
Returns:
True if successful
"""
if not self.enabled or not self.redis_client:
return False
try:
self.redis_client.flushdb()
logger.warning("Cache flushed (all keys deleted)")
return True
except Exception as e:
logger.error(f"Cache flush error: {e}")
return False
def warm_cache(self, symbols: List[str], data_router: Any):
"""Pre-populate cache with data for symbols.
Args:
symbols: List of stock tickers
data_router: DataProviderRouter instance
"""
logger.info(f"Warming cache for {len(symbols)} symbols...")
for symbol in symbols:
try:
# Fetch and cache quote
quote = data_router.get_quote(symbol)
self.set("quote", quote, symbol)
# Fetch and cache 1-year historical data
historical = data_router.get_historical(symbol, period="1y")
self.set("historical", historical, symbol, "1y")
logger.debug(f"Warmed cache for {symbol}")
except Exception as e:
logger.warning(f"Failed to warm cache for {symbol}: {e}")
logger.info(f"β Cache warming complete")
def close(self):
"""Close Redis connection."""
if self.redis_client:
self.redis_client.close()
logger.info("Cache connection closed")
def __enter__(self):
"""Context manager entry."""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Context manager exit."""
self.close()
# Global cache instance
_cache_manager: Optional[CacheManager] = None
def get_cache_manager() -> CacheManager:
"""Get the global cache manager instance."""
global _cache_manager
if _cache_manager is None:
_cache_manager = CacheManager()
return _cache_manager
|