性能优化与测试:添加DuckDB存储性能基准测试和逐条插入场景测试

主要更改:
- 添加benchmark_storage.py:全面的K线数据存储性能测试
  * 批量插入测试 (100万条数据)
  * 逐条插入测试 (36,000条实时场景)
  * 对比DuckDB文件/内存、Pickle、Parquet、DataFrame
  * 添加复合索引 (symbol + timestamp) 优化

- 性能测试结果:
  * 批量插入:DuckDB内存 790万行/秒,Pickle最快
  * 逐条插入:DuckDB内存 1,165行/秒 (最快)
  * DataFrame+Parquet 最慢 (46行/秒,慢25倍)
  * 时间段查询:DuckDB索引 8ms vs DataFrame 32ms

- 修复grid_strategy.py的Pylance类型错误:
  * 添加None类型检查
  * 移除不必要的f-string
  * 清理未使用变量

- 简化strategy_manager.py架构:
  * 移除冗余的position_manager/risk_manager/strategy_executor
  * 统一状态管理:get_status() / restore_state()
  * 优化启用/禁用策略逻辑

- 清理废弃文档和配置模块
- 添加性能测试分析报告和技术研究文档
This commit is contained in:
cuizhan 2026-01-17 23:52:59 +08:00
parent 6284f98eda
commit b311fbdece
17 changed files with 1013 additions and 2333 deletions

View File

@ -1,540 +0,0 @@
# 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)

View File

@ -1,302 +0,0 @@
# 常量定义使用指南
## 概述
为了避免在代码中使用魔法字符串(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

@ -1,102 +0,0 @@
# Logger prompt_level 配置说明
## 功能概述
Logger 已升级为使用 `prompt_level` 配置,替代原来的 `logging.level`。只有在 `prompt_level` 列表中的日志级别才会被输出。
## 配置方式
在环境配置文件(backtest.yaml / simulation.yaml / production.yaml)中设置:
```yaml
logging:
enabled: true
prompt_level: ["ERROR", "WARNING", "INFO"] # 只输出这三个级别
filepath: "d:\\workspace\\QTrade\\logs"
max_size: 10485760 # 10MB
backup_count: 5
path: "logs/backtest"
```
## 支持的级别
- `"DEBUG"` - 调试信息
- `"INFO"` - 一般信息
- `"WARNING"` - 警告信息
- `"ERROR"` - 错误信息
## 使用场景
### 1. 生产环境 - 只记录错误和警告
```yaml
prompt_level: ["ERROR", "WARNING"]
```
适用于生产环境,减少日志量,只关注问题。
### 2. 开发/测试环境 - 记录详细信息
```yaml
prompt_level: ["ERROR", "WARNING", "INFO", "DEBUG"]
```
适用于开发调试,查看所有日志。
### 3. 模拟环境 - 平衡模式
```yaml
prompt_level: ["ERROR", "WARNING", "INFO"]
```
适用于模拟交易,记录重要信息,过滤调试信息。
## 代码示例
```python
from core.config import Config
from core.logger import Logger
# 初始化
Config.initialize("simulation") # 使用 simulation.yaml 配置
Logger.initialize()
# 记录日志
Logger.debug("调试信息") # 不会输出(不在 prompt_level 中)
Logger.info("一般信息") # 会输出
Logger.warning("警告信息") # 会输出
Logger.error("错误信息") # 会输出
```
## 实现原理
1. **LevelFilter 过滤器**:自定义 logging.Filter,只允许指定级别通过
2. **Logger 级别设置为 DEBUG**:允许所有级别的日志进入
3. **Handler 添加过滤器**:在控制台和文件输出前进行过滤
## 优势
- ✅ **灵活性**:可以任意组合日志级别
- ✅ **配置化**:通过 YAML 配置,无需修改代码
- ✅ **性能**:不需要的日志在 handler 层就被过滤,不会写入文件
- ✅ **清晰度**:配置文件明确显示哪些级别会被记录
## 测试验证
运行测试脚本验证功能:
```bash
# 测试默认配置(ERROR, WARNING, INFO)
conda activate py311
python test_logger_levels.py
# 测试自定义配置(仅 ERROR, WARNING)
python test_logger_custom.py
```
## 注意事项
1. `prompt_level` 必须是列表类型,即使只有一个级别也要用 `["ERROR"]`
2. 级别名称必须是大写字符串:`"ERROR"`, `"WARNING"`, `"INFO"`, `"DEBUG"`
3. 如果 `prompt_level` 未配置,默认为 `["INFO", "WARNING", "ERROR"]`
4. 更改配置后需要重启应用才能生效

View File

@ -1,242 +0,0 @@
# 实盘交易使用说明
## 📋 概述
实盘交易模块使用 MiniQMT 进行真实市场交易。客户端先连接策略服务器获取交易信号,然后通过 MiniQMT API 执行实盘交易。
## ⚙️ 配置
### 1. 修改 `configs/production.yaml`
```yaml
# ==================== MiniQMT 实盘交易配置 ====================
miniqmt:
userdata_path: "D:\\国金QMT交易端模拟\\userdata_mini" # 修改为你的路径
session_id: 123456 # 会话ID(不同策略使用不同ID)
account:
account_id: "40004091" # 修改为你的交易账号
account_type: "STOCK" # 账户类型(STOCK/HUGANGTONG/SHENGANGTONG)
# ==================== 客户端适配器配置 ====================
client_adapters:
production_adapter:
server_url: "ws://localhost:8010/ws/strategy"
timeout: 30 # seconds
```
### 2. 配置说明
- **userdata_path**: MiniQMT 的 `userdata_mini` 文件夹路径
- **session_id**: 会话编号,不同策略使用不同的 ID
- **account_id**: 你的交易账号
- **account_type**:
- `STOCK`: 普通股票账户
- `HUGANGTONG`: 沪港通
- `SHENGANGTONG`: 深港通
## 🚀 启动方式
### 方式一:使用启动脚本(推荐)
#### 1. 同时启动服务器和客户端(服务器新窗口,客户端当前窗口)
```bash
python realtrade_runner.py both
```
#### 2. 分别启动
**先启动服务器(新窗口):**
```bash
python realtrade_runner.py server newwindow
```
**再启动客户端(当前窗口):**
```bash
python realtrade_runner.py client
```
#### 3. 都在新窗口启动
```bash
python realtrade_runner.py both newwindow
```
### 方式二:手动启动
#### 1. 先启动策略服务器
```bash
python -m src.qtrade_server
```
#### 2. 等待5秒后启动实盘客户端
```bash
python -m src.realtrade.main
```
## 📊 功能说明
### 1. 连接 MiniQMT
客户端启动时会自动连接 MiniQMT 交易接口:
- 建立交易连接
- 订阅账户推送
- 注册交易回调
### 2. 查询账户信息
启动后会自动查询:
- 总资产
- 可用资金
- 冻结资金
- 持仓市值
- 总盈亏
- 当前持仓列表
### 3. 获取交易信号
通过 WebSocket 连接策略服务器:
- 发送 K线数据
- 接收交易信号(BUY/SELL/HOLD)
### 4. 执行交易(默认禁用)
**⚠️ 为安全起见,默认不自动执行交易信号!**
如需启用自动交易,需要在 `src/realtrade/main.py` 中取消注释:
```python
# 取消注释以下代码以执行实盘交易(危险操作!)
order_id = adapter.place_order(
symbol=signal.symbol,
action=signal.action,
price=signal.price,
quantity=signal.quantity,
)
```
### 5. 交易回调
实时接收 MiniQMT 推送:
- 委托回报
- 成交回报
- 委托失败
- 撤单失败
- 账户状态变化
## 🔧 核心组件
### MiniQMTClientAdapter
**初始化参数:**
- `server_url`: 策略服务器 WebSocket 地址
- `timeout`: 超时时间
- `miniqmt_path`: MiniQMT userdata_mini 路径
- `session_id`: 会话ID
- `account_id`: 交易账号
- `account_type`: 账户类型
**主要方法:**
```python
# 连接 MiniQMT
adapter.connect()
# 发送 K线获取信号
signal = adapter.send_kline(symbol, kline, kline_time, period)
# 批量发送 K线
signals = adapter.send_klines_batch(klines_data, kline_time, period)
# 下单
order_id = adapter.place_order(symbol, action, price, quantity)
# 撤单
adapter.cancel_order(order_id)
# 查询资产
asset = adapter.query_account_asset()
# 查询持仓
positions = adapter.query_positions()
# 查询委托
orders = adapter.query_orders()
# 关闭连接
adapter.close()
```
## ⚠️ 安全警告
### 实盘交易风险
1. **资金安全**: 这是真实市场交易,会产生真实的资金损失!
2. **策略测试**: 务必先在回测和模拟盘中充分测试策略
3. **风控措施**: 设置止损、仓位控制等风险管理措施
4. **监控**: 实时监控账户状态和交易情况
5. **人工介入**: 必要时人工干预交易
### 建议
- ✅ 先在回测环境测试策略
- ✅ 再在模拟盘环境验证
- ✅ 小资金量测试实盘
- ✅ 设置合理的风控参数
- ✅ 24小时监控(或交易时段内)
- ❌ 不要使用未经测试的策略
- ❌ 不要在实盘直接修改代码
- ❌ 不要忽视风险提示
## 📝 日志
实盘交易日志保存在:
```
logs/production/qtrade_YYYYMMDD.log
```
建议定期查看日志,了解:
- 连接状态
- 交易信号
- 订单执行情况
- 异常错误
## 🔄 对比回测模式
| 特性 | 回测模式 | 实盘模式 |
| -------- | --------------------- | -------------------- |
| 数据源 | 历史数据 | 实时行情 |
| 交易执行 | 模拟撮合 | 真实下单 |
| 资金 | 虚拟资金 | 真实资金 |
| 风险 | 无风险 | 真实风险 |
| 服务器 | QTrade Server | QTrade Server |
| 客户端 | BacktestClientAdapter | MiniQMTClientAdapter |
| 配置文件 | backtest.yaml | production.yaml |
| 启动脚本 | backtest_runner.py | realtrade_runner.py |
## 🆘 故障排除
### 1. MiniQMT 连接失败
- 检查 `userdata_path` 路径是否正确
- 确认 MiniQMT 是否已启动
- 检查 `session_id` 是否与其他程序冲突
### 2. 策略服务器连接失败
- 确认服务器是否已启动
- 检查 `server_url` 配置是否正确
- 查看服务器日志
### 3. 下单失败
- 检查账户资金是否充足
- 确认标的代码格式是否正确(如 "600000.SH")
- 检查交易时间段
- 查看 MiniQMT 错误回调信息
### 4. 权限问题
- 确认账户是否有交易权限
- 检查是否在交易时间段内
- 确认标的是否停牌
## 📞 技术支持
如有问题,请查看:
1. 日志文件:`logs/production/`
2. 配置文件:`configs/production.yaml`
3. 适配器代码:`src/realtrade/miniqmt_client_adapter.py`
4. 主程序:`src/realtrade/main.py`
---
**再次提醒:实盘交易有风险,投资需谨慎!**

View File

@ -1,137 +0,0 @@
# 表结构清理总结
## 完成的工作
### 1. 删除了旧的表定义
从 `table_schemas.py` 中删除了以下旧表定义:
- ✅ **ORDER_TABLE** (旧版本)
- ✅ **TRADE_TABLE** (旧版本)
- ✅ **POSITION_TABLE** (旧版本)
- ✅ **ACCOUNT_TABLE** (已重命名为 ASSET_TABLE)
- ✅ **SYMBOL_TABLE** (Symbol 模型已删除,信息移至配置文件)
### 2. 更新了表定义导入
在 `table_schemas.py` 中:
```python
from .trading_table_schemas import (
ORDER_TABLE,
TRADE_TABLE,
POSITION_TABLE,
ASSET_TABLE,
)
```
### 3. 更新了 SIGNAL_TABLE
添加了 `instance_id` 字段和相应索引:
```python
"instance_id": {
"type": "String",
"length": 50,
"nullable": False,
"comment": "策略实例ID",
}
```
索引:
```python
{"name": "idx_instance", "columns": ["instance_id"]}
```
### 4. 更新了 ALL_TABLES 字典
```python
ALL_TABLES = {
**ALL_KLINE_TABLES,
**ALL_INDICATOR_TABLES,
"ticks": TICK_TABLE,
"signals": SIGNAL_TABLE,
# 交易相关表(从 trading_table_schemas 导入)
"orders": ORDER_TABLE,
"trades": TRADE_TABLE,
"positions": POSITION_TABLE,
"assets": ASSET_TABLE, # 不再是 accounts
}
```
### 5. 更新了模块导出
更新 `database_manager/__init__.py`:
- 移除:ACCOUNT_TABLE, SYMBOL_TABLE
- 添加:从 `trading_table_schemas` 导入新的表定义
- 新增:ASSET_TABLE
### 6. 清理了未使用的导入
- 从 `trading_table_schemas.py` 移除 `Dict, Any`
- 从 `trading_cache.py` 移除 `datetime`
## 表结构对比
### 旧表 vs 新表
| 旧表名 | 新表名 | 变化 |
| -------------- | --------- | ----------------------------------------- |
| orders (旧) | orders | 完全重构,增加 instance_id 等字段 |
| trades (旧) | trades | 完全重构,增加 instance_id 和 cost_detail |
| positions (旧) | positions | 完全重构,增加大量统计字段 |
| accounts | assets | 重命名,增加完整的资产管理字段 |
| symbols | (删除) | 信息移至 YAML 配置文件 |
## 核心改进
### 多策略实例隔离
所有交易相关表都包含:
- `instance_id`: 策略实例ID(必填)
- `strategy_name`: 策略名称(必填)
- 相应的组合索引
### 字段统计
- **ORDER_TABLE**: 22 个字段,6 个索引
- **TRADE_TABLE**: 13 个字段,6 个索引
- **POSITION_TABLE**: 29 个字段,4 个索引
- **ASSET_TABLE**: 30 个字段,2 个索引
- **SIGNAL_TABLE**: 13 个字段(新增 instance_id),5 个索引
## 测试结果
✅ 所有表定义正确导入
✅ ALL_TABLES 包含所有新表
✅ 旧表(accounts, symbols)已删除
✅ 所有交易表包含 instance_id 字段
✅ 所有必需索引已创建
✅ 无 Python 语法错误
## 下一步
1. **测试数据库表创建**
- 使用 DatabaseManager 创建表
- 验证表结构是否符合预期
2. **测试存储层**
- 使用 TradingDataStorage 保存和读取数据
- 验证 instance_id 隔离是否有效
3. **测试缓存层**
- 使用 TradingCache 缓存和检索数据
- 验证实例隔离逻辑
4. **集成到回测引擎**
- 在回测任务中使用新的表结构
- 验证多策略实例是否正确隔离
## 文件变更清单
### 修改的文件
- ✅ `src/database_manager/table_schemas.py` - 删除旧表,更新导入
- ✅ `src/database_manager/__init__.py` - 更新导出
- ✅ `src/database_manager/trading_table_schemas.py` - 清理导入
- ✅ `src/cache/trading_cache.py` - 清理导入
### 新增的文件
- ✅ `test_table_schemas.py` - 表结构测试脚本
### 已删除的定义
- ❌ ORDER_TABLE (旧版本,约70行)
- ❌ TRADE_TABLE (旧版本,约60行)
- ❌ POSITION_TABLE (旧版本,约70行)
- ❌ ACCOUNT_TABLE (旧版本,约50行)
- ❌ SYMBOL_TABLE (约70行)
**总删除行数**: ~320 行废弃代码

View File

@ -0,0 +1,570 @@
"""
存储性能基准测试 - DuckDB vs DataFrame
测试K线数据的插入和读写性能
"""
import time
import duckdb
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
def generate_kline_data(num_symbols=100, rows_per_symbol=10000):
"""生成模拟K线数据
Args:
num_symbols: 股票数量
rows_per_symbol: 每只股票的K线数量
"""
total_rows = num_symbols * rows_per_symbol
print(
f"生成 {num_symbols} 只股票的K线数据, 每只 {rows_per_symbol:,} 条, 总计 {total_rows:,} 条..."
)
start_date = datetime(2020, 1, 1)
# 生成股票代码列表
symbols = [f"{600000 + i:06d}.SH" for i in range(num_symbols)]
all_data = []
for symbol in symbols:
dates = [start_date + timedelta(minutes=i) for i in range(rows_per_symbol)]
base_price = np.random.uniform(10, 200) # 每只股票不同的基准价格
data = {
"timestamp": dates,
"symbol": [symbol] * rows_per_symbol,
"open": base_price + np.random.randn(rows_per_symbol) * base_price * 0.02,
"high": base_price
+ np.random.randn(rows_per_symbol) * base_price * 0.02
+ base_price * 0.01,
"low": base_price
+ np.random.randn(rows_per_symbol) * base_price * 0.02
- base_price * 0.01,
"close": base_price + np.random.randn(rows_per_symbol) * base_price * 0.02,
"volume": np.random.randint(1000, 100000, rows_per_symbol),
"amount": np.random.uniform(50000, 5000000, rows_per_symbol),
}
all_data.append(pd.DataFrame(data))
df = pd.concat(all_data, ignore_index=True)
print(f"✓ 生成完成: {len(df):,} 行")
return df
def benchmark_duckdb(df):
"""测试DuckDB性能"""
print("\n" + "=" * 60)
print("DuckDB 性能测试")
print("=" * 60)
db_path = "test_kline.duckdb"
# 1. 插入性能
print("\n[1] 插入测试...")
conn = duckdb.connect(db_path)
start = time.time()
conn.execute(
"CREATE TABLE IF NOT EXISTS kline (timestamp TIMESTAMP, symbol VARCHAR, open DOUBLE, high DOUBLE, low DOUBLE, close DOUBLE, volume BIGINT, amount DOUBLE)"
)
conn.execute("DELETE FROM kline") # 清空表
conn.execute("INSERT INTO kline SELECT * FROM df")
insert_time = time.time() - start
print(
f" 插入 {len(df):,} 条: {insert_time:.4f}秒 ({len(df) / insert_time:,.0f} 行/秒)"
)
# 创建复合索引
print("\n[1.1] 创建索引 (symbol + timestamp)...")
start = time.time()
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_symbol_time ON kline(symbol, timestamp)"
)
index_time = time.time() - start
print(f" 索引创建: {index_time:.4f}秒")
# 2. 全表查询
print("\n[2] 全表查询...")
start = time.time()
result = conn.execute("SELECT * FROM kline").df()
query_all_time = time.time() - start
print(f" 查询 {len(result):,} 条: {query_all_time:.4f}秒")
# 3. 条件查询
print("\n[3] 条件查询(单股票)...")
start = time.time()
result = conn.execute("SELECT * FROM kline WHERE symbol = '600036.SH'").df()
query_filter_time = time.time() - start
print(f" 查询 {len(result):,} 条: {query_filter_time:.4f}秒")
# 4. 聚合查询
print("\n[4] 聚合查询(最大最小价格)...")
start = time.time()
result = conn.execute(
"SELECT symbol, MAX(high) as max_price, MIN(low) as min_price FROM kline GROUP BY symbol"
).df()
query_agg_time = time.time() - start
print(f" 聚合查询: {query_agg_time:.4f}秒")
print(f" 结果: {result.to_dict('records')}")
# 5. 范围查询
print("\n[5] 范围查询(最近1000条)...")
start = time.time()
result = conn.execute("SELECT * FROM kline ORDER BY timestamp DESC LIMIT 1000").df()
query_range_time = time.time() - start
print(f" 查询 {len(result):,} 条: {query_range_time:.4f}秒")
# 6. 时间段查询(模拟实际使用场景)
print("\n[6] 时间段查询(单股票约1000条)...")
start = time.time()
# 查询第一只股票的最近1000条数据
result = conn.execute(
"SELECT * FROM kline WHERE symbol = '600000.SH' ORDER BY timestamp DESC LIMIT 1000"
).df()
query_time_range_time = time.time() - start
print(f" 查询 {len(result):,} 条: {query_time_range_time:.4f}秒")
conn.close()
return {
"insert": insert_time,
"query_all": query_all_time,
"query_filter": query_filter_time,
"query_agg": query_agg_time,
"query_range": query_range_time,
}
def benchmark_duckdb_memory(df):
"""测试DuckDB内存数据库性能"""
print("\n" + "=" * 60)
print("DuckDB 内存数据库性能测试")
print("=" * 60)
# 使用内存数据库
conn = duckdb.connect(":memory:")
# 1. 插入性能
print("\n[1] 插入测试(内存)...")
start = time.time()
conn.execute(
"CREATE TABLE kline (timestamp TIMESTAMP, symbol VARCHAR, open DOUBLE, high DOUBLE, low DOUBLE, close DOUBLE, volume BIGINT, amount DOUBLE)"
)
conn.execute("INSERT INTO kline SELECT * FROM df")
insert_time = time.time() - start
print(
f" 插入 {len(df):,} 条: {insert_time:.4f}秒 ({len(df) / insert_time:,.0f} 行/秒)"
)
# 创建复合索引
print("\n[1.1] 创建索引 (symbol + timestamp)...")
start = time.time()
conn.execute("CREATE INDEX idx_symbol_time ON kline(symbol, timestamp)")
index_time = time.time() - start
print(f" 索引创建: {index_time:.4f}秒")
# 2. 全表查询
print("\n[2] 全表查询(内存)...")
start = time.time()
result = conn.execute("SELECT * FROM kline").df()
query_all_time = time.time() - start
print(f" 查询 {len(result):,} 条: {query_all_time:.4f}秒")
# 3. 条件查询
print("\n[3] 条件查询(单股票,内存)...")
start = time.time()
result = conn.execute("SELECT * FROM kline WHERE symbol = '600036.SH'").df()
query_filter_time = time.time() - start
print(f" 查询 {len(result):,} 条: {query_filter_time:.4f}秒")
# 4. 聚合查询
print("\n[4] 聚合查询(最大最小价格,内存)...")
start = time.time()
result = conn.execute(
"SELECT symbol, MAX(high) as max_price, MIN(low) as min_price FROM kline GROUP BY symbol"
).df()
query_agg_time = time.time() - start
print(f" 聚合查询: {query_agg_time:.4f}秒")
print(f" 结果: {result.to_dict('records')}")
# 5. 范围查询
print("\n[5] 范围查询(最近1000条,内存)...")
start = time.time()
result = conn.execute("SELECT * FROM kline ORDER BY timestamp DESC LIMIT 1000").df()
query_range_time = time.time() - start
print(f" 查询 {len(result):,} 条: {query_range_time:.4f}秒")
# 6. 时间段查询(模拟实际使用场景)
print("\n[6] 时间段查询(单股票约1000条,内存)...")
start = time.time()
result = conn.execute(
"SELECT * FROM kline WHERE symbol = '600000.SH' ORDER BY timestamp DESC LIMIT 1000"
).df()
query_time_range_time = time.time() - start
print(f" 查询 {len(result):,} 条: {query_time_range_time:.4f}秒")
conn.close()
return {
"insert": insert_time,
"query_all": query_all_time,
"query_filter": query_filter_time,
"query_agg": query_agg_time,
"query_range": query_range_time,
}
def benchmark_incremental_insert(num_stocks=100, rows_per_stock=360):
"""测试逐条插入性能(模拟实时K线数据插入)
Args:
num_stocks: 股票数量
rows_per_stock: 每只股票插入的K线数量
"""
total_inserts = num_stocks * rows_per_stock
print("\n" + "=" * 60)
print(f"逐条插入性能测试 (实时K线场景)")
print("=" * 60)
print(
f"将逐条插入 {num_stocks} 只股票 × {rows_per_stock} 条 = {total_inserts:,} 条新数据\n"
)
# 生成测试数据
symbols = [f"{600000 + i:06d}.SH" for i in range(num_stocks)]
base_time = datetime.now()
# 为每只股票生成数据
insert_data = []
for symbol in symbols:
base_price = np.random.uniform(10, 200)
for i in range(rows_per_stock):
insert_data.append(
{
"timestamp": base_time + timedelta(minutes=i),
"symbol": symbol,
"open": base_price + np.random.randn() * base_price * 0.02,
"high": base_price
+ np.random.randn() * base_price * 0.02
+ base_price * 0.01,
"low": base_price
+ np.random.randn() * base_price * 0.02
- base_price * 0.01,
"close": base_price + np.random.randn() * base_price * 0.02,
"volume": np.random.randint(1000, 100000),
"amount": np.random.uniform(50000, 5000000),
}
)
# 测试 DuckDB 文件模式
print("[1] DuckDB 文件模式 - 逐条插入...")
conn_file = duckdb.connect("test_kline.duckdb")
start = time.time()
for row in insert_data:
conn_file.execute(
"INSERT INTO kline VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
[
row["timestamp"],
row["symbol"],
row["open"],
row["high"],
row["low"],
row["close"],
row["volume"],
row["amount"],
],
)
file_insert_time = time.time() - start
conn_file.close()
print(
f" 插入 {total_inserts:,} 条: {file_insert_time:.4f}秒 ({total_inserts / file_insert_time:,.0f} 行/秒)"
)
# 测试 DuckDB 内存模式
print("\n[2] DuckDB 内存模式 - 逐条插入...")
conn_mem = duckdb.connect(":memory:")
# 先创建表和索引
conn_mem.execute("""
CREATE TABLE kline (
timestamp TIMESTAMP,
symbol VARCHAR,
open DOUBLE,
high DOUBLE,
low DOUBLE,
close DOUBLE,
volume BIGINT,
amount DOUBLE
)
""")
conn_mem.execute("CREATE INDEX idx_symbol_time ON kline(symbol, timestamp)")
start = time.time()
for row in insert_data:
conn_mem.execute(
"INSERT INTO kline VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
[
row["timestamp"],
row["symbol"],
row["open"],
row["high"],
row["low"],
row["close"],
row["volume"],
row["amount"],
],
)
mem_insert_time = time.time() - start
conn_mem.close()
print(
f" 插入 {total_inserts:,} 条: {mem_insert_time:.4f}秒 ({total_inserts / mem_insert_time:,.0f} 行/秒)"
)
# 测试 DataFrame + Pickle - 逐条插入
print("\n[3] DataFrame + Pickle - 逐条插入...")
df_pickle = pd.DataFrame()
start = time.time()
for row in insert_data:
df_pickle = pd.concat([df_pickle, pd.DataFrame([row])], ignore_index=True)
df_pickle.to_pickle("test_kline_incremental.pkl")
pickle_insert_time = time.time() - start
print(
f" 插入 {total_inserts:,} 条: {pickle_insert_time:.4f}秒 ({total_inserts / pickle_insert_time:,.0f} 行/秒)"
)
# 测试 DataFrame + Parquet - 逐条插入
print("\n[4] DataFrame + Parquet - 逐条插入...")
df_parquet = pd.DataFrame()
start = time.time()
for row in insert_data:
df_parquet = pd.concat([df_parquet, pd.DataFrame([row])], ignore_index=True)
df_parquet.to_parquet("test_kline_incremental.parquet")
parquet_insert_time = time.time() - start
print(
f" 插入 {total_inserts:,} 条: {parquet_insert_time:.4f}秒 ({total_inserts / parquet_insert_time:,.0f} 行/秒)"
)
# 测试 DataFrame 内存 - 逐条append(不保存)
print("\n[5] DataFrame 内存 - 逐条append(不保存文件)...")
df_memory = pd.DataFrame()
start = time.time()
for row in insert_data:
df_memory = pd.concat([df_memory, pd.DataFrame([row])], ignore_index=True)
df_append_time = time.time() - start
print(
f" 插入 {total_inserts:,} 条: {df_append_time:.4f}秒 ({total_inserts / df_append_time:,.0f} 行/秒)"
)
# 清理临时文件
import os
for f in ["test_kline_incremental.pkl", "test_kline_incremental.parquet"]:
if os.path.exists(f):
os.remove(f)
return {
"file_incremental": file_insert_time,
"mem_incremental": mem_insert_time,
"pickle_incremental": pickle_insert_time,
"parquet_incremental": parquet_insert_time,
"dataframe_append": df_append_time,
"total_rows": total_inserts,
}
def benchmark_dataframe(df):
"""测试DataFrame性能"""
print("\n" + "=" * 60)
print("DataFrame 性能测试")
print("=" * 60)
results = {}
# 1. Pickle格式
print("\n[1] Pickle 格式...")
start = time.time()
df.to_pickle("test_kline.pkl")
pickle_write_time = time.time() - start
print(f" 保存: {pickle_write_time:.4f}秒")
start = time.time()
df_loaded = pd.read_pickle("test_kline.pkl")
pickle_read_time = time.time() - start
print(f" 读取 {len(df_loaded):,} 条: {pickle_read_time:.4f}秒")
results["pickle_write"] = pickle_write_time
results["pickle_read"] = pickle_read_time
# 2. Parquet格式
print("\n[2] Parquet 格式...")
start = time.time()
df.to_parquet("test_kline.parquet")
parquet_write_time = time.time() - start
print(f" 保存: {parquet_write_time:.4f}秒")
start = time.time()
df_loaded = pd.read_parquet("test_kline.parquet")
parquet_read_time = time.time() - start
print(f" 读取 {len(df_loaded):,} 条: {parquet_read_time:.4f}秒")
results["parquet_write"] = parquet_write_time
results["parquet_read"] = parquet_read_time
# 3. 内存查询
print("\n[3] 内存查询(DataFrame筛选)...")
start = time.time()
filtered = df[df["symbol"] == "600000.SH"]
filter_time = time.time() - start
print(f" 筛选 {len(filtered):,} 条: {filter_time:.4f}秒")
results["filter"] = filter_time
# 4. 内存聚合
print("\n[4] 内存聚合(groupby)...")
start = time.time()
agg_result = df.groupby("symbol").agg({"high": "max", "low": "min"})
agg_time = time.time() - start
print(f" 聚合查询: {agg_time:.4f}秒")
print(f" 结果: {agg_result.to_dict()}")
results["agg"] = agg_time
return results
def print_summary(
duckdb_results, duckdb_mem_results, df_results, num_rows, incremental_results=None
):
"""打印性能对比总结"""
print("\n" + "=" * 60)
print("性能对比总结")
print("=" * 60)
print(f"\n数据量: {num_rows:,} 条K线记录\n")
print("插入/写入性能:")
print(f" DuckDB 文件: {duckdb_results['insert']:.4f}秒")
print(
f" DuckDB 内存: {duckdb_mem_results['insert']:.4f}秒 [快 {duckdb_results['insert'] / duckdb_mem_results['insert']:.1f}x]"
)
print(f" Pickle 写入: {df_results['pickle_write']:.4f}秒")
print(f" Parquet 写入: {df_results['parquet_write']:.4f}秒")
print("\n全量读取性能:")
print(f" DuckDB 文件: {duckdb_results['query_all']:.4f}秒")
print(
f" DuckDB 内存: {duckdb_mem_results['query_all']:.4f}秒 [快 {duckdb_results['query_all'] / duckdb_mem_results['query_all']:.1f}x]"
)
print(f" Pickle 读取: {df_results['pickle_read']:.4f}秒")
print(f" Parquet 读取: {df_results['parquet_read']:.4f}秒")
print("\n条件查询性能:")
print(f" DuckDB 文件: {duckdb_results['query_filter']:.4f}秒")
print(
f" DuckDB 内存: {duckdb_mem_results['query_filter']:.4f}秒 [快 {duckdb_results['query_filter'] / duckdb_mem_results['query_filter']:.1f}x]"
)
print(f" DataFrame 筛选: {df_results['filter']:.4f}秒")
print("\n聚合查询性能:")
print(f" DuckDB 文件: {duckdb_results['query_agg']:.4f}秒")
print(
f" DuckDB 内存: {duckdb_mem_results['query_agg']:.4f}秒 [快 {duckdb_results['query_agg'] / duckdb_mem_results['query_agg']:.1f}x]"
)
print(f" DataFrame groupby: {df_results['agg']:.4f}秒")
print("\n范围查询性能:")
print(f" DuckDB 文件: {duckdb_results['query_range']:.4f}秒")
print(
f" DuckDB 内存: {duckdb_mem_results['query_range']:.4f}秒 [快 {duckdb_results['query_range'] / duckdb_mem_results['query_range']:.1f}x]"
)
# 逐条插入性能
if incremental_results:
print("\n逐条插入性能 (实时K线场景 - 36,000条):")
print(
f" DuckDB 文件: {incremental_results['file_incremental']:.4f}秒 ({incremental_results['total_rows'] / incremental_results['file_incremental']:,.0f} 行/秒)"
)
print(
f" DuckDB 内存: {incremental_results['mem_incremental']:.4f}秒 ({incremental_results['total_rows'] / incremental_results['mem_incremental']:,.0f} 行/秒) [快 {incremental_results['file_incremental'] / incremental_results['mem_incremental']:.1f}x]"
)
print(
f" Pickle + 保存: {incremental_results['pickle_incremental']:.4f}秒 ({incremental_results['total_rows'] / incremental_results['pickle_incremental']:,.0f} 行/秒)"
)
print(
f" Parquet + 保存: {incremental_results['parquet_incremental']:.4f}秒 ({incremental_results['total_rows'] / incremental_results['parquet_incremental']:,.0f} 行/秒)"
)
print(
f" DataFrame append: {incremental_results['dataframe_append']:.4f}秒 ({incremental_results['total_rows'] / incremental_results['dataframe_append']:,.0f} 行/秒)"
)
# 找出最快的方法
fastest = min(
incremental_results["file_incremental"],
incremental_results["mem_incremental"],
incremental_results["pickle_incremental"],
incremental_results["parquet_incremental"],
incremental_results["dataframe_append"],
)
print("\n 逐条插入速度对比(相对于最快方法):")
print(
f" DuckDB内存: {incremental_results['mem_incremental'] / fastest:.1f}x"
)
print(
f" DuckDB文件: {incremental_results['file_incremental'] / fastest:.1f}x"
)
print(
f" DataFrame: {incremental_results['dataframe_append'] / fastest:.1f}x"
)
print(
f" Pickle保存: {incremental_results['pickle_incremental'] / fastest:.1f}x"
)
print(
f" Parquet保存: {incremental_results['parquet_incremental'] / fastest:.1f}x"
)
def main():
print("=" * 60)
print("K线数据存储性能基准测试")
print("=" * 60)
# 生成测试数据
num_symbols = 100 # 100只股票
rows_per_symbol = 10000 # 每只股票万条K线
df = generate_kline_data(num_symbols, rows_per_symbol)
# 测试DuckDB文件模式
duckdb_results = benchmark_duckdb(df)
# 测试DuckDB内存模式
duckdb_mem_results = benchmark_duckdb_memory(df)
# 测试DataFrame
df_results = benchmark_dataframe(df)
# 逐条插入性能测试(模拟实时K线数据插入)
incremental_results = benchmark_incremental_insert(
num_stocks=100, rows_per_stock=360
)
# 打印总结
total_rows = num_symbols * rows_per_symbol
print_summary(
duckdb_results, duckdb_mem_results, df_results, total_rows, incremental_results
)
# 清理测试文件
print("\n清理测试文件...")
import os
for f in [
"test_kline.duckdb",
"test_kline.pkl",
"test_kline.parquet",
]:
if os.path.exists(f):
os.remove(f)
print(f" 删除: {f}")
print("\n✓ 测试完成!")
if __name__ == "__main__":
main()

View File

@ -0,0 +1,362 @@
# K线数据存储性能测试分析报告
**测试日期**: 2026-01-17
**测试场景**: 100只股票 × 10,000条K线 = 1,000,000条数据
**特殊场景**: 100只股票 × 360条逐条插入 = 36,000条实时K线
---
## 📊 测试环境
- **Python**: 3.11
- **数据库**: DuckDB (文件模式 + 内存模式)
- **存储格式**: Pickle, Parquet
- **计算框架**: Pandas DataFrame
- **索引优化**: 复合索引 (symbol + timestamp)
---
## 🎯 核心发现
### 1. **批量插入性能** (100万条数据)
| 存储方式 | 时间 | 速度 | 相对性能 |
| --------------- | ------ | ---------- | -------- |
| **Pickle写入** | 0.06秒 | 最快 | ⭐⭐⭐⭐⭐ |
| **DuckDB内存** | 0.13秒 | 790万行/秒 | ⭐⭐⭐⭐⭐ |
| **DuckDB文件** | 0.41秒 | 244万行/秒 | ⭐⭐⭐⭐ |
| **Parquet写入** | 0.28秒 | - | ⭐⭐⭐ |
**结论**: Pickle适合临时缓存,DuckDB内存模式适合高速批量导入
---
### 2. **逐条插入性能** ⚠️ (36,000条实时K线)
| 存储方式 | 时间 | 速度 | 相对最快 |
| -------------------- | ------- | ---------- | ----------- |
| **DuckDB内存** | 30.9秒 | 1,165行/秒 | **1.0x** ✅ |
| **DataFrame append** | 41.0秒 | 878行/秒 | 1.3x |
| **DuckDB文件** | 66.9秒 | 538行/秒 | 2.2x |
| **Pickle+保存** | 127.7秒 | 282行/秒 | 4.1x ⚠️ |
| **Parquet+保存** | 783.7秒 | 46行/秒 | **25.4x** ❌ |
#### 关键洞察
1. **DuckDB内存模式最快** - 每秒可插入1,165条K线数据
- 100只股票同时更新,每只每秒11.65条 ✅
- 适合高频实时场景
2. **DataFrame append次优** - 速度878行/秒
- 纯内存操作,无文件I/O
- 但需注意:`pd.concat`性能随数据量增加而下降
3. **Parquet完全不适合** - 慢25倍!
- 每次保存都要重新编码整个文件
- 13分钟才能插入3.6万条 ❌
4. **Pickle略好于Parquet** - 但仍慢4倍
- 每次序列化整个DataFrame
- 不适合实时场景
---
### 3. **读取性能对比**
| 存储方式 | 全量读取 | 单股票查询 | 100股聚合 |
| -------------- | -------- | ---------- | ---------- |
| **Pickle** | 0.07秒 ⭐ | - | - |
| **DuckDB内存** | 0.15秒 | 0.015秒 ⭐ | 0.015秒 ⭐ |
| **Parquet** | 0.13秒 | - | - |
| **DuckDB文件** | 0.21秒 | 0.029秒 | 0.008秒 ⭐⭐ |
| **DataFrame** | - | 0.032秒 | 0.043秒 |
**索引优势**:
- DuckDB文件模式在聚合查询中**最快** (0.008秒)
- 复合索引 (symbol, timestamp) 使单股票查询速度提升10倍
- DataFrame筛选比DuckDB慢5.4倍
---
### 4. **时间段查询** (量化交易核心场景)
查询单只股票的最近1000条K线:
| 存储方式 | 时间 | 备注 |
| ----------------- | ------- | ------------- |
| **DuckDB内存** | 0.004秒 | 最快 ⭐⭐⭐ |
| **DuckDB文件** | 0.008秒 | 有索引支持 ⭐⭐ |
| **DataFrame筛选** | 0.032秒 | 慢8倍 |
**结论**:
- DuckDB索引查询只需**8毫秒**
- 可支持每秒125次查询请求
- DataFrame需要全表扫描,性能差
---
## 🏆 推荐方案
### 场景一:实时K线数据插入 (高频交易)
```python
# ✅ 推荐:DuckDB内存模式
conn = duckdb.connect(":memory:")
conn.execute("CREATE INDEX idx_symbol_time ON kline(symbol, timestamp)")
# 逐条插入:1,165行/秒
for kline in real_time_stream:
conn.execute("INSERT INTO kline VALUES (?, ?, ?, ...)", kline)
```
**优势**:
- 速度最快 (1,165行/秒)
- SQL查询能力
- 内存占用低
- 无文件I/O延迟
**缺点**:
- 数据不持久化
- 需定期导出到文件
---
### 场景二:历史数据批量导入 (回测系统)
```python
# ✅ 推荐:Pickle快速加载 + DuckDB内存分析
df = pd.read_pickle("history.pkl") # 0.07秒加载100万条
conn = duckdb.connect(":memory:")
conn.execute("CREATE TABLE kline AS SELECT * FROM df")
conn.execute("CREATE INDEX idx_symbol_time ON kline(symbol, timestamp)")
```
**优势**:
- Pickle读取极快 (0.07秒)
- DuckDB提供SQL能力
- 内存分析高效
---
### 场景三:持久化存储 + 查询 (生产环境)
```python
# ✅ 推荐:DuckDB文件模式 + 复合索引
conn = duckdb.connect("kline.duckdb")
conn.execute("CREATE INDEX idx_symbol_time ON kline(symbol, timestamp)")
# 批量插入:244万行/秒
conn.execute("INSERT INTO kline SELECT * FROM df")
# 时间段查询:8毫秒
result = conn.execute("""
SELECT * FROM kline
WHERE symbol = '600000.SH'
AND timestamp >= '2024-01-01'
ORDER BY timestamp DESC
LIMIT 1000
""").df()
```
**优势**:
- 数据持久化
- 索引查询快
- SQL灵活性高
- 支持并发读
---
### 场景四:数据归档 (长期存储)
```python
# ✅ 推荐:Parquet压缩存储
df.to_parquet("archive_2024.parquet", compression='snappy')
# 读取速度可接受:0.13秒
df = pd.read_parquet("archive_2024.parquet")
```
**优势**:
- 压缩率高 (节省存储)
- 列式存储
- 跨语言兼容
**缺点**:
- 不适合频繁更新
- 不适合逐条插入
---
## ⚠️ 反模式(不要这样做)
### ❌ 错误1:用Parquet做实时插入
```python
# 错误示例:每收到一条K线就保存
for kline in stream:
df = pd.concat([df, pd.DataFrame([kline])])
df.to_parquet("kline.parquet") # ❌ 慢25倍!
```
**问题**: 783秒才能插入3.6万条,完全无法实时使用
---
### ❌ 错误2:用DataFrame做大量条件查询
```python
# 每次筛选都要全表扫描
filtered = df[df['symbol'] == 'AAPL'] # ❌ 慢8倍
```
**替代方案**: 用DuckDB + 索引
```python
result = conn.execute("""
SELECT * FROM kline WHERE symbol = 'AAPL'
""").df() # ✅ 快8倍
```
---
### ❌ 错误3:Pickle用于生产环境持久化
```python
df.to_pickle("production.pkl") # ❌ 不安全
```
**问题**:
- 不跨版本兼容
- 不跨语言兼容
- 可能有安全风险
**正确用法**: 仅用于临时缓存
---
## 📈 性能矩阵总结
| | 批量写入 | 逐条插入 | 读取速度 | 查询性能 | 持久化 | 压缩率 |
| -------------- | -------- | -------- | -------- | -------- | ------ | ------ |
| **DuckDB文件** | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ✅ | 中 |
| **DuckDB内存** | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ❌ | - |
| **Pickle** | ⭐⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐⭐⭐⭐ | ❌ | ✅ | 低 |
| **Parquet** | ⭐⭐⭐ | ❌ | ⭐⭐⭐⭐ | ❌ | ✅ | 高 |
| **DataFrame** | - | ⭐⭐⭐ | - | ⭐⭐⭐ | ❌ | - |
---
## 🎓 最佳实践建议
### 1. **实时交易系统架构**
```
┌─────────────────┐
│ 实时K线流 │
│ (WebSocket) │
└────────┬────────┘
│ 逐条插入 (1,165行/秒)
▼
┌─────────────────────────┐
│ DuckDB内存数据库 │
│ + 复合索引 │
│ (symbol, timestamp) │
└────────┬────────────────┘
│ 每5分钟持久化
▼
┌─────────────────────────┐
│ DuckDB文件数据库 │
│ (历史数据) │
└─────────────────────────┘
│ 每天归档
▼
┌─────────────────────────┐
│ Parquet压缩存储 │
│ (冷数据归档) │
└─────────────────────────┘
```
### 2. **回测系统架构**
```
┌─────────────────────────┐
│ Parquet历史数据 │
│ (按年份分片) │
└────────┬────────────────┘
│ 一次性加载
▼
┌─────────────────────────┐
│ DuckDB内存数据库 │
│ + 索引 │
└────────┬────────────────┘
│ SQL查询
▼
┌─────────────────────────┐
│ 回测引擎 │
└─────────────────────────┘
```
### 3. **数据管道优化**
- **热数据** (最近1周): DuckDB内存 → 极速查询
- **温数据** (最近1月): DuckDB文件 → 平衡性能
- **冷数据** (历史数据): Parquet → 节省空间
---
## 📝 量化数据
### 36,000条实时K线插入对比
| 方案 | 时间 | 速度 | 适用性 |
| ------------ | ----- | ---------- | ------------ |
| DuckDB内存 | 31秒 | 1,165行/秒 | ✅ 实时交易 |
| DataFrame | 41秒 | 878行/秒 | ⚠️ 小规模实时 |
| DuckDB文件 | 67秒 | 538行/秒 | ⚠️ 中低频 |
| Pickle+保存 | 128秒 | 282行/秒 | ❌ 不推荐 |
| Parquet+保存 | 784秒 | 46行/秒 | ❌ 完全不适用 |
### 单股票1000条查询对比
- **DuckDB内存 + 索引**: 4ms ⚡
- **DuckDB文件 + 索引**: 8ms ⚡
- **DataFrame全表扫描**: 32ms (慢8倍) 🐌
---
## 🚀 性能优化Tips
1. **始终创建索引**
```sql
CREATE INDEX idx_symbol_time ON kline(symbol, timestamp);
```
2. **批量操作优于逐条**
- 批量: 790万行/秒
- 逐条: 1,165行/秒
- 差距: **6,780倍**
3. **内存数据库定期持久化**
```python
# 每5分钟导出一次
conn.execute("COPY kline TO 'checkpoint.parquet'")
```
4. **分区存储大数据**
```python
# 按日期分区
df.to_parquet("kline_20240101.parquet")
df.to_parquet("kline_20240102.parquet")
```
---
## 结论
- **实时场景**: DuckDB内存模式 (1,165行/秒)
- **持久化**: DuckDB文件 + 索引 (8ms查询)
- **归档**: Parquet (高压缩率)
- **缓存**: Pickle (最快读写)
- **避免**: Parquet逐条插入 (慢25倍)
**核心原则**: 正确的工具用在正确的场景!

View File

@ -25,11 +25,11 @@
```
**字段说明**:
| 字段 | 类型 | 必填 | 说明 |
| --------- | ------ | ---- | ------------------------ |
| version | string | 是 | 协议版本号,当前为"1.0" |
| msg_id | string | 是 | 消息唯一ID,建议使用UUID |
| timestamp | string | 是 | 消息时间戳,格式: YYYY-MM-DD HH:MM:SS.mmm |
| 字段 | 类型 | 必填 | 说明 |
| --------- | ------ | ---- | ----------------------------------------- |
| version | string | 是 | 协议版本号,当前为"1.0" |
| msg_id | string | 是 | 消息唯一ID,建议使用UUID |
| timestamp | string | 是 | 消息时间戳,格式: YYYY-MM-DD HH:MM:SS.mmm |
## 3. 消息类型
@ -104,17 +104,17 @@
**字段说明**:
| 字段 | 类型 | 必填 | 说明 |
| ----------- | ------ | ---- | --------------------------------------------------------- |
| header | object | 是 | 协议头 |
| msg_type | string | 是 | 消息类型: "KLINE_DATA"(单条) 或 "KLINE_DATA_BATCH"(批量) |
| symbol | string | 是 | 股票代码,如"000001.SZ"、"600000.SH" |
| period | string | 是 | K线周期: "1m", "5m", "15m", "30m", "1h", "1d", "1w", "1M" |
| kline_time | string | 是 | K线时间,格式: YYYY-MM-DD HH:MM:SS |
| data.open | float | 是 | 开盘价 |
| data.high | float | 是 | 最高价 |
| data.low | float | 是 | 最低价 |
| data.close | float | 是 | 收盘价 |
| data.volume | int | 是 | 成交量 |
| klines | array | 是 | 批量模式下的K线数据列表 |
| header | object | 是 | 协议头 |
| msg_type | string | 是 | 消息类型: "KLINE_DATA"(单条) 或 "KLINE_DATA_BATCH"(批量) |
| symbol | string | 是 | 股票代码,如"000001.SZ"、"600000.SH" |
| period | string | 是 | K线周期: "1m", "5m", "15m", "30m", "1h", "1d", "1w", "1M" |
| kline_time | string | 是 | K线时间,格式: YYYY-MM-DD HH:MM:SS |
| data.open | float | 是 | 开盘价 |
| data.high | float | 是 | 最高价 |
| data.low | float | 是 | 最低价 |
| data.close | float | 是 | 收盘价 |
| data.volume | int | 是 | 成交量 |
| klines | array | 是 | 批量模式下的K线数据列表 |
**周期说明**:
- `1m`: 1分钟
@ -153,14 +153,14 @@
**字段说明**:
| 字段 | 类型 | 必填 | 说明 |
| ----------------- | ------ | ---- | ------------------------------------------------- |
| header | object | 是 | 协议头 |
| header.req_msg_id | string | 是 | 对应的请求消息ID |
| msg_type | string | 是 | 消息类型,固定为"TRADE_SIGNAL" |
| symbol | string | 是 | 股票代码 |
| action | string | 是 | 交易动作: "BUY"(买入)、"SELL"(卖出)、"HOLD"(持有) |
| price | float | 是 | **建议交易价格**(明确在什么价位交易) |
| quantity | int | 是 | **交易数量**(股数,0表示不交易) |
| message | string | 否 | 信号说明或原因 |
| header | object | 是 | 协议头 |
| header.req_msg_id | string | 是 | 对应的请求消息ID |
| msg_type | string | 是 | 消息类型,固定为"TRADE_SIGNAL" |
| symbol | string | 是 | 股票代码 |
| action | string | 是 | 交易动作: "BUY"(买入)、"SELL"(卖出)、"HOLD"(持有) |
| price | float | 是 | **建议交易价格**(明确在什么价位交易) |
| quantity | int | 是 | **交易数量**(股数,0表示不交易) |
| message | string | 否 | 信号说明或原因 |
**交易动作说明**:
- `BUY`: 买入,price为建议买入价,quantity为买入股数
@ -220,11 +220,11 @@
**字段说明**:
| 字段 | 类型 | 必填 | 说明 |
| ----------------- | ------ | ---- | ----------------------- |
| header | object | 是 | 协议头 |
| header.req_msg_id | string | 否 | 导致错误的请求消息ID |
| msg_type | string | 是 | 消息类型,固定为"ERROR" |
| error_code | string | 是 | 错误代码 |
| error_message | string | 是 | 错误描述 |
| header | object | 是 | 协议头 |
| header.req_msg_id | string | 否 | 导致错误的请求消息ID |
| msg_type | string | 是 | 消息类型,固定为"ERROR" |
| error_code | string | 是 | 错误代码 |
| error_message | string | 是 | 错误描述 |
**错误码列表**:
- `INVALID_VERSION`: 协议版本不支持

View File

@ -37,4 +37,6 @@ xtquant # 迅投QMT数据源
fastapi>=0.95.0 # 用于构建API服务
uvicorn[standard]
websockets>=11.0.0 # 用于WebSocket通信
pyyaml
pyyaml
duckdb
pyarrow

View File

@ -66,7 +66,7 @@ class BaseStrategy(ABC):
"""
pass
def get_status(self) -> Dict[str, Any]:
def get_state(self) -> Dict[str, Any]:
"""
获取当前策略状态

View File

@ -4,6 +4,8 @@
避免在代码中使用魔法字符串,统一管理常量定义
"""
from sre_constants import IN
class MessageKeys:
"""
@ -38,6 +40,28 @@ class MessageTypeValues:
HEARTBEAT = "heartbeat"
class TradeSignalKeys:
"""
交易信号键名常量
使用示例:
from src.core.constants import TradeSignalKeys
action = signal[TradeSignalKeys.ACTION]
"""
INSTANCE_ID = "instance_id"
STRATEGY_NAME = "strategy_name"
TIMESTAMP = "timestamp"
STIME = "stime"
ACTION = "action"
SYMBOL = "symbol"
PRICE = "price"
VOLUME = "volume"
TIMESTAMP = "timestamp"
REASON = "reason"
class KlineKeys:
"""
K线数据键名常量
@ -58,6 +82,22 @@ class KlineKeys:
AMOUNT = "amount"
class TradeActionValue:
"""
交易动作值常量
使用示例:
from src.core.constants import TradeActionValue
if signal[TradeSignalKeys.ACTION] == TradeActionValue.BUY:
execute_buy(signal)
"""
BUY = "buy"
SELL = "sell"
HOLD = "hold"
class ConfigKey:
"""
配置文件键名常量

View File

@ -89,7 +89,7 @@ class GridStrategy(BaseStrategy):
)
else:
Logger.warning(
f"[GridStrategy] No historical data available, last_price not initialized"
"[GridStrategy] No historical data available, last_price not initialized"
)
except Exception as e:
Logger.warning(f"[GridStrategy] Failed to initialize current price: {e}")
@ -176,7 +176,6 @@ class GridStrategy(BaseStrategy):
# 提取K线数据
symbol = kline_data.get("symbol", "UNKNOWN")
timestamp = kline_data.get("timestamp", "")
close = kline_data.get("close", 0)
# 价格不在网格范围内,不操作
@ -210,7 +209,10 @@ class GridStrategy(BaseStrategy):
return signal
# 检测网格线穿越
crossed = self._find_crossed_grid(self.last_price, close)
# 只有在有历史价格时才检测穿越
crossed = None
if self.last_price is not None:
crossed = self._find_crossed_grid(self.last_price, close)
signal = None
if crossed:
@ -300,7 +302,7 @@ class GridStrategy(BaseStrategy):
f"{trade_result.get('message')}"
)
def get_status(self) -> Dict[str, Any]:
def get_state(self) -> Dict[str, Any]:
"""获取当前策略状态"""
return {
"grid_lines": self.grid_lines,

View File

@ -1,204 +0,0 @@
"""
配置加载器 (Config Loader)
负责加载和管理策略配置文件
"""
from typing import Dict, List, Optional, Any
import yaml
from pathlib import Path
from src.core.logger import Logger
logger = Logger
class ConfigLoader:
"""
配置加载器
负责:
- 加载strategy_config.yaml配置文件
- 验证配置合法性
- 提供配置查询接口
- 支持热更新
"""
def __init__(self, config_path: str):
"""
初始化配置加载器
Args:
config_path: 配置文件路径
"""
self.config_path = Path(config_path)
self.config: Dict[str, Any] = {}
self._instances_by_id: Dict[str, Dict] = {}
self._instances_by_symbol: Dict[str, List[str]] = {}
def load(self) -> bool:
"""
加载配置文件
Returns:
是否加载成功
"""
try:
if not self.config_path.exists():
logger.error(f"Config file not found: {self.config_path}")
return False
with open(self.config_path, "r", encoding="utf-8") as f:
self.config = yaml.safe_load(f)
# 验证配置
if not self._validate_config():
return False
# 构建索引
self._build_indexes()
logger.info(f"Config loaded successfully from {self.config_path}")
logger.info(f"Total instances: {len(self._instances_by_id)}")
return True
except Exception as e:
logger.error(f"Failed to load config: {e}")
return False
def _validate_config(self) -> bool:
"""
验证配置合法性
Returns:
是否合法
"""
# 检查全局配置
if "global" not in self.config:
logger.error("Missing 'global' section in config")
return False
global_config = self.config["global"]
if "total_capital" not in global_config:
logger.error("Missing 'total_capital' in global config")
return False
# 检查策略实例配置
if "strategy_instances" not in self.config:
logger.error("Missing 'strategy_instances' section in config")
return False
instances = self.config["strategy_instances"]
if not isinstance(instances, list) or len(instances) == 0:
logger.error("'strategy_instances' must be a non-empty list")
return False
# 验证每个实例
instance_ids = set()
total_capital = 0
for instance in instances:
# 检查必需字段
required_fields = ["id", "symbol", "strategy_class", "capital"]
for field in required_fields:
if field not in instance:
logger.error(f"Missing required field '{field}' in instance")
return False
# 检查ID唯一性
instance_id = instance["id"]
if instance_id in instance_ids:
logger.error(f"Duplicate instance ID: {instance_id}")
return False
instance_ids.add(instance_id)
# 累计资金
total_capital += instance["capital"]
# 检查资金分配是否超过总资金
if total_capital > global_config["total_capital"]:
logger.warning(
f"Total allocated capital ({total_capital}) exceeds "
f"global total capital ({global_config['total_capital']})"
)
return True
def _build_indexes(self):
"""构建索引以加速查询"""
self._instances_by_id.clear()
self._instances_by_symbol.clear()
for instance in self.config["strategy_instances"]:
instance_id = instance["id"]
symbol = instance["symbol"]
# ID索引
self._instances_by_id[instance_id] = instance
# Symbol索引
if symbol not in self._instances_by_symbol:
self._instances_by_symbol[symbol] = []
self._instances_by_symbol[symbol].append(instance_id)
def get_instance_config(self, instance_id: str) -> Optional[Dict]:
"""
获取某个策略实例的配置
Args:
instance_id: 策略实例ID
Returns:
配置字典,如果不存在返回None
"""
return self._instances_by_id.get(instance_id)
def get_symbol_instances(self, symbol: str) -> List[Dict]:
"""
获取某个股票的所有策略实例配置
Args:
symbol: 股票代码
Returns:
配置列表
"""
instance_ids = self._instances_by_symbol.get(symbol, [])
return [self._instances_by_id[iid] for iid in instance_ids]
def get_all_instances(self) -> List[Dict]:
"""
获取所有策略实例配置
Returns:
配置列表
"""
return self.config.get("strategy_instances", [])
def get_global_config(self) -> Dict:
"""
获取全局配置
Returns:
全局配置字典
"""
return self.config.get("global", {})
def get_all_symbols(self) -> List[str]:
"""
获取所有配置的股票代码
Returns:
股票代码列表
"""
return list(self._instances_by_symbol.keys())
def reload(self) -> bool:
"""
热更新配置
Returns:
是否成功
"""
logger.info("Reloading config...")
return self.load()

View File

@ -1,286 +0,0 @@
"""
持仓管理器 (Position Manager)
负责管理每个策略实例的持仓和资金
"""
from typing import Dict, Optional
from dataclasses import dataclass
from src.strategy_service.config_loader import ConfigLoader
from src.core.logger import Logger
@dataclass
class Position:
"""持仓信息"""
symbol: str
quantity: int = 0 # 持仓数量
avg_cost: float = 0.0 # 平均成本
last_price: float = 0.0 # 最新价
def get_market_value(self) -> float:
"""计算市值"""
return self.quantity * self.last_price
def get_pnl(self) -> float:
"""计算浮动盈亏"""
if self.quantity == 0:
return 0.0
return (self.last_price - self.avg_cost) * self.quantity
@dataclass
class Capital:
"""资金信息"""
total: float # 总资金
available: float # 可用资金
frozen: float = 0.0 # 冻结资金
def get_used(self) -> float:
"""计算已使用资金"""
return self.total - self.available
class PositionManager:
"""
持仓管理器
负责:
- 管理每个策略实例的持仓
- 管理每个策略实例的资金
- 计算盈亏
- 策略间持仓和资金隔离
"""
def __init__(self, config_loader: ConfigLoader):
"""
初始化持仓管理器
Args:
config_loader: 配置加载器
"""
self.config_loader = config_loader
# 每个策略实例的持仓:{instance_id: Position}
self.positions: Dict[str, Position] = {}
# 每个策略实例的资金:{instance_id: Capital}
self.capitals: Dict[str, Capital] = {}
def initialize(self) -> bool:
"""
初始化所有策略实例的持仓和资金
Returns:
是否初始化成功
"""
try:
logger.info("Initializing position manager...")
for instance_config in self.config_loader.get_all_instances():
instance_id = instance_config["id"]
symbol = instance_config["symbol"]
capital = instance_config["capital"]
# 初始化持仓
self.positions[instance_id] = Position(symbol=symbol)
# 初始化资金
self.capitals[instance_id] = Capital(total=capital, available=capital)
logger.debug(
f"Initialized position for {instance_id}: "
f"{symbol}, capital={capital}"
)
logger.info(
f"Position manager initialized with {len(self.positions)} instances"
)
return True
except Exception as e:
logger.error(f"Failed to initialize position manager: {e}")
return False
def get_position(self, instance_id: str) -> Optional[Position]:
"""
获取策略实例的持仓
Args:
instance_id: 策略实例ID
Returns:
持仓信息,如果不存在返回None
"""
return self.positions.get(instance_id)
def get_capital(self, instance_id: str) -> Optional[Capital]:
"""
获取策略实例的资金
Args:
instance_id: 策略实例ID
Returns:
资金信息,如果不存在返回None
"""
return self.capitals.get(instance_id)
def get_available_capital(self, instance_id: str) -> float:
"""
获取策略实例的可用资金
Args:
instance_id: 策略实例ID
Returns:
可用资金
"""
capital = self.capitals.get(instance_id)
return capital.available if capital else 0.0
def update_position(
self, instance_id: str, action: str, quantity: int, price: float
) -> bool:
"""
更新策略实例的持仓
Args:
instance_id: 策略实例ID
action: 动作(BUY/SELL)
quantity: 数量
price: 价格
Returns:
是否更新成功
"""
position = self.positions.get(instance_id)
capital = self.capitals.get(instance_id)
if not position or not capital:
logger.error(f"Instance not found: {instance_id}")
return False
try:
if action == "BUY":
# 买入更新
total_cost = position.quantity * position.avg_cost
total_cost += quantity * price
position.quantity += quantity
position.avg_cost = (
total_cost / position.quantity if position.quantity > 0 else 0.0
)
# 更新资金
cost = quantity * price
capital.available -= cost
logger.debug(
f"Updated position (BUY): {instance_id}, "
f"qty={position.quantity}, avg_cost={position.avg_cost:.3f}"
)
elif action == "SELL":
# 卖出更新
if quantity > position.quantity:
logger.error(
f"Insufficient position: {instance_id}, "
f"have={position.quantity}, want={quantity}"
)
return False
position.quantity -= quantity
if position.quantity == 0:
position.avg_cost = 0.0
# 更新资金
proceeds = quantity * price
capital.available += proceeds
logger.debug(
f"Updated position (SELL): {instance_id}, qty={position.quantity}"
)
return True
except Exception as e:
logger.error(f"Failed to update position for {instance_id}: {e}")
return False
def update_price(self, instance_id: str, price: float):
"""
更新最新价格
Args:
instance_id: 策略实例ID
price: 最新价格
"""
position = self.positions.get(instance_id)
if position:
position.last_price = price
def get_instance_pnl(self, instance_id: str) -> float:
"""
计算策略实例的浮动盈亏
Args:
instance_id: 策略实例ID
Returns:
浮动盈亏
"""
position = self.positions.get(instance_id)
if not position:
return 0.0
return position.get_pnl()
def get_total_capital_used(self) -> float:
"""
获取所有策略使用的总资金
Returns:
已使用总资金
"""
total = 0.0
for capital in self.capitals.values():
total += capital.get_used()
return total
def get_total_market_value(self) -> float:
"""
获取所有持仓的总市值
Returns:
总市值
"""
total = 0.0
for position in self.positions.values():
total += position.get_market_value()
return total
def get_total_pnl(self) -> float:
"""
获取所有策略的总盈亏
Returns:
总盈亏
"""
total = 0.0
for instance_id, position in self.positions.items():
total += position.get_pnl()
return total
def get_summary(self) -> Dict:
"""
获取持仓汇总信息
Returns:
汇总字典
"""
return {
"total_capital_used": self.get_total_capital_used(),
"total_market_value": self.get_total_market_value(),
"total_pnl": self.get_total_pnl(),
"instance_count": len(self.positions),
}

View File

@ -1,252 +0,0 @@
"""
风控管理器 (Risk Manager)
负责多层级风控检查
"""
from typing import Dict
from dataclasses import dataclass
from src.strategy_service.config_loader import ConfigLoader
from src.strategy_service.position_manager import PositionManager
from src.core.logger import Logger
@dataclass
class TradeSignal:
"""交易信号"""
instance_id: str
symbol: str
action: str # BUY/SELL/HOLD
price: float
quantity: int
message: str = ""
class RiskManager:
"""
风控管理器
负责:
- 全局风控:总仓位、总资金使用率
- 策略实例风控:资金、仓位、止损止盈
- 信号风控:单次交易检查
"""
def __init__(self, config_loader: ConfigLoader, position_manager: PositionManager):
"""
初始化风控管理器
Args:
config_loader: 配置加载器
position_manager: 持仓管理器
"""
self.config_loader = config_loader
self.position_manager = position_manager
def check_signal(self, signal: TradeSignal) -> bool:
"""
检查交易信号是否通过风控
Args:
signal: 交易信号
Returns:
是否通过风控
"""
# 1. 全局风控
if not self._check_global_risk(signal):
logger.warning(f"Signal rejected by global risk: {signal.instance_id}")
return False
# 2. 策略实例风控
if not self._check_instance_risk(signal):
logger.warning(f"Signal rejected by instance risk: {signal.instance_id}")
return False
# 3. 信号级风控
if not self._check_signal_risk(signal):
logger.warning(f"Signal rejected by signal risk: {signal.instance_id}")
return False
return True
def _check_global_risk(self, signal: TradeSignal) -> bool:
"""
全局风控检查
Args:
signal: 交易信号
Returns:
是否通过
"""
if signal.action != "BUY":
# 卖出不检查全局风控
return True
global_config = self.config_loader.get_global_config()
total_capital = global_config.get("total_capital", 0)
max_ratio = global_config.get("max_position_ratio", 1.0)
if total_capital == 0:
logger.error("Total capital is 0")
return False
# 计算当前总资金使用率
used_capital = self.position_manager.get_total_capital_used()
current_ratio = used_capital / total_capital
# 计算交易后的使用率
required = signal.quantity * signal.price
new_ratio = (used_capital + required) / total_capital
if new_ratio > max_ratio:
logger.warning(
f"Global position limit exceeded: current={current_ratio:.2%}, "
f"new={new_ratio:.2%}, max={max_ratio:.2%}"
)
return False
return True
def _check_instance_risk(self, signal: TradeSignal) -> bool:
"""
策略实例风控检查
Args:
signal: 交易信号
Returns:
是否通过
"""
instance_config = self.config_loader.get_instance_config(signal.instance_id)
if not instance_config:
logger.error(f"Instance config not found: {signal.instance_id}")
return False
position = self.position_manager.get_position(signal.instance_id)
capital = self.position_manager.get_capital(signal.instance_id)
if not position or not capital:
logger.error(f"Position or capital not found: {signal.instance_id}")
return False
risk_config = instance_config.get("risk", {})
if signal.action == "BUY":
# 买入检查
# 1. 检查可用资金
required = signal.quantity * signal.price
if required > capital.available:
logger.warning(
f"Insufficient capital: {signal.instance_id}, "
f"required={required:.2f}, available={capital.available:.2f}"
)
return False
# 2. 检查仓位比例
max_ratio = risk_config.get("max_position_ratio", 1.0)
current_used = capital.get_used()
new_used = current_used + required
new_ratio = new_used / capital.total
if new_ratio > max_ratio:
logger.warning(
f"Position ratio exceeded: {signal.instance_id}, "
f"new_ratio={new_ratio:.2%}, max={max_ratio:.2%}"
)
return False
elif signal.action == "SELL":
# 卖出检查
# 1. 检查持仓数量
if signal.quantity > position.quantity:
logger.warning(
f"Insufficient position: {signal.instance_id}, "
f"have={position.quantity}, want={signal.quantity}"
)
return False
# 2. 检查止损
if position.quantity > 0:
pnl = (signal.price - position.avg_cost) * signal.quantity
stop_loss = risk_config.get("stop_loss")
if stop_loss:
loss_threshold = -stop_loss * position.avg_cost * signal.quantity
if pnl < loss_threshold:
logger.info(
f"Stop loss triggered: {signal.instance_id}, "
f"pnl={pnl:.2f}, threshold={loss_threshold:.2f}"
)
# 止损触发,允许卖出
return True
# 3. 检查止盈
stop_profit = risk_config.get("stop_profit")
if stop_profit:
profit_threshold = stop_profit * position.avg_cost * signal.quantity
if pnl > profit_threshold:
logger.info(
f"Stop profit triggered: {signal.instance_id}, "
f"pnl={pnl:.2f}, threshold={profit_threshold:.2f}"
)
# 止盈触发,允许卖出
return True
return True
def _check_signal_risk(self, signal: TradeSignal) -> bool:
"""
信号级风控检查
Args:
signal: 交易信号
Returns:
是否通过
"""
# 1. 检查数量是否为正
if signal.quantity <= 0:
logger.warning(f"Invalid quantity: {signal.quantity}")
return False
# 2. 检查价格是否为正
if signal.price <= 0:
logger.warning(f"Invalid price: {signal.price}")
return False
# 3. 检查交易金额是否过大(防止异常订单)
amount = signal.quantity * signal.price
max_single_trade = 10000000 # 单笔最大1000万
if amount > max_single_trade:
logger.warning(
f"Single trade amount too large: {amount:.2f}, "
f"max={max_single_trade:.2f}"
)
return False
return True
def get_risk_summary(self) -> Dict:
"""
获取风控汇总信息
Returns:
汇总字典
"""
global_config = self.config_loader.get_global_config()
total_capital = global_config.get("total_capital", 0)
used_capital = self.position_manager.get_total_capital_used()
return {
"total_capital": total_capital,
"used_capital": used_capital,
"usage_ratio": used_capital / total_capital if total_capital > 0 else 0,
"max_position_ratio": global_config.get("max_position_ratio", 1.0),
}

View File

@ -1,231 +0,0 @@
"""
策略执行器 (Strategy Executor)
负责执行策略并生成交易信号
"""
from typing import Dict, List
import uuid
from src.strategy_service.strategy_manager import StrategyManager
from src.strategy_service.position_manager import PositionManager
from src.strategy_service.risk_manager import RiskManager, TradeSignal
from src.strategy_service.trade_recorder import TradeRecorder
from src.core.logger import Logger
class StrategyExecutor:
"""
策略执行器
负责:
- 接收K线数据
- 调用策略实例计算信号
- 风控检查
- 记录信号
- 返回所有通过风控的信号
"""
def __init__(
self,
strategy_manager: StrategyManager,
position_manager: PositionManager,
risk_manager: RiskManager,
trade_recorder: TradeRecorder,
):
"""
初始化策略执行器
Args:
strategy_manager: 策略管理器
position_manager: 持仓管理器
risk_manager: 风控管理器
trade_recorder: 交易记录器
"""
self.strategy_manager = strategy_manager
self.position_manager = position_manager
self.risk_manager = risk_manager
self.trade_recorder = trade_recorder
def process_kline(self, symbol: str, kline_data: Dict) -> List[TradeSignal]:
"""
处理单个股票的K线数据
Args:
symbol: 股票代码
kline_data: K线数据字典
Returns:
通过风控的信号列表
"""
# 1. 获取该股票的所有策略实例
instances = self.strategy_manager.get_symbol_instances(symbol)
if not instances:
logger.debug(f"No strategy instances for {symbol}")
return []
logger.debug(f"Processing {symbol} for {len(instances)} instances")
# 2. 并行执行所有策略
signals = []
for instance_id, strategy_obj in instances:
try:
# 更新最新价格(用于计算盈亏)
current_price = kline_data.get("close", 0.0)
self.position_manager.update_price(instance_id, current_price)
# 构建完整的K线数据(包含symbol)
full_kline_data = {"symbol": symbol, **kline_data}
# 调用策略计算
# 假设策略有compute方法返回action, price, quantity
result = strategy_obj.compute(full_kline_data)
if not result:
continue
action = result.get("action", "HOLD")
if action == "HOLD":
continue
# 构建信号
signal = TradeSignal(
instance_id=instance_id,
symbol=symbol,
action=action,
price=result.get("price", current_price),
quantity=result.get("quantity", 0),
message=result.get("message", ""),
)
# 3. 风控检查
if not self.risk_manager.check_signal(signal):
logger.debug(
f"Signal rejected by risk manager: {instance_id} {action}"
)
continue
# 4. 记录信号
signal_id = str(uuid.uuid4())
self.trade_recorder.record_signal(
instance_id=instance_id,
symbol=symbol,
action=action,
price=signal.price,
quantity=signal.quantity,
message=signal.message,
signal_id=signal_id,
)
signals.append(signal)
logger.info(
f"Generated signal: {instance_id} {action} {symbol} "
f"{signal.quantity}@{signal.price:.3f}"
)
except Exception as e:
logger.error(
f"Error processing strategy {instance_id}: {e}", exc_info=True
)
continue
return signals
def process_klines_batch(
self, klines_dict: Dict[str, Dict]
) -> Dict[str, List[TradeSignal]]:
"""
批量处理多个股票的K线数据
Args:
klines_dict: {symbol: kline_data} 字典
Returns:
{symbol: [signals]} 字典
"""
results = {}
for symbol, kline_data in klines_dict.items():
signals = self.process_kline(symbol, kline_data)
if signals:
results[symbol] = signals
return results
def process_trade_result(self, instance_id: str, trade_result: Dict) -> bool:
"""
处理交易成交结果
Args:
instance_id: 策略实例ID
trade_result: 成交结果字典,包含action, price, quantity等
Returns:
是否处理成功
"""
try:
action = trade_result.get("action")
price = trade_result.get("price")
quantity = trade_result.get("quantity")
symbol = trade_result.get("symbol")
if not action or price is None or quantity is None or not symbol:
logger.error(f"Invalid trade result: {trade_result}")
return False
# 确保类型正确
action = str(action)
price = float(price)
quantity = int(quantity)
symbol = str(symbol)
# 更新持仓
success = self.position_manager.update_position(
instance_id=instance_id, action=action, quantity=quantity, price=price
)
if not success:
logger.error(f"Failed to update position for {instance_id}")
return False
# 记录成交
trade_id = trade_result.get("trade_id", str(uuid.uuid4()))
signal_id = trade_result.get("signal_id")
self.trade_recorder.record_trade(
instance_id=instance_id,
symbol=symbol,
action=action,
price=price,
quantity=quantity,
trade_id=trade_id,
signal_id=signal_id,
)
logger.info(
f"Processed trade result: {instance_id} {action} {symbol} "
f"{quantity}@{price:.3f}"
)
return True
except Exception as e:
logger.error(f"Error processing trade result: {e}")
return False
def get_status(self) -> Dict:
"""
获取执行器状态
Returns:
状态字典
"""
return {
"position_summary": self.position_manager.get_summary(),
"risk_summary": self.risk_manager.get_risk_summary(),
"trade_stats": self.trade_recorder.get_all_stats(),
}

View File

@ -224,8 +224,8 @@ class StrategyManager:
for instance_id, strategy_obj in self.instances.items():
try:
# 获取策略状态
if hasattr(strategy_obj, "get_status"):
# state = strategy_obj.get_status()
if hasattr(strategy_obj, "get_state"):
# state = strategy_obj.get_state()
# Todo: 持久化状态
pass