实现单品种连续多合约回测
This commit is contained in:
@@ -236,7 +236,7 @@ class ExecutionSimulator:
|
||||
float: 当前的投资组合总价值。
|
||||
"""
|
||||
total_value = self.cash
|
||||
|
||||
|
||||
# 在单品种场景下,我们假设 self.positions 最多只包含一个品种
|
||||
# 并且这个品种就是 current_bar.symbol 所代表的品种
|
||||
symbol_in_position = list(self.positions.keys())[0] if self.positions else None
|
||||
@@ -246,7 +246,7 @@ class ExecutionSimulator:
|
||||
# 持仓市值 = 数量 * 当前市场价格 (current_bar.close)
|
||||
# 无论多头(quantity > 0)还是空头(quantity < 0),这个计算都是正确的
|
||||
total_value += quantity * current_bar.close
|
||||
|
||||
|
||||
# 您也可以选择在这里打印调试信息
|
||||
# print(f" DEBUG Portfolio Value Calculation: Cash={self.cash:.2f}, "
|
||||
# f"Position for {symbol_in_position}: {quantity} @ {current_bar.close:.2f}, "
|
||||
@@ -254,7 +254,7 @@ class ExecutionSimulator:
|
||||
|
||||
# 如果没有持仓,或者持仓品种与当前Bar品种不符 (理论上单品种不会发生)
|
||||
# 那么 total_value 依然是 self.cash
|
||||
|
||||
|
||||
return total_value
|
||||
|
||||
def get_current_positions(self) -> Dict[str, int]:
|
||||
@@ -268,3 +268,22 @@ class ExecutionSimulator:
|
||||
返回所有成交记录的副本。
|
||||
"""
|
||||
return self.trade_log.copy()
|
||||
|
||||
def reset(self, new_initial_capital: float = None, new_initial_positions: Dict[str, int] = None) -> None:
|
||||
"""
|
||||
重置模拟器状态到新的初始条件。
|
||||
可以在总回测开始时调用,或在合约切换时调整资金和持仓。
|
||||
"""
|
||||
print("ExecutionSimulator: 重置状态。")
|
||||
self.cash = new_initial_capital if new_initial_capital is not None else self.initial_capital
|
||||
self.positions = new_initial_positions.copy() if new_initial_positions is not None else {}
|
||||
self.trade_history = []
|
||||
self.current_orders = {}
|
||||
|
||||
def clear_trade_history(self) -> None:
|
||||
"""
|
||||
清空当前模拟器的交易历史。
|
||||
在每个合约片段结束时调用,以便我们只收集当前片段的交易记录。
|
||||
"""
|
||||
print("ExecutionSimulator: 清空交易历史。")
|
||||
self.trade_history = []
|
||||
|
||||
Reference in New Issue
Block a user