Coverage for evaluation/volatility_threshold_calibration.py: 100%

27 statements  

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

1"""Calibrates `phase_v2.topology.elevated_volatility_threshold` per asset class 

2(V5.5.0, Problems.md #129). 

3 

4topology/market_topology.py marks a node "elevated" when its annualized 

5volatility reaches one global cutoff (0.45), and the analyzer's Priority 3 

6then cancels every directional signal for it. Crypto's annualized volatility 

7sits structurally above 0.45, so under a single cutoff BTC/LTC were 

8permanently "elevated": 13 of their 26 book selections in the 2026-08-27 

9backtest died on `topology_elevated_volatility_pressure_overrides_directional_signal`. 

10The cutoff exists to flag a name that is unusually volatile FOR ITS OWN 

11CLASS, so the right level is a per-class percentile of the realized volatility 

12distribution, measured with the exact statistic the topology computes 

13(sample std of the last `window` daily returns x sqrt(252)). 

14 

15Pure pandas/numpy; no I/O. 

16""" 

17 

18from __future__ import annotations 

19 

20import math 

21 

22import numpy as np 

23import pandas as pd 

24 

25ANNUALIZATION_FACTOR = math.sqrt(252) 

26 

27 

28def rolling_annualized_volatility( 

29 frame: pd.DataFrame, 

30 *, 

31 window: int = 24, 

32 ticker_column: str = "ticker", 

33 date_column: str = "date", 

34 close_column: str = "close", 

35) -> pd.Series: 

36 """Per-row annualized volatility of the previous `window` daily returns. 

37 main.py keeps a 25-close deque per symbol, i.e. 24 returns, which is the 

38 default here. Aligned to `frame`'s index; NaN until a full window.""" 

39 ordered = frame.sort_values([ticker_column, date_column]) 

40 returns = ordered.groupby(ticker_column)[close_column].pct_change() 

41 volatility = ( 

42 returns.groupby(ordered[ticker_column]).rolling(window, min_periods=window).std(ddof=1) 

43 .reset_index(level=0, drop=True) 

44 * ANNUALIZATION_FACTOR 

45 ) 

46 return volatility.reindex(frame.index) 

47 

48 

49def calibrate_elevated_volatility_thresholds( 

50 frame: pd.DataFrame, 

51 asset_class_by_ticker: dict[str, str], 

52 *, 

53 percentile: float = 0.80, 

54 window: int = 24, 

55 current_default: float = 0.45, 

56 min_samples: int = 60, 

57 ticker_column: str = "ticker", 

58 date_column: str = "date", 

59 close_column: str = "close", 

60) -> dict: 

61 """Per-asset-class `percentile` of rolling annualized volatility, plus a 

62 `suggested_config` holding only classes whose percentile EXCEEDS 

63 `current_default` (a class already below the global cutoff needs no 

64 override). Classes with fewer than `min_samples` observations are 

65 reported but never suggested.""" 

66 if close_column not in frame.columns: 

67 return {"status": "SKIPPED", "reason": f"no {close_column!r} column in dataset"} 

68 working = frame[[ticker_column, date_column, close_column]].copy() 

69 working["_volatility"] = rolling_annualized_volatility( 

70 frame, window=window, ticker_column=ticker_column, date_column=date_column, close_column=close_column 

71 ) 

72 working["_asset_class"] = working[ticker_column].astype(str).map(asset_class_by_ticker) 

73 working = working.dropna(subset=["_volatility", "_asset_class"]) 

74 

75 by_class: dict[str, dict] = {} 

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

77 for asset_class, group in working.groupby("_asset_class"): 

78 values = group["_volatility"].to_numpy(dtype=float) 

79 # dropna above removed NaN, and a rolling std over a window holding an infinite return is NaN, so every value is finite and a group is non-empty 

80 level = float(np.quantile(values, percentile)) 

81 share_above_default = float((values >= current_default).mean()) 

82 by_class[str(asset_class)] = { 

83 "num_samples": int(values.size), 

84 f"p{int(round(percentile * 100))}": round(level, 4), 

85 "median": round(float(np.median(values)), 4), 

86 "share_at_or_above_current_default": round(share_above_default, 4), 

87 } 

88 if values.size >= min_samples and level > current_default: 

89 suggested[str(asset_class)] = round(level, 4) 

90 

91 return { 

92 "status": "OK", 

93 "percentile": percentile, 

94 "window_returns": window, 

95 "current_default": current_default, 

96 "by_asset_class": by_class, 

97 "suggested_config": {"default": current_default, **dict(sorted(suggested.items()))}, 

98 }