Coverage for src/copytrading_engine/execution/presentation/guru_performance.py: 91%

111 statements  

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

1"""What one guru's copied calls made in one account, read from the ledger and its journal. 

2 

3A closed trade is one filled sell order (the owner's own sale of a copied lot included). The 

4ledger keeps only what each lot holds now, not how each sell was split across its buys, so the 

5journal's fills are replayed through `OwnedLot.reduced`, the same call the ledger made, to learn 

6which buys each sell took from. A lot is trusted only when the replay ends exactly where the 

7ledger's lot is; otherwise its sells are counted as unmatched, never guessed. 

8""" 

9 

10import datetime as dt 

11from collections import defaultdict 

12from dataclasses import dataclass 

13from decimal import Decimal 

14 

15from pydantic import AwareDatetime 

16 

17from copytrading_engine.execution.domain.events import ( 

18 JournalEvent, 

19 LateOrderIncidentOpened, 

20 LateOrderIncidentReopened, 

21 ManualSaleRecorded, 

22 OrderUpdate, 

23) 

24from copytrading_engine.execution.domain.ledger_state import LedgerSnapshot 

25from copytrading_engine.execution.domain.orders import OwnedLot 

26from copytrading_engine.execution.domain.sessions import trade_date 

27from copytrading_engine.execution.domain.values import Money, Value 

28from copytrading_engine.execution.presentation.operator_views import excerpt 

29 

30CENT = Decimal("0.01") 

31ZERO = Decimal(0) 

32 

33# The journal events that carry an order's cumulative fill, which is what the ledger applied. 

34FILL_KINDS = ("order_update", "late_order_incident_opened", "late_order_incident_reopened") 

35REPLAY_KINDS = (*FILL_KINDS, "manual_sale_recorded") 

36 

37 

38class ClosedTrade(Value): 

39 """One sale of copied shares, with the guru's post that bought them.""" 

40 

41 symbol: str 

42 profit_usd: Money 

43 closed_on: dt.date 

44 source_id: str | None 

45 excerpt: str | None 

46 posted_at: AwareDatetime | None 

47 

48 

49class PerformancePoint(Value): 

50 day: dt.date 

51 cumulative_usd: Money 

52 

53 

54class GuruPerformance(Value): 

55 guru_id: str 

56 account_id: str 

57 realized_usd: Money 

58 #: The open copied lots against the broker's price now; None when any of them has no price. 

59 unrealized_usd: Money | None 

60 closed_trades: int 

61 winning_trades: int 

62 #: Sales whose lots the replay could not tell apart; they are in no figure here. 

63 unmatched_sells: int 

64 best: ClosedTrade | None 

65 worst: ClosedTrade | None 

66 #: The realized total at the end of each day that closed a trade, oldest first. 

67 series: tuple[PerformancePoint, ...] 

68 

69 

70@dataclass(slots=True) 

71class _Sale: 

72 """The shares one sell order took from a lot, and what they cost and brought in.""" 

73 

74 lot_key: str 

75 symbol: str 

76 qty: Decimal = ZERO 

77 cost: Decimal = ZERO 

78 proceeds: Decimal = ZERO 

79 last_at: dt.datetime | None = None 

80 priced: bool = True 

81 

82 

83def _lot_as_replayed(final: OwnedLot, held: dict[str, Decimal]) -> OwnedLot: 

84 entries = {entry: held.get(entry, ZERO) for entry in final.entry_remaining} 

85 total = sum(entries.values(), ZERO) 

86 return final.model_copy( 

87 update={ 

88 "entry_remaining": entries, 

89 "remaining_qty": total, 

90 "original_qty": max(final.original_qty, total), 

91 } 

92 ) 

93 

94 

95def _take( 

96 sale: _Sale, 

97 snapshot: LedgerSnapshot, 

98 final: OwnedLot, 

99 held: dict[str, Decimal], 

100 qty: Decimal, 

101 entries: tuple[str, ...] | None, 

102 price: Decimal | None, 

103 at: dt.datetime, 

104) -> bool: 

105 """Reduce the replayed lot as the ledger did, and book what was taken. False when the lot 

106 cannot supply it, which makes the lot unmatched.""" 

107 before = _lot_as_replayed(final, held) 

108 try: 

109 after = before.reduced(qty, entries) 

110 except ValueError: 

111 return False 

112 for entry, left in after.entry_remaining.items(): 

113 taken = before.entry_remaining[entry] - left 

114 held[entry] = left 

115 buy = snapshot.orders.get(entry) 

116 if taken and (buy is None or buy.filled_avg_price is None): 116 ↛ 117line 116 didn't jump to line 117 because the condition on line 116 was never true

117 sale.priced = False 

118 elif taken: 

119 assert buy is not None 

120 assert buy.filled_avg_price is not None 

121 sale.cost += taken * buy.filled_avg_price 

122 if price is None: 122 ↛ 123line 122 didn't jump to line 123 because the condition on line 122 was never true

123 sale.priced = False 

124 else: 

125 sale.proceeds += qty * price 

126 sale.qty += qty 

127 sale.last_at = at 

128 return True 

129 

130 

131def guru_performance( 

132 snapshot: LedgerSnapshot, 

133 events: tuple[JournalEvent, ...], 

134 *, 

135 guru_id: str, 

136 account_id: str, 

137 unrealized_usd: Decimal | None, 

138) -> GuruPerformance: 

139 """`events` are the journal's fills and manual sales, oldest first.""" 

140 lots = { 

141 key: lot 

142 for key, lot in snapshot.lots.items() 

143 if (order := snapshot.orders.get(key)) is not None 

144 and (message := snapshot.messages.get(order.message_id)) is not None 

145 and message.guru == guru_id 

146 } 

147 lot_of = {entry: key for key, lot in lots.items() for entry in lot.entries(key)} 

148 held: dict[str, dict[str, Decimal]] = {key: {} for key in lots} 

149 sales: dict[str, _Sale] = {} 

150 broken: set[str] = set() 

151 filled: dict[str, Decimal] = defaultdict(lambda: ZERO) 

152 

153 for event in events: 

154 payload = event.payload 

155 if isinstance(payload, OrderUpdate | LateOrderIncidentOpened | LateOrderIncidentReopened): 

156 order = snapshot.orders.get(payload.client_id) 

157 delta = payload.filled_qty - filled[payload.client_id] 

158 filled[payload.client_id] = payload.filled_qty 

159 if order is None or delta <= 0: 159 ↛ 160line 159 didn't jump to line 160 because the condition on line 159 was never true

160 continue 

161 if order.side == "buy": 

162 key = lot_of.get(order.client_id) 

163 if key is not None: 

164 held[key][order.client_id] = held[key].get(order.client_id, ZERO) + delta 

165 continue 

166 key = order.lot_id if order.lot_id in lots else None 

167 if key is None: 

168 continue 

169 final = lots[key] 

170 before = _lot_as_replayed(final, held[key]) 

171 # As the ledger applies a fill: no more than the buys the sell named hold. 

172 available = ( 

173 before.remaining_of(order.from_entries) 

174 if order.from_entries 

175 else before.remaining_qty 

176 ) 

177 applied = min(delta, available) 

178 sale = sales.setdefault(order.client_id, _Sale(lot_key=key, symbol=order.symbol)) 

179 if applied < delta or not _take( 

180 sale, 

181 snapshot, 

182 final, 

183 held[key], 

184 applied, 

185 order.from_entries or None, 

186 order.filled_avg_price, 

187 event.at, 

188 ): 

189 broken.add(key) 

190 elif isinstance(payload, ManualSaleRecorded): 190 ↛ 153line 190 didn't jump to line 153 because the condition on line 190 was always true

191 sold = payload.sale 

192 if sold.lot_id not in lots: 192 ↛ 193line 192 didn't jump to line 193 because the condition on line 192 was never true

193 continue 

194 key = sold.lot_id 

195 sale = sales.setdefault( 

196 sold.order.client_order_id, _Sale(lot_key=key, symbol=sold.order.symbol) 

197 ) 

198 if not _take( 198 ↛ 208line 198 didn't jump to line 208 because the condition on line 198 was never true

199 sale, 

200 snapshot, 

201 lots[key], 

202 held[key], 

203 sold.order.filled_qty, 

204 None, 

205 sold.order.filled_avg_price, 

206 event.at, 

207 ): 

208 broken.add(key) 

209 

210 # A lot is trusted only if the replay ends where the ledger's lot is. 

211 for key, lot in lots.items(): 

212 if {e: held[key].get(e, ZERO) for e in lot.entry_remaining} != lot.entry_remaining: 

213 broken.add(key) 

214 

215 trades: list[ClosedTrade] = [] 

216 unmatched = 0 

217 for sale in sales.values(): 

218 if sale.lot_key in broken or not sale.priced or sale.last_at is None: 

219 unmatched += 1 

220 continue 

221 opening = snapshot.orders[sale.lot_key] 

222 message = snapshot.messages[opening.message_id] 

223 trades.append( 

224 ClosedTrade( 

225 symbol=sale.symbol, 

226 profit_usd=(sale.proceeds - sale.cost).quantize(CENT), 

227 closed_on=trade_date(sale.last_at), 

228 source_id=message.key, 

229 excerpt=excerpt(message.text), 

230 posted_at=message.timestamp, 

231 ) 

232 ) 

233 trades.sort(key=lambda trade: trade.closed_on) 

234 by_day: dict[dt.date, Decimal] = defaultdict(lambda: ZERO) 

235 for trade in trades: 

236 by_day[trade.closed_on] += trade.profit_usd 

237 running = ZERO 

238 series: list[PerformancePoint] = [] 

239 for day in sorted(by_day): 

240 running += by_day[day] 

241 series.append(PerformancePoint(day=day, cumulative_usd=running)) 

242 return GuruPerformance( 

243 guru_id=guru_id, 

244 account_id=account_id, 

245 realized_usd=running, 

246 unrealized_usd=unrealized_usd, 

247 closed_trades=len(trades), 

248 winning_trades=sum(1 for trade in trades if trade.profit_usd > 0), 

249 unmatched_sells=unmatched, 

250 best=max(trades, key=lambda trade: trade.profit_usd) if trades else None, 

251 worst=min(trades, key=lambda trade: trade.profit_usd) if trades else None, 

252 series=tuple(series), 

253 )