Files
strategy-lab/to_explore/pyquantnews/82_HierarchicalRiskParity.ipynb
David Brazda e3da60c647 daily update
2024-10-21 20:57:56 +02:00

5.9 KiB

No description has been provided for this image

This code performs hierarchical risk parity (HRP) portfolio optimization using historical price data of selected assets. It fetches historical price data, calculates returns, and constructs a hierarchical tree using the Pearson correlation. The code then optimizes the portfolio using HRP methodology and visualizes the portfolio allocation and risk contributions. This is useful for constructing diversified portfolios that minimize risk through hierarchical clustering.

In [ ]:
import pandas as pd
import riskfolio as rp
from openbb import obb

Define a list of asset symbols for which historical price data will be retrieved

In [ ]:
assets = [
    "XLE", "XLF", "XLU", "XLI", "GDX", 
    "XLK", "XLV", "XLY", "XLP", "XLB", 
    "XOP", "IYR", "XHB", "ITB", "VNQ", 
    "GDXJ", "IYE", "OIH", "XME", "XRT", 
    "SMH", "IBB", "KBE", "KRE", "XTL", 
]

Fetch historical price data for the specified assets and pivot the data into a DataFrame

In [ ]:
data = (
    obb
    .equity
    .price
    .historical(assets, provider="yfinance")
    .to_df()
    .pivot(columns="symbol", values="close")
)

Calculate percentage returns from the historical price data and drop any missing values

In [ ]:
returns = data.pct_change().dropna()

Plot a dendrogram to visualize hierarchical clustering of asset returns using Pearson correlation

In [ ]:
ax = rp.plot_dendrogram(
    returns=returns,
    codependence="pearson",
    linkage="single",
    k=None,
    max_k=10,
    leaf_order=True,
    ax=None,
)

Create an instance of HCPortfolio with the calculated returns for portfolio optimization

In [ ]:
port = rp.HCPortfolio(returns=returns)

Optimize the portfolio using Hierarchical Risk Parity (HRP) with specified parameters

In [ ]:
w = port.optimization(
    model="HRP",
    codependence="pearson",
    rm="MV",
    rf=0.05,
    linkage="single",
    max_k=10,
    leaf_order=True,
)

Plot a pie chart to visualize the portfolio allocation resulting from the HRP optimization

In [ ]:
ax = rp.plot_pie(
    w=w,
    title="HRP Naive Risk Parity",
    others=0.05,
    nrow=25,
    cmap="tab20",
    height=8,
    width=10,
    ax=None,
)

Plot the risk contributions of each asset in the optimized portfolio

In [ ]:
ax = rp.plot_risk_con(
    w=w,
    cov=returns.cov(),
    returns=returns,
    rm="MV",
    rf=0,
    alpha=0.05,
    color="tab:blue",
    height=6,
    width=10,
    t_factor=252,
    ax=None,
)

PyQuant News is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to get started with Python for quant finance. For educational purposes. Not investment advise. Use at your own risk.