diff --git a/docs/OtherOptimizers.rst b/docs/OtherOptimizers.rst index 8b1f4704..9b88316e 100644 --- a/docs/OtherOptimizers.rst +++ b/docs/OtherOptimizers.rst @@ -36,6 +36,17 @@ The advantages of this are that it does not require the inversion of the covaria matrix as with traditional mean-variance optimization, and seems to produce diverse portfolios that perform well out of sample. +Plain HRP can put a large weight on a single low-volatility asset. To limit this, pass +``weight_bounds`` in the same form as ``EfficientFrontier``:: + + hrp = HRPOpt(returns, weight_bounds=(0.02, 0.10)) + weights = hrp.optimize() + +The bounds are enforced inside the recursive bisection, following the constrained HRP of +Pfitzinger and Katzke [3]_: at each split, the share given to each sub-cluster is +clipped so that the cluster's weight stays between the sums of its assets' lower and upper +bounds. The lower bounds must add up to at most 1 and the upper bounds to at least 1. + .. image:: ../media/dendrogram.png :width: 80% :align: center @@ -118,3 +129,4 @@ References .. [1] López de Prado, M. (2016). `Building Diversified Portfolios that Outperform Out of Sample `_. The Journal of Portfolio Management, 42(4), 59–69. .. [2] Bailey and Loópez de Prado (2013). `An Open-Source Implementation of the Critical-Line Algorithm for Portfolio Optimization `_ +.. [3] Pfitzinger, J. and Katzke, N. (2019). `A Constrained Hierarchical Risk Parity Algorithm with Cluster-based Capital Allocation `_. Stellenbosch University, Department of Economics, Working Paper 14/2019. diff --git a/pypfopt/hierarchical_portfolio.py b/pypfopt/hierarchical_portfolio.py index 6dc76d07..fe58d3e0 100644 --- a/pypfopt/hierarchical_portfolio.py +++ b/pypfopt/hierarchical_portfolio.py @@ -51,7 +51,7 @@ class HRPOpt(BaseOptimizer): - ``save_weights_to_file()`` saves the weights to csv, json, or txt. """ - def __init__(self, returns=None, cov_matrix=None): + def __init__(self, returns=None, cov_matrix=None, weight_bounds=(0, 1)): """ Parameters ---------- @@ -59,6 +59,11 @@ def __init__(self, returns=None, cov_matrix=None): asset historical returns cov_matrix : pd.DataFrame covariance of asset returns + weight_bounds : tuple OR tuple list, optional + minimum and maximum weight of each asset OR single min/max pair + if all identical, defaults to (0, 1). The bounds are applied with + the constrained HRP of Pfitzinger and Katzke (2019), so the result stays a + hierarchical risk parity portfolio. Lower bounds must be >= 0. Raises ------ @@ -80,6 +85,32 @@ def __init__(self, returns=None, cov_matrix=None): else: tickers = list(returns.columns) super().__init__(len(tickers), tickers) + self.lower_bounds, self.upper_bounds = self._parse_bounds(weight_bounds) + + def _parse_bounds(self, weight_bounds): + """ + Turn ``weight_bounds`` into a lower and upper bound per ticker, + and check that a fully invested portfolio can meet them. + """ + if len(weight_bounds) == self.n_assets and not np.isscalar(weight_bounds[0]): + bounds = np.array(weight_bounds, dtype=float) + elif len(weight_bounds) == 2: + bounds = np.array([weight_bounds] * self.n_assets, dtype=float) + else: + raise TypeError( + "weight_bounds must be a pair (lower bound, upper bound) OR a collection of bounds for each asset" + ) + lower = pd.Series(bounds[:, 0], index=self.tickers) + upper = pd.Series(bounds[:, 1], index=self.tickers) + + if (lower < 0).any() or (lower > upper).any(): + raise ValueError("each bound must satisfy 0 <= lower <= upper") + if lower.sum() > 1 or upper.sum() < 1: + raise ValueError( + "weight_bounds are infeasible: the lower bounds must add up to at most 1 " + "and the upper bounds to at least 1" + ) + return lower, upper @staticmethod def _get_cluster_var(cov, cluster_items): @@ -122,17 +153,26 @@ def _get_quasi_diag(link): return sch.to_tree(link, rd=False).pre_order() @staticmethod - def _raw_hrp_allocation(cov, ordered_tickers): + def _raw_hrp_allocation(cov, ordered_tickers, lower_bounds=None, upper_bounds=None): """ Given the clusters, compute the portfolio that minimises risk by recursively traversing the hierarchical tree from the top. + If bounds are given, the split between each pair of clusters is clipped so + that every cluster's weight stays between the sum of its assets' lower and + upper bounds (Pfitzinger and Katzke, 2019). Going down to single assets, this keeps + every weight within its own bounds. + Parameters ---------- cov : np.ndarray covariance matrix ordered_tickers : str list list of tickers ordered by distance + lower_bounds : pd.Series, optional + minimum weight of each ticker + upper_bounds : pd.Series, optional + maximum weight of each ticker Returns ------- @@ -157,6 +197,18 @@ def _raw_hrp_allocation(cov, ordered_tickers): first_variance = HRPOpt._get_cluster_var(cov, first_cluster) second_variance = HRPOpt._get_cluster_var(cov, second_cluster) alpha = 1 - first_variance / (first_variance + second_variance) + + if lower_bounds is not None: + # weight of the parent cluster (all its assets have the same w so far) + parent = w[first_cluster[0]] + first_min = lower_bounds[first_cluster].sum() / parent + first_max = upper_bounds[first_cluster].sum() / parent + second_min = lower_bounds[second_cluster].sum() / parent + second_max = upper_bounds[second_cluster].sum() / parent + alpha = min( + max(alpha, first_min, 1 - second_max), first_max, 1 - second_min + ) + w[first_cluster] *= alpha # weight 1 w[second_cluster] *= 1 - alpha # weight 2 return w @@ -195,7 +247,9 @@ def optimize(self, linkage_method="single"): self.clusters = sch.linkage(dist, linkage_method) sort_ix = HRPOpt._get_quasi_diag(self.clusters) ordered_tickers = corr.index[sort_ix].tolist() - hrp = HRPOpt._raw_hrp_allocation(cov, ordered_tickers) + hrp = HRPOpt._raw_hrp_allocation( + cov, ordered_tickers, self.lower_bounds, self.upper_bounds + ) weights = collections.OrderedDict(hrp.sort_index()) self.set_weights(weights) return weights diff --git a/tests/test_hrp.py b/tests/test_hrp.py index 369a1727..84a3ae8e 100644 --- a/tests/test_hrp.py +++ b/tests/test_hrp.py @@ -78,3 +78,63 @@ def test_quasi_dag(): hrp.optimize(linkage_method="single") clusters = hrp.clusters assert HRPOpt._get_quasi_diag(clusters)[:5] == [12, 6, 15, 14, 2] + + +def test_hrp_weight_bounds(): + df = get_data() + returns = df.pct_change().dropna(how="all") + unbounded = pd.Series(HRPOpt(returns).optimize()) + + hrp = HRPOpt(returns, weight_bounds=(0.02, 0.1)) + w = pd.Series(hrp.optimize()) + np.testing.assert_almost_equal(w.sum(), 1) + assert (w >= 0.02 - 1e-9).all() + assert (w <= 0.1 + 1e-9).all() + # the bounds change the plain HRP answer + assert unbounded.max() > 0.1 + assert unbounded.min() < 0.02 + + +def test_hrp_weight_bounds_default_unchanged(): + df = get_data() + returns = df.pct_change().dropna(how="all") + w1 = HRPOpt(returns).optimize() + w2 = HRPOpt(returns, weight_bounds=(0, 1)).optimize() + for ticker in w1: + assert w1[ticker] == pytest.approx(w2[ticker]) + + +def test_hrp_weight_bounds_per_asset(): + df = get_data() + returns = df.pct_change().dropna(how="all") + bounds = [(0, 0.3)] * len(returns.columns) + bounds[0] = (0.15, 0.3) # force a minimum in the first ticker + hrp = HRPOpt(returns, weight_bounds=bounds) + w = pd.Series(hrp.optimize()) + np.testing.assert_almost_equal(w.sum(), 1) + assert w[returns.columns[0]] >= 0.15 - 1e-9 + assert (w <= 0.3 + 1e-9).all() + + +def test_hrp_weight_bounds_with_cov_matrix(): + df = get_data() + S = CovarianceShrinkage(df).ledoit_wolf() + hrp = HRPOpt(cov_matrix=S, weight_bounds=(0, 0.08)) + w = pd.Series(hrp.optimize()) + np.testing.assert_almost_equal(w.sum(), 1) + assert (w <= 0.08 + 1e-9).all() + + +def test_hrp_weight_bounds_errors(): + df = get_data() + returns = df.pct_change().dropna(how="all") + n = len(returns.columns) + with pytest.raises(ValueError): + HRPOpt(returns, weight_bounds=(0.1, 1)) # lower bounds add up to more than 1 + # upper bounds add up to less than 1 + with pytest.raises(ValueError): + HRPOpt(returns, weight_bounds=(0, 0.5 / n)) + with pytest.raises(ValueError): + HRPOpt(returns, weight_bounds=(-0.1, 1)) # HRP is long only + with pytest.raises(TypeError): + HRPOpt(returns, weight_bounds=(0, 0.5, 1))