# Cache存储布局规范 ## 概述 CacheManager使用内存字典 `_cache` 存储市场数据和技术指标,采用扁平化Key-Value结构,支持快速查询和自动元数据管理。 --- ## 核心数据结构 ### 1. 主缓存字典 ```python self._cache: Dict[str, Dict[str, Any]] = {} ``` **结构说明**: - **Key**: `str` - 缓存键,格式为 `"{symbol}_{period}"` - **Value**: `Dict[str, Any]` - 缓存项,包含数据和元数据 --- ## 缓存键(Key)规则 ### 格式 ```python key = f"{symbol}_{period}" ``` ### 示例 | 标的 | 周期 | 缓存键 | | --------- | ---- | -------------- | | 601658.SH | 1d | `601658.SH_1d` | | 000001.SZ | 1h | `000001.SZ_1h` | | 600000.SH | 5m | `600000.SH_5m` | ### 生成方法 ```python def _make_key(self, symbol: str, period: str) -> str: """生成缓存键""" return f"{symbol}_{period}" ``` --- ## 缓存项(Value)结构 ### 完整结构 ```python cached_item = { # ========== K线数据 ========== "klines": pd.DataFrame, # 必需,K线数据 # ========== 元数据 ========== "meta": { "time_range": (datetime, datetime), # 数据时间范围 (最早, 最晚) "loaded_at": datetime, # 加载时间 "last_access": datetime, # 最后访问时间 "access_count": int, # 访问次数 }, # ========== 技术指标(可选)========== "macd": pd.DataFrame, # MACD指标数据 "kdj": pd.DataFrame, # KDJ指标数据 "rsi": pd.DataFrame, # RSI指标数据 "boll": pd.DataFrame, # 布林带指标数据 # ... 其他指标 } ``` --- ## 字段详细说明 ### 1. klines (必需) **类型**: `pd.DataFrame` **索引**: DatetimeIndex (timestamp) **列结构**: ```python columns = ['open', 'high', 'low', 'close', 'volume', 'amount'] ``` **示例数据**: ```python open high low close volume amount timestamp 2024-01-01 09:30:00 10.50 10.80 10.45 10.75 1000000 10750000.00 2024-01-01 10:30:00 10.75 10.95 10.70 10.90 1200000 13080000.00 ``` **特性**: - 按时间排序(升序) - 不能为空(empty check) - 时间索引唯一,无重复 --- ### 2. meta (必需) **类型**: `Dict[str, Any]` **字段说明**: | 字段 | 类型 | 说明 | 自动管理 | | -------------- | ---------------------- | ------------------------------------ | ------------------------ | | `time_range` | `(datetime, datetime)` | 数据时间范围
(最早时间, 最晚时间) | ✅ 自动从klines.index提取 | | `loaded_at` | `datetime` | 数据加载到缓存的时间 | ✅ set()时自动生成 | | `last_access` | `datetime` | 最后一次访问时间 | ✅ get()时自动更新 | | `access_count` | `int` | 累计访问次数 | ✅ get()时自动递增 | **元数据自动生成逻辑**: ```python 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, } ``` --- ### 3. 技术指标字段(可选) **类型**: `pd.DataFrame` **索引**: 与klines相同的DatetimeIndex **命名规则**: 小写指标名称(`indicator_name.lower()`) **常见指标及其列结构**: | 指标 | 字段名 | 列结构 | | ------ | -------- | ------------------------------- | | MACD | `"macd"` | `['dif', 'dea', 'macd']` | | KDJ | `"kdj"` | `['k', 'd', 'j']` | | RSI | `"rsi"` | `['rsi_6', 'rsi_12', 'rsi_24']` | | 布林带 | `"boll"` | `['upper', 'middle', 'lower']` | **示例**: ```python cached_item = { "klines": df_klines, "meta": {...}, "macd": pd.DataFrame({ 'dif': [...], 'dea': [...], 'macd': [...] }, index=df_klines.index), } ``` --- ## 缓存操作流程 ### 1. 写入缓存 (set) ```python def set(self, symbol: str, period: str, data: Dict[str, Any], mark_dirty: bool = False): key = self._make_key(symbol, period) # 自动添加元数据(如果不存在) if "meta" not in data: data["meta"] = {...} # 见上述元数据生成逻辑 # 存储 self._cache[key] = data # 标记脏数据(可选,Phase 3使用) if mark_dirty: self._dirty.add(key) ``` **调用示例**: ```python # 方式1: 只写入K线数据(自动生成meta) cache.set("601658.SH", "1d", {"klines": df_klines}) # 方式2: 写入K线+指标(自动生成meta) cache.set("601658.SH", "1d", { "klines": df_klines, "macd": df_macd }) # 方式3: 完整控制(手动提供meta) cache.set("601658.SH", "1d", { "klines": df_klines, "meta": { "time_range": (start, end), "loaded_at": datetime.now(), "last_access": datetime.now(), "access_count": 0, } }) ``` --- ### 2. 读取缓存 (get_simple) ```python def get_simple(self, symbol: str, period: str) -> Optional[pd.DataFrame]: 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: # 自动更新访问统计 cached["meta"]["last_access"] = datetime.now() cached["meta"]["access_count"] += 1 self._metrics["hit"] += 1 return cache_data self._metrics["miss"] += 1 return None ``` **特性**: - ✅ 自动更新 `last_access` - ✅ 自动递增 `access_count` - ✅ 更新统计指标 `hit`/`miss` --- ### 3. 失效缓存 (invalidate) ```python # 清空全部缓存 cache.invalidate() # 清空某个标的的所有周期 cache.invalidate(symbol="601658.SH") # 清空某个标的的特定周期 cache.invalidate(symbol="601658.SH", period="1d") ``` **实现逻辑**: ```python def invalidate(self, symbol: Optional[str] = None, period: Optional[str] = None): if symbol is None and period is None: # 清空全部 self._cache.clear() self._dirty.clear() elif period is None: # 清空symbol的所有周期 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) else: # 清空指定key key = self._make_key(symbol, period) self._cache.pop(key, None) self._dirty.discard(key) ``` --- ## 辅助数据结构 ### 1. 脏数据集合 ```python self._dirty: set = set() # 存储被修改但未保存的缓存键 ``` **用途**: Phase 3 - 数据持久化 - 标记哪些缓存项需要写回存储 - 用于增量保存优化 **操作**: ```python # 标记为脏数据 cache.set(symbol, period, data, mark_dirty=True) # 清理脏标记 cache._dirty.discard(key) ``` --- ### 2. 统计指标 ```python self._metrics = { "hit": 0, # 缓存命中次数 "miss": 0, # 缓存未命中次数 "total_requests": 0, # 总请求次数 "auto_loads": 0, # 自动加载次数 } ``` **计算**: ```python hit_rate = metrics["hit"] / metrics["total_requests"] if metrics["total_requests"] > 0 else 0 ``` --- ## 内存管理 ### 内存估算 ```python def _estimate_memory(self) -> float: """估算当前缓存内存占用(MB)""" total_bytes = 0 for key, cached in self._cache.items(): # K线数据 klines = cached.get("klines") if klines is not None: 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 ``` ### 内存限制 ```python self.max_memory_mb = config.get("cache", {}).get("max_memory_mb", 1024) ``` **配置示例**: ```yaml cache: max_memory_mb: 1024 # 最大1GB内存 ``` --- ## 完整示例 ### 示例1: 基本K线缓存 ```python # 写入 df = pd.DataFrame({ 'open': [10.5, 10.8], 'high': [10.9, 11.0], 'low': [10.4, 10.7], 'close': [10.8, 10.9], 'volume': [1000000, 1200000], 'amount': [10800000, 13080000] }, index=pd.to_datetime(['2024-01-01', '2024-01-02'])) cache.set("601658.SH", "1d", {"klines": df}) # 读取 klines = cache.get_simple("601658.SH", "1d") # 缓存结构 self._cache = { "601658.SH_1d": { "klines": df, "meta": { "time_range": (Timestamp('2024-01-01'), Timestamp('2024-01-02')), "loaded_at": datetime(2025, 12, 23, 15, 30, 0), "last_access": datetime(2025, 12, 23, 15, 30, 5), "access_count": 1, } } } ``` ### 示例2: K线+指标缓存 ```python # 写入K线和MACD cache.set("000001.SZ", "1h", { "klines": df_klines, "macd": df_macd }) # 读取K线 klines = cache.get_simple("000001.SZ", "1h") # 读取指标 macd = cache.get_indicator("000001.SZ", "1h", "MACD") # 缓存结构 self._cache = { "000001.SZ_1h": { "klines": df_klines, "macd": df_macd, "meta": { "time_range": (start, end), "loaded_at": datetime.now(), "last_access": datetime.now(), "access_count": 2, } } } ``` --- ## 最佳实践 ### ✅ 推荐做法 1. **使用标准Key格式** ```python key = f"{symbol}_{period}" # 统一格式 ``` 2. **自动元数据管理** ```python # 只提供数据,让CacheManager自动添加meta cache.set(symbol, period, {"klines": df}) ``` 3. **指标命名一致** ```python # 使用小写指标名 cache.set(symbol, period, {"klines": df, "macd": df_macd}) ``` 4. **及时失效过期数据** ```python # 数据更新后失效缓存 cache.invalidate(symbol, period) ``` ### ❌ 避免的做法 1. **不要手动构造完整meta** ```python # ❌ 不推荐 data = { "klines": df, "meta": {...} # 手动构造 } # ✅ 推荐 data = {"klines": df} # 自动生成meta ``` 2. **不要直接修改_cache** ```python # ❌ 不推荐 self._cache[key]["klines"] = new_df # ✅ 推荐 cache.set(symbol, period, {"klines": new_df}) ``` 3. **不要跨周期混用数据** ```python # ❌ 错误:不同周期的数据存储在同一个key cache.set("601658.SH", "1d", {"klines_1d": df1, "klines_1h": df2}) # ✅ 正确:分别存储 cache.set("601658.SH", "1d", {"klines": df1}) cache.set("601658.SH", "1h", {"klines": df2}) ``` --- ## 配置参考 ```yaml cache: enabled: true # 启用缓存 mode: static # 缓存模式(static/dynamic) max_memory_mb: 1024 # 最大内存(MB) auto_load: true # 自动从数据库加载 preload: enabled: true # 启用预加载 time_range: "1M" # 预加载时间范围(1M=1个月,1Y=1年) periods: ["1d", "1h"] # 预加载周期 ``` --- ## 统计信息查询 ```python stats = cache.get_stats() # 输出示例 { "enabled": True, "mode": "static", "size": 150, # 缓存项数量 "hit": 1234, # 命中次数 "miss": 56, # 未命中次数 "total_requests": 1290, # 总请求数 "hit_rate": 0.9566, # 命中率 95.66% "auto_loads": 45, # 自动加载次数 "memory_mb": 234.5, # 内存占用 234.5 MB "symbols": { # 分标的统计 "601658.SH": { "periods": ["1d", "1h"], "access_count": 100, "last_access": "2025-12-23 15:30:00" } } } ``` --- ## 版本历史 | 版本 | 日期 | 变更说明 | | ---- | ---------- | --------------------------- | | 1.0 | 2025-12-23 | 初始版本 - 定义基本存储结构 | --- ## 参考文件 - 源代码: [src/cache/cache_manager.py](../src/cache/cache_manager.py) - 配置: [configs/backtest.yaml](../configs/backtest.yaml)