Coverage for evaluation/tranche_book.py: 100%

61 statements  

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

1"""Staggered tranche book, offline (V6.2.0, todo lead 3 "phase luck", rule R-STAGGER). 

2 

3The shipped book rebalances every 20 sessions on one phase, and which phase it lands on moves its validation Sharpe 

4between -1.02 and +0.57. K tranches - each the same book at 1/K of the gross cap and ceil(top/K) / ceil(bottom/K) 

5names, rebalancing at evenly spread phase offsets (`portfolio.book_construction.tranche_offsets`) - average that timing 

6luck out, the overlapping-portfolio construction of the momentum literature. 

7 

8Offline the tranche book is the SUM of K phase-shifted runs of the calibrated simulator (`simulate_rank_book`), each 

9with `tranche_book_params`'s share of the book: returns are linear in weights, so the sum is the combined book's 

10return, except that (a) trades the tranches would net are each charged (conservative) and (b) the per-name / class / 

11position caps apply per tranche instead of to the sum. The kill switch watches the whole portfolio in live, so each 

12tranche's kill switch is fed the other tranches' returns from a first pass (`kill_switch_extra_returns`, the 

13mechanism V6.1.0 uses for P&L outside a simulation). The legacy signal runs once, in tranche 0, at its full budget. 

14""" 

15 

16from __future__ import annotations 

17 

18import math 

19from dataclasses import replace 

20 

21import numpy as np 

22 

23from evaluation.rank_book_simulator import RankBookSimulationResult, simulate_rank_book 

24from portfolio.book_construction import tranche_book_params, tranche_offsets 

25 

26 

27def tranche_kwargs(kwargs: dict, tranches: int) -> list[dict]: 

28 """The K sub-book kwargs: tranche k's names, gross, position cap and phase (tranche 0 keeps the base phase).""" 

29 count = max(1, int(tranches)) 

30 every = int(kwargs["rebalance_every_bars"]) 

31 base_phase = int(kwargs.get("rebalance_counter_start", 0)) 

32 params = tranche_book_params(int(kwargs["top_n"]), int(kwargs["bottom_n"]), float(kwargs["gross_exposure"]), count, 

33 kwargs.get("max_active_positions")) 

34 subs = [] 

35 for index, offset in enumerate(tranche_offsets(every, count)): 

36 sub = dict(kwargs, top_n=params["top_n"], bottom_n=params["bottom_n"], gross_exposure=params["gross_exposure_cap"], 

37 rebalance_counter_start=(base_phase - offset) % max(1, every)) 

38 if kwargs.get("max_active_positions"): 

39 sub["max_active_positions"] = params["max_active_positions"] 

40 if index > 0: 

41 sub["legacy_component"] = None 

42 subs.append(sub) 

43 return subs 

44 

45 

46def simulate_tranche_book(frame, *, tranches: int = 1, simulate=simulate_rank_book, trading_days_per_year: int = 252, 

47 **kwargs) -> RankBookSimulationResult: 

48 """`simulate_rank_book(frame, **kwargs)` for K = 1; for K > 1 the combined result of K staggered tranches (module 

49 docstring). `simulate` is injectable for tests; the cash sweep sizes from the whole book and is not supported here.""" 

50 if int(tranches) <= 1: 

51 return simulate(frame, **kwargs) 

52 if kwargs.get("cash_sweep"): 

53 raise ValueError("the tranche book is scored ex-sweep (alpha); add the sweep to the combined book instead") 

54 subs = tranche_kwargs(kwargs, tranches) 

55 base_extra = dict(kwargs.get("kill_switch_extra_returns") or {}) 

56 first = [simulate(frame, **sub) for sub in subs] 

57 results = first 

58 if kwargs.get("kill_switch_config"): 

59 returns = [dict(zip(result.per_date, result.per_date_net_return, strict=False)) for result in first] 

60 results = [] 

61 for index, sub in enumerate(subs): 

62 extra = dict(base_extra) 

63 for other, series in enumerate(returns): 

64 if other == index: 

65 continue 

66 for date, value in series.items(): 

67 extra[date] = extra.get(date, 0.0) + value 

68 results.append(simulate(frame, **dict(sub, kill_switch_extra_returns=extra))) 

69 return combine_tranche_results(results, trading_days_per_year=trading_days_per_year) 

70 

71 

72def combine_tranche_results(results: list[RankBookSimulationResult], *, trading_days_per_year: int = 252) -> RankBookSimulationResult: 

73 """One result for the summed tranche book: per-date net returns added, Sharpe / drawdown / totals recomputed from the 

74 sum, turnover / cost / counts added, exposures added, per-component returns added by name.""" 

75 dates = sorted({date for result in results for date in result.per_date}) 

76 by_tranche = [dict(zip(result.per_date, result.per_date_net_return, strict=False)) for result in results] 

77 net = np.asarray([sum(series.get(date, 0.0) for series in by_tranche) for date in dates], dtype=float) 

78 cumulative = np.cumprod(1.0 + net) if len(net) else np.asarray([1.0]) 

79 peak = np.maximum.accumulate(cumulative) 

80 std = float(net.std(ddof=1)) if len(net) > 1 else 0.0 

81 sharpe = float(net.mean() / std * math.sqrt(trading_days_per_year)) if std > 0 else 0.0 

82 components: dict[str, dict[str, float]] = {} 

83 for result in results: 

84 for name, series in (result.per_date_component_returns or {}).items(): 

85 target = components.setdefault(name, {}) 

86 for date, value in series.items(): 

87 target[date] = target.get(date, 0.0) + value 

88 locked = sorted({date for result in results for date in result.kill_switch_locked_date_list}) 

89 veto_reasons: dict[str, int] = {} 

90 for result in results: 

91 for reason, count in result.veto_reasons.items(): 

92 veto_reasons[reason] = veto_reasons.get(reason, 0) + count 

93 return replace( 

94 results[0], 

95 net_sharpe=sharpe, gross_sharpe=sharpe, 

96 net_total_return=float(cumulative[-1] - 1.0), gross_total_return=float(cumulative[-1] - 1.0), 

97 net_max_drawdown=float((cumulative / peak - 1.0).min()) if len(net) else 0.0, 

98 annualized_turnover=sum(result.annualized_turnover for result in results), 

99 cost_drag_annual_bps=sum(result.cost_drag_annual_bps for result in results), 

100 num_rebalances=sum(result.num_rebalances for result in results), 

101 num_dates_used=len(dates), 

102 mean_names_long=sum(result.mean_names_long for result in results), 

103 mean_names_short=sum(result.mean_names_short for result in results), 

104 per_date_net_return=[float(value) for value in net], per_date=dates, 

105 num_vetoed_rebalances=sum(result.num_vetoed_rebalances for result in results), veto_reasons=veto_reasons, 

106 num_kill_switch_locked_dates=len(locked), kill_switch_locked_date_list=locked, 

107 mean_gross_exposure=sum(result.mean_gross_exposure for result in results), 

108 mean_net_exposure=sum(result.mean_net_exposure for result in results), 

109 rebalance_log=[entry for result in results for entry in result.rebalance_log], 

110 weights_log=[], per_date_component_returns=components, 

111 )