Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(quantlib): HRP aligns the covariance's own rows to its columns too (#1555)

Haozhe Wu6fbbec99b2fa
diff --git a/agent/src/quantlib/portfolio.py b/agent/src/quantlib/portfolio.py
index a3514e15d..a53bf9d57 100644
--- a/agent/src/quantlib/portfolio.py
+++ b/agent/src/quantlib/portfolio.py
@@ -116,6 +116,13 @@ def hierarchical_risk_parity(
"""
is_df = isinstance(cov, pd.DataFrame)
labels = cov.columns.tolist() if is_df else None
+ if is_df:
+ # The matrix is read positionally below, so a frame whose rows are in
+ # another order than its columns is the same misalignment as a
+ # reordered corr: align it by label, reject a different label set.
+ if set(cov.index) != set(labels):
+ raise ValueError("Covariance matrix row labels must match its column labels")
+ cov = cov.loc[labels, labels]
cov_mat = np.asarray(cov, dtype=float)
if cov_mat.ndim != 2 or cov_mat.shape[0] != cov_mat.shape[1]:
diff --git a/agent/tests/quantlib/test_portfolio.py b/agent/tests/quantlib/test_portfolio.py
index ffdb49568..54e57f8d3 100644
--- a/agent/tests/quantlib/test_portfolio.py
+++ b/agent/tests/quantlib/test_portfolio.py
@@ -88,3 +88,29 @@ def test_hrp_rejects_correlation_with_different_labels() -> None:
corr = pd.DataFrame(np.eye(2), index=["A", "C"], columns=["A", "C"])
with pytest.raises(ValueError, match="labels must match"):
hierarchical_risk_parity(cov, corr)
+
+
+def test_hrp_aligns_covariance_rows_to_its_columns() -> None:
+ """Swapping two rows of a labelled cov moved weights silently (0.0351/0.0403 → 0.0375/0.0375)."""
+ tickers = ["AAPL", "MSFT", "GOOGL", "TLT"]
+ std = np.array([0.30, 0.28, 0.32, 0.08])
+ corr = np.array(
+ [
+ [1.00, 0.70, 0.65, -0.10],
+ [0.70, 1.00, 0.60, -0.05],
+ [0.65, 0.60, 1.00, -0.08],
+ [-0.10, -0.05, -0.08, 1.00],
+ ]
+ )
+ cov = pd.DataFrame(corr * np.outer(std, std), index=tickers, columns=tickers)
+ rows_swapped = cov.loc[["MSFT", "AAPL", "GOOGL", "TLT"], tickers]
+
+ pd.testing.assert_series_equal(
+ hierarchical_risk_parity(rows_swapped), hierarchical_risk_parity(cov)
+ )
+
+
+def test_hrp_rejects_covariance_rows_labelled_differently_from_columns() -> None:
+ cov = pd.DataFrame(np.eye(2) * 0.04, index=["A", "C"], columns=["A", "B"])
+ with pytest.raises(ValueError, match="row labels must match"):
+ hierarchical_risk_parity(cov)