Coverage for portfolio/direction_overlay.py: 100%

59 statements  

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

1"""Direction-probability overlay on the cross-sectional rank (V6.4.0, lead L2; default off). 

2 

3The rank heads alone drive the book. If a head's direction probability is calibrated well enough to add information, it is 

4applied here to the percentile ranks the book is built from, in one of two ways, both within each rank group: 

5 

6 blend rank + weight * z(calibrated probability - 0.5), re-ranked to a percentile 

7 agree_filter a long candidate (rank >= the group median) needs p >= 0.5 - margin, a short candidate (below it) 

8 needs p <= 0.5 + margin; a name that disagrees is moved to the group median rank, i.e. out of the book 

9 

10Pure Python (no numpy), so `main.py` and the offline simulator call the same function. `calibration` is the fitted map 

11from `evaluation.probability_calibration` ({"method": "temperature", "temperature": T} or {"method": "isotonic", "x": [...], 

12"y": [...]}); none = the raw probability. 

13""" 

14 

15from __future__ import annotations 

16 

17import math 

18from bisect import bisect_right 

19 

20from portfolio.rank_signal import MAIN_RANK_GROUP, cross_sectional_rank_scores 

21 

22MODES = ("blend", "agree_filter") 

23 

24 

25def resolve_direction_overlay(raw: dict | None) -> dict | None: 

26 """`phase_v2.rank_signal.direction_overlay` -> params, or None when absent / disabled / malformed (the shipped book).""" 

27 if not isinstance(raw, dict) or not bool(raw.get("enabled", False)) or str(raw.get("mode", "")) not in MODES: 

28 return None 

29 return {"mode": str(raw["mode"]), "weight": float(raw.get("weight", 0.0)), "margin": float(raw.get("margin", 0.0)), 

30 "calibration": raw.get("calibration") if isinstance(raw.get("calibration"), dict) else None} 

31 

32 

33def calibrate_probability(probability: float, calibration: dict | None) -> float: 

34 """The fitted map applied to one probability; unknown or missing maps leave it unchanged.""" 

35 p = min(max(float(probability), 1e-12), 1.0 - 1e-12) 

36 if not calibration: 

37 return p 

38 method = calibration.get("method") 

39 if method == "temperature": 

40 temperature = float(calibration.get("temperature", 1.0)) 

41 return 1.0 / (1.0 + math.exp(-math.log(p / (1.0 - p)) / temperature)) if temperature > 0.0 else p 

42 if method == "isotonic": 

43 xs, ys = calibration.get("x") or [], calibration.get("y") or [] 

44 if len(xs) != len(ys) or not xs: 

45 return p 

46 if p <= xs[0]: 

47 return float(ys[0]) 

48 if p >= xs[-1]: 

49 return float(ys[-1]) 

50 right = bisect_right(xs, p) 

51 x0, x1, y0, y1 = xs[right - 1], xs[right], ys[right - 1], ys[right] 

52 return float(y0 + (y1 - y0) * (p - x0) / (x1 - x0)) if x1 > x0 else float(y1) 

53 return p 

54 

55 

56def _z_scores(values: dict[str, float]) -> dict[str, float]: 

57 if len(values) < 2: 

58 return dict.fromkeys(values, 0.0) 

59 mean = sum(values.values()) / len(values) 

60 variance = sum((value - mean) ** 2 for value in values.values()) / (len(values) - 1) 

61 std = math.sqrt(variance) 

62 return dict.fromkeys(values, 0.0) if std <= 1e-12 else {symbol: (value - mean) / std for symbol, value in values.items()} 

63 

64 

65def apply_direction_overlay( 

66 ranks: dict[str, float], probabilities: dict[str, float | None], params: dict | None, 

67 group_by_symbol: dict[str, str] | None = None, 

68) -> dict[str, float]: 

69 """The overlay on one bar's percentile `ranks` ({symbol: rank}); `params` from `resolve_direction_overlay` (None or an 

70 empty rank dict returns `ranks` untouched). Symbols without a probability keep their rank (z = 0 / no filter).""" 

71 if not params or not ranks: 

72 return dict(ranks) 

73 groups: dict[str, dict[str, float]] = {} 

74 for symbol, rank in ranks.items(): 

75 groups.setdefault((group_by_symbol or {}).get(str(symbol), MAIN_RANK_GROUP), {})[symbol] = rank 

76 result: dict[str, float] = {} 

77 for group in groups.values(): 

78 centred = { 

79 symbol: calibrate_probability(probabilities[symbol], params["calibration"]) - 0.5 

80 for symbol in group if probabilities.get(symbol) is not None and math.isfinite(float(probabilities[symbol])) 

81 } 

82 if params["mode"] == "blend": 

83 z = _z_scores(centred) 

84 combined = {symbol: rank + params["weight"] * z.get(symbol, 0.0) for symbol, rank in group.items()} 

85 result.update(cross_sectional_rank_scores(combined) or group) 

86 else: 

87 ordered = sorted(group.values()) 

88 middle = len(ordered) // 2 

89 median = ordered[middle] if len(ordered) % 2 else (ordered[middle - 1] + ordered[middle]) / 2.0 

90 margin = params["margin"] 

91 for symbol, rank in group.items(): 

92 p = centred.get(symbol) 

93 if p is not None and ((rank >= median and p < -margin) or (rank < median and p > margin)): 

94 result[symbol] = median 

95 else: 

96 result[symbol] = rank 

97 return result