简单波动率策略,实现+网格搜索

This commit is contained in:
2025-06-22 23:03:50 +08:00
parent 355e451aac
commit a81a32ce73
19 changed files with 115435 additions and 748 deletions

View File

@@ -36,6 +36,7 @@ class BacktestEngine:
commission_rate (float): 交易佣金率。
"""
self.data_manager = data_manager
self.initial_capital = initial_capital
self.simulator = ExecutionSimulator(
initial_capital=initial_capital,
slippage_rate=slippage_rate,
@@ -76,6 +77,7 @@ class BacktestEngine:
# 设置当前Bar到Context供策略访问
self.context.set_current_bar(current_bar)
self.simulator.update_time(current_time=current_bar.datetime)
# 更新历史Bar缓存
self._history_bars.append(current_bar)
@@ -129,7 +131,7 @@ class BacktestEngine:
for symbol_held, quantity in positions_to_close.items():
if quantity != 0:
print(f"[{last_processed_bar.datetime}] 回测结束平仓: 平仓 {symbol_held} ({quantity} 手) @ {last_processed_bar.close:.2f}")
direction = "SELL" if quantity > 0 else "BUY"
direction = "CLOSE_LONG" if quantity > 0 else "CLOSE_SELL"
volume = abs(quantity)
# 使用当前合约的最后一根Bar的价格进行平仓
@@ -148,6 +150,17 @@ class BacktestEngine:
print(f"总计处理了 {len(self.portfolio_snapshots)} 根K线。")
print(f"总计发生了 {len(self.trade_history)} 笔交易。")
final_portfolio_value = 0.0
if last_processed_bar:
final_portfolio_value = self.simulator.get_portfolio_value(last_processed_bar)
else: # 如果数据为空,或者回测根本没跑,则净值为初始资金
final_portfolio_value = self.initial_capital
total_return_percentage = ((final_portfolio_value - self.initial_capital) / self.initial_capital) * 100
print(f"最终总净值: {final_portfolio_value:.2f}")
print(f"总收益率: {total_return_percentage:.2f}%")
def get_backtest_results(self) -> Dict[str, Any]:
"""
返回回测结果数据,供结果分析模块使用。