Compare commits

...

2 Commits

Author SHA1 Message Date
b311fbdece 性能优化与测试:添加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()
  * 优化启用/禁用策略逻辑

- 清理废弃文档和配置模块
- 添加性能测试分析报告和技术研究文档
2026-01-17 23:52:59 +08:00
6284f98eda 重构策略状态管理:统一由StrategyManager管理状态持久化
主要变更:
1. BaseStrategy新增get_status()和restore_state()方法
2. StrategyManager统一管理状态保存和恢复
   - close()方法调用get_status()保存状态
   - initialize()方法调用restore_state()恢复状态
3. GridStrategy实现状态管理接口
4. 网格策略支持断点续传
5. 新增消息类型常量定义
6. 重构MiniQMT客户端适配器的K线数据处理
7. 统一使用Logger替换LazyLogger
8. 配置文件支持多数据库类型
2026-01-17 14:37:57 +08:00
35 changed files with 2361 additions and 2954 deletions

View File

@ -4,17 +4,20 @@
environment:
mode: "backtest"
# ==================== MySQL 配置 ====================
# ==================== 数据持久化 配置 ====================
database:
host: "127.0.0.1"
port: 3306
user: "root"
password: "1234"
database: "qtrade_backtest"
pool_size: 5
pool_recycle: 3600
echo: false
current_db: "mysql" # 当前使用的数据库类型: mysql/duckdb
mysql:
host: "127.0.0.1"
port: 3306
user: "root"
password: "1234"
database: "qtrade_sim"
pool_size: 5
pool_recycle: 3600
echo: false
duckdb:
filepath: "d:/workspace/QTrade/data/qtrade_backtest.duckdb"
# ==================== 缓存配置 ====================
cache:
type: "memory" # memory-内存缓存

View File

@ -6,15 +6,18 @@ environment:
# ==================== MySQL 配置 ====================
database:
host: "127.0.0.1"
port: 3306
user: "root"
password: "1234"
database: "qtrade_live"
pool_size: 5
pool_recycle: 3600
echo: false
current_db: "mysql" # 当前使用的数据库类型: mysql/duckdb
mysql:
host: "127.0.0.1"
port: 3306
user: "root"
password: "1234"
database: "qtrade_sim"
pool_size: 5
pool_recycle: 3600
echo: false
duckdb:
filepath: "d:/workspace/QTrade/data/qtrade_live.duckdb"
# ==================== 缓存配置 ====================
cache:
type: "memory" # memory-内存缓存

View File

@ -4,17 +4,20 @@
environment:
mode: "simulation"
# ==================== MySQL 配置 ====================
# ==================== 数据持久化 配置 ====================
database:
host: "127.0.0.1"
port: 3306
user: "root"
password: "1234"
database: "qtrade_sim"
pool_size: 5
pool_recycle: 3600
echo: false
current_db: "mysql" # 当前使用的数据库类型: mysql/duckdb
mysql:
host: "127.0.0.1"
port: 3306
user: "root"
password: "1234"
database: "qtrade_sim"
pool_size: 5
pool_recycle: 3600
echo: false
duckdb:
filepath: "d:/workspace/QTrade/data/qtrade_sim.duckdb"
# ==================== 缓存配置 ====================
cache:
type: "memory" # memory-内存缓存

View File

@ -2,7 +2,9 @@
# 平安银行 - 每条K线都打印,不生成信号
instance_id: "debug_000001"
symbol: "000001.SZ" # 股票代码
is_enabled: true # 是否启用该策略实例
symbol: ["600593.SH","601288.SH"] # 股票代码
symbol_name: ["大连圣亚","农业银行"] # 股票名称
symbol_name: "平安银行" # 股票名称
symbol_type: "stock" # 股票类型,stock,etf,future,option,bond
symbol_decimal_places: 2 # 小数位数, 股票为2,期货,ETF等为3

View File

@ -1,17 +0,0 @@
# 策略实例配置: debug_600000
# 浦发银行 - 每5条打印一次
instance_id: "debug_600000"
symbol: "600000.SH"
strategy_class: "DebugStrategy"
capital: 120000
# 策略参数
params:
print_every: 5 # 每5条K线打印一次
simulate_signal: false
# 风控参数
risk:
max_position_ratio: 0.7
stop_loss: 0.04

View File

@ -0,0 +1,34 @@
# 策略实例配置: debug_cross_test_1
# 交叉测试策略1 - 监控农业银行和平安银行
instance_id: "debug_cross_test_1"
is_enabled: true # 是否启用该策略实例
symbol: ["601288.SH", "000001.SZ"] # 农业银行, 平安银行
symbol_name: ["农业银行", "平安银行"]
symbol_type: "stock"
symbol_decimal_places: 2
strategy_class: "DebugStrategy"
capital: 200000
# 策略参数
params:
print_every: 1
simulate_signal: false
# 风控参数
risk:
max_position_ratio: 0.6
stop_loss: 0.03
# ==================== 仅对回测生效 ====================
backtrade:
trading_type: t1
trading_fees:
commission_rate: 0.00005
min_commission: 5.0
stamp_tax_rate: 0.001
transfer_fee_rate: 0.00002
slippage: 0.0001
start_date: "2025-01-01"
end_date: "2025-12-31"
period: "1m"

View File

@ -0,0 +1,34 @@
# 策略实例配置: debug_cross_test_2
# 交叉测试策略2 - 仅监控贵州茅台
instance_id: "debug_cross_test_2"
is_enabled: false # 是否启用该策略实例(测试禁用功能)
symbol: "600519.SH" # 贵州茅台 (单个symbol,字符串格式)
symbol_name: "贵州茅台"
symbol_type: "stock"
symbol_decimal_places: 2
strategy_class: "DebugStrategy"
capital: 500000
# 策略参数
params:
print_every: 1
simulate_signal: false
# 风控参数
risk:
max_position_ratio: 0.5
stop_loss: 0.02
# ==================== 仅对回测生效 ====================
backtrade:
trading_type: t1
trading_fees:
commission_rate: 0.00005
min_commission: 5.0
stamp_tax_rate: 0.001
transfer_fee_rate: 0.00002
slippage: 0.0001
start_date: "2025-01-01"
end_date: "2025-12-31"
period: "1m"

View File

@ -0,0 +1,34 @@
# 策略实例配置: debug_cross_test_3
# 交叉测试策略3 - 监控农业银行和招商银行
instance_id: "debug_cross_test_3"
is_enabled: true # 是否启用该策略实例
symbol: ["601288.SH", "600036.SH"] # 农业银行, 招商银行
symbol_name: ["农业银行", "招商银行"]
symbol_type: "stock"
symbol_decimal_places: 2
strategy_class: "DebugStrategy"
capital: 150000
# 策略参数
params:
print_every: 1
simulate_signal: false
# 风控参数
risk:
max_position_ratio: 0.7
stop_loss: 0.04
# ==================== 仅对回测生效 ====================
backtrade:
trading_type: t1
trading_fees:
commission_rate: 0.00005
min_commission: 5.0
stamp_tax_rate: 0.001
transfer_fee_rate: 0.00002
slippage: 0.0001
start_date: "2025-01-01"
end_date: "2025-12-31"
period: "1m"

View File

@ -1,18 +0,0 @@
# 策略实例配置: debug_signal_000001
# 平安银行 - 带信号模拟
instance_id: "debug_signal_000001"
symbol: "000001.SZ"
strategy_class: "DebugStrategy"
capital: 80000
# 策略参数
params:
print_every: 1
simulate_signal: true # 生成模拟信号
signal_threshold: 2.0 # 价格变化2%触发信号
# 风控参数
risk:
max_position_ratio: 0.6
stop_loss: 0.03

View File

@ -0,0 +1,56 @@
# 策略实例配置: grid_test_001
# 网格策略测试 - 招商银行
instance_id: "grid_test_001"
is_enabled: true # 是否启用该策略实例
symbol: "601288.SH" # 农业银行
symbol_name: "农业银行"
symbol_type: "stock"
symbol_decimal_places: 2
strategy_class: "GridStrategy"
capital: 100000
# 初始化策略参数
params:
current_price: 39.0 # 当前价格(用于初始化网格)
grid_upper: 42.0 # 网格上限价格
grid_lower: 36.0 # 网格下限价格
grid_count: 10 # 网格数量(在上下限之间分成10个格子)
quantity_per_grid: 100 # 每个网格交易100股
max_position: 1000 # 最大持仓1000股(防止持仓过重)
stop_loss_pct: 0.15 # 止损比例15%(相对于持仓均价)
# 风控参数
risk:
max_position_ratio: 0.8 # 最大仓位80%
stop_loss: 0.15 # 止损15%
# ==================== 策略说明 ====================
# 网格交易策略适合震荡行情,通过在价格区间内低买高卖获利
#
# 工作原理:
# 1. 价格区间:36.0 - 42.0 元
# 2. 10个网格,每格间距:(42-36)/10 = 0.6元
# 3. 网格线:36.0, 36.6, 37.2, 37.8, 38.4, 39.0, 39.6, 40.2, 40.8, 41.4, 42.0
# 4. 价格下穿网格线时买入100股
# 5. 价格上穿网格线时卖出100股
# 6. 最大持仓1000股(10次买入)
# 7. 亏损超过15%时止损
#
# 示例:
# - 价格从38.5跌到37.0 → 下穿37.8和37.2网格 → 买入200股
# - 价格从37.0涨到38.5 → 上穿37.2和37.8网格 → 卖出200股
# - 每次完整波动获利:(37.8-37.2) * 100 + (37.2-37.8) 的往返 = 赚取价差
# ==================== 仅对回测生效 ====================
backtrade:
trading_type: t1 # 交易类型 T+1
trading_fees:
commission_rate: 0.00005 # 佣金率 万0.5
min_commission: 5.0 # 最低佣金 5元
stamp_tax_rate: 0.001 # 印花税率 0.1%(仅卖出时收取)
transfer_fee_rate: 0.00002 # 过户费率 万0.2
slippage: 0.0001 # 滑点 0.01%
start_date: "2025-01-01" # 回测开始日期
end_date: "2025-12-31" # 回测结束日期
period: "1m" # 回测K线周期

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

@ -26,8 +26,8 @@ workspace = Path(__file__).parent
"""
STOCK_POOL = [
{"symbol": "601288.SH", "symbol_name": "农业银行", "period": "1m"},
{"symbol": "600593.SH", "symbol_name": "大连圣亚", "period": "5m"},
# {"symbol": "601288.SH", "symbol_name": "农业银行", "period": "1m"},
{"symbol": "600593.SH", "symbol_name": "大连圣亚", "period": "1m"},
# 添加更多股票...
]

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

@ -9,6 +9,7 @@ from typing import Dict, Any, Optional
import logging
from src.core.strategy_context import StrategyContext
from src.core.logger import Logger
logger = logging.getLogger(__name__)
@ -65,6 +66,24 @@ class BaseStrategy(ABC):
"""
pass
def get_state(self) -> Dict[str, Any]:
"""
获取当前策略状态
Returns:
策略状态字典
"""
return {}
def restore_state(self, state: Dict[str, Any]):
"""
恢复策略状态
Args:
state: 策略状态字典
"""
pass
def on_init(self):
"""
初始化回调(可选实现)

View File

@ -4,6 +4,99 @@
避免在代码中使用魔法字符串,统一管理常量定义
"""
from sre_constants import IN
class MessageKeys:
"""
消息类型键名常量
使用示例:
from src.core.constants import MessageKeys
msg_type = message[MessageKeys.TYPE]
"""
TYPE = "type"
SYMBOL = "symbol"
PERIOD = "period"
INDICATOR = "indicator"
class MessageTypeValues:
"""
消息类型值常量
使用示例:
from src.core.constants import MessageTypeValues
if message[MessageTypeKeys.TYPE] == MessageTypeValues.KLINE_DATA:
process_kline(message)
"""
KLINE_DATA = "kline_data"
TRADE_SIGNALS = "trade_signals"
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线数据键名常量
使用示例:
from src.core.constants import KlineKey
open_price = kline_data[KlineKey.OPEN]
"""
TIMESTAMP = "timestamp"
READABLE_TIME = "readable_time"
OPEN = "open"
HIGH = "high"
LOW = "low"
CLOSE = "close"
VOLUME = "volume"
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

@ -62,12 +62,12 @@ class DatabaseManager:
user: 数据库用户名
password: 数据库密码
"""
self.host = host or Config.get("database.host", "127.0.0.1")
self.port = port or Config.get("database.port", 3306)
self.user = user or Config.get("database.user", "root")
self.password = password or Config.get("database.password", "")
self.pool_size = Config.get("database.pool_size", 5)
self.pool_recycle = Config.get("database.pool_recycle", 3600)
self.host = host or Config.get("database.mysql.host")
self.port = port or Config.get("database.mysql.port")
self.user = user or Config.get("database.mysql.user")
self.password = password or Config.get("database.mysql.password")
self.pool_size = Config.get("database.mysql.pool_size")
self.pool_recycle = Config.get("database.mysql.pool_recycle")
# 创建不指定数据库的连接(用于管理数据库)
self._admin_engine = self._create_admin_engine()

View File

@ -17,6 +17,7 @@ from src.cache.cache_manager import CacheManager
from src.database_manager.db_manager import DatabaseManager
from src.data_storage.mysql_storage import MySQLStorage
from src.core.constants import KlineKeys, MessageKeys, MessageTypeValues
# ==================== 全局对象 ====================
stratge_config_dir: str = "config/strategies"
@ -148,7 +149,7 @@ async def handle_kline_data(message: dict) -> dict:
处理单条K线数据
Args:
message: 请求消息
message: 请求消息(原始消息,由策略管理器处理)
Returns:
业务响应数据(由 WebSocketServer 包装成完整响应)
@ -156,31 +157,16 @@ async def handle_kline_data(message: dict) -> dict:
Raises:
Exception: 处理失败时抛出异常
"""
# 检查是否为K线更新类型
if message.get(MessageKeys.TYPE) != MessageTypeValues.KLINE_DATA:
Logger.warning("Received non-KLINE_DATA message in handle_kline_data")
return {}
if not strategy_manager:
raise RuntimeError("Strategy manager not initialized")
symbol = message.get("symbol")
kline_time = message.get("kline_time")
data = message.get("data", {})
if not symbol:
raise ValueError("Symbol is required")
Logger.info(f"Processing K-line: {symbol} {kline_time}")
# 构建完整的K线数据
kline_data = {
"symbol": symbol,
"timestamp": kline_time,
"open": data.get("open"),
"high": data.get("high"),
"low": data.get("low"),
"close": data.get("close"),
"volume": data.get("volume"),
}
# 分发到策略管理器
signals = strategy_manager.dispatch_kline(symbol, kline_data)
signals = strategy_manager.dispatch_klinedata_message(message)
# 返回业务数据
return {
@ -189,55 +175,6 @@ async def handle_kline_data(message: dict) -> dict:
}
async def handle_kline_batch(message: dict) -> dict:
"""
处理批量K线数据
Args:
message: 请求消息
Returns:
业务响应数据(由 WebSocketServer 包装成完整响应)
Raises:
Exception: 处理失败时抛出异常
"""
if not strategy_manager:
raise RuntimeError("Strategy manager not initialized")
batch_data = message.get("batch_data", [])
all_signals = []
Logger.info(f"Processing batch: {len(batch_data)} symbols")
# 处理每个标的的K线
for item in batch_data:
symbol = item.get("symbol")
kline_time = item.get("kline_time")
data = item.get("data", {})
# 构建完整的K线数据
kline_data = {
"symbol": symbol,
"timestamp": kline_time,
"open": data.get("open"),
"high": data.get("high"),
"low": data.get("low"),
"close": data.get("close"),
"volume": data.get("volume"),
}
# 分发到策略管理器
signals = strategy_manager.dispatch_kline(symbol, kline_data)
all_signals.extend(signals)
# 返回业务数据
return {
"msg_type": "TRADE_SIGNALS",
"signals": all_signals,
}
def start_server():
"""
启动服务器
@ -333,8 +270,7 @@ def start_server():
ws_server = WebSocketServer(title="QTrade Strategy Server", version="1.0.0")
# 注册消息处理器
ws_server.register_handler("KLINE_DATA", handle_kline_data)
ws_server.register_handler("KLINE_DATA_BATCH", handle_kline_batch)
ws_server.register_handler(MessageTypeValues.KLINE_DATA, handle_kline_data)
# 启动服务器
ws_server.start(host=host, port=port)

View File

@ -8,12 +8,10 @@ MiniQMT 实盘交易客户端适配器
- 执行实盘交易委托
"""
from typing import Optional, Dict
from typing import Optional
from datetime import datetime
from dataclasses import dataclass
import pandas as pd
import uuid
from cycler import K
from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback
from xtquant.xttype import StockAccount
from xtquant import xtconstant
@ -21,6 +19,7 @@ from xtquant import xtdata
from src.networks.client.ws_client import WSClient
from src.core.logger import Logger
from src.core.constants import KlineKeys, MessageKeys, MessageTypeValues
g_wsclient: Optional[WSClient] = None
@ -39,31 +38,116 @@ def get_wsclient() -> Optional[WSClient]:
return g_wsclient
# 实时行情数据回调
# on_data(datas),回调参数datas格式为 { stock1 : data1, stock2 : data2, ... }
def on_realtime_data(datas):
Logger.info(f"Received realtime data: {datas}")
"""
实时行情数据回调
Args:
datas: 行情数据字典,格式为 {symbol: [data1, data2, ...]}
每个data包含: time, open, high, low, close, volume, amount等字段
"""
if not datas:
return
Logger.info("=" * 60)
Logger.info(f"收到实时行情数据,标的数量: {len(datas)}")
# 初始化消息字典
message: dict = {MessageKeys.TYPE: MessageTypeValues.KLINE_DATA}
# 遍历每个标的的行情数据
symbols = datas.keys()
for symbol in symbols:
data = datas[symbol]
if data:
# data 格式示例:
# {
# 'time': 1768529940000, # 时间戳(毫秒)
# 'open': 7.24, # 开盘价
# 'high': 7.24, # 最高价
# 'low': 7.23, # 最低价
# 'close': 7.23, # 收盘价
# 'volume': 5798, # 成交量
# 'amount': 4193948.0, # 成交额
# 'settlementPrice': 0.0, # 结算价
# 'openInterest': 13, # 持仓量
# 'dr': 1.0, # 除权因子
# 'totaldr': 2.24, # 累计除权因子
# 'preClose': 7.18, # 前收盘价
# 'suspendFlag': 23 # 停牌标志
# }
# 解析时间戳
time_value = data.get("time")
readable_time = _parse_timestamp(time_value)
Logger.info(f" 股票代码: {symbol} | 时间: {readable_time} | ")
# 构建发送到策略服务器的消息
message[symbol] = {
KlineKeys.TIMESTAMP: time_value,
KlineKeys.READABLE_TIME: readable_time,
KlineKeys.OPEN: data.get("open"),
KlineKeys.HIGH: data.get("high"),
KlineKeys.LOW: data.get("low"),
KlineKeys.CLOSE: data.get("close"),
KlineKeys.VOLUME: data.get("volume"),
KlineKeys.AMOUNT: data.get("amount"),
}
Logger.info(
f"symbol : {symbol} | readable_time: {readable_time} | data: {message[symbol]}"
)
Logger.info("------------------get_market_data_ex---------------------")
data_from_getdata = xtdata.get_market_data_ex(
field_list=[
"time",
"stime",
"open",
"high",
"low",
"close",
"volume",
"amount",
],
stock_list=[symbol],
period="1m",
start_time="20240101",
end_time="",
count=1, # 获取最近5条数据
dividend_type="none", # 不复权
)
Logger.info(f"获取到的数据: {data_from_getdata}")
# 发送到策略服务器
wsclient = get_wsclient()
if wsclient:
message = []
for symbol, data in datas.items():
# 构造消息
signals = wsclient.send(message)
Logger.info(f"收到交易信号: {signals}")
# 处理交易信号
message = {
"symbol": symbol,
"datetime": data.get(
"datetime", datetime.now().strftime("%Y-%m-%d %H:%M:%S")
),
"open": data.get("open", 0.0),
"high": data.get("high", 0.0),
"low": data.get("low", 0.0),
"close": data.get("close", 0.0),
"volume": data.get("volume", 0),
}
# respone = wsclient.send("kline_data", message)
# 获取买卖信号
Logger.info(f"Sent data to server: {message}")
def _parse_timestamp(timestamp: int) -> str:
"""
解析时间戳为可读格式
Args:
timestamp: 时间戳(秒或毫秒)
Returns:
格式化的时间字符串
"""
if not isinstance(timestamp, (int, float)):
return "无效时间"
try:
# 判断是毫秒还是秒时间戳
if timestamp > 1e12:
dt = datetime.fromtimestamp(timestamp / 1000)
else:
dt = datetime.fromtimestamp(timestamp)
return dt.strftime("%Y-%m-%d %H:%M:%S")
except Exception as e:
Logger.warning(f"时间戳解析失败: {timestamp}, 错误: {e}")
return "时间解析失败"
class MiniQMTTraderCallback(XtQuantTraderCallback):

3
src/realtrade/sn.md Normal file
View File

@ -0,0 +1,3 @@
国金证券QMT测试账号信息:
登录账号:40004091
登录密码:259800

View File

@ -0,0 +1,335 @@
"""
网格交易策略 (Grid Trading Strategy)
通过在预设的价格区间内设置多个买卖网格,
在价格波动时自动低买高卖,赚取价差收益。
策略原理:
1. 设定价格区间(上限、下限)和网格数量
2. 在区间内均匀分布N个网格线
3. 价格下穿网格线时买入
4. 价格上穿网格线时卖出
5. 通过频繁的波段操作获利
适用场景:
- 震荡市场
- 波动性较大但趋势不明显的标的
- 适合流动性好的股票/ETF
"""
from typing import Dict, Any, Optional
from src.core.base_strategy import BaseStrategy
from src.core.logger import Logger
class GridStrategy(BaseStrategy):
"""
网格交易策略
在预设价格区间内布置网格,自动低买高卖
"""
def on_init(self):
"""初始化回调"""
# 网格参数
self.grid_upper = self.params.get("grid_upper", 100.0) # 网格上限
self.grid_lower = self.params.get("grid_lower", 50.0) # 网格下限
self.grid_count = self.params.get("grid_count", 10) # 网格数量
self.quantity_per_grid = self.params.get(
"quantity_per_grid", 100
) # 每格交易数量
# 风控参数
self.max_position = self.params.get("max_position", 5000) # 最大持仓数量
self.stop_loss_pct = self.params.get(
"stop_loss_pct", 0.15
) # 止损百分比(默认15%)
# 初始化状态
self.grid_lines = [] # 网格线价格列表
self.last_price = None # 上一次价格
self.last_action = None # 上一次操作
self.kline_count = 0
# 如果没有网格线,则计算新的
if not self.grid_lines:
self._calculate_grid_lines()
# 获取持仓信息
position = self.context.get_position()
capital = self.context.get_capital()
Logger.info(f"[GridStrategy] Initialized: {self.context.instance_id}")
Logger.info(f" Symbol: {self.context.symbol}")
Logger.info(f" Grid Range: {self.grid_lower:.2f} - {self.grid_upper:.2f}")
Logger.info(f" Grid Count: {self.grid_count}")
Logger.info(f" Quantity per Grid: {self.quantity_per_grid}")
Logger.info(f" Max Position: {self.max_position}")
Logger.info(f" Stop Loss: {self.stop_loss_pct * 100:.1f}%")
Logger.info(f" Initial Capital: {capital.initial_cash:.2f}")
Logger.info(f" Current Position: {position.shares:.0f} shares")
# 打印网格线
Logger.info(" Grid Lines:")
for i, line in enumerate(self.grid_lines):
Logger.info(f" Grid {i + 1}: {line:.2f}")
# 获取当前价格作为初始价格(从最近的K线数据)
self._init_current_price()
def _init_current_price(self):
"""初始化当前价格(从最近的K线数据获取)"""
try:
# 从缓存获取最近的K线数据
klines = self.context.get_klines(last_n=1)
if klines is not None and not klines.empty:
self.last_price = float(klines.iloc[-1]["close"])
Logger.info(
f"[GridStrategy] Initialized current price: {self.last_price:.2f}"
)
else:
Logger.warning(
"[GridStrategy] No historical data available, last_price not initialized"
)
except Exception as e:
Logger.warning(f"[GridStrategy] Failed to initialize current price: {e}")
def _calculate_grid_lines(self):
"""计算网格线价格"""
if self.grid_count <= 1:
Logger.error("Grid count must be greater than 1")
return
# 在区间内均匀分布网格线
step = (self.grid_upper - self.grid_lower) / self.grid_count
self.grid_lines = [
self.grid_lower + step * i for i in range(self.grid_count + 1)
]
def _find_crossed_grid(self, old_price: float, new_price: float) -> Optional[tuple]:
"""
检测是否穿越网格线
Args:
old_price: 旧价格
new_price: 新价格
Returns:
(网格索引, 方向) 或 None
方向: 'up' 表示上穿, 'down' 表示下穿
"""
if old_price is None or new_price == old_price:
return None
# 检查每条网格线
for i, grid_line in enumerate(self.grid_lines):
# 下穿:价格从上往下穿过网格线(买入信号)
if old_price > grid_line >= new_price:
return (i, "down")
# 上穿:价格从下往上穿过网格线(卖出信号)
elif old_price < grid_line <= new_price:
return (i, "up")
return None
def _check_stop_loss(self, current_price: float) -> bool:
"""
检查是否触发止损
Args:
current_price: 当前价格
Returns:
是否需要止损
"""
position = self.context.get_position()
# 没有持仓不需要止损
if position.shares <= 0:
return False
# 计算持仓成本和当前亏损比例
avg_price = position.avg_price
loss_pct = (current_price - avg_price) / avg_price
# 亏损超过止损线
if loss_pct < -self.stop_loss_pct:
Logger.warning(
f"Stop loss triggered! Loss: {loss_pct * 100:.2f}%, "
f"Avg Price: {avg_price:.2f}, Current: {current_price:.2f}"
)
return True
return False
def compute(self, kline_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""
处理K线数据并生成交易信号
Args:
kline_data: K线数据字典
Returns:
信号字典或None
"""
self.kline_count += 1
# 提取K线数据
symbol = kline_data.get("symbol", "UNKNOWN")
close = kline_data.get("close", 0)
# 价格不在网格范围内,不操作
if close < self.grid_lower or close > self.grid_upper:
Logger.debug(
f"[{self.context.instance_id}] Price {close:.2f} out of grid range "
f"[{self.grid_lower:.2f}, {self.grid_upper:.2f}]"
)
self.last_price = close
return None
# 获取持仓信息
position = self.context.get_position()
current_shares = position.shares
# 检查止损
if self._check_stop_loss(close):
signal = {
"action": "SELL",
"symbol": symbol,
"price": close,
"quantity": int(current_shares), # 全部卖出
"reason": f"Stop loss triggered at {close:.2f}",
}
Logger.info(
f"[{self.context.instance_id}] STOP LOSS: "
f"Sell {signal['quantity']} @ {close:.2f}"
)
self.last_price = close
self.last_action = "SELL"
return signal
# 检测网格线穿越
# 只有在有历史价格时才检测穿越
crossed = None
if self.last_price is not None:
crossed = self._find_crossed_grid(self.last_price, close)
signal = None
if crossed:
grid_idx, direction = crossed
grid_price = self.grid_lines[grid_idx]
if direction == "down":
# 下穿网格线 -> 买入信号
# 检查是否超过最大持仓
if current_shares + self.quantity_per_grid <= self.max_position:
signal = {
"action": "BUY",
"symbol": symbol,
"price": close,
"quantity": self.quantity_per_grid,
"reason": f"Price crossed down grid {grid_idx + 1} at {grid_price:.2f}",
}
Logger.info(
f"[{self.context.instance_id}] Grid {grid_idx + 1} BUY: "
f"{self.quantity_per_grid} @ {close:.2f} "
f"(Grid: {grid_price:.2f})"
)
self.last_action = "BUY"
else:
Logger.warning(
f"[{self.context.instance_id}] Max position reached: "
f"{current_shares}/{self.max_position}"
)
elif direction == "up":
# 上穿网格线 -> 卖出信号
# 检查是否有持仓可卖
if current_shares >= self.quantity_per_grid:
signal = {
"action": "SELL",
"symbol": symbol,
"price": close,
"quantity": self.quantity_per_grid,
"reason": f"Price crossed up grid {grid_idx + 1} at {grid_price:.2f}",
}
Logger.info(
f"[{self.context.instance_id}] Grid {grid_idx + 1} SELL: "
f"{self.quantity_per_grid} @ {close:.2f} "
f"(Grid: {grid_price:.2f})"
)
self.last_action = "SELL"
else:
Logger.debug(
f"[{self.context.instance_id}] Insufficient shares: "
f"{current_shares} < {self.quantity_per_grid}"
)
# 更新状态
self.last_price = close
# 定期打印状态(每10根K线)
if self.kline_count % 10 == 0:
capital = self.context.get_capital()
Logger.debug(
f"[{self.context.instance_id}] Status: "
f"Price={close:.2f}, Position={current_shares}, "
f"Cash={capital.available_cash:.2f}"
)
return signal
def on_trade(self, trade_result: Dict[str, Any]):
"""
交易回调
Args:
trade_result: 交易结果
"""
if trade_result.get("success"):
action = trade_result.get("action")
symbol = trade_result.get("symbol")
price = trade_result.get("price")
quantity = trade_result.get("quantity")
Logger.info(
f"[{self.context.instance_id}] Trade executed: "
f"{action} {quantity} {symbol} @ {price:.2f}"
)
else:
Logger.error(
f"[{self.context.instance_id}] Trade failed: "
f"{trade_result.get('message')}"
)
def get_state(self) -> Dict[str, Any]:
"""获取当前策略状态"""
return {
"grid_lines": self.grid_lines,
"last_price": self.last_price,
"last_action": self.last_action,
"kline_count": self.kline_count,
"grid_upper": self.grid_upper,
"grid_lower": self.grid_lower,
"grid_count": self.grid_count,
}
def restore_state(self, state: Dict[str, Any]):
"""恢复策略状态"""
if not state:
return
self.grid_lines = state.get("grid_lines", [])
self.last_price = state.get("last_price")
self.last_action = state.get("last_action")
self.kline_count = state.get("kline_count", 0)
self.grid_upper = state.get("grid_upper", self.grid_upper)
self.grid_lower = state.get("grid_lower", self.grid_lower)
self.grid_count = state.get("grid_count", self.grid_count)
# 如果恢复了网格线,需要重新初始化当前价格
if self.grid_lines:
Logger.info(
f"[GridStrategy] Restored state: {len(self.grid_lines)} grid lines"
)
self._init_current_price()

View File

@ -1,333 +0,0 @@
"""
策略管理器 (Strategy Manager)
负责:
1. 加载多个策略配置文件 (config/strategies/*.yaml)
2. 实例化策略对象
3. 维护 symbol -> [策略实例] 的映射
4. 分发K线数据到对应策略
5. 聚合所有策略返回的信号
"""
from typing import Dict, List, Tuple, Any, Optional
from pathlib import Path
import yaml
import importlib
from src.core.strategy_context import StrategyContext
from src.core.logger import Logger
class StrategyManager:
"""
策略管理器
管理多个策略实例,支持:
- 一个symbol配置多个策略实例
- 策略配置文件独立管理
- 动态加载策略类
"""
def __init__(
self,
config_dir: str,
cache_manager,
):
"""
初始化策略管理器
Args:
config_dir: 策略配置文件目录
cache_manager: 缓存管理器(共享实例)
"""
self.config_dir = Path(config_dir)
# 直接持有共享资源
self._cache_manager = cache_manager
# 策略实例字典: {instance_id: strategy_object}
self.instances: Dict[str, Any] = {}
# Symbol索引: {symbol: [(instance_id, strategy_object), ...]}
self.symbol_index: Dict[str, List[Tuple[str, Any]]] = {}
# 配置缓存: {instance_id: config_dict}
self.configs: Dict[str, Dict] = {}
Logger.info(f"StrategyManager initialized with config_dir: {config_dir}")
def load_configs(self) -> bool:
"""
加载所有策略配置文件
Returns:
是否加载成功
"""
try:
if not self.config_dir.exists():
Logger.error(f"Config directory not found: {self.config_dir}")
return False
# 查找所有yaml文件
config_files = list(self.config_dir.glob("*.yaml"))
if not config_files:
Logger.warning(f"No config files found in {self.config_dir}")
return False
Logger.info(f"Found {len(config_files)} config files")
# 加载每个配置文件
for config_file in config_files:
try:
with open(config_file, "r", encoding="utf-8") as f:
config = yaml.safe_load(f)
instance_id = config.get("instance_id")
if not instance_id:
Logger.error(f"Missing instance_id in {config_file}")
continue
self.configs[instance_id] = config
Logger.info(f"Loaded config: {instance_id} from {config_file.name}")
except Exception as e:
Logger.error(f"Failed to load {config_file}: {e}")
continue
Logger.info(f"Successfully loaded {len(self.configs)} strategy configs")
return len(self.configs) > 0
except Exception as e:
Logger.error(f"Failed to load configs: {e}", exc_info=True)
return False
def initialize(self) -> bool:
"""
初始化所有策略实例
Returns:
是否初始化成功
"""
try:
Logger.info("Initializing strategy instances...")
# 先加载配置
if not self.load_configs():
Logger.error("Failed to load strategy configs")
return False
# 创建每个策略实例
for instance_id, config in self.configs.items():
try:
# 提取配置信息
symbol = config.get("symbol")
strategy_class_name = config.get("strategy_class")
params = config.get("params", {})
if not symbol or not strategy_class_name:
Logger.error(f"Invalid config for {instance_id}")
continue
# 动态加载策略类
strategy_class = self._load_strategy_class(strategy_class_name)
if not strategy_class:
Logger.error(
f"Failed to load strategy class: {strategy_class_name}"
)
continue
# 创建策略上下文
context = StrategyContext(
cache_manager=self._cache_manager,
instance_id=instance_id,
symbol=symbol,
instance_config=config,
)
# 创建策略实例(传入context)
strategy_obj = strategy_class(context=context, **params)
# 调用初始化回调
if hasattr(strategy_obj, "on_init"):
strategy_obj.on_init()
# 存储实例
self.instances[instance_id] = strategy_obj
# 建立symbol索引
if symbol not in self.symbol_index:
self.symbol_index[symbol] = []
self.symbol_index[symbol].append((instance_id, strategy_obj))
Logger.info(
f"✓ Created instance: {instance_id} ({strategy_class_name}) for {symbol}"
)
except Exception as e:
Logger.error(
f"Failed to create instance {instance_id}: {e}", exc_info=True
)
continue
# 打印统计信息
Logger.info("=" * 60)
Logger.info("Strategy initialization completed:")
Logger.info(f" Total instances: {len(self.instances)}")
Logger.info(f" Symbols covered: {len(self.symbol_index)}")
for symbol, instances_list in self.symbol_index.items():
Logger.info(f" {symbol}: {len(instances_list)} instance(s)")
Logger.info("=" * 60)
return len(self.instances) > 0
except Exception as e:
Logger.error(f"Failed to initialize: {e}", exc_info=True)
return False
def _load_strategy_class(self, class_name: str):
"""
动态加载策略类
Args:
class_name: 策略类名 (如 "DebugStrategy")
Returns:
策略类或None
"""
try:
# 将类名转换为模块名 (DebugStrategy -> debug_strategy)
module_name = self._class_to_module_name(class_name)
# 导入模块 (src.strategies.debug_strategy)
module_path = f"src.strategies.{module_name}"
module = importlib.import_module(module_path)
# 获取类
strategy_class = getattr(module, class_name)
return strategy_class
except Exception as e:
Logger.error(f"Failed to load strategy class {class_name}: {e}")
return None
def _class_to_module_name(self, class_name: str) -> str:
"""
将类名转换为模块名
DebugStrategy -> debug_strategy
MAStrategy -> ma_strategy
"""
import re
# 驼峰转下划线
s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", class_name)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
def dispatch_kline(self, symbol: str, kline_data: Dict) -> List[Dict]:
"""
分发K线数据到该symbol的所有策略实例
Args:
symbol: 股票代码
kline_data: K线数据字典
Returns:
信号列表: [
{instance_id: "xxx", action: "BUY", ...},
{instance_id: "yyy", action: "SELL", ...}
]
"""
# 查找该symbol的所有策略实例
instances_list = self.symbol_index.get(symbol, [])
if not instances_list:
Logger.debug(f"No strategy instances for {symbol}")
return []
Logger.debug(
f"Dispatching K-line to {len(instances_list)} instances for {symbol}"
)
# 收集所有信号
all_signals = []
for instance_id, strategy_obj in instances_list:
try:
# 调用策略compute方法
result = strategy_obj.compute(kline_data)
if not result:
continue
action = result.get("action", "HOLD")
if action == "HOLD":
continue
# 构建信号(添加instance_id)
signal = {
"instance_id": instance_id,
"symbol": result.get("symbol", symbol),
"action": action,
"price": result.get("price", 0.0),
"quantity": result.get("quantity", 0),
"message": result.get("reason", result.get("message", "")),
}
all_signals.append(signal)
Logger.info(f"Signal from {instance_id}: {action} {symbol}")
except Exception as e:
Logger.error(f"Error in instance {instance_id}: {e}", exc_info=True)
continue
return all_signals
def get_instance(self, instance_id: str) -> Optional[Any]:
"""
获取指定策略实例
Args:
instance_id: 实例ID
Returns:
策略对象或None
"""
return self.instances.get(instance_id)
def get_instances_by_symbol(self, symbol: str) -> List[Tuple[str, Any]]:
"""
获取symbol对应的所有策略实例
Args:
symbol: 股票代码
Returns:
[(instance_id, strategy_obj), ...]
"""
return self.symbol_index.get(symbol, [])
def get_all_instances(self) -> Dict[str, Any]:
"""
获取所有策略实例
Returns:
{instance_id: strategy_object}
"""
return self.instances.copy()
def get_status(self) -> Dict[str, Any]:
"""
获取管理器状态
Returns:
状态字典
"""
return {
"total_instances": len(self.instances),
"symbols": list(self.symbol_index.keys()),
"instances_by_symbol": {
symbol: [inst_id for inst_id, _ in instances]
for symbol, instances in self.symbol_index.items()
},
}

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 LazyLogger
logger = LazyLogger("ConfigLoader")
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,288 +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 LazyLogger
logger = LazyLogger("PositionManager")
@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,254 +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 LazyLogger
logger = LazyLogger("RiskManager")
@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,233 +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 LazyLogger
logger = LazyLogger("StrategyExecutor")
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

@ -1,207 +1,443 @@
"""
"""
策略管理器 (Strategy Manager)
负责管理所有策略实例的创建、缓存和查询
负责:
1. 加载多个策略配置文件 (config/strategies/*.yaml)
2. 实例化策略对象
3. 维护 symbol -> [策略实例] 的映射
4. 分发K线数据到对应策略
5. 聚合所有策略返回的信号
"""
from typing import Dict, List, Tuple, Optional, Type, Any
import re
from typing import Dict, List, Tuple, Any, Optional
from pathlib import Path
import yaml
import importlib
from src.strategy_service.config_loader import ConfigLoader
from src.core.logger import LazyLogger
logger = LazyLogger("StrategyManager")
from src.core.strategy_context import StrategyContext
from src.core.logger import Logger
class StrategyManager:
"""
策略管理器
负责:
- 管理所有策略实例对象
- 根据配置创建策略实例
- 提供策略实例查询接口
- 策略生命周期管理
管理多个策略实例,支持:
- 一个symbol配置多个策略实例
- 策略配置文件独立管理
- 动态加载策略类
"""
def __init__(self, config_loader: ConfigLoader):
def __init__(
self,
config_dir: str,
cache_manager,
):
"""
初始化策略管理器
Args:
config_loader: 配置加载器
config_dir: 策略配置文件目录
cache_manager: 缓存管理器(共享实例)
"""
self.config_loader = config_loader
# 策略实例字典:{instance_id: strategy_object}
self.config_dir = Path(config_dir)
# 直接持有共享资源
self._cache_manager = cache_manager
# 策略实例字典: {instance_id: strategy_object}
self.instances: Dict[str, Any] = {}
# 按股票索引:{symbol: [instance_id1, instance_id2, ...]}
self.symbol_instances: Dict[str, List[str]] = {}
# Symbol索引: {symbol: [(instance_id, strategy_object), ...]}
self.symbol_index: Dict[str, List[Tuple[str, Any]]] = {}
# 配置缓存: {instance_id: config_dict}
self.configs: Dict[str, Dict] = {}
# 存储策略id - > 股票 映射
self.strategy_symbol_map: Dict[str, str] = {}
# 存储策略id - > 策略类名 映射
self.strategy_class_map: Dict[str, str] = {}
# 存储股票 - > 策略id列表 映射
self.symbol_strategy_map: Dict[str, List[str]] = {}
Logger.info(f"StrategyManager initialized with config_dir: {config_dir}")
def load_configs(self) -> bool:
"""
加载所有策略配置文件
Returns:
是否加载成功
"""
try:
if not self.config_dir.exists():
Logger.error(f"Config directory not found: {self.config_dir}")
return False
# 查找所有yaml文件
config_files = list(self.config_dir.glob("*.yaml"))
if not config_files:
Logger.warning(f"No config files found in {self.config_dir}")
return False
Logger.info(f"Found {len(config_files)} config files")
# 加载每个配置文件
for config_file in config_files:
try:
with open(config_file, "r", encoding="utf-8") as f:
config = yaml.safe_load(f)
instance_id = config.get("instance_id")
if not instance_id:
Logger.error(f"Missing instance_id in {config_file}")
continue
self.configs[instance_id] = config
Logger.info(f"Loaded config: {instance_id} from {config_file.name}")
except Exception as e:
Logger.error(f"Failed to load {config_file}: {e}")
continue
Logger.info(f"Successfully loaded {len(self.configs)} strategy configs")
return len(self.configs) > 0
except Exception as e:
Logger.error(f"Failed to load configs: {e}", exc_info=True)
return False
def initialize(self) -> bool:
"""
初始化所有策略实例
根据配置创建每个策略实例对象
Returns:
是否初始化成功
"""
try:
logger.info("Initializing strategy manager...")
Logger.info("Initializing strategy instances...")
for instance_config in self.config_loader.get_all_instances():
instance_id = instance_config["id"]
symbol = instance_config["symbol"]
strategy_class_name = instance_config["strategy_class"]
params = instance_config.get("params", {})
# 先加载配置
if not self.load_configs():
Logger.error("Failed to load strategy configs")
return False
# 获取策略类
strategy_class = self._get_strategy_class(strategy_class_name)
if not strategy_class:
logger.error(
f"Failed to load strategy class: {strategy_class_name}"
)
continue
# 创建策略实例
# 创建每个策略实例
for instance_id, config in self.configs.items():
try:
strategy_obj = strategy_class(**params)
# 提取配置信息
symbol = config.get("symbol")
strategy_class_name = config.get("strategy_class")
params = config.get("params", {})
is_enabled = config.get("is_enabled", True) # 默认启用
if not symbol or not strategy_class_name:
Logger.error(f"Invalid config for {instance_id}")
continue
# 处理 symbol 可能是字符串或列表
if isinstance(symbol, str):
symbols = [symbol]
elif isinstance(symbol, list):
symbols = symbol
else:
Logger.error(
f"Invalid symbol type for {instance_id}: {type(symbol)}"
)
continue
# 动态加载策略类
strategy_class = self._load_strategy_class(strategy_class_name)
if not strategy_class:
Logger.error(
f"Failed to load strategy class: {strategy_class_name}"
)
continue
# 创建策略上下文(传入第一个symbol作为主symbol)
context = StrategyContext(
cache_manager=self._cache_manager,
instance_id=instance_id,
symbol=symbols[0], # 主symbol
instance_config=config,
)
# 创建策略实例(传入context)
strategy_obj = strategy_class(context=context, **params)
# 尝试恢复策略状态
# Todo: 读取状态文件,并初始化
# state_key = f"strategy_state_{instance_id}"
# saved_state = self._cache_manager.get(state_key)
# if saved_state and hasattr(strategy_obj, "restore_state"):
# strategy_obj.restore_state(saved_state)
# Logger.info(f"Restored state for instance: {instance_id}")
# 调用初始化回调
if hasattr(strategy_obj, "on_init"):
strategy_obj.on_init()
# 存储实例
self.instances[instance_id] = strategy_obj
# 建立symbol索引
if symbol not in self.symbol_instances:
self.symbol_instances[symbol] = []
self.symbol_instances[symbol].append(instance_id)
# 为每个symbol建立索引
for sym in symbols:
if sym not in self.symbol_index:
self.symbol_index[sym] = []
self.symbol_index[sym].append((instance_id, strategy_obj))
logger.info(
f"Created strategy instance: {instance_id} "
f"({strategy_class_name}) for {symbol}"
# 记录启用状态
status_icon = "[+]" if is_enabled else "[-]"
status_text = "enabled" if is_enabled else "disabled"
Logger.info(
f"{status_icon} Created instance: {instance_id} ({strategy_class_name}) for {symbols} [{status_text}]"
)
except Exception as e:
logger.error(
f"Failed to create strategy instance {instance_id}: {e}"
Logger.error(
f"Failed to create instance {instance_id}: {e}", exc_info=True
)
continue
logger.info(
f"Strategy manager initialized with {len(self.instances)} instances"
)
return True
# 打印统计信息
Logger.info("=" * 60)
Logger.info("Strategy initialization completed:")
Logger.info(f" Total instances: {len(self.instances)}")
Logger.info(f" Symbols covered: {len(self.symbol_index)}")
for symbol, instances_list in self.symbol_index.items():
Logger.info(f" {symbol}: {len(instances_list)} instance(s)")
Logger.info("=" * 60)
return len(self.instances) > 0
except Exception as e:
logger.error(f"Failed to initialize strategy manager: {e}")
Logger.error(f"Failed to initialize: {e}", exc_info=True)
return False
def _get_strategy_class(self, class_name: str) -> Optional[Type]:
def close(self) -> None:
"""
动态加载策略类
关闭策略管理器,保存所有策略状态
"""
Logger.info("Closing StrategyManager and saving all strategy states...")
for instance_id, strategy_obj in self.instances.items():
try:
# 获取策略状态
if hasattr(strategy_obj, "get_state"):
# state = strategy_obj.get_state()
# Todo: 持久化状态
pass
except Exception as e:
Logger.error(
f"Error saving state for instance {instance_id}: {e}",
exc_info=True,
)
Logger.info("StrategyManager closed.")
def dispatch_klinedata_message(self, message: dict) -> List[Dict]:
"""
分发K线数据到该symbol的所有策略实例
Args:
class_name: 策略类名
message: K线消息字典,格式为 {symbol: kline_data, ...}
Returns:
策略类,如果加载失败返回None
信号列表: [
{instance_id: "xxx", action: "BUY", ...},
{instance_id: "yyy", action: "SELL", ...}
]
"""
try:
# 尝试从strategies模块加载
# 假设策略类在 strategies 目录下,文件名为类名的小写蛇形命名
# 例如: MAStrategy -> ma_strategy.py
module_name = self._class_name_to_module_name(class_name)
module_path = f"strategies.{module_name}"
# 收集所有信号
all_signals = []
module = importlib.import_module(module_path)
strategy_class = getattr(module, class_name)
# 获取K线Symbol和数据
symbols = message.keys()
# 过滤掉不是'xxxxxx.SH, or xxxxxx.SZ'等格式的key
# 正则规则:^开头 + 6位数字 + . + 任意字符(至少1个) + $结尾
pattern = r"^\d{6}\..+$"
# 列表推导式筛选
valid_symbols = [symbol for symbol in symbols if re.match(pattern, symbol)]
return strategy_class
# 遍历每个合法symbol
for symbol in valid_symbols:
# 获取该symbol的K线数据
kline_data = message[symbol]
except Exception as e:
logger.error(f"Failed to load strategy class {class_name}: {e}")
return None
# 获取该symbol对应的策略实例列表
instances_list = self.symbol_index.get(symbol, [])
def _class_name_to_module_name(self, class_name: str) -> str:
"""
将类名转换为模块名
例如: MAStrategy -> ma_strategy
if not instances_list:
Logger.debug(f"No strategy instances for {symbol}")
continue
Args:
class_name: 类名
# 开始分发symbol数据到各个策略实例
for instance_id, strategy_obj in instances_list:
try:
# 检查策略是否启用
config = self.configs.get(instance_id, {})
is_enabled = config.get("is_enabled", True)
Returns:
模块名
"""
# 简单的驼峰转蛇形
import re
if not is_enabled:
Logger.debug(
f"Skipped disabled instance: {instance_id} for {symbol}"
)
continue
s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", class_name)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
# 调用策略compute方法
result = strategy_obj.compute(kline_data)
if not result:
continue
action = result.get("action", "HOLD")
if action == "HOLD":
continue
# 构建信号(添加instance_id)
signal = {
"instance_id": instance_id,
"symbol": result.get("symbol", symbol),
"action": action,
"price": result.get("price", 0.0),
"quantity": result.get("quantity", 0),
"message": result.get("reason", result.get("message", "")),
}
all_signals.append(signal)
Logger.info(f"Signal from {instance_id}: {action} {symbol}")
except Exception as e:
Logger.error(f"Error in instance {instance_id}: {e}", exc_info=True)
continue
return all_signals
def get_instance(self, instance_id: str) -> Optional[Any]:
"""
获取某个策略实例对象
获取指定策略实例
Args:
instance_id: 策略实例ID
instance_id: 实例ID
Returns:
策略实例对象,如果不存在返回None
策略对象或None
"""
return self.instances.get(instance_id)
def get_symbol_instances(self, symbol: str) -> List[Tuple[str, Any]]:
def get_instances_by_symbol(self, symbol: str) -> List[Tuple[str, Any]]:
"""
获取某个股票的所有策略实例
获取symbol对应的所有策略实例
Args:
symbol: 股票代码
Returns:
[(instance_id, strategy_object), ...] 列表
[(instance_id, strategy_obj), ...]
"""
instance_ids = self.symbol_instances.get(symbol, [])
return [
(instance_id, self.instances[instance_id])
for instance_id in instance_ids
if instance_id in self.instances
]
return self.symbol_index.get(symbol, [])
def get_all_instances(self) -> Dict[str, Any]:
"""
获取所有策略实例
Returns:
{instance_id: strategy_object} 字典
{instance_id: strategy_object}
"""
return self.instances
return self.instances.copy()
def reload_instance(self, instance_id: str) -> bool:
def get_status(self) -> Dict[str, Any]:
"""
重新加载某个策略实例
Args:
instance_id: 策略实例ID
获取管理器状态
Returns:
是否成功
状态字典
"""
instance_config = self.config_loader.get_instance_config(instance_id)
if not instance_config:
logger.error(f"Instance config not found: {instance_id}")
return {
"total_instances": len(self.instances),
"symbols": list(self.symbol_index.keys()),
"instances_by_symbol": {
symbol: [inst_id for inst_id, _ in instances]
for symbol, instances in self.symbol_index.items()
},
}
def set_instance_enabled(self, instance_id: str, enabled: bool) -> bool:
"""
动态设置策略实例的启用/禁用状态
Args:
instance_id: 实例ID
enabled: True=启用, False=禁用
Returns:
是否设置成功
"""
if instance_id not in self.configs:
Logger.error(f"Instance {instance_id} not found")
return False
self.configs[instance_id]["is_enabled"] = enabled
status_text = "enabled" if enabled else "disabled"
icon = "[+]" if enabled else "[-]"
Logger.info(f"{icon} Instance {instance_id} is now {status_text}")
return True
def get_instance_status(self, instance_id: str) -> Optional[bool]:
"""
获取策略实例的启用状态
Args:
instance_id: 实例ID
Returns:
True=启用, False=禁用, None=不存在
"""
if instance_id not in self.configs:
return None
return self.configs[instance_id].get("is_enabled", True)
# ==================== 私有方法 ====================
def _load_strategy_class(self, class_name: str):
"""
动态加载策略类
Args:
class_name: 策略类名 (如 "DebugStrategy")
Returns:
策略类或None
"""
try:
strategy_class_name = instance_config["strategy_class"]
params = instance_config.get("params", {})
# 将类名转换为模块名 (DebugStrategy -> debug_strategy)
module_name = self._class_to_module_name(class_name)
strategy_class = self._get_strategy_class(strategy_class_name)
if not strategy_class:
return False
# 导入模块 (src.strategies.debug_strategy)
module_path = f"src.strategies.{module_name}"
module = importlib.import_module(module_path)
strategy_obj = strategy_class(**params)
self.instances[instance_id] = strategy_obj
# 获取类
strategy_class = getattr(module, class_name)
logger.info(f"Reloaded strategy instance: {instance_id}")
return True
return strategy_class
except Exception as e:
logger.error(f"Failed to reload instance {instance_id}: {e}")
return False
Logger.error(f"Failed to load strategy class {class_name}: {e}")
return None
def _class_to_module_name(self, class_name: str) -> str:
"""
将类名转换为模块名
DebugStrategy -> debug_strategy
MAStrategy -> ma_strategy
"""
import re
# 驼峰转下划线
s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", class_name)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()

View File

@ -9,9 +9,7 @@ from datetime import datetime
from dataclasses import dataclass, asdict
import json
from src.core.logger import LazyLogger
logger = LazyLogger("TradeRecorder")
from src.core.logger import Logger
@dataclass
@ -98,7 +96,7 @@ class TradeRecorder:
self.signal_records[instance_id] = []
self.signal_records[instance_id].append(record)
logger.debug(
Logger.debug(
f"Recorded signal: {instance_id} {action} {symbol} {quantity}@{price:.3f}"
)
@ -142,7 +140,7 @@ class TradeRecorder:
self.trade_records[instance_id] = []
self.trade_records[instance_id].append(record)
logger.info(
Logger.info(
f"Recorded trade: {instance_id} {action} {symbol} "
f"{quantity}@{price:.3f}, amount={amount:.2f}"
)
@ -261,7 +259,7 @@ class TradeRecorder:
with open(filepath, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
logger.info(f"Records exported to {filepath}")
Logger.info(f"Records exported to {filepath}")
except Exception as e:
logger.error(f"Failed to export records: {e}")
Logger.error(f"Failed to export records: {e}")

270
test_strategy_manager.py Normal file
View File

@ -0,0 +1,270 @@
"""
测试策略管理器 - 验证多symbol支持
测试内容:
1. 加载包含多个symbol的配置文件
2. 初始化策略实例
3. 验证symbol索引是否正确建立
4. 模拟分发K线数据到多个symbol
"""
import sys
import os
from pathlib import Path
# 添加项目根目录到路径
workspace = Path(__file__).parent
sys.path.insert(0, str(workspace))
from src.core.config import Config
from src.core.logger import Logger
from src.strategy_service.strategy_manager import StrategyManager
from src.cache.cache_manager import CacheManager
def test_strategy_manager():
"""测试策略管理器的多symbol支持"""
print("=" * 80)
print("开始测试策略管理器")
print("=" * 80)
# 1. 初始化配置
print("\n[1] 初始化配置...")
try:
Config.initialize() # 自动读取global.yaml的current_mode
print("[OK] 配置加载成功")
except Exception as e:
print(f"✗ 配置加载失败: {e}")
return False
# 2. 初始化日志
print("\n[2] 初始化日志...")
try:
Logger.initialize(default_name="TestStrategyManager")
print("[OK] 日志初始化成功")
except Exception as e:
print(f"✗ 日志初始化失败: {e}")
return False
# 3. 初始化缓存管理器
print("\n[3] 初始化缓存管理器...")
try:
cache_manager = CacheManager()
print("[OK] 缓存管理器创建成功")
except Exception as e:
print(f"✗ 缓存管理器创建失败: {e}")
return False
# 4. 创建策略管理器
print("\n[4] 创建策略管理器...")
try:
strategy_manager = StrategyManager(
config_dir="configs/strategies", cache_manager=cache_manager
)
print("✓ 策略管理器创建成功")
except Exception as e:
print(f"✗ 策略管理器创建失败: {e}")
return False
# 5. 初始化策略实例
print("\n[5] 初始化策略实例...")
try:
success = strategy_manager.initialize()
if success:
print("[OK] 策略实例初始化成功")
else:
print("✗ 策略实例初始化失败")
return False
except Exception as e:
print(f"✗ 策略实例初始化异常: {e}")
import traceback
traceback.print_exc()
return False
# 6. 检查symbol索引
print("\n[6] 检查symbol索引...")
print(f"总共加载了 {len(strategy_manager.instances)} 个策略实例")
print(f"覆盖了 {len(strategy_manager.symbol_index)} 个symbol")
for symbol, instances_list in strategy_manager.symbol_index.items():
print(f"\n Symbol: {symbol}")
print(f" 策略实例数量: {len(instances_list)}")
for instance_id, strategy_obj in instances_list:
print(f" - {instance_id} ({strategy_obj.__class__.__name__})")
# 7. 测试分发K线数据
print("\n[7] 测试K线数据分发...")
# 构造测试K线数据消息(包含多个symbol,覆盖交叉测试场景)
test_message = {
"600593.SH": { # 只被 debug_000001 监控
"symbol": "600593.SH",
"timestamp": "2026-01-17 14:30:00",
"open": 10.50,
"high": 10.80,
"low": 10.40,
"close": 10.75,
"volume": 1000000,
"amount": 10700000.0,
},
"601288.SH": { # 被 debug_000001, debug_cross_test_1, debug_cross_test_3 监控(交叉)
"symbol": "601288.SH",
"timestamp": "2026-01-17 14:30:00",
"open": 3.20,
"high": 3.25,
"low": 3.18,
"close": 3.22,
"volume": 5000000,
"amount": 16100000.0,
},
"000001.SZ": { # 只被 debug_cross_test_1 监控
"symbol": "000001.SZ",
"timestamp": "2026-01-17 14:30:00",
"open": 11.20,
"high": 11.35,
"low": 11.15,
"close": 11.30,
"volume": 3000000,
"amount": 33800000.0,
},
"600519.SH": { # 只被 debug_cross_test_2 监控
"symbol": "600519.SH",
"timestamp": "2026-01-17 14:30:00",
"open": 1580.00,
"high": 1595.00,
"low": 1575.00,
"close": 1590.00,
"volume": 100000,
"amount": 158700000.0,
},
"600036.SH": { # 只被 debug_cross_test_3 监控
"symbol": "600036.SH",
"timestamp": "2026-01-17 14:30:00",
"open": 38.50,
"high": 38.80,
"low": 38.40,
"close": 38.75,
"volume": 2000000,
"amount": 77400000.0,
},
"meta": { # 非symbol数据,应该被过滤
"type": "kline_data",
"version": "1.0",
},
}
print("\n发送测试K线数据到策略管理器...")
print(
f" 包含symbols: 600593.SH, 601288.SH (交叉), 000001.SZ, 600519.SH, 600036.SH"
)
print(f" 期望行为:")
print(f" - 600593.SH → 触发 debug_000001")
print(
f" - 601288.SH → 触发 debug_000001, debug_cross_test_1, debug_cross_test_3 (交叉)"
)
print(f" - 000001.SZ → 触发 debug_cross_test_1")
print(f" - 600519.SH → 触发 debug_cross_test_2")
print(f" - 600036.SH → 触发 debug_cross_test_3")
try:
signals = strategy_manager.dispatch_klinedata_message(test_message)
print(f"\n✓ K线数据分发成功")
print(f" 返回信号数量: {len(signals)}")
if signals:
print("\n 信号详情:")
for i, signal in enumerate(signals, 1):
print(f" [{i}] {signal}")
else:
print(" (没有生成交易信号,这是正常的,因为DebugStrategy默认不生成信号)")
except Exception as e:
print(f"✗ K线数据分发失败: {e}")
import traceback
traceback.print_exc()
return False
# 8. 打印最终状态
print("\n[8] 策略管理器状态:")
status = strategy_manager.get_status()
print(f" 总实例数: {status['total_instances']}")
print(f" 覆盖symbols: {status['symbols']}")
print(f" Symbol映射:")
for symbol, instance_ids in status["instances_by_symbol"].items():
print(f" {symbol}: {instance_ids}")
# 9. 测试动态开关功能
print("\n" + "=" * 80)
print("[9] 测试动态启用/禁用功能...")
print("=" * 80)
# 9.1 查看当前状态
print("\n9.1 查看所有实例的启用状态:")
for instance_id in strategy_manager.instances.keys():
enabled = strategy_manager.get_instance_status(instance_id)
icon = "[+]" if enabled else "[-]"
status_text = "enabled" if enabled else "disabled"
print(f" {icon} {instance_id}: {status_text}")
# 9.2 禁用 debug_000001
print("\n9.2 禁用 debug_000001...")
strategy_manager.set_instance_enabled("debug_000001", False)
# 9.3 启用 debug_cross_test_2
print("\n9.3 启用 debug_cross_test_2...")
strategy_manager.set_instance_enabled("debug_cross_test_2", True)
# 9.4 再次分发数据,验证开关生效
print("\n9.4 再次分发K线数据,验证动态开关...")
print(" 期望行为:")
print(" - 600593.SH → 不触发(debug_000001已禁用)")
print(
" - 601288.SH → 触发 debug_cross_test_1, debug_cross_test_3(debug_000001已禁用)"
)
print(" - 600519.SH → 触发 debug_cross_test_2(已启用)")
try:
signals = strategy_manager.dispatch_klinedata_message(test_message)
print(f"\n[OK] K线数据分发成功")
print(f" 返回信号数量: {len(signals)}")
if signals:
print("\n 信号详情:")
for i, signal in enumerate(signals, 1):
print(f" [{i}] {signal}")
else:
print(" (没有生成交易信号,这是正常的)")
except Exception as e:
print(f"[ERR] K线数据分发失败: {e}")
import traceback
traceback.print_exc()
return False
# 9.5 验证最终状态
print("\n9.5 验证最终启用状态:")
for instance_id in strategy_manager.instances.keys():
enabled = strategy_manager.get_instance_status(instance_id)
icon = "[+]" if enabled else "[-]"
status_text = "enabled" if enabled else "disabled"
print(f" {icon} {instance_id}: {status_text}")
print("\n" + "=" * 80)
print("[OK] 所有测试通过!")
print("=" * 80)
return True
if __name__ == "__main__":
try:
success = test_strategy_manager()
sys.exit(0 if success else 1)
except Exception as e:
print(f"\n✗ 测试失败: {e}")
import traceback
traceback.print_exc()
sys.exit(1)