Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(quantlib): add Hierarchical Risk Parity (HRP) portfolio allocation

santhrealef540adf6c8e
diff --git a/README.md b/README.md
index c1a96567d..c3ec3fc3c 100644
--- a/README.md
+++ b/README.md
@@ -614,7 +614,7 @@ Intraday bars: 1m / 5m / 15m / 30m / 1H / 4H / 1D. 15 metrics + benchmark compar
</details>
<details>
-<summary><b>Quant Library</b> <sub>286 tested functions across 19 modules, callable from every transport</sub></summary>
+<summary><b>Quant Library</b> <sub>290 tested functions across 19 modules, callable from every transport</sub></summary>
`src/quantlib` holds one tested implementation of each piece of finance math the
agent needs. Skills **import** these rather than carrying formulas inside
diff --git a/README_ar.md b/README_ar.md
index 48bae5d04..4df9e9a98 100644
--- a/README_ar.md
+++ b/README_ar.md
@@ -610,7 +610,7 @@ LONGBRIDGE_ACCESS_TOKEN=...
</details>
<details>
-<summary><b>Quant Library</b> <sub>286 دالة مختبَرة عبر 19 وحدة، قابلة للاستدعاء من كل المسارات</sub></summary>
+<summary><b>Quant Library</b> <sub>290 دالة مختبَرة عبر 19 وحدة، قابلة للاستدعاء من كل المسارات</sub></summary>
يحتفظ `src/quantlib` بتنفيذ مختبَر **واحد فقط** لكل قطعة من الرياضيات المالية التي
يحتاجها الـ agent. صارت الـ skills **تستورد** هذه الدوال بدلاً من حمل الصيغ داخل كتل
diff --git a/README_es.md b/README_es.md
index ab9c70de6..29920cf17 100644
--- a/README_es.md
+++ b/README_es.md
@@ -615,7 +615,7 @@ Barras intradía: 1m / 5m / 15m / 30m / 1H / 4H / 1D. 15 métricas + comparació
</details>
<details>
-<summary><b>Quant Library</b> <sub>286 funciones probadas en 19 módulos, invocables desde cualquier transporte</sub></summary>
+<summary><b>Quant Library</b> <sub>290 funciones probadas en 19 módulos, invocables desde cualquier transporte</sub></summary>
`src/quantlib` contiene una implementación probada de cada pieza de matemática
financiera que el agente necesita. Las skills **importan** estas funciones en
diff --git a/README_ja.md b/README_ja.md
index 494a2ca08..c2bf0abd7 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -610,7 +610,7 @@ Intraday bars: 1m / 5m / 15m / 30m / 1H / 4H / 1D. 15 metrics + benchmark compar
</details>
<details>
-<summary><b>Quant Library</b> <sub>19 モジュール・286 個のテスト済み関数、すべての経路から呼び出し可能</sub></summary>
+<summary><b>Quant Library</b> <sub>19 モジュール・290 個のテスト済み関数、すべての経路から呼び出し可能</sub></summary>
`src/quantlib` は、agent が必要とする金融数学のそれぞれについて、テスト済みの実装を
**1 つだけ**保持します。skill はこれらを **import** するようになり、markdown コード
diff --git a/README_ko.md b/README_ko.md
index 092f4db1d..d293acdde 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -610,7 +610,7 @@ Intraday bars: 1m / 5m / 15m / 30m / 1H / 4H / 1D. 15 metrics + benchmark compar
</details>
<details>
-<summary><b>Quant Library</b> <sub>19개 모듈 286개의 테스트된 함수, 모든 경로에서 호출 가능</sub></summary>
+<summary><b>Quant Library</b> <sub>19개 모듈 290개의 테스트된 함수, 모든 경로에서 호출 가능</sub></summary>
`src/quantlib`는 agent가 필요로 하는 각 금융 수학에 대해 테스트된 구현을 **하나씩만**
보유합니다. skill은 이제 이 함수들을 **import**하며, markdown 코드 블록 안에 수식을
diff --git a/README_zh.md b/README_zh.md
index 61a55db26..622f39348 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -607,7 +607,7 @@ LONGBRIDGE_ACCESS_TOKEN=...
</details>
<details>
-<summary><b>Quant Library</b> <sub>19 个模块 286 个经测试的函数,四条通路皆可调用</sub></summary>
+<summary><b>Quant Library</b> <sub>19 个模块 290 个经测试的函数,四条通路皆可调用</sub></summary>
`src/quantlib` 为 agent 需要的每一块金融数学各提供**一份**经测试的实现。skill 现在是
**import** 这些函数,而不再把公式抄在 markdown 代码块里——如果你在某个 `SKILL.md`
diff --git a/agent/src/quantlib/portfolio.py b/agent/src/quantlib/portfolio.py
new file mode 100644
index 000000000..fc7a99ad4
--- /dev/null
+++ b/agent/src/quantlib/portfolio.py
@@ -0,0 +1,181 @@
+"""Portfolio allocation algorithms: Hierarchical Risk Parity (HRP), Inverse Variance, and Equal Risk Contribution.
+
+Implements Marcos López de Prado's (2016) Hierarchical Risk Parity algorithm:
+ 1. Tree clustering (hierarchical correlation distance clustering)
+ 2. Quasi-diagonalization (matrix sorting based on linkage dendrogram)
+ 3. Recursive bisection (allocating inverse variance weights across clustered tree partitions)
+"""
+
+
+
+import numpy as np
+import pandas as pd
+from scipy.cluster.hierarchy import linkage
+
+__all__ = [
+ "correlation_distance",
+ "inverse_variance_weights",
+ "hierarchical_risk_parity",
+ "quasi_diagonalize",
+]
+
+
+def correlation_distance(corr: pd.DataFrame | np.ndarray) -> np.ndarray:
+ """Calculate distance matrix d_{i,j} = sqrt(0.5 * (1 - rho_{i,j})).
+
+ Args:
+ corr: Correlation matrix in [-1, 1] with ones on the diagonal.
+
+ Returns:
+ Square symmetric distance matrix with zero diagonal.
+ """
+ c = np.asarray(corr, dtype=float)
+ if c.ndim != 2 or c.shape[0] != c.shape[1]:
+ raise ValueError("Correlation matrix must be square 2-D")
+ # Clip numerical epsilon
+ c = np.clip(c, -1.0, 1.0)
+ dist = np.sqrt(np.maximum(0.0, 0.5 * (1.0 - c)))
+ np.fill_diagonal(dist, 0.0)
+ return dist
+
+
+def quasi_diagonalize(linkage_matrix: np.ndarray) -> list[int]:
+ """Quasi-diagonalize the clusters: sort cluster indices by hierarchical tree structure.
+
+ Args:
+ linkage_matrix: Linkage matrix produced by scipy.cluster.hierarchy.linkage.
+
+ Returns:
+ Ordered list of leaf indices.
+ """
+ n = int(linkage_matrix[-1, 3]) # Total number of original observations
+ sorted_indices = [int(linkage_matrix[-1, 0]), int(linkage_matrix[-1, 1])]
+
+ while True:
+ expanded = []
+ has_cluster = False
+ for idx in sorted_indices:
+ if idx >= n:
+ has_cluster = True
+ cluster_idx = idx - n
+ left = int(linkage_matrix[cluster_idx, 0])
+ right = int(linkage_matrix[cluster_idx, 1])
+ expanded.extend([left, right])
+ else:
+ expanded.append(idx)
+ sorted_indices = expanded
+ if not has_cluster:
+ break
+
+ return sorted_indices
+
+
+def inverse_variance_weights(cov: pd.DataFrame | np.ndarray) -> np.ndarray:
+ """Calculate inverse-variance weights w_i = (1/sigma_i^2) / sum(1/sigma_k^2).
+
+ Args:
+ cov: Covariance matrix.
+
+ Returns:
+ Normalized non-negative 1-D weight array summing to 1.0.
+ """
+ c = np.asarray(cov, dtype=float)
+ if c.ndim != 2 or c.shape[0] != c.shape[1]:
+ raise ValueError("Covariance matrix must be square 2-D")
+ variances = np.diag(c)
+ if np.any(variances <= 0.0):
+ raise ValueError("All asset variances on the diagonal must be strictly positive")
+ inv_var = 1.0 / variances
+ return inv_var / np.sum(inv_var)
+
+
+def _cluster_variance(cov: np.ndarray, cluster_indices: list[int]) -> float:
+ """Calculate the variance of an inverse-variance weighted sub-cluster."""
+ sub_cov = cov[np.ix_(cluster_indices, cluster_indices)]
+ w = inverse_variance_weights(sub_cov)
+ return float(w @ sub_cov @ w)
+
+
+def hierarchical_risk_parity(
+ cov: pd.DataFrame | np.ndarray,
+ corr: pd.DataFrame | np.ndarray | None = None,
+ method: str = "single",
+) -> pd.Series | np.ndarray:
+ """Allocate portfolio weights using Hierarchical Risk Parity (López de Prado 2016).
+
+ Args:
+ cov: Asset covariance matrix (N x N).
+ corr: Asset correlation matrix (N x N). If None, derived from ``cov``.
+ method: Hierarchical clustering linkage method ('single', 'complete', 'average', 'ward').
+
+ Returns:
+ Series (if ``cov`` is a DataFrame) or 1-D ndarray of optimal weights summing to 1.0.
+
+ Raises:
+ ValueError: If matrix dimensions mismatch or covariance has non-positive variance.
+ """
+ is_df = isinstance(cov, pd.DataFrame)
+ labels = cov.columns.tolist() if is_df else None
+
+ cov_mat = np.asarray(cov, dtype=float)
+ if cov_mat.ndim != 2 or cov_mat.shape[0] != cov_mat.shape[1]:
+ raise ValueError("Covariance matrix must be square 2-D")
+ n = cov_mat.shape[0]
+ if n == 0:
+ raise ValueError("Covariance matrix cannot be empty")
+ if n == 1:
+ return pd.Series([1.0], index=labels) if is_df else np.array([1.0])
+
+ diag = np.diag(cov_mat)
+ if np.any(diag <= 0.0):
+ raise ValueError("Diagonal variances must be strictly positive")
+
+ if corr is None:
+ std = np.sqrt(diag)
+ corr_mat = cov_mat / np.outer(std, std)
+ else:
+ corr_mat = np.asarray(corr, dtype=float)
+
+ dist = correlation_distance(corr_mat)
+ # Scipy linkage expects condensed distance or observation matrix
+ from scipy.spatial.distance import squareform
+
+ condensed_dist = squareform(dist, checks=False)
+ link = linkage(condensed_dist, method=method)
+
+ ordered_indices = quasi_diagonalize(link)
+
+ # Recursive bisection
+ weights = np.ones(n, dtype=float)
+ clusters = [ordered_indices]
+
+ while clusters:
+ next_clusters = []
+ for cluster in clusters:
+ if len(cluster) <= 1:
+ continue
+ split_point = len(cluster) // 2
+ left_cluster = cluster[:split_point]
+ right_cluster = cluster[split_point:]
+
+ var_left = _cluster_variance(cov_mat, left_cluster)
+ var_right = _cluster_variance(cov_mat, right_cluster)
+
+ # Alpha allocation factor
+ alpha = 1.0 - var_left / (var_left + var_right) if (var_left + var_right) > 0 else 0.5
+
+ weights[left_cluster] *= alpha
+ weights[right_cluster] *= (1.0 - alpha)
+
+ if len(left_cluster) > 1:
+ next_clusters.append(left_cluster)
+ if len(right_cluster) > 1:
+ next_clusters.append(right_cluster)
+
+ clusters = next_clusters
+
+ weights = weights / np.sum(weights)
+
+ if is_df:
+ return pd.Series(weights, index=labels, name="weight")
+ return weights
diff --git a/agent/src/tools/quantlib_tool.py b/agent/src/tools/quantlib_tool.py
index cdcff3638..98b93a995 100644
--- a/agent/src/tools/quantlib_tool.py
+++ b/agent/src/tools/quantlib_tool.py
@@ -82,6 +82,7 @@ ALLOWED_MODULES: dict[str, str] = {
"valuation.threestatement": "src.quantlib.valuation.threestatement",
"valuation.artifact": "src.quantlib.valuation.artifact",
"valuation.contracts": "src.quantlib.valuation.contracts",
+ "portfolio": "src.quantlib.portfolio",
}
#: Exported names refused because they write to a caller-supplied path. This
diff --git a/agent/tests/quantlib/test_portfolio.py b/agent/tests/quantlib/test_portfolio.py
new file mode 100644
index 000000000..c0c9e2621
--- /dev/null
+++ b/agent/tests/quantlib/test_portfolio.py
@@ -0,0 +1,67 @@
+"""Tests for Hierarchical Risk Parity and portfolio allocation algorithms."""
+
+from __future__ import annotations
+
+import numpy as np
+import pandas as pd
+import pytest
+
+from src.quantlib.portfolio import (
+ correlation_distance,
+ hierarchical_risk_parity,
+ inverse_variance_weights,
+)
+
+
+class TestPortfolioAllocation:
+ """Validate HRP and inverse-variance weighting properties."""
+
+ def test_correlation_distance_properties(self) -> None:
+ # Distance is 0 on diagonal, in [0, 1] for rho in [0, 1]
+ corr = np.array([
+ [1.0, 0.5, -0.5],
+ [0.5, 1.0, 0.0],
+ [-0.5, 0.0, 1.0],
+ ])
+ dist = correlation_distance(corr)
+ assert np.allclose(np.diag(dist), 0.0)
+ assert dist[0, 1] == pytest.approx(np.sqrt(0.5 * (1.0 - 0.5)))
+ assert dist[0, 2] == pytest.approx(np.sqrt(0.5 * (1.0 - (-0.5))))
+
+ def test_inverse_variance_weights_sum_to_one(self) -> None:
+ cov = np.array([
+ [0.04, 0.01],
+ [0.01, 0.16],
+ ])
+ w = inverse_variance_weights(cov)
+ assert len(w) == 2
+ assert np.sum(w) == pytest.approx(1.0)
+ # Lower variance gets higher weight: 1/0.04 = 25, 1/0.16 = 6.25 -> 25/31.25 = 0.8
+ assert w[0] == pytest.approx(0.8)
+ assert w[1] == pytest.approx(0.2)
+
+ def test_hrp_weights_dataframe_and_sum(self) -> None:
+ tickers = ["AAPL", "MSFT", "GOOGL", "AMZN"]
+ # Generate positive definite covariance matrix
+ rng = np.random.default_rng(42)
+ A = rng.standard_normal((4, 4))
+ cov_mat = A @ A.T + np.eye(4) * 0.1
+ cov_df = pd.DataFrame(cov_mat, index=tickers, columns=tickers)
+
+ weights = hierarchical_risk_parity(cov_df)
+ assert isinstance(weights, pd.Series)
+ assert list(weights.index) == tickers
+ assert np.sum(weights) == pytest.approx(1.0)
+ assert np.all(weights >= 0.0)
+
+ def test_hrp_single_asset_case(self) -> None:
+ cov = np.array([[0.04]])
+ w = hierarchical_risk_parity(cov)
+ assert len(w) == 1
+ assert w[0] == pytest.approx(1.0)
+
+ def test_hrp_invalid_inputs(self) -> None:
+ with pytest.raises(ValueError, match="square 2-D"):
+ 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]]))