主要改动: 1. Config类改为单例模式,支持根据global.yaml的current_mode自动加载环境配置 2. Logger类改为单例模式,通过类方法直接访问 3. 拆分配置文件:global.yaml仅指定模式,backtest.yaml/simulation.yaml/production.yaml存储各环境配置 4. 移除所有config参数传递,使用Config.get()直接访问 5. 移除所有logger实例传递,使用Logger.info()等类方法直接访问 6. 修复初始化顺序:Config.initialize() -> Logger.initialize() -> 其他组件 7. 修复Logger参数默认值,确保所有方法可正常调用 8. 新增三个环境配置文件结构统一,只有参数值不同 9. 客户端URL端口修正为8030(回测)/8020(模拟)/8010(实盘) 配置文件变更: - configs/global.yaml:简化为仅包含current_mode - configs/backtest.yaml:回测环境完整配置 - configs/simulation.yaml:模拟环境完整配置 - configs/production.yaml:实盘环境完整配置 代码重构: - src/core/config.py:单例模式,自动加载环境配置 - src/core/logger.py:单例模式,类方法访问 - 所有模块:移除config/logger参数,使用单例访问
134 lines
4.4 KiB
Python
134 lines
4.4 KiB
Python
"""
|
||
回测引擎 (Backtest Engine)
|
||
|
||
简单的回测引擎类
|
||
"""
|
||
|
||
from typing import List, Optional
|
||
|
||
from src.data_service.data_service import DataService
|
||
from src.backtest.bt_task import BacktestTask
|
||
from src.backtest.bt_client_adapter import BacktestClientAdapter
|
||
from src.core.logger import Logger
|
||
|
||
|
||
class BacktestEngine:
|
||
"""回测引擎"""
|
||
|
||
def __init__(
|
||
self,
|
||
data_service: DataService,
|
||
backtest_client: Optional[BacktestClientAdapter] = None,
|
||
):
|
||
"""
|
||
初始化回测引擎
|
||
|
||
Args:
|
||
data_service: 数据服务实例
|
||
backtest_client: 策略客户端适配器(可选,如果提供则发送数据到策略服务器)
|
||
"""
|
||
self.data_service = data_service
|
||
self.backtest_client = backtest_client
|
||
self.tasks: List[BacktestTask] = [] # 任务列表
|
||
|
||
if self.backtest_client:
|
||
Logger.info("BacktestEngine initialized with BacktestClientAdapter")
|
||
else:
|
||
Logger.info("BacktestEngine initialized without BacktestClientAdapter")
|
||
|
||
def add_task(self, task: BacktestTask) -> None:
|
||
"""
|
||
添加回测任务
|
||
|
||
Args:
|
||
task: 回测任务对象
|
||
"""
|
||
self.tasks.append(task)
|
||
Logger.info(
|
||
f"Task added: {task.strategy_name} on {task.symbols} "
|
||
f"({task.start_date.date()} to {task.end_date.date()}, {task.period})"
|
||
)
|
||
|
||
def get_tasks(self) -> List[BacktestTask]:
|
||
"""
|
||
获取所有任务
|
||
|
||
Returns:
|
||
任务列表
|
||
"""
|
||
return self.tasks
|
||
|
||
def clear_tasks(self) -> None:
|
||
"""清空所有任务"""
|
||
self.tasks.clear()
|
||
Logger.info("All tasks cleared")
|
||
|
||
def run(self) -> None:
|
||
"""运行所有回测任务"""
|
||
if not self.tasks:
|
||
Logger.warning("No tasks to run")
|
||
return
|
||
|
||
Logger.info(f"Starting {len(self.tasks)} backtest task(s)")
|
||
|
||
for task_idx, task in enumerate(self.tasks, 1):
|
||
Logger.info("=" * 60)
|
||
Logger.info(f"Task {task_idx}/{len(self.tasks)}: {task.strategy_name}")
|
||
Logger.info(
|
||
f"Symbols: {task.symbols}, Period: {task.period}, "
|
||
f"Time: {task.start_date.date()}~{task.end_date.date()}"
|
||
)
|
||
|
||
# 1. 获取数据
|
||
data_dict = {}
|
||
for symbol in task.symbols:
|
||
df = self.data_service.get_klines(
|
||
symbol=symbol,
|
||
period=task.period,
|
||
startdate=task.start_date,
|
||
enddate=task.end_date,
|
||
)
|
||
if df is not None and not df.empty:
|
||
data_dict[symbol] = df
|
||
Logger.info(f" {symbol}: {len(df)} records")
|
||
|
||
if not data_dict:
|
||
Logger.error("Data is empty, skipping this task")
|
||
continue
|
||
|
||
# 2. 播放数据
|
||
all_timestamps = set()
|
||
for df in data_dict.values():
|
||
all_timestamps.update(df.index)
|
||
timestamps = sorted(all_timestamps)
|
||
|
||
Logger.info(f"Starting to play {len(timestamps)} timestamps")
|
||
|
||
for idx, timestamp in enumerate(timestamps, 1):
|
||
current_bars = {}
|
||
for symbol, df in data_dict.items():
|
||
if timestamp in df.index:
|
||
current_bars[symbol] = df.loc[timestamp]
|
||
|
||
# 如果配置了BacktestClientAdapter,发送K线数据到策略服务器
|
||
if self.backtest_client:
|
||
for symbol, bar in current_bars.items():
|
||
# 使用send_kline接口,传入period信息
|
||
response = self.backtest_client.send_kline(
|
||
symbol=symbol,
|
||
kline=bar,
|
||
kline_time=timestamp,
|
||
period=task.period,
|
||
)
|
||
# 处理返回信号
|
||
if response is not None:
|
||
Logger.info(f"Received response: {response}")
|
||
|
||
# 每50个时间点输出一次进度
|
||
if idx % 50 == 0:
|
||
Logger.info(f" Progress: {idx}/{len(timestamps)}")
|
||
Logger.info(f"Task {task_idx} completed")
|
||
|
||
Logger.info("=" * 60)
|
||
Logger.info("All backtest tasks completed")
|