QTrade/src/cache/cache_manager.py
cuizhan 0f23037448 重构架构:实现单一职责原则和最小接口设计
主要修改:
1. CacheManager 负责数据库降级(单一职责)
   - 缓存未命中自动从数据库加载
   - 移除 StrategyManager/Context 的 db_manager 依赖

2. 添加 StrategyContext 核心组件
   - Position: 持仓管理
   - Capital: 资金管理
   - RiskState: 风险控制
   - BaseStrategy: 策略基类

3. 配置与类型修复
   - global.yaml 添加完整缓存配置
   - 修复 Pylance 类型推断错误
   - Config.load_with_global() 合并全局配置

4. 技术设计文档
   - 架构重构总结
   - 缓存设计方案
   - Context 共享策略
   - 接口最小化原则
2025-12-27 22:52:40 +08:00

270 lines
8.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
缓存管理器 - 纯Key-Value缓存实现
提供简单高效的内存缓存接口,不包含业务逻辑
职责:只负责数据的存取,不涉及数据加载、验证、计算
"""
import logging
from typing import Dict, Optional, Any, Union
import pandas as pd
from src.core.config import Config
logger = logging.getLogger(__name__)
class CacheManager:
"""
纯缓存管理器
职责:
- Key-Value存储:按symbol_period组织数据
- 元数据管理:自动维护数据时间范围
- 内存管理:支持内存限制和统计
- 缓存失效:支持精确和批量失效
不包含:
- ✗ 数据加载逻辑(由DataService负责)
- ✗ 数据验证逻辑(由DataService负责)
- ✗ 指标计算逻辑(由DataService负责)
"""
def __init__(self, config: Union[dict, Config], db_manager=None):
"""
初始化缓存管理器
Args:
config: 配置字典或Config对象,包含cache相关配置
db_manager: 数据库管理器(可选),用于缓存未命中时从数据库加载
"""
self.config = config
self._db_manager = db_manager
# 获取缓存配置
cache_config = config.get("cache", {})
self.enabled = cache_config.get("enabled", True)
self.max_memory_mb = cache_config.get("max_memory_mb", 4096) # 默认4GB
# 核心数据结构
self._cache: Dict[str, Dict[str, Any]] = {}
logger.info(
f"CacheManager initialized: enabled={self.enabled}, max_memory={self.max_memory_mb}MB, "
f"db_fallback={'enabled' if db_manager else 'disabled'}"
)
def get_klines(self, symbol: str, period: str) -> Optional[pd.DataFrame]:
"""
获取K线数据(带数据库降级)
Args:
symbol: 标的代码
period: 周期
Returns:
K线DataFrame或None
"""
if not self.enabled:
return None
key = self._make_key(symbol, period)
# 1. 先查缓存
if key in self._cache:
cached = self._cache[key]
cache_data = cached.get("klines")
if cache_data is not None and not cache_data.empty:
return cache_data
# 2. 缓存未命中,尝试从数据库加载
if self._db_manager:
logger.debug(f"Cache miss: {key}, loading from database")
try:
# 从数据库加载所有数据
df = self._db_manager.load_klines_all(symbol, period)
if df is not None and not df.empty:
# 加载成功,填充缓存
self.set_klines(symbol, period, {"klines": df})
logger.info(
f"Loaded {len(df)} rows from database and cached: {key}"
)
return df
except Exception as e:
logger.error(f"Failed to load from database: {key}, error: {e}")
# 3. 数据库也没有
return None
def set_klines(self, symbol: str, period: str, data: Dict[str, Any]) -> None:
"""
设置缓存数据
Args:
symbol: 标的代码
period: 周期
data: 数据字典,必须包含'klines'键,可选包含指标数据
"""
if not self.enabled:
return
key = self._make_key(symbol, period)
# 构造缓存项
if "meta" not in data:
# 自动添加元数据
klines = data.get("klines")
if klines is not None and not klines.empty:
time_range = (klines.index.min(), klines.index.max())
else:
time_range = (None, None)
data["meta"] = {
"time_range": time_range,
}
self._cache[key] = data
logger.debug(f"Cache set: {key}, time_range={data['meta']['time_range']}")
def get_indicator(
self, symbol: str, period: str, indicator_type: str
) -> Optional[pd.DataFrame]:
"""
获取指标数据(纯缓存查询)
Args:
symbol: 标的代码
period: 周期
indicator_type: 指标类型(如IndicatorType.MACD)
Returns:
指标DataFrame或None
"""
if not self.enabled:
return None
key = self._make_key(symbol, period)
if key in self._cache:
cached = self._cache[key]
if indicator_type in cached:
indicator_data = cached[indicator_type]
if indicator_data is not None and not indicator_data.empty:
return indicator_data
return None
def set_indicator(
self,
symbol: str,
period: str,
indicator_type: str,
indicator_data: pd.DataFrame,
) -> None:
"""
设置指标数据
Args:
symbol: 标的代码
period: 周期
indicator_type: 指标类型(如IndicatorType.MACD)
indicator_data: 指标DataFrame
"""
if not self.enabled:
return
key = self._make_key(symbol, period)
if key in self._cache:
# 更新已有缓存项
self._cache[key][indicator_type] = indicator_data
logger.debug(f"Cache set indicator: {key}_{indicator_type}")
else:
logger.warning(
f"Cannot set indicator {indicator_type} for {key}: klines not cached. "
f"Please cache klines first using set()."
)
def clear_klines(self, symbol: str, period: str) -> None:
"""
清除指定标的和周期的K线缓存
Args:
symbol: 标的代码
period: 周期
"""
if not self.enabled:
return
key = self._make_key(symbol, period)
if key in self._cache:
del self._cache[key]
logger.debug(f"Cache cleared: {key}")
def clear_indicator(self, symbol: str, period: str, indicator_type: str) -> None:
"""
清除指定标的、周期和指标类型的缓存
Args:
symbol: 标的代码
period: 周期
indicator_type: 指标类型(如IndicatorType.MACD)
"""
if not self.enabled:
return
key = self._make_key(symbol, period)
if key in self._cache and indicator_type in self._cache[key]:
del self._cache[key][indicator_type]
logger.debug(f"Cache cleared indicator: {key}_{indicator_type}")
def get_stats(self) -> Dict[str, Any]:
"""
获取缓存统计信息
Returns:
统计信息字典
"""
# 按标的统计
symbols_stats = {}
for key, cached in self._cache.items():
symbol = key.split("_")[0]
if symbol not in symbols_stats:
symbols_stats[symbol] = {
"periods": [],
}
period = "_".join(key.split("_")[1:])
symbols_stats[symbol]["periods"].append(period)
return {
"enabled": self.enabled,
"size": len(self._cache),
"memory_mb": self._estimate_memory(),
"max_memory_mb": self.max_memory_mb,
"symbols": symbols_stats,
}
def _make_key(self, symbol: str, period: str) -> str:
"""构造缓存键"""
return f"{symbol}_{period}"
def _estimate_memory(self) -> float:
"""估算当前缓存占用的内存大小(MB)"""
total_bytes = 0
for cached in self._cache.values():
for item in cached.values():
if isinstance(item, pd.DataFrame):
total_bytes += item.memory_usage(deep=True).sum()
elif isinstance(item, dict):
# 粗略估算字典大小
total_bytes += sum(
len(str(k)) + len(str(v)) for k, v in item.items()
)
return total_bytes / (1024 * 1024) # 转换为MB