QTrade/src/backtest/bt_engine.py
cuizhan 61feb5daa0 Add batch kline sending method and fix type hints
- Added send_klines_batch() method in BacktestClientAdapter for sending multiple symbols' klines in one request
- Updated imports to include Dict and List types
- Fixed Pylance type checking warning in xtquant_downloader.py (added type: ignore for xtdc.close())
- Updated bt_engine.py for compatibility with new adapter methods
2025-12-26 17:49:13 +08:00

138 lines
4.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
回测引擎 (Backtest Engine)
简单的回测引擎类
"""
import re
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 get_logger
logger = get_logger("BacktestEngine")
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")