Skip to content
Merged
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
4 changes: 1 addition & 3 deletions pypfopt/hierarchical_portfolio.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,6 @@ def optimize(self, linkage_method="single"):
OrderedDict
weights for the HRP portfolio
"""
if linkage_method not in sch._LINKAGE_METHODS:
raise ValueError("linkage_method must be one recognised by scipy")

if self.returns is None:
cov = self.cov_matrix
corr = cov_to_corr(self.cov_matrix).round(6)
Expand All @@ -192,6 +189,7 @@ def optimize(self, linkage_method="single"):
matrix = np.sqrt(np.clip((1.0 - corr) / 2.0, a_min=0.0, a_max=1.0))
dist = ssd.squareform(matrix, checks=False)

# Let the public API validate methods; SciPy's private registry can change.
self.clusters = sch.linkage(dist, linkage_method)
sort_ix = HRPOpt._get_quasi_diag(self.clusters)
ordered_tickers = corr.index[sort_ix].tolist()
Expand Down
11 changes: 11 additions & 0 deletions tests/test_hrp.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,17 @@
from tests.utilities_for_tests import get_data, resource


@pytest.mark.parametrize(
"method", ["single", "complete", "average", "weighted", "centroid", "median", "ward"]
)
def test_documented_linkage_methods(method):
cov = pd.DataFrame(np.eye(3), index=list("ABC"), columns=list("ABC"))
weights = HRPOpt(cov_matrix=cov).optimize(linkage_method=method)
assert set(weights) == set("ABC")
assert sum(weights.values()) == pytest.approx(1)
assert all(weight > 0 for weight in weights.values())


def test_hrp_errors():
with pytest.raises(ValueError):
hrp = HRPOpt()
Expand Down
Loading