https://github.com/tschm/pyhrp
Run hierarchical risk parity algorithms
https://github.com/tschm/pyhrp
asset-management hierarchy
Last synced: 9 months ago
JSON representation
Run hierarchical risk parity algorithms
- Host: GitHub
- URL: https://github.com/tschm/pyhrp
- Owner: tschm
- License: mit
- Created: 2020-04-22T20:06:36.000Z (over 5 years ago)
- Default Branch: main
- Last Pushed: 2024-04-16T01:37:49.000Z (over 1 year ago)
- Last Synced: 2024-04-17T07:18:47.383Z (over 1 year ago)
- Topics: asset-management, hierarchy
- Language: Python
- Homepage:
- Size: 7.25 MB
- Stars: 15
- Watchers: 3
- Forks: 16
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- Contributing: CONTRIBUTING.md
- License: LICENSE.txt
- Code of conduct: CODE_OF_CONDUCT.md
Awesome Lists containing this project
README
# [pyhrp](https://tschm.github.io/pyhrp/book)
[](https://badge.fury.io/py/pyhrp)
[](LICENSE)
[](https://pepy.tech/project/pyhrp)
[](https://coveralls.io/github/tschm/pyhrp?branch=main)
[](https://results.pre-commit.ci/latest/github/tschm/pyhrp/main)
[](https://codespaces.new/tschm/pyhrp)
A recursive implementation of the Hierarchical Risk Parity (hrp) approach
by Marcos Lopez de Prado.
We take heavily advantage of the scipy.cluster.hierarchy package.

Here's a simple example
```python
>>> import pandas as pd
>>> from pyhrp.hrp import build_tree
>>> from pyhrp.algos import risk_parity
>>> from pyhrp.cluster import Asset
>>> prices = pd.read_csv("src/tests/resources/stock_prices.csv", index_col=0, parse_dates=True)
>>> prices.columns = [Asset(name=column) for column in prices.columns]
>>> returns = prices.pct_change().dropna(axis=0, how="all")
>>> cov, cor = returns.cov(), returns.corr()
# Compute the dendrogram based on the correlation matrix and Ward's metric
>>> dendrogram = build_tree(cor, method='ward')
>>> dendrogram.plot()
# Compute the weights on the dendrogram
>>> root = risk_parity(root=dendrogram.root, cov=cov)
>>> ax = root.portfolio.plot(names=dendrogram.names)
```
For your convenience you can bypass the construction of the covariance and
correlation matrix, and the construction of the dendrogram.
```python
>>> from pyhrp.hrp import hrp
>>> root = hrp(prices=prices, method="ward", bisection=False)
```
You may expect a weight series here but instead the `hrp` function returns a
`Node` object. The `node` simplifies all further post-analysis.
```python
>>> weights = root.portfolio.weights
>>> variance = root.portfolio.variance(cov)
# You can drill deeper into the tree
>>> left = root.left
>>> right = root.right
```
## uv
Starting with
```bash
make install
```
will install [uv](https://github.com/astral-sh/uv) and create
the virtual environment defined in
pyproject.toml and locked in uv.lock.
## marimo
We install [marimo](https://marimo.io) on the fly within the aforementioned
virtual environment. Executing
```bash
make marimo
```
will install and start marimo.