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
24 changes: 24 additions & 0 deletions .github/workflows/discrete-allocation.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: Discrete allocation regressions
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
jobs:
discrete-allocation:
runs-on: ubuntu-latest
timeout-minutes: 10
strategy:
matrix:
python-version: ['3.11', '3.12']
steps:
- uses: actions/checkout@v6
with:
persist-credentials: false
- uses: astral-sh/setup-uv@v7
with:
python-version: ${{ matrix.python-version }}
- run: uv venv
- run: uv pip install -e . pytest ecos
- run: uv run --no-sync pytest tests/test_discrete_allocation.py -q
3 changes: 2 additions & 1 deletion pypfopt/discrete_allocation.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,8 @@ def lp_portfolio(self, reinvest=False, verbose=False, solver=None):
self.allocation = self._remove_zero_positions(self.allocation)
return self.allocation, long_leftover + short_leftover

p = self.latest_prices.values
# Match the weight order by ticker; Series order and extra prices may differ.
p = self.latest_prices.loc[[ticker for ticker, _ in self.weights]].values
n = len(p)
w = np.fromiter([i[1] for i in self.weights], dtype=float)

Expand Down
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
15 changes: 15 additions & 0 deletions tests/test_discrete_allocation.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,21 @@
from tests.utilities_for_tests import get_data, setup_efficient_frontier


@pytest.mark.parametrize(
"prices",
[
pd.Series({"B": 100.0, "A": 10.0}),
pd.Series({"UNUSED": 5.0, "B": 100.0, "A": 10.0}),
],
)
def test_lp_portfolio_aligns_prices_with_weight_tickers(prices):
da = DiscreteAllocation({"A": 0.5, "B": 0.5}, prices, total_portfolio_value=200)
allocation, leftover = da.lp_portfolio(solver="SCIPY")
assert allocation == {"A": 10, "B": 1}
assert leftover == pytest.approx(0)
assert sum(prices[ticker] * shares for ticker, shares in allocation.items()) == 200


def test_get_latest_prices():
df = get_data()
latest_prices = get_latest_prices(df)
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