QTrade/src/cache/cache_manager.py
cuizhan 199f0ba2ce feat: 实现常量体系和指标自动更新机制
主要更新:
- 新增 src/core/constants.py: 统一管理所有字符串常量(Period, IndicatorType, KlineColumns, IndicatorColumns)
- 统一命名规范: 所有指标类型和列名使用小写格式
- 实现 DataService.from_config() 工厂方法,自动初始化所有依赖组件
- 实现下载数据后自动重新计算指标功能
- 更新所有指标计算器使用 IndicatorColumns 常量定义列名
- 修复 table_schemas.py 表名格式bug (indicators_{period}_{indicator})
- 新增数据库清理脚本,删除旧格式的指标表
- 优化配置文件,调整指标参数

文档:
- docs/constants_guide.md: 常量使用指南
- docs/cache_storage_layout.md: 缓存和存储架构说明
2025-12-23 17:56:01 +08:00

248 lines
7.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]):
"""
初始化缓存管理器
Args:
config: 配置字典或Config对象,包含cache相关配置
"""
self.config = config
# 获取缓存配置
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"
)
def get_klines(self, symbol: str, period: str) -> Optional[pd.DataFrame]:
"""
获取缓存数据(纯Key-Value查询)
Args:
symbol: 标的代码
period: 周期
Returns:
缓存中的K线DataFrame或None
"""
if not self.enabled:
return None
key = self._make_key(symbol, period)
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
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