Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions docs/OtherOptimizers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -118,3 +129,4 @@ References

.. [1] López de Prado, M. (2016). `Building Diversified Portfolios that Outperform Out of Sample <https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2708678>`_. 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 <https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2197616>`_
.. [3] Pfitzinger, J. and Katzke, N. (2019). `A Constrained Hierarchical Risk Parity Algorithm with Cluster-based Capital Allocation <https://ideas.repec.org/p/sza/wpaper/wpapers328.html>`_. Stellenbosch University, Department of Economics, Working Paper 14/2019.
60 changes: 57 additions & 3 deletions pypfopt/hierarchical_portfolio.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,19 @@ 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
----------
returns : pd.DataFrame
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
------
Expand All @@ -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):
Expand Down Expand Up @@ -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
-------
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
60 changes: 60 additions & 0 deletions tests/test_hrp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))