Coverage for src/copytrading_engine/parsing/history.py: 95%

44 statements  

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

1"""The guru's recent calls, as the reader sees them beside a new post (ADR-0010). 

2 

3A guru's book is replayed from the calls the engine copied, each owner correction in place of 

4the reading it corrects: every buy stays open until a sell closes it (by its price, or every buy 

5of the stock when the sell names none). The reader is shown every open buy, however old, and the 

6last few closed calls, by reference (c1, c2, …), stock, price, and size only: never the posts' 

7text, which is the guru's and untrusted. 

8""" 

9 

10import datetime as dt 

11from collections.abc import Iterable 

12from dataclasses import dataclass 

13from decimal import Decimal 

14from typing import Literal 

15 

16from copytrading_engine.shared.signals import Instruction 

17 

18CLOSED_SHOWN = 10 

19 

20 

21@dataclass(frozen=True, slots=True) 

22class PastCall: 

23 """One call the engine copied, or the owner corrected, for this guru.""" 

24 

25 source_key: str 

26 index: int 

27 at: dt.datetime 

28 instruction: Instruction 

29 

30 

31@dataclass(frozen=True, slots=True) 

32class RecentCall: 

33 """A call as the reader is shown it, by a reference it can name in `repeats`.""" 

34 

35 ref: str 

36 source_key: str 

37 index: int 

38 at: dt.datetime 

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

40 symbol: str 

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

42 price: Decimal | None 

43 fraction: Decimal | None 

44 usd_amount: Decimal | None 

45 entry_price: Decimal | None 

46 open: bool 

47 

48 

49def recent_calls(past: Iterable[PastCall]) -> tuple[RecentCall, ...]: 

50 """Every open buy and the last few closed calls, oldest first, numbered c1, c2, …""" 

51 ordered = sorted(past, key=lambda call: (call.at, call.source_key, call.index)) 

52 open_buys: dict[tuple[str, int], PastCall] = {} 

53 closed: list[PastCall] = [] 

54 for call in ordered: 

55 instruction = call.instruction 

56 if instruction.action == "buy": 

57 open_buys[(call.source_key, call.index)] = call 

58 continue 

59 closed.append(call) 

60 if instruction.action != "close": 

61 continue 

62 for key, buy in list(open_buys.items()): 

63 same_stock = buy.instruction.symbol == instruction.symbol 

64 named = ( 

65 instruction.entry_price is None or buy.instruction.price == instruction.entry_price 

66 ) 

67 if same_stock and named: 

68 closed.append(open_buys.pop(key)) 

69 shown = sorted( 

70 [*open_buys.values(), *sorted(closed, key=lambda c: c.at)[-CLOSED_SHOWN:]], 

71 key=lambda call: (call.at, call.source_key, call.index), 

72 ) 

73 still_open = set(open_buys) 

74 return tuple( 

75 RecentCall( 

76 ref=f"c{number}", 

77 source_key=call.source_key, 

78 index=call.index, 

79 at=call.at, 

80 action=call.instruction.action, 

81 symbol=call.instruction.symbol, 

82 price=call.instruction.price, 

83 fraction=call.instruction.fraction, 

84 usd_amount=call.instruction.usd_amount, 

85 entry_price=call.instruction.entry_price, 

86 open=(call.source_key, call.index) in still_open, 

87 ) 

88 for number, call in enumerate(shown, start=1) 

89 ) 

90 

91 

92def describe(calls: tuple[RecentCall, ...], now: dt.datetime) -> str: 

93 """The calls as the reader's instructions list them: fields only, one per line.""" 

94 lines = [] 

95 for call in calls: 

96 minutes = max(0, int((now - call.at).total_seconds() // 60)) 

97 parts = [ 

98 call.ref, 

99 call.action, 

100 call.symbol, 

101 f"at {call.price}" if call.price is not None else "at market", 

102 ] 

103 if call.fraction is not None: 103 ↛ 105line 103 didn't jump to line 105 because the condition on line 103 was always true

104 parts.append(f"share {call.fraction.normalize()}") 

105 if call.entry_price is not None: 105 ↛ 106line 105 didn't jump to line 106 because the condition on line 105 was never true

106 parts.append(f"from the buy at {call.entry_price}") 

107 parts.append("open" if call.open else "closed") 

108 parts.append(f"{minutes} min ago") 

109 lines.append(" · ".join(parts)) 

110 return "\n".join(lines)