Coverage for portfolio/class_sleeve.py: 100%

55 statements  

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

1"""Asset-class sleeves (V5.8.0): a small, separately budgeted long/short book over ONE asset class ranked among itself. 

2 

3V5.7.0 built this for forex only (`portfolio/forex_sleeve.py`). V5.8.0 needs the same structure for bonds: ranked in the 

4equity pool, the 22 bond ETFs mostly expressed a bonds-vs-equities market bet (within-bond holdout IC ~0) and every bond 

5ETF the BT7 book traded lost money. A class sleeve takes the class out of the main book's pool, ranks it among itself, 

6holds `per_side` longs and shorts, and funds each leg with half of its own gross budget. 

7 

8Pure, no I/O, no Lean imports. `main.py` and the research scripts / simulator call the same functions. 

9""" 

10 

11from __future__ import annotations 

12 

13import math 

14from collections.abc import Mapping 

15from dataclasses import dataclass 

16 

17from portfolio.book_construction import BookAllocation 

18 

19 

20@dataclass(frozen=True) 

21class ClassSleeveConfig: 

22 """Settings of one asset-class sleeve: whether it runs, names per side and its weights.""" 

23 asset_class: str 

24 enabled: bool = False 

25 per_side: int = 2 

26 gross_budget: float = 0.0 

27 max_weight_per_name: float | None = None 

28 rebalance_every_bars: int = 20 

29 min_trade_usd: float = 0.0 

30 min_rank_confidence_spread: float = 0.0 

31 hysteresis_rank_margin: float = 0.0 

32 signal: str = "model_rank" # "model_rank" (the blended live score) or "ts_momentum" (features/fx_signals.py) 

33 

34 

35def resolve_class_sleeve_config(asset_class: str, raw: dict | None) -> ClassSleeveConfig: 

36 """Config block (`phase_v2.<class>_sleeve`) -> ClassSleeveConfig. Absent block = disabled.""" 

37 raw = raw or {} 

38 

39 def _number(key: str, default: float) -> float: 

40 try: 

41 value = float(raw.get(key, default)) 

42 except (TypeError, ValueError): 

43 return default 

44 return value if math.isfinite(value) else default 

45 

46 max_weight = _number("max_weight_per_name", _number("max_weight_per_pair", 0.0)) 

47 return ClassSleeveConfig( 

48 asset_class=str(asset_class), 

49 enabled=bool(raw.get("enabled", False)), 

50 per_side=max(1, int(_number("per_side", 2))), 

51 gross_budget=max(0.0, _number("gross_budget", 0.0)), 

52 max_weight_per_name=max_weight if max_weight > 0.0 else None, 

53 rebalance_every_bars=max(1, int(_number("rebalance_every_bars", 20))), 

54 min_trade_usd=max(0.0, _number("min_trade_usd", 0.0)), 

55 min_rank_confidence_spread=max(0.0, _number("min_rank_confidence_spread", 0.0)), 

56 hysteresis_rank_margin=max(0.0, _number("hysteresis_rank_margin", 0.0)), 

57 signal=str(raw.get("signal", "model_rank")) if str(raw.get("signal", "model_rank")) in ("model_rank", "ts_momentum") else "model_rank", 

58 ) 

59 

60 

61def build_class_sleeve_weights( 

62 allocations: Mapping[str, BookAllocation], gross_budget: float, max_weight_per_name: float | None = None 

63) -> dict[str, float]: 

64 """Signed target weight (fraction of NAV) per selected name: each leg gets `gross_budget / 2`, split evenly over its 

65 names, optionally capped per name. A one-sided book (no shorts, no longs) gets {} - a class sleeve is dollar-neutral by 

66 construction, never a directional bet on the class. Non-finite or non-positive budget -> {}.""" 

67 if not allocations or not math.isfinite(float(gross_budget)) or gross_budget <= 0.0: 

68 return {} 

69 longs = [symbol for symbol, allocation in allocations.items() if allocation.role == "long"] 

70 shorts = [symbol for symbol, allocation in allocations.items() if allocation.role == "short"] 

71 if not longs or not shorts: 

72 return {} 

73 cap = abs(float(max_weight_per_name)) if max_weight_per_name else None 

74 weights: dict[str, float] = {} 

75 for legs, sign in ((longs, 1.0), (shorts, -1.0)): 

76 per_name = (gross_budget / 2.0) / len(legs) 

77 if cap is not None: 

78 per_name = min(per_name, cap) 

79 weights.update(dict.fromkeys(legs, sign * per_name)) 

80 return weights 

81 

82 

83def resize_below_minimum(delta_units: float, price: float, min_trade_usd: float) -> bool: 

84 """True when a resize of `delta_units` at `price` is worth less than `min_trade_usd` in notional (a fixed per-order 

85 fee would cost more bps than the move is worth). `min_trade_usd <= 0` disables the check (False). Non-finite inputs -> 

86 True (do not trade on garbage).""" 

87 try: 

88 minimum = float(min_trade_usd) 

89 notional = abs(float(delta_units)) * float(price) 

90 except (TypeError, ValueError): 

91 return True 

92 # V6.6.7 (#374): a NaN minimum compared False both ways and let the trade through; None raised TypeError 

93 if not math.isfinite(minimum): 

94 return True 

95 if minimum <= 0.0: 

96 return False 

97 return (not math.isfinite(notional)) or notional < minimum 

98 

99 

100def sleeve_classes_out_of_main_pool(configs: Mapping[str, ClassSleeveConfig], class_enabled: Mapping[str, bool]) -> frozenset[str]: 

101 """Asset classes that leave the main book's candidate pool: those with an enabled sleeve whose class may trade.""" 

102 return frozenset( 

103 name for name, config in configs.items() if config.enabled and bool(class_enabled.get(name, True)) 

104 )