Coverage for portfolio/hrp_allocation.py: 100%
85 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""V5.4.3 - Hierarchical Risk Parity (HRP) allocation.
3Implements López de Prado (2016)'s HRP algorithm as an alternative to the
4current equal-rank long/short allocation. Builds a correlation-distance
5dendrogram via scipy's linkage, then allocates by inverse-variance within
6each cluster using a top-down recursive bisection.
8Config-gated: `phase_v2.portfolio_book.allocation_method: "hrp"` (default
9`"rank"` = byte-identical equal-rank behavior). Pure numpy/scipy — no I/O,
10no torch."""
12from __future__ import annotations
14import math
16import numpy as np
17import pandas as pd
19LINKAGE_METHODS = ("ward", "single", "average", "complete")
22def compute_hrp_weights(returns: pd.DataFrame, linkage_method: str = "ward") -> pd.Series:
23 """Computes HRP weights from a (dates × tickers) returns DataFrame.
25 Steps:
26 1. Correlation distance matrix: d = sqrt(0.5 * (1 - corr))
27 2. Hierarchical clustering (`linkage_method` on the condensed distance; López de Prado uses "single")
28 3. Quasi-diagonal ordering via dendrogram leaf order
29 4. Top-down recursive bisection: split each cluster by inverse-variance
31 A column with no variance (a flat or empty series) has no inverse variance, so it is left out: the result holds the
32 other tickers only, summing to 1.0 (V6.6.9, #383: it used to turn every weight into NaN). Raises ValueError on an
33 unknown linkage method."""
34 if linkage_method not in LINKAGE_METHODS:
35 raise ValueError(f"unknown linkage method {linkage_method!r}; expected one of {LINKAGE_METHODS}")
36 variances = returns.var()
37 tickers = [ticker for ticker in returns.columns if math.isfinite(float(variances[ticker])) and float(variances[ticker]) > 0.0]
38 returns = returns[tickers]
39 n = len(tickers)
40 if n < 2:
41 return pd.Series({t: 1.0 / max(n, 1) for t in tickers}, dtype=float)
42 from scipy.cluster.hierarchy import leaves_list, linkage # lazy: the library facade imports this module and scipy is optional
43 from scipy.spatial.distance import squareform
45 corr = returns.corr().fillna(0.0)
46 covariance = returns.cov()
48 # Correlation distance
49 dist = np.sqrt(np.clip(0.5 * (1.0 - corr.values), 0.0, None))
50 np.fill_diagonal(dist, 0.0)
51 condensed = squareform(dist, checks=False)
53 link = linkage(condensed, method=linkage_method)
55 # Quasi-diagonal ordering (dendrogram leaf order)
56 ordered = leaves_list(link).tolist()
58 # Recursive bisection
59 weights = pd.Series(1.0, index=[tickers[i] for i in ordered])
60 cluster_items = [ordered]
62 while len(cluster_items) > 0:
63 next_clusters = []
64 for items in cluster_items:
65 if len(items) <= 1:
66 continue
67 half = len(items) // 2
68 left, right = items[:half], items[half:]
70 left_var = _cluster_var(covariance, [tickers[i] for i in left])
71 right_var = _cluster_var(covariance, [tickers[i] for i in right])
72 total = left_var + right_var
73 if total <= 0:
74 split = 0.5
75 else:
76 split = 1.0 - left_var / total
78 for item in left:
79 weights[tickers[item]] *= split
80 for item in right:
81 weights[tickers[item]] *= (1.0 - split)
83 next_clusters.extend([left, right])
84 cluster_items = next_clusters
86 return weights / weights.sum()
89def _cluster_var(covariance: pd.DataFrame, tickers_subset: list[str]) -> float:
90 """Inverse-variance of a cluster = variance of the cluster's own
91 inverse-variance-weighted portfolio."""
92 block = covariance.loc[tickers_subset, tickers_subset].values
93 ivp = 1.0 / np.diag(block)
94 ivp /= ivp.sum()
95 return float(ivp @ block @ ivp)
98def aligned_returns(returns_by_ticker: dict[str, list[float]], tickers: list[str]) -> pd.DataFrame:
99 """The frame HRP estimates on (V6.6.9, #383). The lists are return histories sampled on ONE calendar, newest last, so
100 they are aligned at their END: the old positional alignment from the start put a different date in each column
101 whenever the lengths differed. A list shorter than half the longest one (or under 2 returns) is left out rather than
102 cutting every other history down to it; the caller gives such a name its leg's mean weight."""
103 histories = {ticker: list(returns_by_ticker[ticker]) for ticker in tickers if ticker in returns_by_ticker}
104 longest = max((len(values) for values in histories.values()), default=0)
105 floor = max(2, math.ceil(longest / 2.0))
106 usable = {ticker: values for ticker, values in histories.items() if len(values) >= floor}
107 if not usable:
108 return pd.DataFrame()
109 length = min(len(values) for values in usable.values())
110 return pd.DataFrame({ticker: values[-length:] for ticker, values in usable.items()}, dtype=float)
113def _leg_weights(tickers: list[str], estimated: pd.Series, total: float) -> dict[str, float]:
114 """One leg, summing to `total`: HRP proportions for the names it estimated, the mean of those for a name it could not
115 (no history, no variance), equal weight when it estimated none."""
116 if not tickers:
117 return {}
118 raw = {ticker: float(estimated[ticker]) for ticker in tickers if ticker in estimated.index and math.isfinite(float(estimated[ticker])) and float(estimated[ticker]) > 0.0}
119 if not raw:
120 return dict.fromkeys(tickers, total / len(tickers))
121 mean = sum(raw.values()) / len(raw)
122 filled = {ticker: raw.get(ticker, mean) for ticker in tickers}
123 scale = total / sum(filled.values())
124 return {ticker: value * scale for ticker, value in filled.items()}
127def build_hrp_allocation(
128 returns_by_ticker: dict[str, list[float]],
129 *,
130 selected_tickers_long: list[str],
131 selected_tickers_short: list[str],
132 gross_exposure: float = 1.0,
133 linkage_method: str = "ward",
134) -> dict[str, float]:
135 """Builds an HRP-weighted allocation dict for the current book's long and
136 short legs. With BOTH legs populated, longs get positive HRP weights ×
137 gross/2 and shorts negative × gross/2 (dollar-neutral book). A
138 SINGLE-SIDED book (one leg empty - e.g. the long-only book
139 `phase5.backtest.strategy_mode: "long_flat"` produces, the shipped
140 default) gives the present leg the FULL gross - V5.4.4 fix: the
141 original unconditional gross/2 split silently halved a long-only
142 book's exposure. Falls back to equal weight within each leg when HRP
143 can't converge.
145 `returns_by_ticker` must hold returns sampled on one calendar (`aligned_returns`). The result always covers exactly the
146 selected names (V6.6.9, #383): a name HRP could not estimate gets the mean weight of its leg's estimated names
147 instead of a silent zero."""
148 all_selected = selected_tickers_long + selected_tickers_short
149 if not all_selected:
150 return {}
152 # V5.4.4's single-sided/two-sided gross split, shared by the HRP path
153 # below and the fallback here so they can never disagree.
154 long_weight_total = gross_exposure / 2.0 if selected_tickers_short else gross_exposure
155 short_weight_total = -(gross_exposure / 2.0 if selected_tickers_long else gross_exposure)
157 def _equal_weight_fallback() -> dict[str, float]:
158 # Equal weight WITHIN EACH LEG - each leg sums exactly to its own
159 # leg total above. V5.4.5 (development/Problems.md #118): the
160 # original fallback divided gross across BOTH legs combined
161 # (`gross / len(longs + shorts)`), so an asymmetric two-sided book
162 # (e.g. 6 longs / 2 shorts) came out with net exposure
163 # +/-0.5*gross instead of dollar-neutral.
164 return {**_leg_weights(selected_tickers_long, pd.Series(dtype=float), long_weight_total),
165 **_leg_weights(selected_tickers_short, pd.Series(dtype=float), short_weight_total)}
167 returns_df = aligned_returns(returns_by_ticker, all_selected)
168 if returns_df.shape[1] < 2 or returns_df.empty:
169 return _equal_weight_fallback()
171 try:
172 hrp_all = compute_hrp_weights(returns_df, linkage_method)
173 except Exception:
174 return _equal_weight_fallback()
176 return {**_leg_weights(selected_tickers_long, hrp_all, long_weight_total),
177 **_leg_weights(selected_tickers_short, hrp_all, short_weight_total)}