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: 缓存和存储架构说明
This commit is contained in:
cuizhan 2025-12-23 17:56:01 +08:00
parent 74fec74930
commit 199f0ba2ce
18 changed files with 2268 additions and 780 deletions

View File

@ -67,6 +67,7 @@ data_checker:
# 行情配置(公用)
market:
kline_periods:
- "tick"
- "1m"
- "5m"
- "15m"

View File

@ -0,0 +1,540 @@
# 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)` | 数据时间范围<br>(最早时间, 最晚时间) | ✅ 自动从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)

302
docs/constants_guide.md Normal file
View File

@ -0,0 +1,302 @@
# 常量定义使用指南
## 概述
为了避免在代码中使用魔法字符串(magic strings),我们集中定义了所有常用的字符串常量。这样可以:
1. ✅ **避免拼写错误** - IDE可以提供代码补全
2. ✅ **统一管理** - 修改常量只需在一处更改
3. ✅ **类型安全** - 减少运行时错误
4. ✅ **易于维护** - 代码更清晰,易于理解
## 常量类
### Period - 周期常量
定义了所有支持的K线周期:
```python
from src.core.constants import Period
# 日线
Period.DAY_1 # "1d"
Period.DAY_3 # "3d"
Period.DAY_5 # "5d"
# 周线/月线
Period.WEEK_1 # "1w"
Period.MONTH_1 # "1M"
# 小时线
Period.HOUR_1 # "1h"
Period.HOUR_2 # "2h"
Period.HOUR_4 # "4h"
# 分钟线
Period.MIN_1 # "1m"
Period.MIN_5 # "5m"
Period.MIN_15 # "15m"
Period.MIN_30 # "30m"
```
**常用方法**:
```python
# 检查周期是否有效
if Period.is_valid("1d"):
print("有效的周期")
# 获取所有周期
all_periods = Period.get_all()
print(all_periods) # ['1d', '3d', '5d', ...]
```
### Indicator - 技术指标常量
定义了所有支持的技术指标:
```python
from src.core.constants import Indicator
# 趋势类指标
Indicator.MACD # "MACD"
Indicator.MA # "MA"
Indicator.EMA # "EMA"
Indicator.BOLL # "BOLL"
# 震荡类指标
Indicator.KDJ # "KDJ"
Indicator.RSI # "RSI"
Indicator.CCI # "CCI"
# 量能类指标
Indicator.VOL # "VOL"
Indicator.OBV # "OBV"
# 波动类指标
Indicator.ATR # "ATR"
```
**常用方法**:
```python
# 检查指标是否有效
if Indicator.is_valid("MACD"):
print("有效的指标")
# 获取所有指标
all_indicators = Indicator.get_all()
print(all_indicators) # ['MACD', 'MA', 'EMA', ...]
```
### CacheKey - 缓存键名常量
定义了缓存数据结构中使用的键名:
```python
from src.core.constants import CacheKey
CacheKey.KLINES # "klines"
CacheKey.META # "meta"
CacheKey.TIME_RANGE # "time_range"
CacheKey.INDICATORS # "indicators"
```
### ConfigKey - 配置键名常量
定义了配置文件中使用的键名:
```python
from src.core.constants import ConfigKey
# 缓存配置
ConfigKey.CACHE_ENABLED # "cache_enabled"
ConfigKey.CACHE_MAX_MEMORY_MB # "cache_max_memory_mb"
# 数据库配置
ConfigKey.DB_TYPE # "db_type"
ConfigKey.DB_PATH # "db_path"
```
## 使用示例
### ❌ 不推荐的写法(使用魔法字符串)
```python
# 容易拼写错误,IDE无法提供补全
klines = service.get_klines("000001", "1d", start, end)
macd = service.get_indicator("000001", "1d", "MACD")
# 如果拼错了,只能在运行时才能发现错误
klines = service.get_klines("000001", "1dd", start, end) # 拼写错误!
```
### ✅ 推荐的写法(使用常量)
```python
from src.core.constants import Period, Indicator
# 使用常量,IDE可以提供代码补全
klines = service.get_klines("000001", Period.DAY_1, start, end)
macd = service.get_indicator("000001", Period.DAY_1, Indicator.MACD)
# 如果拼错常量名,IDE会立即提示错误
klines = service.get_klines("000001", Period.DAY_11, start, end) # IDE会提示错误!
```
## 实际应用场景
### 场景1: 数据获取
```python
from src.core.constants import Period
from src.data_service.data_service import DataService
from datetime import datetime
service = DataService.from_config(config)
start = datetime(2024, 1, 1)
end = datetime(2024, 12, 31)
# 获取不同周期的数据
daily = service.get_klines("000001", Period.DAY_1, start, end)
hourly = service.get_klines("000001", Period.HOUR_1, start, end)
minute = service.get_klines("000001", Period.MIN_5, start, end)
```
### 场景2: 指标计算
```python
from src.core.constants import Period, Indicator
# 获取多个指标
macd = service.get_indicator("000001", Period.DAY_1, Indicator.MACD)
kdj = service.get_indicator("000001", Period.DAY_1, Indicator.KDJ)
rsi = service.get_indicator("000001", Period.DAY_1, Indicator.RSI)
```
### 场景3: 用户输入验证
```python
from src.core.constants import Period
def get_klines_safe(service, symbol, period_str, start, end):
"""安全地获取K线数据,验证周期"""
if not Period.is_valid(period_str):
raise ValueError(
f"无效的周期: {period_str}\n"
f"支持的周期: {', '.join(Period.get_all())}"
)
return service.get_klines(symbol, period_str, start, end)
# 使用
try:
klines = get_klines_safe(service, "000001", "1d", start, end) # 成功
klines = get_klines_safe(service, "000001", "2d", start, end) # 抛出异常
except ValueError as e:
print(f"错误: {e}")
```
### 场景4: 批量操作
```python
from src.core.constants import Period
# 下载多个周期的数据
periods_to_download = [
Period.DAY_1,
Period.HOUR_1,
Period.MIN_5,
]
for period in periods_to_download:
service.download_klines(
symbols=["000001", "600000"],
start_date=start,
end_date=end,
periods=[period]
)
```
### 场景5: 动态筛选
```python
from src.core.constants import Period
# 只处理分钟级别的数据
minute_periods = [p for p in Period.get_all() if p.endswith('m')]
print(f"分钟级周期: {minute_periods}")
# 输出: ['1m', '5m', '15m', '30m', '60m']
# 只处理日线级别的数据
day_periods = [p for p in Period.get_all() if p.endswith('d')]
print(f"日线级周期: {day_periods}")
# 输出: ['1d', '3d', '5d']
```
## 迁移指南
如果你的代码中已经使用了字符串,可以按以下步骤迁移:
### 步骤1: 导入常量
```python
# 在文件顶部添加导入
from src.core.constants import Period, Indicator
```
### 步骤2: 替换字符串
```python
# 查找所有 "1d" 并替换为 Period.DAY_1
# 查找所有 "1h" 并替换为 Period.HOUR_1
# 查找所有 "MACD" 并替换为 Indicator.MACD
```
### 步骤3: 测试
```python
# 运行测试确保一切正常
python -m pytest tests/
```
## 注意事项
1. **向后兼容性**:常量的值保持不变,所以现有代码不会受影响
2. **逐步迁移**:可以逐步替换,不需要一次性全部改完
3. **字符串仍可用**:如果某些地方确实需要使用字符串(如配置文件),仍然可以使用
4. **验证函数**:使用 `is_valid()` 方法验证用户输入或外部数据
## 扩展常量
如果需要添加新的周期或指标:
```python
# 在 src/core/constants.py 中添加
class Period:
# ... 现有常量 ...
# 添加新周期
MIN_3 = "3m" # 3分钟线
# 记得更新 ALL 列表
ALL = [
# ... 现有周期 ...
MIN_3,
]
```
## 完整示例
查看 `examples/constants_usage_example.py` 获取完整的使用示例。
运行示例:
```bash
python examples/constants_usage_example.py
```
## 总结
使用常量定义是一个简单但有效的最佳实践,可以显著提高代码质量和可维护性。建议在所有新代码中使用常量,并逐步迁移旧代码。

View File

@ -0,0 +1,126 @@
"""
删除旧格式的指标表
旧格式: macd_1d, kdj_1d, ma_1d 等
新格式: indicators_1d_macd, indicators_1d_kdj 等
"""
import sys
import os
from pathlib import Path
# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
# 设置环境变量
os.environ["CONFIG_FILE"] = "configs/backtest.yaml"
from src.database_manager import DatabaseManager
from src.core import get_config
from sqlalchemy import text
def identify_old_tables(all_tables):
"""识别旧格式的指标表"""
old_indicators = ["macd", "kdj", "boll", "rsi", "ma", "ema"]
old_periods = ["1m", "5m", "15m", "30m", "60m", "1d", "1w"]
old_tables = []
for indicator in old_indicators:
for period in old_periods:
table_name = f"{indicator}_{period}"
if table_name in all_tables:
old_tables.append(table_name)
return old_tables
def main():
print("\n" + "=" * 70)
print(" 删除旧格式的指标表")
print("=" * 70)
# 初始化数据库管理器
config = get_config()
db_manager = DatabaseManager()
database = config.get("database.database")
print(f"\n当前数据库: {database}")
# 获取所有表
all_tables = db_manager.list_tables(database)
# 识别旧格式的表
old_tables = identify_old_tables(all_tables)
if not old_tables:
print("\n✓ 没有发现旧格式的指标表")
return
print(f"\n发现 {len(old_tables)} 个旧格式的指标表:")
for table in sorted(old_tables):
print(f" • {table}")
# 确认删除
print("\n⚠️ 警告: 这些表将被永久删除!")
print("旧格式: {indicator}_{period} (例如: macd_1d)")
print("新格式: indicators_{period}_{indicator} (例如: indicators_1d_macd)")
response = input("\n确认删除这些旧表? (输入 'YES' 确认): ").strip()
if response != "YES":
print("\n✗ 操作已取消")
return
# 删除表
print("\n开始删除...")
db_url = (
f"mysql+pymysql://{config.get('database.user')}:"
f"{config.get('database.password')}@"
f"{config.get('database.host')}:{config.get('database.port')}"
f"/{database}"
)
from sqlalchemy import create_engine
engine = create_engine(db_url, echo=False)
success_count = 0
fail_count = 0
try:
with engine.connect() as conn:
# 禁用外键检查
conn.execute(text("SET FOREIGN_KEY_CHECKS = 0"))
for table in old_tables:
try:
conn.execute(text(f"DROP TABLE `{table}`"))
conn.commit()
print(f"✓ 删除成功: {table}")
success_count += 1
except Exception as e:
print(f"✗ 删除失败: {table} - {str(e)}")
fail_count += 1
# 恢复外键检查
conn.execute(text("SET FOREIGN_KEY_CHECKS = 1"))
conn.commit()
finally:
engine.dispose()
print("\n" + "=" * 70)
print(f"完成: 成功删除 {success_count} 个表, 失败 {fail_count} 个")
print("=" * 70 + "\n")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n\n✗ 操作被用户中断")
sys.exit(1)
except Exception as e:
print(f"\n✗ 错误: {str(e)}")
sys.exit(1)

View File

@ -0,0 +1,53 @@
"""快速删除旧格式的指标表"""
import sys
import os
from pathlib import Path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
os.environ["CONFIG_FILE"] = "configs/backtest.yaml"
from src.database_manager import DatabaseManager
from src.core import get_config
from sqlalchemy import create_engine, text
config = get_config()
db = DatabaseManager()
db_name = config.get("database.database")
# 获取所有旧格式的表
tables = db.list_tables(db_name)
old_tables = [
t
for t in tables
if any(
t.startswith(f"{ind}_") for ind in ["macd", "kdj", "boll", "rsi", "ma", "ema"]
)
and not t.startswith("indicators_")
]
print(f"\n发现 {len(old_tables)} 个旧格式的表")
print("开始删除...\n")
# 创建数据库连接
db_url = (
f"mysql+pymysql://{config.get('database.user')}:"
f"{config.get('database.password')}@"
f"{config.get('database.host')}:{config.get('database.port')}"
f"/{db_name}"
)
engine = create_engine(db_url)
with engine.connect() as conn:
conn.execute(text("SET FOREIGN_KEY_CHECKS = 0"))
for table in old_tables:
conn.execute(text(f"DROP TABLE `{table}`"))
print(f"✓ 已删除: {table}")
conn.execute(text("SET FOREIGN_KEY_CHECKS = 1"))
conn.commit()
engine.dispose()
print(f"\n✓ 成功删除 {len(old_tables)} 个旧表\n")

View File

@ -31,6 +31,7 @@ import mplfinance as mpf
from src.core.config import Config
from src.data_service import DataService
from src.core.constants import Period
# 设置控制台编码为UTF-8解决中文乱码
if sys.platform == "win32":
@ -93,23 +94,136 @@ class KlineCanvas(FigureCanvasQTAgg):
# 启用键盘焦点
self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
def keyPressEvent(self, event):
"""处理键盘事件"""
print(
f"[键盘] 按下: {event.key()}, 数据量: {len(self.full_data) if self.full_data is not None else 0}"
# 防止resize过于频繁触发重绘
self._resize_timer = None
# 鼠标悬停显示数据
self.current_display_data = None # 当前显示的数据
self.current_macd_data = None # MACD数据
self.current_rsi_data = None # RSI数据
self.crosshair_vlines = [] # 十字光标垂直线列表(多个子图)
self.info_text = None # 信息文本
# 连接鼠标移动事件
self.mpl_connect("motion_notify_event", self.on_mouse_move)
def resizeEvent(self, event):
"""处理窗口缩放事件 - 延迟重绘避免崩溃"""
super().resizeEvent(event)
# 不立即重绘,避免缩放时频繁重绘导致崩溃
# 窗口缩放会自动触发matplotlib的重绘
def on_mouse_move(self, event):
"""鼠标移动事件 - 显示OHLC和指标信息"""
if event.inaxes is None or self.current_display_data is None:
return
# 检查鼠标是否在任一子图上
if event.inaxes not in self.fig.axes:
return
try:
# 获取鼠标位置对应的数据索引
x_index = int(round(event.xdata))
if 0 <= x_index < len(self.current_display_data):
# 获取该K线的数据
data_row = self.current_display_data.iloc[x_index]
# 获取时间信息(从_original_index列)
if "_original_index" in data_row:
time_value = data_row["_original_index"]
date_str = (
time_value.strftime("%Y-%m-%d %H:%M")
if hasattr(time_value, "strftime")
else str(time_value)
)
else:
date_str = f"Index: {x_index}"
# 构建显示文本 - OHLC
info_text = (
f"{date_str}\n"
f"O: {data_row['open']:.2f} H: {data_row['high']:.2f}\n"
f"L: {data_row['low']:.2f} C: {data_row['close']:.2f}\n"
f"Vol: {data_row['volume']:.0f}"
)
# 添加MACD数据
if self.current_macd_data is not None and x_index < len(
self.current_macd_data
):
macd_row = self.current_macd_data.iloc[x_index]
info_text += (
f"\n\nMACD\n"
f"DIF: {macd_row['dif']:.3f}\n"
f"DEA: {macd_row['dea']:.3f}\n"
f"Hist: {macd_row['histogram']:.3f}"
)
# 添加RSI数据
if self.current_rsi_data is not None and x_index < len(
self.current_rsi_data
):
rsi_row = self.current_rsi_data.iloc[x_index]
info_text += (
f"\n\nRSI\n"
f"RSI6: {rsi_row['rsi6']:.1f}\n"
f"RSI12: {rsi_row['rsi12']:.1f}\n"
f"RSI24: {rsi_row['rsi24']:.1f}"
)
# 清除旧的十字光标和文本
for line in self.crosshair_vlines:
line.remove()
self.crosshair_vlines.clear()
if self.info_text is not None:
self.info_text.remove()
# 在所有子图上绘制十字光标垂直线
for ax in self.fig.axes:
vline = ax.axvline(
x=x_index,
color="yellow",
linewidth=0.8,
alpha=0.7,
linestyle="--",
)
self.crosshair_vlines.append(vline)
# 在第一个子图(K线图)的右上角显示信息文本
ax1 = self.fig.axes[0]
self.info_text = ax1.text(
0.98,
0.95,
info_text,
transform=ax1.transAxes,
verticalalignment="top",
horizontalalignment="right",
bbox=dict(
boxstyle="round",
facecolor="#1a1a1a",
alpha=0.9,
edgecolor="yellow",
),
color="white",
fontsize=8,
family="monospace",
)
self.draw_idle()
except Exception:
pass # 忽略鼠标移动时的错误
def keyPressEvent(self, event):
"""处理键盘事件"""
if self.full_data is None or len(self.full_data) == 0:
print("[键盘] 无数据,忽略")
return
step = max(1, self.display_count // 10) # 每次移动10%
total_len = len(self.full_data)
print(
f"[键盘] 当前: start={self.current_start}, end={self.current_end}, display={self.display_count}, total={total_len}"
)
if event.key() == Qt.Key.Key_Left:
# 左移
if self.current_start > 0:
@ -117,10 +231,7 @@ class KlineCanvas(FigureCanvasQTAgg):
self.current_end = min(
total_len, self.current_start + self.display_count
)
print(f"[键盘] 左移到: {self.current_start}-{self.current_end}")
self.update_display()
else:
print("[键盘] 已在最开始")
elif event.key() == Qt.Key.Key_Right:
# 右移
@ -130,10 +241,7 @@ class KlineCanvas(FigureCanvasQTAgg):
self.current_end = min(
total_len, self.current_start + self.display_count
)
print(f"[键盘] 右移到: {self.current_start}-{self.current_end}")
self.update_display()
else:
print("[键盘] 已在最末尾")
elif event.key() == Qt.Key.Key_Up:
# 放大(显示更少数据)
@ -146,7 +254,6 @@ class KlineCanvas(FigureCanvasQTAgg):
self.current_end = min(
total_len, self.current_start + self.display_count
)
print(f"[键盘] 放大到: {self.display_count}条")
self.update_display()
elif event.key() == Qt.Key.Key_Down:
@ -160,21 +267,18 @@ class KlineCanvas(FigureCanvasQTAgg):
self.current_end = min(
total_len, self.current_start + self.display_count
)
print(f"[键盘] 缩小到: {self.display_count}条")
self.update_display()
elif event.key() == Qt.Key.Key_Home:
# 回到最开始
self.current_start = 0
self.current_end = min(total_len, self.display_count)
print("[键盘] 跳转到开始")
self.update_display()
elif event.key() == Qt.Key.Key_End:
# 跳到最后
# 跳转到末尾
self.current_start = max(0, total_len - self.display_count)
self.current_end = total_len
print("[键盘] 跳转到末尾")
self.update_display()
def update_display(self):
@ -217,10 +321,6 @@ class KlineCanvas(FigureCanvasQTAgg):
self.current_start = max(0, total_len - self.display_count)
self.current_end = total_len
print(
f"[Canvas] 加载数据: 总量={total_len}, 显示={self.display_count}, 范围={self.current_start}-{self.current_end}"
)
# 显示
self.update_display()
@ -232,10 +332,22 @@ class KlineCanvas(FigureCanvasQTAgg):
if df is None or df.empty:
return
# 数据量检查
data_len = len(df)
if data_len < 2:
return
# 保存当前显示的数据,用于鼠标悬停
# 重置索引,使其从0开始,与mplfinance的x轴坐标对应
# 同时保存原始索引值用于显示时间
self.current_display_data = df.copy()
self.current_display_data["_original_index"] = df.index
self.current_display_data = self.current_display_data.reset_index(drop=True)
# 清空旧图
self.fig.clear()
# 准备数据
# 准备数据 - 用于绘制(保留原始索引用于时间轴)
plot_df = df.copy()
for col in ["open", "high", "low", "close", "volume"]:
if col not in plot_df.columns and col.capitalize() in plot_df.columns:
@ -259,17 +371,49 @@ class KlineCanvas(FigureCanvasQTAgg):
self.fig.patch.set_facecolor("#0a0a0a")
# 绘制K线和更多均线(5/10/20/30/60)
# 根据数据量动态选择均线周期
# 避免均线周期大于数据量导致的问题
ma_periods = []
for period in [5, 10, 20, 30, 60]:
if data_len >= period + 5: # 留一些余量
ma_periods.append(period)
# 如果数据量不足,至少显示一条均线
if not ma_periods and data_len >= 3:
ma_periods = [min(3, data_len - 1)]
# 先绘制K线(不包含均线)
mpf.plot(
plot_df,
type="candle",
style=self.style,
mav=(5, 10, 20, 30, 60),
volume=ax2,
ax=ax1,
warn_too_much_data=10000,
)
# 手动绘制MA均线以显示图例
ma_colors = ["#00ff00", "#ffff00", "#ff00ff", "#00ffff", "#ffa500"]
for i, period in enumerate(ma_periods):
ma = plot_df["close"].rolling(window=period).mean()
ax1.plot(
ma.values,
label=f"MA{period}",
color=ma_colors[i % len(ma_colors)],
linewidth=1,
alpha=0.8,
)
# 显示MA图例
if ma_periods:
ax1.legend(
loc="upper left",
fontsize=8,
facecolor="#0a0a0a",
edgecolor="white",
labelcolor="white",
)
# 计算并绘制MACD
self._plot_macd(plot_df, ax3)
@ -308,6 +452,19 @@ class KlineCanvas(FigureCanvasQTAgg):
def _plot_macd(self, df, ax):
"""绘制MACD指标"""
try:
# 数据量检查:MACD需要至少26+9=35条数据
if len(df) < 35:
ax.text(
0.5,
0.5,
f"数据不足(需要35条,当前{len(df)}条)",
ha="center",
va="center",
color="white",
transform=ax.transAxes,
)
return
# 计算MACD
exp1 = df["close"].ewm(span=12, adjust=False).mean()
exp2 = df["close"].ewm(span=26, adjust=False).mean()
@ -315,6 +472,13 @@ class KlineCanvas(FigureCanvasQTAgg):
signal = macd.ewm(span=9, adjust=False).mean()
histogram = macd - signal
# 保存MACD数据供鼠标悬停使用
import pandas as pd
self.current_macd_data = pd.DataFrame(
{"dif": macd, "dea": signal, "histogram": histogram}
).reset_index(drop=True)
# 绘制MACD柱状图
colors = ["#00ff00" if x >= 0 else "#ff0000" for x in histogram]
ax.bar(range(len(histogram)), histogram, color=colors, alpha=0.6, width=0.8)
@ -338,7 +502,24 @@ class KlineCanvas(FigureCanvasQTAgg):
def _plot_rsi(self, df, ax):
"""绘制RSI指标"""
try:
# 数据量检查:RSI需要至少period+1条数据
if len(df) < 25: # 最大周期24+1
ax.text(
0.5,
0.5,
f"数据不足(需要25条,当前{len(df)}条)",
ha="center",
va="center",
color="white",
transform=ax.transAxes,
)
return
# 计算RSI(6,12,24)
import pandas as pd
rsi_data = {}
for period in [6, 12, 24]:
delta = df["close"].diff()
gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
@ -346,11 +527,17 @@ class KlineCanvas(FigureCanvasQTAgg):
rs = gain / loss
rsi = 100 - (100 / (1 + rs))
# 保存RSI数据
rsi_data[f"rsi{period}"] = rsi
colors = {6: "#ffff00", 12: "#00ffff", 24: "#ff00ff"}
ax.plot(
rsi.values, color=colors[period], linewidth=1, label=f"RSI{period}"
)
# 保存RSI数据供鼠标悬停使用
self.current_rsi_data = pd.DataFrame(rsi_data).reset_index(drop=True)
# 绘制参考线
ax.axhline(80, color="red", linewidth=0.5, alpha=0.5, linestyle="--")
ax.axhline(50, color="white", linewidth=0.5, alpha=0.3)
@ -443,25 +630,27 @@ class DataDownloadThread(QThread):
f"开始下载: {', '.join(self.symbols)} | {', '.join(self.periods)} | {self.start_date.date()} ~ {self.end_date.date()}"
)
print(
f"下载参数: symbols={self.symbols}, periods={self.periods}, {self.start_date} ~ {self.end_date}"
f"[下载线程] 下载参数: symbols={self.symbols}, periods={self.periods}, {self.start_date} ~ {self.end_date}"
)
print("[下载线程] 开始调用 download_klines...")
self.data_service.download_klines(
symbols=self.symbols,
start_date=self.start_date,
end_date=self.end_date,
periods=self.periods,
)
print("[下载线程] download_klines 调用完成")
success_msg = (
f"下载完成: {len(self.symbols)}个标的, {len(self.periods)}个周期"
)
print(success_msg)
print(f"[下载线程] {success_msg}")
self.finished.emit(True, success_msg)
except Exception as e:
error_msg = f"下载失败: {str(e)}"
print(error_msg)
print(f"[下载线程] {error_msg}")
import traceback
traceback.print_exc()
@ -511,8 +700,17 @@ class SimpleKlineViewer(QMainWindow):
# 周期选择
control_layout.addWidget(QLabel("周期:"))
self.period_combo = QComboBox()
self.period_combo.addItems(["1m", "5m", "15m", "30m", "60m", "1d"])
self.period_combo.setCurrentText("1d") # 默认日线
self.period_combo.addItems(
[
Period.MIN_1,
Period.MIN_5,
Period.MIN_15,
Period.MIN_30,
Period.MIN_60,
Period.DAY_1,
]
)
self.period_combo.setCurrentText(Period.DAY_1) # 默认日线
self.period_combo.currentTextChanged.connect(self.on_period_changed)
control_layout.addWidget(self.period_combo)
@ -565,7 +763,7 @@ class SimpleKlineViewer(QMainWindow):
def on_period_changed(self, period):
"""周期切换时自动调整日期范围"""
if period == "1d":
if period == Period.DAY_1:
# 日线:默认一年
self.start_date_edit.setDate(QDate(2024, 1, 1))
self.end_date_edit.setDate(QDate(2025, 12, 15))

View File

@ -1,16 +1,13 @@
"""
缓存管理器 - 透明缓存实现
缓存管理器 - 纯Key-Value缓存实现
提供统一的缓存管理接口,支持市场数据缓存和指标计算
使用StorageLayer实现存储解耦
提供简单高效的内存缓存接口,不包含业务逻辑
职责:只负责数据的存取,不涉及数据加载、验证、计算
"""
import logging
from typing import Dict, List, Optional, Any, Union
from datetime import datetime
from typing import Dict, Optional, Any, Union
import pandas as pd
from src.indicator_calculator.indicator_manager import IndicatorManager
from src.data_storage.storage_layer import StorageLayer
from src.core.config import Config
logger = logging.getLogger(__name__)
@ -18,222 +15,74 @@ logger = logging.getLogger(__name__)
class CacheManager:
"""
智能缓存管理器
纯缓存管理器
特性:
- 透明缓存:自动处理缓存命中/未命中
- 自动加载:缓存未命中时自动从Storage加载
- 指标计算:集成指标计算器
职责:
- Key-Value存储:按symbol_period组织数据
- 元数据管理:自动维护数据时间范围
- 内存管理:支持内存限制和统计
- 缓存失效:支持精确和批量失效
不包含:
- ✗ 数据加载逻辑(由DataService负责)
- ✗ 数据验证逻辑(由DataService负责)
- ✗ 指标计算逻辑(由DataService负责)
"""
def __init__(
self,
config: Union[dict, Config],
storage: StorageLayer,
indicator_calc: Optional[IndicatorManager] = None,
):
def __init__(self, config: Union[dict, Config]):
"""
初始化缓存管理器
Args:
config: 配置字典或Config对象,包含cache相关配置
storage: 存储层实例
indicator_calc: 指标计算器实例(可选,如不提供则自动创建)
"""
self.config = config
self.storage = storage
# 指标计算器(独立模块)
self.indicator_calc = (
indicator_calc if indicator_calc is not None else IndicatorManager()
)
# 获取缓存配置
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)
self.auto_load = cache_config.get("auto_load", True) # 新增:自动加载
self.max_memory_mb = cache_config.get("max_memory_mb", 4096) # 默认4GB
# 核心数据结构
self._cache: Dict[str, Dict[str, Any]] = {}
self._dirty: set = set() # 脏数据集合(Phase 3使用)
# 统计信息
self._metrics = {"hit": 0, "miss": 0, "total_requests": 0, "auto_loads": 0}
logger.info(
f"CacheManager initialized: mode={self.mode}, enabled={self.enabled}, max_memory={self.max_memory_mb}MB"
f"CacheManager initialized: enabled={self.enabled}, max_memory={self.max_memory_mb}MB"
)
def preload(self, symbols: List[str]) -> None:
def get_klines(self, symbol: str, period: str) -> Optional[pd.DataFrame]:
"""
预加载数据
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}"
)
# 计算时间范围
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)
loaded_count = 0
for i, symbol in enumerate(symbols):
for period in periods:
try:
# 从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})
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]:
"""
获取K线数据(透明缓存)
特性:
- 优先从缓存获取
- 缓存未命中时自动从Storage加载(如果enabled和auto_load)
- 自动缓存加载的数据
获取缓存数据(纯Key-Value查询)
Args:
symbol: 标的代码
period: 周期(如'1m', '1d')
start: 开始时间(可选)
end: 结束时间(可选)
period: 周期
Returns:
K线DataFrame,如果未找到返回None
缓存中的K线DataFrame或None
"""
self._metrics["total_requests"] += 1
if not self.enabled:
# 缓存禁用,直接从storage加载
return self.storage.load_klines(symbol, period, start, end)
return None
key = self._make_key(symbol, period)
# 1. 检查缓存
if key in self._cache:
cached = self._cache[key]
cache_data = cached.get("klines")
# 更新访问统计
cached["meta"]["last_access"] = datetime.now()
cached["meta"]["access_count"] += 1
if cache_data is not None and not cache_data.empty:
return cache_data
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
# 2. 缓存未命中
self._metrics["miss"] += 1
logger.debug(f"Cache miss: {key}")
# 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
def set(
self, symbol: str, period: str, data: Dict[str, Any], mark_dirty: bool = False
) -> None:
def set_klines(self, symbol: str, period: str, data: Dict[str, Any]) -> None:
"""
设置缓存数据
Args:
symbol: 标的代码
period: 周期
data: 数据字典,应包含'klines'键
mark_dirty: 是否标记为脏数据(Phase 3使用)
data: 数据字典,必须包含'klines'键,可选包含指标数据
"""
if not self.enabled:
return
@ -251,56 +100,104 @@ class CacheManager:
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:
def get_indicator(
self, symbol: str, period: str, indicator_type: str
) -> Optional[pd.DataFrame]:
"""
失效缓存
获取指标数据(纯缓存查询)
Args:
symbol: 标的代码,None表示全部
period: 周期,None表示该标的所有周期
symbol: 标的代码
period: 周期
indicator_type: 指标类型(如IndicatorType.MACD)
Returns:
指标DataFrame或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")
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
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:
# 更新已有缓存项
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]
self._dirty.discard(key)
logger.info(f"Invalidated 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]:
"""
@ -309,223 +206,42 @@ class CacheManager:
Returns:
统计信息字典
"""
total = self._metrics["total_requests"]
hit_rate = self._metrics["hit"] / total if total > 0 else 0
# 按标的统计
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(),
"hit_count": self._metrics["hit"],
"miss_count": self._metrics["miss"],
"auto_loads": self._metrics["auto_loads"],
"total_requests": total,
"hit_rate": hit_rate,
"mode": self.mode,
"enabled": self.enabled,
"max_memory_mb": self.max_memory_mb,
"symbols": symbols_stats,
}
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")
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
# ========== 内部方法 ==========
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()
def _make_key(self, symbol: str, period: str) -> str:
"""生成缓存键"""
"""构造缓存键"""
return f"{symbol}_{period}"
def _estimate_memory(self) -> float:
"""
估算当前缓存内存占用(MB)
Returns:
内存占用(MB)
"""
try:
"""估算当前缓存占用的内存大小(MB)"""
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()
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
except Exception as e:
logger.error(f"Failed to estimate memory: {e}")
return 0.0

303
src/core/constants.py Normal file
View File

@ -0,0 +1,303 @@
"""
常量定义 - 集中管理所有字符串常量
避免在代码中使用魔法字符串,统一管理常量定义
"""
class Period:
"""
周期常量定义(与 global.yaml 中的 kline_periods 保持一致)
使用示例:
from src.core.constants import Period
klines = data_service.get_klines(symbol, Period.DAY_1, start, end)
"""
# Tick数据
TICK = "tick"
# 分钟线
MIN_1 = "1m"
MIN_5 = "5m"
MIN_15 = "15m"
MIN_30 = "30m"
MIN_60 = "60m"
# 日线
DAY_1 = "1d"
# 周线
WEEK_1 = "1w"
# 所有支持的周期(与配置文件保持一致)
ALL = [
TICK,
MIN_1,
MIN_5,
MIN_15,
MIN_30,
MIN_60,
DAY_1,
WEEK_1,
]
@classmethod
def is_valid(cls, period: str) -> bool:
"""检查周期是否有效"""
return period in cls.ALL
@classmethod
def get_all(cls) -> list:
"""获取所有周期"""
return cls.ALL.copy()
class IndicatorType:
"""
技术指标常量定义(与 global.yaml 中的 enabled_indicators 保持一致)
使用示例:
from src.core.constants import Indicator
macd = data_service.get_indicator(symbol, Period.DAY_1, Indicator.MACD)
"""
# 支持的指标(与配置文件保持一致,统一使用小写)
MACD = "macd"
KDJ = "kdj"
BOLL = "boll"
RSI = "rsi"
# 所有支持的指标
ALL = [
MACD,
KDJ,
BOLL,
RSI,
]
@classmethod
def is_valid(cls, indicator: str) -> bool:
"""检查指标是否有效"""
return indicator in cls.ALL
@classmethod
def get_all(cls) -> list:
"""获取所有指标"""
return cls.ALL.copy()
class MarketType:
"""
市场类型常量
使用示例:
from src.core.constants import MarketType
if symbol.startswith('6'):
market = MarketType.STOCK_CN
"""
STOCK_CN = "stock_cn" # 中国A股
STOCK_US = "stock_us" # 美股
STOCK_HK = "stock_hk" # 港股
FUTURES = "futures" # 期货
FOREX = "forex" # 外汇
CRYPTO = "crypto" # 数字货币
ALL = [STOCK_CN, STOCK_US, STOCK_HK, FUTURES, FOREX, CRYPTO]
class DataSource:
"""
数据源常量
使用示例:
from src.core.constants import DataSource
downloader = DataDownloader(source=DataSource.AKSHARE)
"""
AKSHARE = "akshare"
TUSHARE = "tushare"
BAOSTOCK = "baostock"
SINA = "sina"
ALL = [AKSHARE, TUSHARE, BAOSTOCK, SINA]
class CacheKey:
"""
缓存键名常量
使用示例:
from src.core.constants import CacheKey
cache_data = {CacheKey.KLINES: df, CacheKey.META: meta}
"""
KLINES = "klines"
META = "meta"
TIME_RANGE = "time_range"
INDICATORS = "indicators"
class KlineColumns:
"""
K线数据列名常量
定义DataFrame和数据库表的标准列名
使用示例:
from src.core.constants import KlineColumns
df[KlineColumns.OPEN] = data['open']
"""
# 主键/索引
TIMESTAMP = "timestamp"
SYMBOL = "symbol"
# OHLCV数据
OPEN = "open"
HIGH = "high"
LOW = "low"
CLOSE = "close"
VOLUME = "volume"
AMOUNT = "amount"
# 所有列(用于数据库表创建和验证)
ALL = [TIMESTAMP, SYMBOL, OPEN, HIGH, LOW, CLOSE, VOLUME, AMOUNT]
# OHLCV列(不含timestamp和symbol)
OHLCV = [OPEN, HIGH, LOW, CLOSE, VOLUME, AMOUNT]
class IndicatorColumns:
"""
技术指标列名常量
定义各个指标的DataFrame列名
使用示例:
from src.core.constants import IndicatorColumns
macd_columns = IndicatorColumns.get_columns(IndicatorType.MACD)
"""
# MACD指标列
MACD_DIF = "macd_dif"
MACD_DEA = "macd_dea"
MACD_HISTOGRAM = "macd_histogram"
MACD_ALL = [MACD_DIF, MACD_DEA, MACD_HISTOGRAM]
# KDJ指标列
KDJ_K = "kdj_k"
KDJ_D = "kdj_d"
KDJ_J = "kdj_j"
KDJ_ALL = [KDJ_K, KDJ_D, KDJ_J]
# BOLL指标列
BOLL_UPPER = "boll_upper"
BOLL_MID = "boll_mid"
BOLL_LOWER = "boll_lower"
BOLL_WIDTH = "boll_width"
BOLL_ALL = [BOLL_UPPER, BOLL_MID, BOLL_LOWER, BOLL_WIDTH]
# RSI指标列
RSI_FAST = "rsi_fast"
RSI_MID = "rsi_mid"
RSI_SLOW = "rsi_slow"
RSI_ALL = [RSI_FAST, RSI_MID, RSI_SLOW]
@classmethod
def get_columns(cls, indicator_type: str) -> list:
"""
获取指定指标的所有列名
Args:
indicator_type: 指标类型(如IndicatorType.MACD)
Returns:
列名列表
"""
mapping = {
"macd": cls.MACD_ALL,
"kdj": cls.KDJ_ALL,
"boll": cls.BOLL_ALL,
"rsi": cls.RSI_ALL,
}
return mapping.get(indicator_type, [])
@classmethod
def get_all_columns(cls) -> list:
"""获取所有指标的列名"""
return cls.MACD_ALL + cls.KDJ_ALL + cls.BOLL_ALL + cls.RSI_ALL
class ConfigKey:
"""
配置键名常量
使用示例:
from src.core.constants import ConfigKey
cache_enabled = config.get(ConfigKey.CACHE_ENABLED, True)
"""
# 缓存配置
CACHE_ENABLED = "cache_enabled"
CACHE_MAX_MEMORY_MB = "cache_max_memory_mb"
# 数据库配置
DB_TYPE = "db_type"
DB_PATH = "db_path"
# 数据源配置
DATA_SOURCE = "data_source"
# 日志配置
LOG_LEVEL = "log_level"
LOG_PATH = "log_path"
class ErrorCode:
"""
错误码常量
使用示例:
from src.core.constants import ErrorCode
raise ValueError(f"Error {ErrorCode.INVALID_PERIOD}: Invalid period")
"""
INVALID_PERIOD = 1001
INVALID_INDICATOR = 1002
INVALID_SYMBOL = 1003
INVALID_DATE_RANGE = 1004
DATA_NOT_FOUND = 2001
DATA_INCOMPLETE = 2002
CACHE_ERROR = 3001
STORAGE_ERROR = 3002
DOWNLOAD_ERROR = 3003
VALIDATION_ERROR = 4001
CALCULATION_ERROR = 4002
# 导出所有常量类
__all__ = [
"Period",
"IndicatorType",
"KlineColumns",
"IndicatorColumns",
"MarketType",
"DataSource",
"CacheKey",
"ConfigKey",
"ErrorCode",
]

View File

@ -235,9 +235,13 @@ class DownloaderManager:
logger.debug(f"{key}: updating from {start_date.date()}")
else:
# 没有数据,下载最近3个月
start_date = end_date - timedelta(days=90)
logger.debug(f"{key}: no existing data, downloading 3 months")
# 没有数据,无法进行增量更新
logger.error(
f"{key}: no existing data found, cannot perform incremental update. "
f"Please use download_and_save() with explicit date range first."
)
results[key] = -1
continue
# 下载增量数据
download_result = self.download_and_save(

View File

@ -11,8 +11,11 @@ import pandas as pd
from src.cache.cache_manager import CacheManager
from src.data_storage.storage_layer import StorageLayer
from src.data_downloader.downloader_manager import DownloaderManager
from src.data_validator.data_validator import DataValidator
from src.indicator_calculator.indicator_manager import IndicatorManager
from src.core.logger import get_logger
from src.core.config import Config
from src.core.constants import IndicatorType, KlineColumns, IndicatorColumns
logger = get_logger("DataService")
@ -52,7 +55,6 @@ class DataService:
config: Union[Dict, Config],
storage: StorageLayer,
cache: CacheManager,
downloader: Optional[DownloaderManager] = None,
):
"""
初始化数据服务
@ -61,75 +63,186 @@ class DataService:
config: 配置字典或Config对象
storage: 存储层实例
cache: 缓存管理器实例
downloader: 下载器管理器实例(可选)
"""
self.config = config
self.storage = storage
self.cache = cache
self.downloader = downloader
logger.info("DataService initialized")
# 直接在DataService中初始化validator和downloader
self.validator = DataValidator(config if isinstance(config, dict) else None)
self.downloader = DownloaderManager(config, storage)
# 初始化指标计算器
indicator_configs = {}
if isinstance(config, Config):
indicators_section = config.get("indicators", {})
enabled_indicators = indicators_section.get("enabled_indicators", [])
# 只提取各指标的参数配置
for indicator_name in enabled_indicators:
if indicator_name in indicators_section:
indicator_configs[indicator_name] = indicators_section[
indicator_name
]
elif isinstance(config, dict):
indicators_section = config.get("indicators", {})
enabled_indicators = indicators_section.get("enabled_indicators", [])
# 只提取各指标的参数配置
for indicator_name in enabled_indicators:
if indicator_name in indicators_section:
indicator_configs[indicator_name] = indicators_section[
indicator_name
]
self.indicator_manager = IndicatorManager(indicator_configs)
logger.info(
"DataService initialized with validator, downloader and indicator_manager"
)
@classmethod
def from_config(cls, config: Union[Dict, Config]) -> "DataService":
"""
从配置创建DataService实例(工厂方法)
从配置创建 DataService 实例(工厂方法)
自动初始化所有依赖组件
自动初始化所有依赖组件:storage、cache、validator、downloader
Args:
config: 配置字典或Config对象
config: 配置对象或配置字典
Returns:
DataService实例
DataService 实例
Example:
config = Config()
config.load_with_global("configs/backtest.yaml")
service = DataService.from_config(config)
"""
# 导入MySQLStorage(避免循环导入)
from src.data_storage.mysql_storage import MySQLStorage
# 初始化存储层(MySQLStorage现在接受Union[Dict, Config])
# 初始化 storage
storage = MySQLStorage(config)
# 初始化缓存管理器(CacheManager现在也支持Union[Dict, Config])
cache = CacheManager(config, storage)
# 初始化 cache
cache = CacheManager(config)
# 初始化下载器管理器
downloader = DownloaderManager(config, storage)
logger.info("DataService created from config")
return cls(config, storage, cache, downloader)
# 创建 DataService 实例
return cls(config, storage, cache)
# ========== K线数据 ==========
def get_klines(
self,
symbol: str,
period: str,
start: Optional[datetime] = None,
end: Optional[datetime] = None,
startdate: Optional[datetime] = None,
enddate: Optional[datetime] = None,
) -> Optional[pd.DataFrame]:
"""
获取K线数据
获取K线数据(智能获取+自动补全)
自动处理:
1. 优先从缓存获取
2. 缓存未命中自动从存储加载
3. 返回DataFrame或None
流程:
1. 先从cache获取(纯缓存,不做检查)
2. validator检查缓存数据完整性
3. 如果不满足,从数据库加载
4. validator检查数据库数据完整性
5. 如果还不满足,触发下载
6. 下载完成后重新获取
Args:
symbol: 标的代码
period: 周期(如'1d', '1h')
start: 开始时间
end: 结束时间
startdate: 开始时间
enddate: 结束时间
Returns:
K线DataFrame或None
"""
return self.cache.get(symbol, period, start, end)
# 参数检查:必须提供时间范围
if startdate is None or enddate is None:
logger.error(
f"Invalid parameters for {symbol} {period}: "
f"start={startdate}, end={enddate}. Both start and end must be provided."
)
return None
# ========== 步骤1: 检查缓存 ==========
cache_data = self.cache.get_klines(symbol, period)
if cache_data is not None and not cache_data.empty:
# validator检查缓存数据完整性
validation_result = self.validator.validate_completeness(
cache_data, startdate, enddate, period
)
if validation_result.passed:
logger.debug(f"Cache data is complete for {symbol} {period}")
# 返回时间切片
mask = (cache_data.index >= startdate) & (cache_data.index <= enddate)
return cache_data[mask]
else:
logger.info(
f"Cache data incomplete for {symbol} {period}: "
f"{validation_result.details.get('issues', [])}"
)
# ========== 步骤2: 从数据库加载 ==========
logger.debug(f"Loading from storage: {symbol} {period}")
db_data = self.storage.load_klines(symbol, period, startdate, enddate)
if db_data is not None and not db_data.empty:
# validator检查数据库数据完整性
validation_result = self.validator.validate_completeness(
db_data, startdate, enddate, period
)
if validation_result.passed:
# 数据完整,更新缓存并返回
self.cache.set_klines(symbol, period, {"klines": db_data})
logger.debug(f"DB data is complete, cached: {symbol} {period}")
mask = (db_data.index >= startdate) & (db_data.index <= enddate)
return db_data[mask]
else:
logger.info(
f"DB data incomplete for {symbol} {period}: "
f"{validation_result.details.get('issues', [])}"
)
# ========== 步骤3: 触发下载 ==========
logger.info(
f"Data incomplete/missing for {symbol} {period}, triggering download"
)
try:
# 下载数据
self.downloader.download_and_save(
symbols=[symbol],
start_date=startdate,
end_date=enddate,
periods=[period],
)
# 下载完成后重新获取
final_data = self.storage.load_klines(symbol, period, startdate, enddate)
if final_data is not None and not final_data.empty:
# 更新缓存
self.cache.set_klines(symbol, period, {"klines": final_data})
logger.info(
f"Downloaded and loaded {len(final_data)} records for {symbol} {period}"
)
# 重新计算和保存指标
self._recalculate_and_save_indicators(symbol, period, final_data)
mask = (final_data.index >= startdate) & (final_data.index <= enddate)
return final_data[mask]
else:
logger.warning(
f"Download completed but still no data for {symbol} {period}"
)
return None
except Exception as e:
logger.error(f"Failed to download data for {symbol} {period}: {e}")
return None
def get_multiple(
self,
@ -220,9 +333,76 @@ class DataService:
Returns:
指标DataFrame或None
"""
return self.cache.get_indicator(
symbol, period, indicator_name, params, start, end
# 先尝试从缓存获取指标
# 验证指标类型是否有效
if not IndicatorType.is_valid(indicator_name):
logger.error(f"Unknown indicator type: {indicator_name}")
return None
# 直接使用indicator_name(字符串)
indicator_data = self.cache.get_indicator(symbol, period, indicator_name)
if indicator_data is not None:
# 缓存命中,返回时间切片
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.info(f"Calculating indicator: {symbol}_{period}_{indicator_name}")
# 获取K线数据
klines = self.get_klines(symbol, period, start, end)
if klines is None or klines.empty:
logger.warning(
f"No klines available for indicator calculation: {symbol}_{period}"
)
return None
# 计算指标
try:
indicator_data = self.indicator_manager.calculate(
klines, indicator_names=[indicator_name.lower()]
)
# 提取指标列(根据指标名称获取相应的列)
indicator_columns = self._get_indicator_columns(
indicator_data, indicator_name
)
if indicator_columns.empty:
logger.warning(f"No indicator columns found for: {indicator_name}")
return None
# 保存到存储和缓存
self.storage.save_indicators(
symbol, period, indicator_name, indicator_columns
)
self.cache.set_indicator(symbol, period, indicator_name, indicator_columns)
logger.info(
f"Indicator calculated and cached: {symbol}_{period}_{indicator_name}"
)
# 返回时间切片
if start is not None or end is not None:
mask = pd.Series(True, index=indicator_columns.index)
if start is not None:
mask &= indicator_columns.index >= start
if end is not None:
mask &= indicator_columns.index <= end
return indicator_columns[mask]
return indicator_columns
except Exception as e:
logger.error(f"Failed to calculate indicator {indicator_name}: {e}")
return None
def get_multiple_indicators(
self,
@ -271,22 +451,10 @@ class DataService:
symbols: 标的列表
periods: 周期列表(None则使用配置)
"""
if periods:
# 临时修改配置
original_periods = (
self.config.get("cache", {}).get("preload", {}).get("periods")
logger.warning(
"DataService.preload() is deprecated. "
"Data will be automatically cached when accessed via get_klines()."
)
self.config["cache"]["preload"]["periods"] = periods
self.cache.preload(symbols)
# 恢复配置
if original_periods:
self.config["cache"]["preload"]["periods"] = original_periods
else:
self.cache.preload(symbols)
logger.info(f"Preloaded {len(symbols)} symbols")
def invalidate(self, symbol: Optional[str] = None, period: Optional[str] = None):
"""
@ -296,8 +464,8 @@ class DataService:
symbol: 标的代码(None=全部)
period: 周期(None=该标的所有周期)
"""
self.cache.invalidate(symbol, period)
logger.debug(f"Invalidated cache: {symbol}_{period}")
# TODO: 实现缓存失效逻辑
logger.warning("Cache invalidation not implemented in simplified CacheManager")
def exists(
self,
@ -335,6 +503,100 @@ class DataService:
"""
return self.storage.get_date_range(symbol, period)
# ========== 内部辅助方法 ==========
def _recalculate_and_save_indicators(
self, symbol: str, period: str, klines: pd.DataFrame
) -> None:
"""
重新计算并保存所有启用的指标
Args:
symbol: 标的代码
period: 周期
klines: K线数据
"""
enabled_indicators = self.indicator_manager.get_enabled_indicators()
if not enabled_indicators:
logger.debug(
f"No indicators enabled, skip calculation for {symbol}_{period}"
)
return
logger.info(
f"Recalculating {len(enabled_indicators)} indicators for {symbol}_{period}"
)
try:
# 计算所有指标
data_with_indicators = self.indicator_manager.calculate(klines)
# 逐个保存指标
for indicator_name in enabled_indicators:
try:
# 提取指标列
indicator_columns = self._get_indicator_columns(
data_with_indicators, indicator_name
)
if not indicator_columns.empty:
# 保存到存储
self.storage.save_indicators(
symbol, period, indicator_name, indicator_columns
)
# 更新缓存
self.cache.set_indicator(
symbol, period, indicator_name, indicator_columns
)
logger.debug(
f"Saved indicator: {symbol}_{period}_{indicator_name}"
)
else:
logger.warning(
f"No columns found for indicator: {indicator_name}"
)
except Exception as e:
logger.error(f"Failed to save indicator {indicator_name}: {e}")
continue
except Exception as e:
logger.error(f"Failed to calculate indicators: {e}")
def _get_indicator_columns(
self, df: pd.DataFrame, indicator_name: str
) -> pd.DataFrame:
"""
从DataFrame中提取指标相关的列(使用常量定义)
Args:
df: 包含指标数据的DataFrame
indicator_name: 指标名称(应该是小写,如macd, kdj, boll, rsi)
Returns:
只包含指标列的DataFrame
"""
# indicator_name应该已经是小写,直接使用
# 使用IndicatorColumns常量获取列名
expected_columns = IndicatorColumns.get_columns(indicator_name)
if not expected_columns:
logger.warning(f"Unknown indicator: {indicator_name}")
return pd.DataFrame()
# 只保留DataFrame中实际存在的列
existing_columns = [col for col in expected_columns if col in df.columns]
if not existing_columns:
logger.warning(
f"No columns found for indicator {indicator_name} in DataFrame. "
f"Expected: {expected_columns}, Available: {list(df.columns)}"
)
return pd.DataFrame()
return df[existing_columns]
# ========== 统计和诊断 ==========
def get_stats(self) -> Dict:

View File

@ -685,7 +685,9 @@ ALL_KLINE_TABLES = {
from .table_utils import SUPPORTED_INDICATORS
ALL_INDICATOR_TABLES = {
f"{indicator}_{period}": create_indicator_table_definition(indicator, period)
f"indicators_{period}_{indicator}": create_indicator_table_definition(
indicator, period
)
for indicator in SUPPORTED_INDICATORS
for period in SUPPORTED_PERIODS
}

View File

@ -6,6 +6,7 @@ import pandas as pd
import talib
from talib._ta_lib import MA_Type
from .base_indicator import BaseIndicator
from src.core.constants import IndicatorColumns
class BOLLIndicator(BaseIndicator):
@ -65,19 +66,19 @@ class BOLLIndicator(BaseIndicator):
matype=MA_Type.SMA,
)
# 统一列名规范
result["boll_upper"] = upper
result["boll_mid"] = middle
result["boll_lower"] = lower
# 统一列名规范(使用常量)
result[IndicatorColumns.BOLL_UPPER] = upper
result[IndicatorColumns.BOLL_MID] = middle
result[IndicatorColumns.BOLL_LOWER] = lower
# 计算布林带宽度(可选,用于判断波动性)
result["boll_width"] = upper - lower
result[IndicatorColumns.BOLL_WIDTH] = upper - lower
return result
def get_column_names(self) -> List[str]:
"""获取BOLL指标的列名"""
return ["boll_upper", "boll_mid", "boll_lower", "boll_width"]
return IndicatorColumns.BOLL_ALL
@property
def name(self) -> str:

View File

@ -6,6 +6,7 @@ import pandas as pd
import talib
from talib._ta_lib import MA_Type
from .base_indicator import BaseIndicator
from src.core.constants import IndicatorColumns
class KDJIndicator(BaseIndicator):
@ -74,17 +75,17 @@ class KDJIndicator(BaseIndicator):
slowd_matype=MA_Type.SMA,
)
# 统一列名规范
result["kdj_k"] = slowk
result["kdj_d"] = slowd
# 计算J值:J = 3K - 2D
result["kdj_j"] = 3 * slowk - 2 * slowd
# 统一列名规范(使用常量)
result[IndicatorColumns.KDJ_K] = slowk
result[IndicatorColumns.KDJ_D] = slowd
# J = 3K - 2D
result[IndicatorColumns.KDJ_J] = 3 * slowk - 2 * slowd
return result
def get_column_names(self) -> List[str]:
"""获取KDJ指标的列名"""
return ["kdj_k", "kdj_d", "kdj_j"]
return IndicatorColumns.KDJ_ALL
@property
def name(self) -> str:

View File

@ -5,6 +5,7 @@ import numpy as np
import pandas as pd
import talib
from .base_indicator import BaseIndicator
from src.core.constants import IndicatorColumns
class MACDIndicator(BaseIndicator):
@ -72,18 +73,18 @@ class MACDIndicator(BaseIndicator):
signalperiod=signal_period,
)
# 统一列名规范
result["macd_dif"] = macd
result["macd_dea"] = signal
# 统一列名规范(使用常量)
result[IndicatorColumns.MACD_DIF] = macd
result[IndicatorColumns.MACD_DEA] = signal
# ta-lib的MACD柱值已经是 DIF-DEA,不需要乘以2
# 但为了保持与国内软件一致,这里乘以2
result["macd_histogram"] = hist * 2
result[IndicatorColumns.MACD_HISTOGRAM] = hist * 2
return result
def get_column_names(self) -> List[str]:
"""获取MACD指标的列名"""
return ["macd_dif", "macd_dea", "macd_histogram"]
return IndicatorColumns.MACD_ALL
@property
def name(self) -> str:

View File

@ -5,6 +5,7 @@ import numpy as np
import pandas as pd
import talib
from .base_indicator import BaseIndicator
from src.core.constants import IndicatorColumns
class RSIIndicator(BaseIndicator):
@ -67,16 +68,20 @@ class RSIIndicator(BaseIndicator):
close_array = np.asarray(result["close"].values, dtype=np.float64)
# 使用ta-lib计算不同周期的RSI
# 列名使用rsi_fast、rsi_mid、rsi_slow,更直观易懂
result["rsi_fast"] = talib.RSI(close_array, timeperiod=fast_period)
result["rsi_mid"] = talib.RSI(close_array, timeperiod=mid_period)
result["rsi_slow"] = talib.RSI(close_array, timeperiod=slow_period)
# 列名使用rsi_fast、rsi_mid、rsi_slow,更直观易懂(使用常量)
result[IndicatorColumns.RSI_FAST] = talib.RSI(
close_array, timeperiod=fast_period
)
result[IndicatorColumns.RSI_MID] = talib.RSI(close_array, timeperiod=mid_period)
result[IndicatorColumns.RSI_SLOW] = talib.RSI(
close_array, timeperiod=slow_period
)
return result
def get_column_names(self) -> List[str]:
"""获取RSI指标的列名"""
return ["rsi_fast", "rsi_mid", "rsi_slow"]
return IndicatorColumns.RSI_ALL
@property
def name(self) -> str:

View File

@ -1,243 +0,0 @@
"""
QTrade 主程序
下载历史数据并保存到数据库
注意:此文件使用旧的DataProvider接口,建议重构使用 src.data.DataService
"""
import sys
from pathlib import Path
from datetime import datetime
# 添加项目根目录到路径
if __name__ == "__main__":
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from src.core.config import Config, set_config
from src.core.logger import get_logger
from src.data_service import DataService
from src.indicator_calculator.indicator_manager import IndicatorManager
logger = get_logger("Main")
def download_data():
"""下载历史数据并保存到数据库"""
logger.info("=" * 80)
logger.info("开始下载历史数据")
logger.info("=" * 80)
# 配置下载参数
symbols = [
"601658.SH", # 邮储银行
"159915.SZ", # 创业板ETF
]
start_date = datetime(2025, 12, 1)
end_date = datetime(2025, 12, 15)
periods = ["1m", "1d"]
logger.info("\n下载配置:")
logger.info(f" 股票代码: {', '.join(symbols)}")
logger.info(f" 时间范围: {start_date.date()} ~ {end_date.date()}")
logger.info(f" 数据周期: {', '.join(periods)}")
try:
# 获取配置
config = Config()
config.load_with_global("configs/backtest.yaml")
# 创建数据服务(自动初始化所有依赖)
service = DataService.from_config(config)
# 下载数据
service.download_klines(
symbols=symbols,
start_date=start_date,
end_date=end_date,
periods=periods,
)
logger.info("\n" + "=" * 80)
logger.info(" 数据下载完成!")
logger.info("=" * 80)
except Exception as e:
logger.error(f"\n 下载失败: {e}", exc_info=True)
raise
def verify_data():
"""验证已下载的数据"""
logger.info("\n" + "=" * 80)
logger.info("验证已下载的数据")
logger.info("=" * 80)
symbols = ["601658.SH", "159915.SZ"]
start_date = datetime(2025, 12, 1)
end_date = datetime(2025, 12, 15)
period = "1m"
try:
# 获取配置
config = Config()
config.load_with_global("configs/backtest.yaml")
# 创建数据服务
service = DataService.from_config(config)
# 验证数据
logger.info("\n数据验证结果:")
for symbol in symbols:
df = service.get_klines(symbol, period, start_date, end_date)
if df is None or df.empty:
logger.warning(f" {symbol}: 无数据")
else:
logger.info(f" {symbol}: {len(df)} 条记录")
logger.info(f" 时间范围: {df.index[0]} ~ {df.index[-1]}")
logger.info(
f" 收盘价: {df['close'].min():.2f} ~ {df['close'].max():.2f}"
)
logger.info(f" 成交量: {df['volume'].sum():,.0f}")
logger.info("\n" + "=" * 80)
logger.info(" 数据验证完成!")
logger.info("=" * 80)
except Exception as e:
logger.error(f"\n 验证失败: {e}", exc_info=True)
raise
def calculate_indicators():
"""计算并保存指标数据"""
logger.info("\n" + "=" * 80)
logger.info("开始计算技术指标")
logger.info("=" * 80)
symbols = ["601658.SH", "159915.SZ"]
start_date = datetime(2025, 12, 1)
end_date = datetime(2025, 12, 15)
periods = ["1m", "1d"]
try:
# 获取配置
config = Config()
config.load_with_global("configs/backtest.yaml")
# 创建数据服务
service = DataService.from_config(config)
# 获取指标配置
indicator_configs = config.get("indicators", {})
enabled_indicators = indicator_configs.get("enabled_indicators", [])
if not enabled_indicators:
logger.warning("未配置指标,跳过计算")
return
# 为每个指标创建配置字典
indicators_config = {}
for ind_name in enabled_indicators:
ind_config = indicator_configs.get(ind_name.lower(), {})
indicators_config[ind_name.lower()] = ind_config
logger.info(f"\n配置的指标: {', '.join(enabled_indicators)}")
# 创建指标管理器
indicator_manager = IndicatorManager(indicators_config)
# 为每个标的和周期计算指标
total_saved = 0
for symbol in symbols:
for period in periods:
logger.info(f"\n处理 {symbol} [{period}]...")
# 获取K线数据
klines = service.get_klines(symbol, period, start_date, end_date)
if klines is None or klines.empty:
logger.warning(f" {symbol} [{period}]: 无K线数据,跳过")
continue
logger.info(f" 获取到 {len(klines)} 条K线数据")
# 计算所有指标
df_with_indicators = indicator_manager.calculate(klines)
# 保存每个指标
for ind_name in enabled_indicators:
try:
# 提取指标列
indicator = indicator_manager.indicators.get(ind_name.lower())
if not indicator:
continue
indicator_cols = indicator.get_column_names()
indicator_data = df_with_indicators[indicator_cols]
# 保存到数据库
saved_count = service.storage.save_indicators(
symbol=symbol,
period=period,
indicator_name=ind_name.lower(),
data=indicator_data,
)
total_saved += saved_count
logger.info(
f" ✓ {ind_name.upper()}: 保存 {saved_count} 条记录"
)
except Exception as e:
logger.error(f" ✗ {ind_name.upper()}: 保存失败 - {e}")
logger.info("\n" + "=" * 80)
logger.info(f" 指标计算完成!共保存 {total_saved} 条记录")
logger.info("=" * 80)
except Exception as e:
logger.error(f"\n 指标计算失败: {e}", exc_info=True)
raise
def main():
"""主函数"""
# 初始化配置
logger.info("初始化配置...")
config = Config()
config.load_with_global("configs/backtest.yaml")
set_config(config)
logger.info(f" 配置加载完成: {config.get('app.name')}")
# 检查 token
token = config.get("data_source.xtquant.xtquant_token")
if not token:
logger.error("\n" + "=" * 80)
logger.error("错误: XtQuant token 未配置!")
logger.error("=" * 80)
logger.error("\n请在 configs/global.yaml 中配置 token:")
logger.error("data_source:")
logger.error(" xtquant:")
logger.error(' xtquant_token: "your_token_here"')
logger.error("\n" + "=" * 80)
return
# 执行下载
download_data()
# 计算指标
calculate_indicators()
# 验证数据
verify_data()
logger.info("\n 所有任务完成!")
if __name__ == "__main__":
main()

216
test_dataservice.py Normal file
View File

@ -0,0 +1,216 @@
"""
测试DataService功能
测试项目:
1. DataService初始化
2. 获取K线数据(缓存、数据库、下载)
3. 数据完整性验证
4. 指标计算和更新
5. 缓存机制
"""
import sys
from datetime import datetime
from src.core.config import Config
from src.data_service import DataService
from src.core.constants import Period, IndicatorType
print("=" * 80)
print("DataService 功能测试")
print("=" * 80)
# ========== 测试1: 初始化 ==========
print("\n【测试1】DataService初始化")
print("-" * 80)
try:
config = Config()
config.load_with_global("configs/backtest.yaml")
print("✓ 配置加载成功")
service = DataService.from_config(config)
print("✓ DataService初始化成功")
print(f" - Storage: {type(service.storage).__name__}")
print(f" - Cache: {type(service.cache).__name__}")
print(f" - Validator: {type(service.validator).__name__}")
print(f" - Downloader: {type(service.downloader).__name__}")
print(f" - IndicatorManager: {type(service.indicator_manager).__name__}")
except Exception as e:
print(f"✗ 初始化失败: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
# ========== 测试2: 获取K线数据 ==========
print("\n【测试2】获取K线数据")
print("-" * 80)
test_symbol = "601658.SH"
test_period = Period.DAY_1
start_date = datetime(2024, 1, 1)
end_date = datetime(2024, 3, 31)
print(f"查询参数:")
print(f" - 标的: {test_symbol}")
print(f" - 周期: {test_period}")
print(f" - 时间: {start_date.date()} ~ {end_date.date()}")
try:
klines = service.get_klines(test_symbol, test_period, start_date, end_date)
if klines is not None and not klines.empty:
print(f"✓ 数据获取成功")
print(f" - 记录数: {len(klines)}")
print(f" - 时间范围: {klines.index[0]} ~ {klines.index[-1]}")
print(f" - 列名: {list(klines.columns)}")
print(f"\n前3条数据:")
print(klines.head(3))
else:
print("✗ 未获取到数据")
except Exception as e:
print(f"✗ 获取数据失败: {e}")
import traceback
traceback.print_exc()
# ========== 测试3: 缓存验证 ==========
print("\n【测试3】缓存验证")
print("-" * 80)
try:
# 第二次获取相同数据,应该从缓存返回
import time
start_time = time.time()
klines2 = service.get_klines(test_symbol, test_period, start_date, end_date)
elapsed = time.time() - start_time
if klines2 is not None:
print(f"✓ 缓存获取成功")
print(f" - 耗时: {elapsed * 1000:.2f}ms")
print(f" - 记录数: {len(klines2)}")
# 检查缓存统计
stats = service.get_stats()
print(f" - 缓存状态: {stats}")
else:
print("✗ 缓存获取失败")
except Exception as e:
print(f"✗ 缓存测试失败: {e}")
import traceback
traceback.print_exc()
# ========== 测试4: 不同周期数据 ==========
print("\n【测试4】获取不同周期数据")
print("-" * 80)
periods_to_test = [Period.MIN_5, Period.MIN_15, Period.DAY_1]
test_start = datetime(2024, 12, 1)
test_end = datetime(2024, 12, 15)
for period in periods_to_test:
try:
print(f"\n测试周期: {period}")
klines = service.get_klines(test_symbol, period, test_start, test_end)
if klines is not None and not klines.empty:
print(f" ✓ 成功 - {len(klines)} 条记录")
else:
print(f" ⊗ 无数据")
except Exception as e:
print(f" ✗ 失败: {e}")
# ========== 测试5: 获取指标数据 ==========
print("\n【测试5】获取指标数据")
print("-" * 80)
if klines is not None and not klines.empty:
indicators_to_test = [
IndicatorType.MACD,
IndicatorType.KDJ,
IndicatorType.BOLL,
IndicatorType.RSI,
]
for indicator_name in indicators_to_test:
try:
print(f"\n测试指标: {indicator_name}")
indicator_data = service.get_indicator(
test_symbol, test_period, indicator_name, start=start_date, end=end_date
)
if indicator_data is not None and not indicator_data.empty:
print(f" ✓ 成功 - {len(indicator_data)} 条记录")
print(f" - 列名: {list(indicator_data.columns)}")
print(f" 前3行:")
print(indicator_data.head(3))
else:
print(f" ⊗ 无数据(可能需要先计算)")
except Exception as e:
print(f" ✗ 失败: {e}")
import traceback
traceback.print_exc()
else:
print("跳过指标测试(无K线数据)")
# ========== 测试6: 批量获取 ==========
print("\n【测试6】批量获取多标的数据")
print("-" * 80)
symbols = ["601658.SH", "159915.SZ"]
try:
print(f"批量获取: {symbols}")
multi_data = service.get_multiple(symbols, test_period, start_date, end_date)
print(f"✓ 批量获取完成")
for symbol, data in multi_data.items():
if data is not None:
print(f" - {symbol}: {len(data)} 条记录")
else:
print(f" - {symbol}: 无数据")
except Exception as e:
print(f"✗ 批量获取失败: {e}")
import traceback
traceback.print_exc()
# ========== 测试7: 健康检查 ==========
print("\n【测试7】系统健康检查")
print("-" * 80)
try:
health = service.health_check()
print("健康状态:")
for component, status in health.items():
status_icon = "✓" if status else "✗"
print(f" {status_icon} {component}: {status}")
except Exception as e:
print(f"✗ 健康检查失败: {e}")
# ========== 测试8: 数据存在性检查 ==========
print("\n【测试8】数据存在性检查")
print("-" * 80)
try:
exists = service.exists(test_symbol, test_period, start_date, end_date)
print(f"数据存在性: {'存在' if exists else '不存在'}")
date_range = service.get_date_range(test_symbol, test_period)
if date_range:
print(f"数据时间范围: {date_range[0]} ~ {date_range[1]}")
else:
print("无数据范围信息")
except Exception as e:
print(f"✗ 检查失败: {e}")
# ========== 测试总结 ==========
print("\n" + "=" * 80)
print("测试完成")
print("=" * 80)
print("\n提示:")
print("- 如果某些测试失败,可能是因为数据库中没有对应数据")
print("- 可以使用 download_klines() 方法先下载数据")
print("- 指标数据需要先计算才能获取")

View File

@ -98,7 +98,7 @@ def test_basic_flow():
print("✓ 测试数据准备完成")
# 2. 创建CacheManager
cache = CacheManager(config, storage)
cache = CacheManager(config)
print("✓ CacheManager创建成功")
# 3. 创建DataService