Coverage for src/copytrading_engine/trading/domain/profiles.py: 92%

97 statements  

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

1"""Guru profiles (learned playbook) and read-only evaluation.""" 

2 

3import hashlib 

4import json 

5from collections.abc import Sequence 

6from decimal import ROUND_DOWN, Decimal 

7from typing import Literal, Self 

8 

9from pydantic import BaseModel, ConfigDict, Field, model_validator 

10 

11from copytrading_engine.execution.domain.risk import requested_entry_budget 

12from copytrading_engine.execution.domain.sizing import RouteConnection 

13from copytrading_engine.parsing.application import transform 

14from copytrading_engine.parsing.extraction import Decoder 

15from copytrading_engine.parsing.routes import Route 

16from copytrading_engine.shared.raw_message import RawMessage 

17from copytrading_engine.shared.signals import Instruction 

18 

19type ExitBasis = Literal["original_position", "remaining_position"] 

20PROFILE_EVALUATION_COST_NOTICE = ( 

21 "Model calls use the configured provider; provider charges may apply." 

22) 

23 

24 

25PLAYBOOK_MAX_LENGTH = 8_000 

26 

27 

28class ProfileDraft(BaseModel): 

29 """What the owner saves for one guru: a playbook prompt. 

30 

31 The playbook is owner-written (usually edited from a learned draft) and reaches the model as 

32 trusted guidance. It never bypasses grounding: a ticker must appear in the post itself, or the 

33 playbook must state the name-to-ticker mapping. 

34 """ 

35 

36 model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True) 

37 

38 guru_id: str = Field(pattern=r"^[a-zA-Z0-9_-]{1,64}$") 

39 display_name: str = Field(min_length=1, max_length=100) 

40 playbook: str = Field(max_length=PLAYBOOK_MAX_LENGTH) 

41 

42 @model_validator(mode="after") 

43 def validate_inputs(self) -> Self: 

44 if not self.display_name.strip(): 

45 raise ValueError("Profile name is required") 

46 return self 

47 

48 

49class LearnedPlaybook(BaseModel): 

50 """A draft for the owner to edit: nothing here is saved or used until they save the profile.""" 

51 

52 model_config = ConfigDict(extra="forbid", frozen=True) 

53 

54 posts_read: int = Field(ge=0) 

55 playbook: str = Field(max_length=PLAYBOOK_MAX_LENGTH) 

56 summary: str 

57 provider: str 

58 model: str 

59 cost_notice: str = PROFILE_EVALUATION_COST_NOTICE 

60 

61 

62def _profile_digest(data: dict[str, object]) -> str: 

63 encoded = json.dumps(data, sort_keys=True, separators=(",", ":"), ensure_ascii=False) 

64 return hashlib.sha256(encoded.encode()).hexdigest() 

65 

66 

67class ProfileRevision(BaseModel): 

68 """Immutable, content-addressed interpretation settings for one stable guru.""" 

69 

70 model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True) 

71 

72 guru_id: str = Field(pattern=r"^[a-zA-Z0-9_-]{1,64}$") 

73 display_name: str = Field(min_length=1, max_length=100) 

74 playbook: str = Field(max_length=PLAYBOOK_MAX_LENGTH) 

75 profile_revision: str = Field(pattern=r"^[0-9a-f]{64}$") 

76 

77 @model_validator(mode="after") 

78 def validate_revision(self) -> Self: 

79 base = self.model_dump(mode="json", exclude={"profile_revision"}) 

80 if self.profile_revision != _profile_digest(base): 80 ↛ 81line 80 didn't jump to line 81 because the condition on line 80 was never true

81 raise ValueError("Profile revision does not match its immutable content") 

82 return self 

83 

84 def route(self) -> Route: 

85 """How the reader and its rules treat this guru's posts.""" 

86 return Route( 

87 playbook=self.playbook, guru_id=self.guru_id, profile_revision=self.profile_revision 

88 ) 

89 

90 

91class ProfileBuilder: 

92 """Build content-addressed profile revisions.""" 

93 

94 def build(self, draft: ProfileDraft) -> ProfileRevision: 

95 draft = ProfileDraft.model_validate(draft.model_dump()) 

96 data = draft.model_dump(mode="json") 

97 return ProfileRevision(**data, profile_revision=_profile_digest(data)) 

98 

99 def prepared_profiles(self) -> tuple[ProfileRevision, ...]: 

100 return ( 

101 self.build( 

102 ProfileDraft( 

103 guru_id="prepared-standard", 

104 display_name="Standard stock alerts", 

105 playbook="", 

106 ) 

107 ), 

108 ) 

109 

110 

111class InstructionEvaluation(BaseModel): 

112 model_config = ConfigDict(extra="forbid", frozen=True) 

113 

114 action: Literal["buy", "reduce", "close"] 

115 symbol: str 

116 # None for a sell at the market (ADR-0007). 

117 price: Decimal | None 

118 fraction: Decimal | None 

119 entry_price: Decimal | None 

120 exit_basis: ExitBasis | None 

121 action_evidence: str 

122 symbol_evidence: str 

123 price_evidence: str | None 

124 fraction_evidence: str | None 

125 # A buy sized in dollars ("$200 of NFLX"), and the post's words for it. 

126 usd_amount: Decimal | None = None 

127 usd_amount_evidence: str | None = None 

128 

129 

130class DestinationEvaluation(BaseModel): 

131 model_config = ConfigDict(extra="forbid", frozen=True) 

132 

133 account_id: str 

134 action: Literal["buy", "reduce", "close"] 

135 symbol: str 

136 budget_usd: Decimal | None 

137 estimated_quantity: Decimal | None 

138 exit_basis: ExitBasis | None 

139 reason: str 

140 

141 

142def size_destinations( 

143 instructions: Sequence[Instruction | InstructionEvaluation], 

144 destinations: Sequence[RouteConnection], 

145) -> tuple[DestinationEvaluation, ...]: 

146 """What each account would do with each instruction: a buy's budget and shares after the 

147 owner's limits; a sell takes from what the account holds. Nothing is placed.""" 

148 evaluations: list[DestinationEvaluation] = [] 

149 for connection in destinations: 

150 for instruction in instructions: 

151 if instruction.action == "buy": 151 ↛ 176line 151 didn't jump to line 176 because the condition on line 151 was always true

152 assert instruction.price is not None # a buy always has the guru's price 

153 # A call with no size buys the account's largest single buy, which the app shows. 

154 sized = requested_entry_budget( 

155 connection, instruction.fraction, instruction.usd_amount, unsized_usd=None 

156 ) 

157 quantity = ( 

158 (sized.budget / instruction.price).quantize( 

159 Decimal("0.000001"), rounding=ROUND_DOWN 

160 ) 

161 if sized.budget is not None 

162 else None 

163 ) 

164 evaluations.append( 

165 DestinationEvaluation( 

166 account_id=connection.account_id, 

167 action=instruction.action, 

168 symbol=instruction.symbol, 

169 budget_usd=sized.budget, 

170 estimated_quantity=quantity, 

171 exit_basis=None, 

172 reason=sized.reason, 

173 ) 

174 ) 

175 else: 

176 evaluations.append( 

177 DestinationEvaluation( 

178 account_id=connection.account_id, 

179 action=instruction.action, 

180 symbol=instruction.symbol, 

181 budget_usd=None, 

182 estimated_quantity=None, 

183 exit_basis=instruction.exit_basis, 

184 reason="sells_from_holdings", 

185 ) 

186 ) 

187 return tuple(evaluations) 

188 

189 

190class ProfileEvaluation(BaseModel): 

191 model_config = ConfigDict(extra="forbid", frozen=True) 

192 

193 message_identity: str 

194 guru_id: str 

195 profile_revision: str 

196 provider: str 

197 model: str 

198 decision: Literal["trade", "ignore", "review"] 

199 reason: str 

200 simulated: Literal[True] = True 

201 no_order: Literal[True] = True 

202 cost_notice: str = PROFILE_EVALUATION_COST_NOTICE 

203 instructions: tuple[InstructionEvaluation, ...] = () 

204 destinations: tuple[DestinationEvaluation, ...] = () 

205 review_reasons: tuple[str, ...] = () 

206 

207 

208class ProfileEvaluationService: 

209 """Interpret one historical message and size destinations without execution.""" 

210 

211 def __init__(self, decoder: Decoder, *, provider: str, model: str) -> None: 

212 if not provider or not model: 212 ↛ 213line 212 didn't jump to line 213 because the condition on line 212 was never true

213 raise ValueError("Provider and model identity are required") 

214 self._decoder = decoder 

215 self.provider = provider 

216 self.model = model 

217 

218 async def evaluate( 

219 self, 

220 message: RawMessage, 

221 profile: ProfileRevision, 

222 *, 

223 destinations: tuple[RouteConnection, ...], 

224 ) -> ProfileEvaluation: 

225 message = RawMessage.model_validate(message.model_dump()) 

226 if len(destinations) > 20 or len({item.account_id for item in destinations}) != len( 226 ↛ 229line 226 didn't jump to line 229 because the condition on line 226 was never true

227 destinations 

228 ): 

229 raise ValueError("Evaluation destinations must be unique and bounded") 

230 signal = await transform(message, profile.route(), self._decoder, self.model) 

231 instructions = tuple( 

232 InstructionEvaluation( 

233 action=item.action, 

234 symbol=item.symbol, 

235 price=item.price, 

236 fraction=item.fraction, 

237 usd_amount=item.usd_amount, 

238 entry_price=item.entry_price, 

239 exit_basis=item.exit_basis, 

240 action_evidence=item.action_evidence, 

241 symbol_evidence=item.symbol_evidence, 

242 price_evidence=item.price_evidence, 

243 fraction_evidence=item.fraction_evidence, 

244 usd_amount_evidence=item.usd_amount_evidence, 

245 ) 

246 for item in signal.evidence 

247 ) 

248 evaluations = size_destinations(instructions, destinations) 

249 review_reasons = [signal.reason] if signal.decision == "review" else [] 

250 review_reasons += [ 

251 item.reason 

252 for item in evaluations 

253 if item.action == "buy" and item.reason not in {"ready", "unsized_buy"} 

254 ] 

255 return ProfileEvaluation( 

256 message_identity=message.identity, 

257 guru_id=profile.guru_id, 

258 profile_revision=profile.profile_revision, 

259 provider=self.provider, 

260 model=self.model, 

261 decision=signal.decision, 

262 reason=signal.reason, 

263 instructions=instructions, 

264 destinations=evaluations, 

265 review_reasons=tuple(dict.fromkeys(review_reasons)), 

266 )