Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(quantlib): align HRP correlation labels

Lanre Shittu45750798be00
diff --git a/agent/src/quantlib/portfolio.py b/agent/src/quantlib/portfolio.py
index fc7a99ad4..a3514e15d 100644
--- a/agent/src/quantlib/portfolio.py
+++ b/agent/src/quantlib/portfolio.py
@@ -134,7 +134,13 @@ def hierarchical_risk_parity(
std = np.sqrt(diag)
corr_mat = cov_mat / np.outer(std, std)
else:
+ if is_df and isinstance(corr, pd.DataFrame):
+ if set(corr.index) != set(labels) or set(corr.columns) != set(labels):
+ raise ValueError("Correlation matrix labels must match covariance labels")
+ corr = corr.loc[labels, labels]
corr_mat = np.asarray(corr, dtype=float)
+ if corr_mat.shape != cov_mat.shape:
+ raise ValueError("Correlation matrix dimensions must match covariance matrix")
dist = correlation_distance(corr_mat)
# Scipy linkage expects condensed distance or observation matrix
diff --git a/agent/tests/quantlib/test_portfolio.py b/agent/tests/quantlib/test_portfolio.py
index c0c9e2621..ffdb49568 100644
--- a/agent/tests/quantlib/test_portfolio.py
+++ b/agent/tests/quantlib/test_portfolio.py
@@ -65,3 +65,26 @@ class TestPortfolioAllocation:
hierarchical_risk_parity(np.array([1.0, 2.0]))
with pytest.raises(ValueError, match="strictly positive"):
hierarchical_risk_parity(np.array([[0.0, 0.0], [0.0, 0.04]]))
+
+
+def test_hrp_aligns_dataframe_correlation_to_covariance_labels() -> None:
+ labels = ["A", "B", "C"]
+ cov = pd.DataFrame(
+ [[0.04, 0.01, 0.00], [0.01, 0.09, 0.02], [0.00, 0.02, 0.16]],
+ index=labels,
+ columns=labels,
+ )
+ corr = cov.div(np.sqrt(np.diag(cov)), axis=0).div(np.sqrt(np.diag(cov)), axis=1)
+ reordered = corr.loc[["C", "A", "B"], ["C", "A", "B"]]
+
+ expected = hierarchical_risk_parity(cov, corr)
+ actual = hierarchical_risk_parity(cov, reordered)
+
+ pd.testing.assert_series_equal(actual, expected)
+
+
+def test_hrp_rejects_correlation_with_different_labels() -> None:
+ cov = pd.DataFrame(np.eye(2), index=["A", "B"], columns=["A", "B"])
+ 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)