Coverage for experience/observation_metrics.py: 100%

73 statements  

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

1"""Pure aggregation functions over experience-event dicts (Phase V2-15). 

2 

3Every function here operates on a plain list[dict], where each dict has the 

4same shape as experience.redis_queue.build_experience_event()'s return value 

5(or the JSONB-decoded `payload` column read back from Postgres via 

6`cursor.fetchall()`). There is exactly one implementation shape - callers 

7choose where the list comes from (Redis/in-memory log or a Postgres query), 

8not which function to call. 

9""" 

10 

11from __future__ import annotations 

12 

13from typing import Any 

14 

15import numpy as np 

16 

17SIGNALS = ("buy", "sell", "hold") 

18ACTIONS = ("observe", "simulate", "trade", "reduce_risk", "retrain_candidate") 

19 

20 

21def count_observations(events: list[dict]) -> int: 

22 """The number of observation-mode events.""" 

23 return len(events) 

24 

25 

26def signal_distribution(events: list[dict]) -> dict[str, int]: 

27 """How many observation-mode events carried each signal.""" 

28 counts = dict.fromkeys(SIGNALS, 0) 

29 for event in events: 

30 signal = event.get("signal") 

31 if signal in counts: 

32 counts[signal] += 1 

33 return counts 

34 

35 

36def action_distribution(events: list[dict]) -> dict[str, int]: 

37 """How many observation-mode events took each action.""" 

38 counts = dict.fromkeys(ACTIONS, 0) 

39 for event in events: 

40 action = event.get("action") 

41 if action in counts: 

42 counts[action] += 1 

43 return counts 

44 

45 

46def rejected_by_reason(events: list[dict]) -> dict[str, int]: 

47 """How many observation-mode decisions were rejected for each reason.""" 

48 counts: dict[str, int] = {} 

49 for event in events: 

50 if event.get("action") == "trade": 

51 continue 

52 reasons = (event.get("market_analysis") or {}).get("reasons") or [] 

53 for reason in reasons: 

54 counts[reason] = counts.get(reason, 0) + 1 

55 return counts 

56 

57 

58def _realized_pnls(events: list[dict]) -> list[float]: 

59 pnls = [] 

60 for event in events: 

61 pnl = (event.get("portfolio") or {}).get("last_realized_pnl") 

62 if pnl is not None: 

63 pnls.append(float(pnl)) 

64 return pnls 

65 

66 

67def simulated_win_loss(events: list[dict]) -> dict[str, Any]: 

68 """Wins, losses and win rate of the simulated round trips in observation mode.""" 

69 pnls = _realized_pnls(events) 

70 wins = sum(1 for pnl in pnls if pnl > 0) 

71 losses = sum(1 for pnl in pnls if pnl < 0) 

72 total = wins + losses 

73 return { 

74 "wins": wins, 

75 "losses": losses, 

76 "win_rate": (wins / total) if total > 0 else 0.0, 

77 } 

78 

79 

80def _simulated_equity_series(events: list[dict]) -> list[float]: 

81 return [ 

82 float(event["portfolio"]["total_value"]) 

83 for event in events 

84 if (event.get("portfolio") or {}).get("simulated") and event["portfolio"].get("total_value") is not None 

85 ] 

86 

87 

88def simulated_sharpe(events: list[dict], periods_per_year: int = 252) -> float: 

89 """The annualised Sharpe of the simulated equity in observation mode; 0.0 with fewer than two points.""" 

90 equity_series = _simulated_equity_series(events) 

91 if len(equity_series) < 2: 

92 return 0.0 

93 

94 equity_array = np.asarray(equity_series, dtype=float) 

95 previous = equity_array[:-1] 

96 current = equity_array[1:] 

97 with np.errstate(divide="ignore", invalid="ignore"): 

98 returns = np.where(previous != 0, (current - previous) / previous, 0.0) 

99 

100 std = float(np.std(returns)) 

101 if std == 0.0: 

102 return 0.0 

103 

104 mean = float(np.mean(returns)) 

105 return (mean / std) * (periods_per_year**0.5) 

106 

107 

108def simulated_max_drawdown(events: list[dict]) -> float: 

109 """The largest peak-to-trough fall of the simulated equity in observation mode, as a negative fraction.""" 

110 equity_series = _simulated_equity_series(events) 

111 if not equity_series: 

112 return 0.0 

113 

114 peak = equity_series[0] 

115 max_drawdown = 0.0 

116 for equity in equity_series: 

117 peak = max(peak, equity) 

118 if peak > 0: 

119 drawdown = equity / peak - 1.0 

120 max_drawdown = min(max_drawdown, drawdown) 

121 return max_drawdown 

122 

123 

124def compute_observation_summary(events: list[dict]) -> dict[str, Any]: 

125 """The observation-mode summary the readiness checks read: counts, distributions, rejections and the simulated record.""" 

126 return { 

127 "count_observations": count_observations(events), 

128 "signal_distribution": signal_distribution(events), 

129 "action_distribution": action_distribution(events), 

130 "rejected_by_reason": rejected_by_reason(events), 

131 "simulated_win_loss": simulated_win_loss(events), 

132 "simulated_sharpe": simulated_sharpe(events), 

133 "simulated_max_drawdown": simulated_max_drawdown(events), 

134 }