Coverage for evaluation/confidence_threshold_calibration.py: 100%

45 statements  

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

1"""Calibrates `phase6.risk.min_confidence_to_trade` (and, when book 

2selection data is available, `phase6.risk.min_confidence_to_trade_book_selected`) 

3from real data (V5.2.6, development/Problems.md) - the same "derive the 

4number, don't guess it" discipline `aq evaluate --calibrate-edge` and 

5`aq evaluate --calibrate-book-spread` already established for 

6`phase_v2.costs.edge_bps_per_rank_unit` and 

7`phase_v2.portfolio_book.min_rank_confidence_spread`. 

8 

9Deliberately reuses, never re-derives: `portfolio.rank_signal.cross_sectional_rank_scores()` 

10(the exact normalization main.py applies before book selection) and 

11`portfolio.book_construction.build_rank_based_book()` (the exact 

12top_n/bottom_n selection main.py's live book uses, for the book-selected 

13split) and `analyzer.market_analyzer.compute_trade_metric()` (the exact 

14confidence-metric formula the live gate compares against 

15min_confidence_to_trade). A calibrated threshold computed here can never 

16silently disagree with what the live gate would have done on the same 

17historical day, because it is the same code, not a parallel 

18approximation. 

19""" 

20 

21from __future__ import annotations 

22 

23import numpy as np 

24import pandas as pd 

25 

26from analyzer.market_analyzer import compute_trade_metric 

27from portfolio.book_construction import build_rank_based_book 

28from portfolio.rank_signal import cross_sectional_rank_scores 

29 

30_CONFIDENCE_DISTRIBUTION_PERCENTILES = {"p10": 0.10, "p25": 0.25, "median": 0.50, "p75": 0.75} 

31 

32 

33def _empty_distribution() -> dict: 

34 return {"min": None, "p10": None, "p25": None, "median": None, "p75": None, "max": None} 

35 

36 

37def _percentile_of_paying_confidence(confidences: list[float], percentile: float) -> tuple[float, dict]: 

38 if not confidences: 

39 return 0.0, _empty_distribution() 

40 array = np.array(confidences, dtype=np.float64) 

41 distribution = {"min": float(np.min(array)), "max": float(np.max(array))} 

42 for name, quantile in _CONFIDENCE_DISTRIBUTION_PERCENTILES.items(): 

43 distribution[name] = float(np.quantile(array, quantile)) 

44 return float(np.quantile(array, percentile)), distribution 

45 

46 

47def calibrate_confidence_threshold( 

48 dataset: pd.DataFrame, 

49 *, 

50 raw_score_column: str, 

51 forward_return_column: str, 

52 ticker_column: str = "ticker", 

53 date_column: str = "date", 

54 top_n: int, 

55 bottom_n: int, 

56 round_trip_cost_fraction: float = 0.001, 

57 percentile: float = 0.10, 

58) -> dict: 

59 """Per date (sorted): normalizes that date's raw scores exactly as 

60 main.py's Pass 1 does (`cross_sectional_rank_scores()`), computes each 

61 symbol's book-member confidence via the SAME formula main.py uses for 

62 a book-selected symbol (`min(1.0, abs(normalized_rank - 0.5) * 2.0)` - 

63 see main.py's Pass 2, `confidence = min(1.0, abs(book_allocation.predicted_rank_20d - 0.5) * 2.0)`), 

64 and separately determines whether that date's natural top_n/bottom_n 

65 selection (`build_rank_based_book()`, no gate, no hysteresis - same 

66 "measure each day's independent natural dispersion" reasoning 

67 `calibrate_book_confidence_spread()` already uses) would have picked 

68 each symbol, for the book-selected/non-book-selected split. 

69 

70 A row "would have been worth taking" when its DIRECTIONAL realized 

71 edge clears round_trip_cost_fraction: `direction = 1 if 

72 normalized_rank >= 0.5 else -1`, `realized_edge = direction * 

73 forward_return - round_trip_cost_fraction`. The calibrated threshold 

74 is the given percentile of confidence AMONG ONLY the rows that 

75 actually paid - the same "percentile of a real, achieved distribution, 

76 not a guess" discipline `calibrate_book_confidence_spread()` already 

77 established, applied to confidence instead of spread. 

78 

79 Returns: 

80 {"calibrated_min_confidence_to_trade": float, 

81 "calibrated_min_confidence_to_trade_book_selected": float, 

82 "percentile": float, 

83 "num_rows_used": int, 

84 "num_rows_used_book_selected": int, 

85 "num_dates_skipped_thin_universe": int, 

86 "confidence_distribution": {...}, 

87 "confidence_distribution_book_selected": {...}} 

88 

89 An empty/all-thin dataset returns both calibrated values as 0.0 (the 

90 gate's own "always trade" no-op value) and all-None distributions, 

91 never raises.""" 

92 paying_confidences: list[float] = [] 

93 paying_confidences_book_selected: list[float] = [] 

94 num_dates_skipped_thin_universe = 0 

95 

96 for _date, group in dataset.groupby(date_column, sort=True): 

97 raw_scores = { 

98 str(ticker): float(score) 

99 for ticker, score in zip(group[ticker_column], group[raw_score_column], strict=False) 

100 if score is not None and not (isinstance(score, float) and np.isnan(score)) 

101 } 

102 normalized = cross_sectional_rank_scores(raw_scores) 

103 if not normalized: 

104 num_dates_skipped_thin_universe += 1 

105 continue 

106 

107 candidates = { 

108 symbol: {"predicted_rank_20d": rank, "trading_eligible": True} for symbol, rank in normalized.items() 

109 } 

110 book_allocations = build_rank_based_book( 

111 candidates, 

112 top_n=top_n, 

113 bottom_n=bottom_n, 

114 min_rank_confidence_spread=0.0, 

115 spread_check_ranks=raw_scores, 

116 ) 

117 book_selected_symbols = set(book_allocations.keys()) 

118 

119 forward_return_by_ticker = { 

120 str(ticker): float(value) 

121 for ticker, value in zip(group[ticker_column], group[forward_return_column], strict=False) 

122 if value is not None and not (isinstance(value, float) and np.isnan(value)) 

123 } 

124 

125 for symbol, normalized_rank in normalized.items(): 

126 forward_return = forward_return_by_ticker.get(symbol) 

127 if forward_return is None: 

128 continue 

129 confidence = compute_trade_metric( 

130 confidence=min(1.0, abs(normalized_rank - 0.5) * 2.0), 

131 regime_confidence=0.0, 

132 topology={}, 

133 liquidity={}, 

134 use_composite_signal_score=False, 

135 ) 

136 direction = 1.0 if normalized_rank >= 0.5 else -1.0 

137 realized_edge = direction * forward_return - round_trip_cost_fraction 

138 if realized_edge > 0.0: 

139 paying_confidences.append(confidence) 

140 if symbol in book_selected_symbols: 

141 paying_confidences_book_selected.append(confidence) 

142 

143 calibrated_general, distribution_general = _percentile_of_paying_confidence(paying_confidences, percentile) 

144 calibrated_book_selected, distribution_book_selected = _percentile_of_paying_confidence( 

145 paying_confidences_book_selected, percentile 

146 ) 

147 

148 return { 

149 "calibrated_min_confidence_to_trade": calibrated_general, 

150 "calibrated_min_confidence_to_trade_book_selected": calibrated_book_selected, 

151 "percentile": percentile, 

152 "num_rows_used": len(paying_confidences), 

153 "num_rows_used_book_selected": len(paying_confidences_book_selected), 

154 "num_dates_skipped_thin_universe": num_dates_skipped_thin_universe, 

155 "confidence_distribution": distribution_general, 

156 "confidence_distribution_book_selected": distribution_book_selected, 

157 }