2025-12-19 06:27:22 +08:00
|
|
|
|
"""
|
2025-12-19 07:13:01 +08:00
|
|
|
|
缓存管理器 - 透明缓存实现
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
2025-12-19 06:49:29 +08:00
|
|
|
|
提供统一的缓存管理接口,支持市场数据缓存和指标计算
|
2025-12-19 07:13:01 +08:00
|
|
|
|
使用StorageLayer实现存储解耦
|
2025-12-19 06:27:22 +08:00
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
import logging
|
|
|
|
|
|
from typing import Dict, List, Optional, Any
|
|
|
|
|
|
from datetime import datetime
|
|
|
|
|
|
import pandas as pd
|
2025-12-19 07:33:08 +08:00
|
|
|
|
from src.indicator_calculator.indicator_manager import IndicatorManager
|
2025-12-19 07:13:01 +08:00
|
|
|
|
from src.data.storage_layer import StorageLayer
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class CacheManager:
|
|
|
|
|
|
"""
|
2025-12-19 07:13:01 +08:00
|
|
|
|
智能缓存管理器
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
2025-12-19 07:13:01 +08:00
|
|
|
|
特性:
|
|
|
|
|
|
- 透明缓存:自动处理缓存命中/未命中
|
|
|
|
|
|
- 自动加载:缓存未命中时自动从Storage加载
|
|
|
|
|
|
- 指标计算:集成指标计算器
|
|
|
|
|
|
- 内存管理:支持内存限制和统计
|
2025-12-19 06:27:22 +08:00
|
|
|
|
"""
|
|
|
|
|
|
|
2025-12-19 06:49:29 +08:00
|
|
|
|
def __init__(
|
|
|
|
|
|
self,
|
|
|
|
|
|
config: dict,
|
2025-12-19 07:13:01 +08:00
|
|
|
|
storage: StorageLayer,
|
2025-12-19 06:49:29 +08:00
|
|
|
|
indicator_calc: Optional[IndicatorManager] = None,
|
|
|
|
|
|
):
|
2025-12-19 06:27:22 +08:00
|
|
|
|
"""
|
|
|
|
|
|
初始化缓存管理器
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
config: 配置字典,包含cache相关配置
|
2025-12-19 07:13:01 +08:00
|
|
|
|
storage: 存储层实例
|
2025-12-19 06:49:29 +08:00
|
|
|
|
indicator_calc: 指标计算器实例(可选,如不提供则自动创建)
|
2025-12-19 06:27:22 +08:00
|
|
|
|
"""
|
|
|
|
|
|
self.config = config
|
2025-12-19 07:13:01 +08:00
|
|
|
|
self.storage = storage
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
2025-12-19 06:49:29 +08:00
|
|
|
|
# 指标计算器(独立模块)
|
|
|
|
|
|
self.indicator_calc = (
|
|
|
|
|
|
indicator_calc if indicator_calc is not None else IndicatorManager()
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2025-12-19 06:27:22 +08:00
|
|
|
|
# 获取缓存配置
|
|
|
|
|
|
cache_config = config.get("cache", {})
|
|
|
|
|
|
self.enabled = cache_config.get("enabled", True)
|
|
|
|
|
|
self.mode = cache_config.get("mode", "static")
|
|
|
|
|
|
self.max_memory_mb = cache_config.get("max_memory_mb", 1024)
|
2025-12-19 07:13:01 +08:00
|
|
|
|
self.auto_load = cache_config.get("auto_load", True) # 新增:自动加载
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
|
|
|
|
|
# 核心数据结构
|
|
|
|
|
|
self._cache: Dict[str, Dict[str, Any]] = {}
|
|
|
|
|
|
self._dirty: set = set() # 脏数据集合(Phase 3使用)
|
|
|
|
|
|
|
|
|
|
|
|
# 统计信息
|
2025-12-19 07:13:01 +08:00
|
|
|
|
self._metrics = {"hit": 0, "miss": 0, "total_requests": 0, "auto_loads": 0}
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
|
|
|
|
|
logger.info(
|
|
|
|
|
|
f"CacheManager initialized: mode={self.mode}, enabled={self.enabled}, max_memory={self.max_memory_mb}MB"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
def preload(self, symbols: List[str]) -> None:
|
|
|
|
|
|
"""
|
|
|
|
|
|
预加载数据
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
symbols: 标的列表,由调用方提供
|
|
|
|
|
|
- 回测:从回测配置获取标的池
|
|
|
|
|
|
- 实盘:从交易系统获取持仓+关注列表
|
|
|
|
|
|
"""
|
|
|
|
|
|
if not self.enabled:
|
|
|
|
|
|
logger.warning("Cache is disabled, skip preload")
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
preload_config = self.config.get("cache", {}).get("preload", {})
|
|
|
|
|
|
if not preload_config.get("enabled", True):
|
|
|
|
|
|
logger.info("Preload is disabled in config")
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
time_range = preload_config.get("time_range", "1M")
|
|
|
|
|
|
periods = preload_config.get("periods", ["1m", "1d"])
|
|
|
|
|
|
|
|
|
|
|
|
logger.info(
|
|
|
|
|
|
f"Starting preload: {len(symbols)} symbols, periods={periods}, time_range={time_range}, mode={self.mode}"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2025-12-19 07:13:01 +08:00
|
|
|
|
# 计算时间范围
|
|
|
|
|
|
end_date = datetime.now()
|
|
|
|
|
|
if time_range.endswith("M"):
|
|
|
|
|
|
months = int(time_range[:-1])
|
|
|
|
|
|
from datetime import timedelta
|
|
|
|
|
|
|
|
|
|
|
|
start_date = end_date - timedelta(days=months * 30)
|
|
|
|
|
|
elif time_range.endswith("Y"):
|
|
|
|
|
|
years = int(time_range[:-1])
|
|
|
|
|
|
from datetime import timedelta
|
|
|
|
|
|
|
|
|
|
|
|
start_date = end_date - timedelta(days=years * 365)
|
|
|
|
|
|
else:
|
|
|
|
|
|
logger.warning(f"Unknown time_range format: {time_range}, using 1M")
|
|
|
|
|
|
from datetime import timedelta
|
|
|
|
|
|
|
|
|
|
|
|
start_date = end_date - timedelta(days=30)
|
|
|
|
|
|
|
2025-12-19 06:27:22 +08:00
|
|
|
|
loaded_count = 0
|
|
|
|
|
|
for i, symbol in enumerate(symbols):
|
|
|
|
|
|
for period in periods:
|
|
|
|
|
|
try:
|
2025-12-19 07:13:01 +08:00
|
|
|
|
# 从Storage加载数据
|
|
|
|
|
|
klines = self.storage.load_klines(
|
|
|
|
|
|
symbol, period, start_date, end_date
|
|
|
|
|
|
)
|
|
|
|
|
|
if klines is not None and not klines.empty:
|
|
|
|
|
|
self.set(symbol, period, {"klines": klines})
|
2025-12-19 06:27:22 +08:00
|
|
|
|
loaded_count += 1
|
|
|
|
|
|
|
|
|
|
|
|
# 定期输出进度
|
|
|
|
|
|
if (i + 1) % 10 == 0:
|
|
|
|
|
|
logger.info(f"Preload progress: {i + 1}/{len(symbols)} symbols")
|
|
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
logger.error(f"Failed to preload {symbol}_{period}: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
# 输出统计信息
|
|
|
|
|
|
memory_mb = self._estimate_memory()
|
|
|
|
|
|
logger.info(
|
|
|
|
|
|
f"Preload completed: {loaded_count} items loaded, memory={memory_mb:.1f}MB"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
def get(
|
|
|
|
|
|
self,
|
|
|
|
|
|
symbol: str,
|
|
|
|
|
|
period: str,
|
|
|
|
|
|
start: Optional[datetime] = None,
|
|
|
|
|
|
end: Optional[datetime] = None,
|
|
|
|
|
|
) -> Optional[pd.DataFrame]:
|
|
|
|
|
|
"""
|
2025-12-19 07:13:01 +08:00
|
|
|
|
获取K线数据(透明缓存)
|
|
|
|
|
|
|
|
|
|
|
|
特性:
|
|
|
|
|
|
- 优先从缓存获取
|
|
|
|
|
|
- 缓存未命中时自动从Storage加载(如果enabled和auto_load)
|
|
|
|
|
|
- 自动缓存加载的数据
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
symbol: 标的代码
|
|
|
|
|
|
period: 周期(如'1m', '1d')
|
|
|
|
|
|
start: 开始时间(可选)
|
|
|
|
|
|
end: 结束时间(可选)
|
|
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
|
K线DataFrame,如果未找到返回None
|
|
|
|
|
|
"""
|
2025-12-19 07:13:01 +08:00
|
|
|
|
self._metrics["total_requests"] += 1
|
|
|
|
|
|
|
2025-12-19 06:27:22 +08:00
|
|
|
|
if not self.enabled:
|
2025-12-19 07:13:01 +08:00
|
|
|
|
# 缓存禁用,直接从storage加载
|
|
|
|
|
|
return self.storage.load_klines(symbol, period, start, end)
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
|
|
|
|
|
key = self._make_key(symbol, period)
|
|
|
|
|
|
|
2025-12-19 07:13:01 +08:00
|
|
|
|
# 1. 检查缓存
|
2025-12-19 06:27:22 +08:00
|
|
|
|
if key in self._cache:
|
|
|
|
|
|
cached = self._cache[key]
|
|
|
|
|
|
|
|
|
|
|
|
# 更新访问统计
|
|
|
|
|
|
cached["meta"]["last_access"] = datetime.now()
|
|
|
|
|
|
cached["meta"]["access_count"] += 1
|
|
|
|
|
|
|
|
|
|
|
|
self._metrics["hit"] += 1
|
|
|
|
|
|
|
|
|
|
|
|
# 返回数据切片
|
|
|
|
|
|
klines = cached.get("klines")
|
|
|
|
|
|
if klines is not None and not klines.empty:
|
|
|
|
|
|
if start is not None or end is not None:
|
|
|
|
|
|
# 按时间范围切片
|
|
|
|
|
|
mask = pd.Series(True, index=klines.index)
|
|
|
|
|
|
if start is not None:
|
|
|
|
|
|
mask &= klines.index >= start
|
|
|
|
|
|
if end is not None:
|
|
|
|
|
|
mask &= klines.index <= end
|
|
|
|
|
|
return klines[mask]
|
|
|
|
|
|
return klines
|
|
|
|
|
|
|
|
|
|
|
|
logger.warning(f"Cache hit but no klines data for {key}")
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
2025-12-19 07:13:01 +08:00
|
|
|
|
# 2. 缓存未命中
|
2025-12-19 06:27:22 +08:00
|
|
|
|
self._metrics["miss"] += 1
|
|
|
|
|
|
logger.debug(f"Cache miss: {key}")
|
|
|
|
|
|
|
2025-12-19 07:13:01 +08:00
|
|
|
|
# 3. 自动从Storage加载(如果启用)
|
|
|
|
|
|
if self.auto_load:
|
|
|
|
|
|
self._metrics["auto_loads"] += 1
|
|
|
|
|
|
klines = self.storage.load_klines(symbol, period, start, end)
|
|
|
|
|
|
|
|
|
|
|
|
if klines is not None and not klines.empty:
|
|
|
|
|
|
# 自动缓存
|
|
|
|
|
|
self.set(symbol, period, {"klines": klines})
|
|
|
|
|
|
logger.debug(f"Auto-loaded and cached: {key}, {len(klines)} records")
|
|
|
|
|
|
|
|
|
|
|
|
# 返回时间切片(如果需要)
|
|
|
|
|
|
if start is not None or end is not None:
|
|
|
|
|
|
mask = pd.Series(True, index=klines.index)
|
|
|
|
|
|
if start is not None:
|
|
|
|
|
|
mask &= klines.index >= start
|
|
|
|
|
|
if end is not None:
|
|
|
|
|
|
mask &= klines.index <= end
|
|
|
|
|
|
return klines[mask]
|
|
|
|
|
|
return klines
|
|
|
|
|
|
else:
|
|
|
|
|
|
logger.debug(f"No data in storage: {key}")
|
|
|
|
|
|
return None
|
|
|
|
|
|
else:
|
|
|
|
|
|
# auto_load禁用,返回None
|
|
|
|
|
|
return None
|
2025-12-19 06:27:22 +08:00
|
|
|
|
|
|
|
|
|
|
def set(
|
|
|
|
|
|
self, symbol: str, period: str, data: Dict[str, Any], mark_dirty: bool = False
|
|
|
|
|
|
) -> None:
|
|
|
|
|
|
"""
|
|
|
|
|
|
设置缓存数据
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
symbol: 标的代码
|
|
|
|
|
|
period: 周期
|
|
|
|
|
|
data: 数据字典,应包含'klines'键
|
|
|
|
|
|
mark_dirty: 是否标记为脏数据(Phase 3使用)
|
|
|
|
|
|
"""
|
|
|
|
|
|
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,
|
|
|
|
|
|
"loaded_at": datetime.now(),
|
|
|
|
|
|
"last_access": datetime.now(),
|
|
|
|
|
|
"access_count": 0,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
self._cache[key] = data
|
|
|
|
|
|
|
|
|
|
|
|
if mark_dirty:
|
|
|
|
|
|
self._dirty.add(key)
|
|
|
|
|
|
|
|
|
|
|
|
logger.debug(f"Cache set: {key}, time_range={data['meta']['time_range']}")
|
|
|
|
|
|
|
|
|
|
|
|
def invalidate(
|
|
|
|
|
|
self, symbol: Optional[str] = None, period: Optional[str] = None
|
|
|
|
|
|
) -> None:
|
|
|
|
|
|
"""
|
|
|
|
|
|
失效缓存
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
symbol: 标的代码,None表示全部
|
|
|
|
|
|
period: 周期,None表示该标的所有周期
|
|
|
|
|
|
"""
|
|
|
|
|
|
if symbol is None and period is None:
|
|
|
|
|
|
# 清空全部缓存
|
|
|
|
|
|
count = len(self._cache)
|
|
|
|
|
|
self._cache.clear()
|
|
|
|
|
|
self._dirty.clear()
|
|
|
|
|
|
logger.info(f"Invalidated all cache: {count} items cleared")
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
if period is None:
|
|
|
|
|
|
# 清空某个symbol的所有周期
|
|
|
|
|
|
if symbol is not None:
|
|
|
|
|
|
keys_to_remove = [
|
|
|
|
|
|
k for k in self._cache.keys() if k.startswith(f"{symbol}_")
|
|
|
|
|
|
]
|
|
|
|
|
|
for k in keys_to_remove:
|
|
|
|
|
|
del self._cache[k]
|
|
|
|
|
|
self._dirty.discard(k)
|
|
|
|
|
|
logger.info(
|
|
|
|
|
|
f"Invalidated cache for {symbol}: {len(keys_to_remove)} items cleared"
|
|
|
|
|
|
)
|
|
|
|
|
|
else:
|
|
|
|
|
|
# 清空特定缓存
|
|
|
|
|
|
if symbol is not None:
|
|
|
|
|
|
key = self._make_key(symbol, period)
|
|
|
|
|
|
if key in self._cache:
|
|
|
|
|
|
del self._cache[key]
|
|
|
|
|
|
self._dirty.discard(key)
|
|
|
|
|
|
logger.info(f"Invalidated cache: {key}")
|
|
|
|
|
|
|
|
|
|
|
|
def get_stats(self) -> Dict[str, Any]:
|
|
|
|
|
|
"""
|
|
|
|
|
|
获取缓存统计信息
|
|
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
|
统计信息字典
|
|
|
|
|
|
"""
|
|
|
|
|
|
total = self._metrics["total_requests"]
|
|
|
|
|
|
hit_rate = self._metrics["hit"] / total if total > 0 else 0
|
|
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
|
"size": len(self._cache),
|
|
|
|
|
|
"memory_mb": self._estimate_memory(),
|
|
|
|
|
|
"hit_count": self._metrics["hit"],
|
|
|
|
|
|
"miss_count": self._metrics["miss"],
|
2025-12-19 07:13:01 +08:00
|
|
|
|
"auto_loads": self._metrics["auto_loads"],
|
2025-12-19 06:27:22 +08:00
|
|
|
|
"total_requests": total,
|
|
|
|
|
|
"hit_rate": hit_rate,
|
|
|
|
|
|
"mode": self.mode,
|
|
|
|
|
|
"enabled": self.enabled,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
def shutdown(self, save_data: bool = False) -> None:
|
|
|
|
|
|
"""
|
|
|
|
|
|
关闭缓存管理器
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
save_data: 是否保存数据(Phase 3实现)
|
|
|
|
|
|
"""
|
|
|
|
|
|
stats = self.get_stats()
|
|
|
|
|
|
logger.info(
|
|
|
|
|
|
f"CacheManager shutdown: size={stats['size']}, hit_rate={stats['hit_rate']:.2%}, memory={stats['memory_mb']:.1f}MB"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
if save_data:
|
|
|
|
|
|
# Phase 3: 实现数据持久化
|
|
|
|
|
|
logger.warning("Data persistence not implemented in Phase 1")
|
|
|
|
|
|
|
2025-12-19 06:49:29 +08:00
|
|
|
|
def get_indicator(
|
|
|
|
|
|
self,
|
|
|
|
|
|
symbol: str,
|
|
|
|
|
|
period: str,
|
|
|
|
|
|
indicator_name: str,
|
|
|
|
|
|
params: Optional[Dict[str, Any]] = None,
|
|
|
|
|
|
start: Optional[datetime] = None,
|
|
|
|
|
|
end: Optional[datetime] = None,
|
|
|
|
|
|
) -> Optional[pd.DataFrame]:
|
|
|
|
|
|
"""
|
|
|
|
|
|
获取指标数据
|
|
|
|
|
|
|
|
|
|
|
|
实现逻辑:
|
|
|
|
|
|
1. 检查缓存中是否有该指标数据
|
|
|
|
|
|
2. 如无,先获取K线数据(调用self.get())
|
|
|
|
|
|
3. 使用IndicatorCalculator计算指标
|
|
|
|
|
|
4. 缓存计算结果
|
|
|
|
|
|
5. 返回指标数据
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
symbol: 标的代码
|
|
|
|
|
|
period: 周期
|
|
|
|
|
|
indicator_name: 指标名称(如'MACD', 'KDJ')
|
|
|
|
|
|
params: 指标参数(可选)
|
|
|
|
|
|
start: 开始时间(可选)
|
|
|
|
|
|
end: 结束时间(可选)
|
|
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
|
指标DataFrame,如果未找到返回None
|
|
|
|
|
|
"""
|
|
|
|
|
|
if not self.enabled:
|
|
|
|
|
|
# 缓存未启用,直接计算
|
|
|
|
|
|
klines = self.get(symbol, period, start, end)
|
|
|
|
|
|
if klines is None or klines.empty:
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
# 临时创建一个IndicatorManager并配置指标
|
|
|
|
|
|
temp_manager = IndicatorManager()
|
|
|
|
|
|
temp_manager.add_indicator(indicator_name.lower(), params)
|
|
|
|
|
|
result_df = temp_manager.calculate(klines)
|
|
|
|
|
|
|
|
|
|
|
|
# 从结果DataFrame中提取指标列
|
|
|
|
|
|
return self._extract_indicator_columns(result_df, indicator_name.lower())
|
|
|
|
|
|
|
|
|
|
|
|
self._metrics["total_requests"] += 1
|
|
|
|
|
|
key = self._make_key(symbol, period)
|
|
|
|
|
|
|
|
|
|
|
|
# 检查缓存中是否已有该指标
|
|
|
|
|
|
if key in self._cache:
|
|
|
|
|
|
cached = self._cache[key]
|
|
|
|
|
|
indicator_key = indicator_name.lower()
|
|
|
|
|
|
|
|
|
|
|
|
if indicator_key in cached:
|
|
|
|
|
|
# 指标缓存命中
|
|
|
|
|
|
self._metrics["hit"] += 1
|
|
|
|
|
|
cached["meta"]["last_access"] = datetime.now()
|
|
|
|
|
|
cached["meta"]["access_count"] += 1
|
|
|
|
|
|
|
|
|
|
|
|
indicator_data = cached[indicator_key]
|
|
|
|
|
|
|
|
|
|
|
|
# 时间切片
|
|
|
|
|
|
if indicator_data is not None and not indicator_data.empty:
|
|
|
|
|
|
if start is not None or end is not None:
|
|
|
|
|
|
mask = pd.Series(True, index=indicator_data.index)
|
|
|
|
|
|
if start is not None:
|
|
|
|
|
|
mask &= indicator_data.index >= start
|
|
|
|
|
|
if end is not None:
|
|
|
|
|
|
mask &= indicator_data.index <= end
|
|
|
|
|
|
return indicator_data[mask]
|
|
|
|
|
|
return indicator_data
|
|
|
|
|
|
|
|
|
|
|
|
logger.warning(
|
|
|
|
|
|
f"Cache hit but indicator data is empty for {key}_{indicator_name}"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
# 缓存未命中,需要计算
|
|
|
|
|
|
self._metrics["miss"] += 1
|
|
|
|
|
|
logger.debug(f"Indicator cache miss: {key}_{indicator_name}")
|
|
|
|
|
|
|
|
|
|
|
|
# 1. 获取K线数据(可能从缓存或DB加载)
|
|
|
|
|
|
klines = self.get(symbol, period, start, end)
|
|
|
|
|
|
if klines is None or klines.empty:
|
|
|
|
|
|
logger.warning(
|
|
|
|
|
|
f"No klines available for indicator calculation: {symbol}_{period}"
|
|
|
|
|
|
)
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
# 2. 计算指标
|
|
|
|
|
|
try:
|
|
|
|
|
|
# 使用临时的IndicatorManager
|
|
|
|
|
|
temp_manager = IndicatorManager()
|
|
|
|
|
|
temp_manager.add_indicator(indicator_name.lower(), params)
|
|
|
|
|
|
result_df = temp_manager.calculate(klines)
|
|
|
|
|
|
|
|
|
|
|
|
# 提取指标列
|
|
|
|
|
|
indicator_data = self._extract_indicator_columns(
|
|
|
|
|
|
result_df, indicator_name.lower()
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
if indicator_data is None or indicator_data.empty:
|
|
|
|
|
|
logger.warning(
|
|
|
|
|
|
f"Indicator calculation returned empty data: {symbol}_{period}_{indicator_name}"
|
|
|
|
|
|
)
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
# 3. 缓存指标结果
|
|
|
|
|
|
indicator_key = indicator_name.lower()
|
|
|
|
|
|
if key not in self._cache:
|
|
|
|
|
|
# 如果K线缓存项不存在,创建一个
|
|
|
|
|
|
self._cache[key] = {
|
|
|
|
|
|
"klines": klines,
|
|
|
|
|
|
"meta": {
|
|
|
|
|
|
"time_range": (klines.index.min(), klines.index.max()),
|
|
|
|
|
|
"loaded_at": datetime.now(),
|
|
|
|
|
|
"last_access": datetime.now(),
|
|
|
|
|
|
"access_count": 0,
|
|
|
|
|
|
},
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
self._cache[key][indicator_key] = indicator_data
|
|
|
|
|
|
logger.debug(f"Indicator cached: {key}_{indicator_name}")
|
|
|
|
|
|
|
|
|
|
|
|
return indicator_data
|
|
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
logger.error(
|
|
|
|
|
|
f"Failed to calculate indicator {indicator_name} for {symbol}_{period}: {e}"
|
|
|
|
|
|
)
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
2025-12-19 06:27:22 +08:00
|
|
|
|
# ========== 内部方法 ==========
|
|
|
|
|
|
|
2025-12-19 06:49:29 +08:00
|
|
|
|
def _extract_indicator_columns(
|
|
|
|
|
|
self, df: pd.DataFrame, indicator_name: str
|
|
|
|
|
|
) -> Optional[pd.DataFrame]:
|
|
|
|
|
|
"""
|
|
|
|
|
|
从计算结果DataFrame中提取指标列
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
df: 包含指标列的DataFrame
|
|
|
|
|
|
indicator_name: 指标名称(小写)
|
|
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
|
只包含指标列的DataFrame
|
|
|
|
|
|
"""
|
|
|
|
|
|
# 查找所有以indicator_name开头的列
|
|
|
|
|
|
indicator_columns = [
|
|
|
|
|
|
col for col in df.columns if col.startswith(indicator_name + "_")
|
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
|
if not indicator_columns:
|
|
|
|
|
|
logger.warning(
|
|
|
|
|
|
f"No indicator columns found for {indicator_name}, available columns: {df.columns.tolist()}"
|
|
|
|
|
|
)
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
return df[indicator_columns].copy()
|
|
|
|
|
|
|
2025-12-19 06:27:22 +08:00
|
|
|
|
def _make_key(self, symbol: str, period: str) -> str:
|
|
|
|
|
|
"""生成缓存键"""
|
|
|
|
|
|
return f"{symbol}_{period}"
|
|
|
|
|
|
|
|
|
|
|
|
def _estimate_memory(self) -> float:
|
|
|
|
|
|
"""
|
|
|
|
|
|
估算当前缓存内存占用(MB)
|
|
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
|
内存占用(MB)
|
|
|
|
|
|
"""
|
|
|
|
|
|
try:
|
|
|
|
|
|
total_bytes = 0
|
|
|
|
|
|
|
|
|
|
|
|
for key, cached in self._cache.items():
|
|
|
|
|
|
klines = cached.get("klines")
|
|
|
|
|
|
if klines is not None:
|
|
|
|
|
|
# DataFrame内存占用
|
|
|
|
|
|
total_bytes += klines.memory_usage(deep=True).sum()
|
|
|
|
|
|
|
|
|
|
|
|
# 其他指标数据
|
|
|
|
|
|
for field in ["macd", "kdj", "rsi", "boll"]:
|
|
|
|
|
|
df = cached.get(field)
|
|
|
|
|
|
if df is not None:
|
|
|
|
|
|
total_bytes += df.memory_usage(deep=True).sum()
|
|
|
|
|
|
|
|
|
|
|
|
return total_bytes / (1024 * 1024) # 转换为MB
|
|
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
logger.error(f"Failed to estimate memory: {e}")
|
|
|
|
|
|
return 0.0
|