Coverage for experience/simulated_portfolio.py: 100%

85 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""In-memory simulated portfolio for Phase V2-15 (Observation Mode). 

2 

3SimulatedPortfolioState never references self.Portfolio, QCAlgorithm, or any 

4broker/Lean object - it is a plain Python bookkeeping class fed hypothetical 

5fill prices computed by execution.order_gate.simulate_fill. Its snapshot() 

6output is a strict superset of the real portfolio dict already passed to 

7experience.redis_queue.build_experience_event(portfolio=...), so that 

8function's signature never needs to change. 

9""" 

10 

11from __future__ import annotations 

12 

13from typing import Any 

14 

15from execution.order_gate import simulate_fill 

16 

17 

18class SimulatedPortfolioState: 

19 """Tracks fake cash/holdings/equity for a single algorithm run.""" 

20 

21 def __init__(self, initial_cash: float) -> None: 

22 self.initial_cash = float(initial_cash) 

23 self.cash = float(initial_cash) 

24 self.holdings: dict[str, dict[str, float]] = {} 

25 self.peak_equity = float(initial_cash) 

26 self.cumulative_turnover = 0.0 

27 self.equity_curve: list[dict] = [] 

28 self.trade_log: list[dict] = [] 

29 self._last_prices: dict[str, float] = {} 

30 self._last_realized_pnl: float | None = None 

31 

32 def _equity(self) -> float: 

33 holdings_value = sum( 

34 holding["quantity"] * self._last_prices.get(symbol_key, holding["avg_price"]) 

35 for symbol_key, holding in self.holdings.items() 

36 ) 

37 return self.cash + holdings_value 

38 

39 def _exposure(self) -> float: 

40 equity = self._equity() 

41 if equity <= 0: 

42 return 0.0 

43 holdings_value = sum( 

44 abs(holding["quantity"] * self._last_prices.get(symbol_key, holding["avg_price"])) 

45 for symbol_key, holding in self.holdings.items() 

46 ) 

47 return holdings_value / equity 

48 

49 def enter_long( 

50 self, 

51 symbol_key: str, 

52 close_price: float, 

53 target_weight: float, 

54 bar_index: int, 

55 slippage_bps: float = 0.0, 

56 ) -> None: 

57 self._last_prices[symbol_key] = close_price 

58 equity = self._equity() 

59 fill = simulate_fill( 

60 close_price=close_price, target_weight=target_weight, equity=equity, slippage_bps=slippage_bps 

61 ) 

62 

63 existing = self.holdings.get(symbol_key, {"quantity": 0.0, "avg_price": close_price}) 

64 delta_quantity = fill["quantity"] - existing["quantity"] 

65 self.cash -= delta_quantity * fill["fill_price"] 

66 self.cumulative_turnover += abs(delta_quantity * fill["fill_price"]) 

67 

68 self.holdings[symbol_key] = {"quantity": fill["quantity"], "avg_price": fill["fill_price"]} 

69 self._last_realized_pnl = None 

70 self.trade_log.append( 

71 { 

72 "bar_index": bar_index, 

73 "symbol": symbol_key, 

74 "action": "enter_long", 

75 "quantity": fill["quantity"], 

76 "price": fill["fill_price"], 

77 "realized_pnl": None, 

78 } 

79 ) 

80 

81 def exit(self, symbol_key: str, close_price: float, bar_index: int) -> None: 

82 self._last_prices[symbol_key] = close_price 

83 holding = self.holdings.pop(symbol_key, None) 

84 if holding is None or holding["quantity"] == 0: 

85 return 

86 

87 realized_pnl = (close_price - holding["avg_price"]) * holding["quantity"] 

88 proceeds = holding["quantity"] * close_price 

89 self.cash += proceeds 

90 self.cumulative_turnover += abs(proceeds) 

91 self._last_realized_pnl = realized_pnl 

92 

93 self.trade_log.append( 

94 { 

95 "bar_index": bar_index, 

96 "symbol": symbol_key, 

97 "action": "exit", 

98 "quantity": holding["quantity"], 

99 "price": close_price, 

100 "realized_pnl": realized_pnl, 

101 } 

102 ) 

103 

104 def exit_using_last_known_price(self, symbol_key: str, bar_index: int) -> None: 

105 """Sibling of exit() (needs an explicit close_price, unavailable to 

106 main.py's per-bar asset-class-disablement sweep - it runs before 

107 Pass 1 builds this bar's close prices) and liquidate_all() (which 

108 already solves this exact problem for the whole portfolio via 

109 self._last_prices' per-symbol fallback, for the total-drawdown- 

110 breach path). This is liquidate_all()'s SELECTIVE sibling, exiting 

111 only symbol_key instead of every holding - delegates to exit() so 

112 there is exactly one place the realized-pnl/cash/trade_log math 

113 lives. No-op if symbol_key isn't currently held.""" 

114 holding = self.holdings.get(symbol_key) 

115 if holding is None or holding["quantity"] == 0: 

116 return 

117 close_price = self._last_prices.get(symbol_key, holding["avg_price"]) 

118 self.exit(symbol_key, close_price, bar_index) 

119 

120 def liquidate_all(self, bar_index: int) -> None: 

121 total_realized_pnl = 0.0 

122 for symbol_key in list(self.holdings.keys()): 

123 holding = self.holdings.pop(symbol_key) 

124 close_price = self._last_prices.get(symbol_key, holding["avg_price"]) 

125 realized_pnl = (close_price - holding["avg_price"]) * holding["quantity"] 

126 proceeds = holding["quantity"] * close_price 

127 self.cash += proceeds 

128 self.cumulative_turnover += abs(proceeds) 

129 total_realized_pnl += realized_pnl 

130 self.trade_log.append( 

131 { 

132 "bar_index": bar_index, 

133 "symbol": symbol_key, 

134 "action": "liquidate_all", 

135 "quantity": holding["quantity"], 

136 "price": close_price, 

137 "realized_pnl": realized_pnl, 

138 } 

139 ) 

140 

141 if self.trade_log and self.trade_log[-1]["bar_index"] == bar_index: 

142 self._last_realized_pnl = total_realized_pnl 

143 

144 def mark_to_market(self, prices_by_symbol: dict[str, float], bar_index: int | None = None) -> None: 

145 self._last_prices.update(prices_by_symbol) 

146 equity = self._equity() 

147 self.peak_equity = max(self.peak_equity, equity) 

148 self.equity_curve.append( 

149 { 

150 "bar_index": bar_index, 

151 "equity": equity, 

152 "cash": self.cash, 

153 "exposure": self._exposure(), 

154 "drawdown": self._drawdown(equity), 

155 } 

156 ) 

157 

158 def position_value(self, symbol_key: str) -> float: 

159 """Current mark-to-market notional value of a held symbol, 0.0 if flat.""" 

160 holding = self.holdings.get(symbol_key) 

161 if holding is None: 

162 return 0.0 

163 price = self._last_prices.get(symbol_key, holding["avg_price"]) 

164 return holding["quantity"] * price 

165 

166 def _drawdown(self, equity: float) -> float: 

167 if self.peak_equity <= 0: 

168 return 0.0 

169 return equity / self.peak_equity - 1.0 

170 

171 def snapshot(self, consume_realized_pnl: bool = True) -> dict[str, Any]: 

172 """Portfolio snapshot compatible with build_experience_event(portfolio=...). 

173 

174 By default this consumes (clears) the pending realized-PnL value so 

175 it is attributed to exactly one experience event rather than bleeding 

176 into later, unrelated snapshots. 

177 """ 

178 equity = self._equity() 

179 last_realized_pnl = self._last_realized_pnl 

180 if consume_realized_pnl: 

181 self._last_realized_pnl = None 

182 

183 return { 

184 "total_value": equity, 

185 "cash": self.cash, 

186 "current_drawdown": self._drawdown(equity), 

187 "simulated": True, 

188 "holdings_value": equity - self.cash, 

189 "exposure": self._exposure(), 

190 "turnover_to_date": self.cumulative_turnover, 

191 "peak_equity": self.peak_equity, 

192 "last_realized_pnl": last_realized_pnl, 

193 }