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
13 changes: 12 additions & 1 deletion pypfopt/hierarchical_portfolio.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,17 @@
from pypfopt.risk_models import cov_to_corr


_VALID_LINKAGE_METHODS = {
"single",
"complete",
"average",
"weighted",
"centroid",
"median",
"ward",
}
Comment on lines +26 to +34


class HRPOpt(BaseOptimizer):
"""
A HRPOpt object (inheriting from BaseOptimizer) constructs a hierarchical
Expand Down Expand Up @@ -176,7 +187,7 @@ def optimize(self, linkage_method="single"):
OrderedDict
weights for the HRP portfolio
"""
if linkage_method not in sch._LINKAGE_METHODS:
if linkage_method not in _VALID_LINKAGE_METHODS:
raise ValueError("linkage_method must be one recognised by scipy")

if self.returns is None:
Expand Down
15 changes: 15 additions & 0 deletions tests/test_hrp.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,21 @@ def test_hrp_errors():
hrp.optimize(linkage_method="blah")


@pytest.mark.parametrize(
"linkage_method",
["single", "complete", "average", "weighted", "centroid", "median", "ward"],
)
def test_hrp_linkage_methods(linkage_method):
df = get_data()
returns = df.pct_change().dropna(how="all")
hrp = HRPOpt(returns)

weights = hrp.optimize(linkage_method=linkage_method)

assert isinstance(weights, dict)
np.testing.assert_almost_equal(sum(weights.values()), 1)
Comment on lines +35 to +36


def test_hrp_portfolio():
df = get_data()
returns = df.pct_change().dropna(how="all")
Expand Down