同步本地回测与tqsdk回测
This commit is contained in:
@@ -89,9 +89,12 @@ class BacktestEngine:
|
||||
# 主回测循环
|
||||
while True:
|
||||
current_bar = self.data_manager.get_next_bar()
|
||||
|
||||
if current_bar is None:
|
||||
break # 没有更多数据,回测结束
|
||||
|
||||
self.all_bars.append(current_bar)
|
||||
|
||||
if self.start_time and current_bar.datetime < self.start_time:
|
||||
continue
|
||||
|
||||
@@ -104,11 +107,11 @@ class BacktestEngine:
|
||||
# 1. 重置 is_rollover_bar 标记
|
||||
self.is_rollover_bar = False
|
||||
|
||||
# 4. 更新 Context 和 Simulator 的当前 Bar 和时间
|
||||
self.context.set_current_bar(current_bar)
|
||||
self.simulator.update_time(current_time=current_bar.datetime)
|
||||
|
||||
# 2. 如果启用换月模式,并且检测到合约 symbol 变化
|
||||
if current_bar.symbol != self._last_processed_bar_symbol:
|
||||
print(self.roll_over_mode,
|
||||
self._last_processed_bar_symbol,
|
||||
current_bar.symbol, self._last_processed_bar_symbol)
|
||||
if self.roll_over_mode and \
|
||||
self._last_processed_bar_symbol is not None and \
|
||||
current_bar.symbol != self._last_processed_bar_symbol:
|
||||
@@ -141,20 +144,22 @@ class BacktestEngine:
|
||||
# 3. 更新策略关注的当前合约 symbol
|
||||
self.strategy.symbol = current_bar.symbol
|
||||
|
||||
# 4. 更新 Context 和 Simulator 的当前 Bar 和时间
|
||||
self.context.set_current_bar(current_bar)
|
||||
self.simulator.update_time(current_time=current_bar.datetime)
|
||||
|
||||
# 5. 更新引擎内部的历史 Bar 缓存
|
||||
self._history_bars.append(current_bar)
|
||||
if len(self._history_bars) > self._max_history_bars:
|
||||
self._history_bars.pop(0)
|
||||
|
||||
# 6. 处理待撮合订单 (在调用策略 on_bar 之前,确保订单在当前 K 线开盘价撮合)
|
||||
self.simulator.process_pending_orders(current_bar)
|
||||
# self.simulator.process_pending_orders(current_bar)
|
||||
self.strategy.on_open_bar(current_bar)
|
||||
|
||||
# 7. 调用策略的 on_bar 方法
|
||||
self.strategy.on_bar(current_bar)
|
||||
# self.strategy.on_bar(current_bar)
|
||||
self.simulator.process_pending_orders(current_bar)
|
||||
|
||||
self.strategy.on_close_bar(current_bar)
|
||||
self.simulator.process_pending_orders(current_bar)
|
||||
|
||||
|
||||
# 8. 记录投资组合快照
|
||||
current_portfolio_value = self.simulator.get_portfolio_value(current_bar)
|
||||
@@ -170,7 +175,6 @@ class BacktestEngine:
|
||||
price_at_snapshot=price_at_snapshot
|
||||
)
|
||||
self.portfolio_snapshots.append(snapshot)
|
||||
self.all_bars.append(current_bar)
|
||||
|
||||
# 9. 更新 `_last_processed_bar_symbol` 和 `last_processed_bar` 为当前 Bar,为下一轮循环做准备
|
||||
self._last_processed_bar_symbol = current_bar.symbol
|
||||
@@ -221,4 +225,8 @@ class BacktestEngine:
|
||||
}
|
||||
|
||||
def get_simulator(self) -> ExecutionSimulator:
|
||||
return self.simulator
|
||||
return self.simulator
|
||||
|
||||
def get_bar_history(self):
|
||||
return self.all_bars
|
||||
|
||||
|
||||
Reference in New Issue
Block a user