Coverage for src/copytrading_engine/assistant/insights.py: 97%
55 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
1"""What the assistant may know beyond the agent API, read from the existing operator views."""
3import datetime as dt
4from collections import Counter
5from decimal import Decimal
6from typing import Protocol
8from pydantic import BaseModel, ConfigDict
10from copytrading_engine.assistant.wording import plain
11from copytrading_engine.trading.presentation.operator_models import (
12 SourceActivity,
13 SourceActivityPage,
14)
16PAGE = 100
17# An order went out: copied by itself, or approved by the owner from a held call.
18FILLED = {"order_linked", "approved_by_owner"}
19PENDING = "pending"
22class Operator(Protocol):
23 async def source_activity(self, before_seq: int | None, limit: int) -> SourceActivityPage: ...
26class AccountOutcome(BaseModel):
27 model_config = ConfigDict(frozen=True)
28 account_id: str
29 outcome: str
30 reason: str
33class SkipExplanation(BaseModel):
34 model_config = ConfigDict(frozen=True)
35 source_id: str
36 untrusted_source_text: str
37 understood_as: list[str]
38 accounts: list[AccountOutcome]
41class GuruRecord(BaseModel):
42 model_config = ConfigDict(frozen=True)
43 guru_id: str
44 days: int
45 posts: int
46 calls: int
47 copied: int
48 skipped: dict[str, int]
51def _money(value: Decimal) -> str:
52 return f"${value.normalize():f}"
55def _reason(code: str) -> str:
56 if code in FILLED: 56 ↛ 57line 56 didn't jump to line 57 because the condition on line 56 was never true
57 return "An order was placed."
58 if code == PENDING:
59 return "Still being processed."
60 return plain(code) or code
63async def _items(operator: Operator, since: dt.datetime | None = None) -> list[SourceActivity]:
64 items: list[SourceActivity] = []
65 before: int | None = None
66 while True:
67 page = await operator.source_activity(before, PAGE)
68 for item in page.items:
69 if since is not None and item.source_at < since:
70 return items
71 items.append(item)
72 # A page that does not move further back would repeat forever; it is the last one.
73 if page.next_before_seq is None or (before is not None and page.next_before_seq >= before):
74 return items
75 before = page.next_before_seq
78async def guru_record(operator: Operator, guru_id: str, days: int, now: dt.datetime) -> GuruRecord:
79 """Counts per call (a post with instructions): copied when any account linked an order.
81 Every other call that is not still pending adds each distinct skip reason across its
82 accounts once.
83 """
84 since = now - dt.timedelta(days=days)
85 mine = [item for item in await _items(operator, since) if item.guru_id == guru_id]
86 calls = [item for item in mine if item.instructions]
87 copied = 0
88 skipped: Counter[str] = Counter()
89 for item in calls:
90 codes = {code for d in item.destinations for code in d.instruction_outcomes}
91 if codes & FILLED:
92 copied += 1
93 elif PENDING not in codes:
94 skipped.update(codes)
95 return GuruRecord(
96 guru_id=guru_id,
97 days=days,
98 posts=len(mine),
99 calls=len(calls),
100 copied=copied,
101 skipped=dict(skipped),
102 )
105async def explain_skip(operator: Operator, source_id: str) -> SkipExplanation:
106 item = next((i for i in await _items(operator) if i.source_id == source_id), None)
107 if item is None:
108 raise KeyError(source_id)
109 return SkipExplanation(
110 source_id=source_id,
111 untrusted_source_text=item.text,
112 understood_as=[
113 f"{i.action} {i.symbol} at "
114 + (_money(i.price) if i.price is not None else "the market")
115 for i in item.instructions
116 ],
117 accounts=[
118 AccountOutcome(account_id=d.account_id, outcome=code, reason=_reason(code))
119 for d in item.destinations
120 for code in d.instruction_outcomes
121 ],
122 )