0
# Hierarchical Clustering
1
2
Hierarchical clustering-based portfolio optimization using advanced clustering algorithms for asset allocation based on correlation structures. The HCPortfolio class implements Hierarchical Risk Parity (HRP), Nested Clustered Optimization (NCO), and other clustering-based portfolio construction methods.
3
4
## Capabilities
5
6
### HCPortfolio Class
7
8
Hierarchical clustering portfolio optimization class for correlation-based asset allocation.
9
10
```python { .api }
11
class HCPortfolio:
12
def __init__(self, returns=None, kappa=0.30, kappa_g=None):
13
"""
14
Initialize HCPortfolio object.
15
16
Parameters:
17
- returns (DataFrame): Assets returns data
18
- kappa (float): Deformation parameter for RLVaR/RLDaR (0-1) (default: 0.30)
19
- kappa_g (float): Deformation parameter for RLVaR gains (default: None)
20
"""
21
```
22
23
### Hierarchical Optimization
24
25
Main optimization method supporting multiple clustering-based portfolio models.
26
27
```python { .api }
28
def optimization(self, model='HRP', codependence='pearson', covariance='hist',
29
obj='MinRisk', rm='MV', rf=0, l=0, linkage='single',
30
max_k=10, leaf_order=True):
31
"""
32
Hierarchical clustering portfolio optimization.
33
34
Parameters:
35
- model (str): Optimization model ('HRP', 'HERC', 'NCO', 'HERC2')
36
- codependence (str): Codependence measure ('pearson', 'spearman', 'abs_pearson',
37
'abs_spearman', 'distance_corr', 'mutual_info', 'tail')
38
- covariance (str): Covariance estimation method ('hist', 'ewma1', 'ewma2',
39
'ledoit', 'oas', 'shrunk', 'gl', 'jlogo', 'fixed', 'spectral', 'shrink')
40
- obj (str): Objective function ('MinRisk', 'Utility', 'Sharpe', 'MaxRet')
41
- rm (str): Risk measure for optimization
42
- rf (float): Risk-free rate
43
- l (float): Risk aversion parameter
44
- linkage (str): Linkage method ('single', 'complete', 'average', 'weighted',
45
'centroid', 'median', 'ward', 'DBHT')
46
- max_k (int): Maximum number of clusters for NCO
47
- leaf_order (bool): Optimize leaf order in dendrogram
48
49
Returns:
50
DataFrame: Optimal portfolio weights
51
"""
52
```
53
54
### Properties
55
56
Key properties for accessing portfolio data and parameters.
57
58
```python { .api }
59
@property
60
def returns(self):
61
"""Get/set assets returns DataFrame."""
62
63
@property
64
def assetslist(self):
65
"""Get list of asset names."""
66
67
@property
68
def kappa(self):
69
"""Get/set RLVaR deformation parameter."""
70
71
@property
72
def kappa_g(self):
73
"""Get/set RLVaR deformation parameter for gains."""
74
```
75
76
## Model Types
77
78
### Hierarchical Risk Parity (HRP)
79
80
Allocates capital by recursively bisecting the correlation matrix based on hierarchical clustering, providing diversification benefits without traditional mean-variance optimization.
81
82
### Hierarchical Equal Risk Contribution (HERC)
83
84
Extension of HRP that allocates capital to equalize risk contributions across clusters and within clusters, providing better risk budgeting.
85
86
### Nested Clustered Optimization (NCO)
87
88
Combines hierarchical clustering with traditional optimization by first clustering assets and then optimizing within and across clusters.
89
90
### HERC2
91
92
Advanced version of HERC with improved risk contribution calculations and cluster allocation methods.
93
94
## Usage Example
95
96
```python
97
import riskfolio as rp
98
import pandas as pd
99
100
# Load returns data
101
returns = pd.read_csv('returns.csv', index_col=0, parse_dates=True)
102
103
# Create hierarchical portfolio
104
hc_port = rp.HCPortfolio(returns=returns)
105
106
# Hierarchical Risk Parity optimization
107
w_hrp = hc_port.optimization(
108
model='HRP',
109
codependence='pearson',
110
covariance='hist',
111
obj='MinRisk',
112
rm='MV',
113
linkage='ward'
114
)
115
116
# Nested Clustered Optimization
117
w_nco = hc_port.optimization(
118
model='NCO',
119
codependence='pearson',
120
covariance='hist',
121
obj='Sharpe',
122
rm='MV',
123
rf=0.02,
124
linkage='ward',
125
max_k=10
126
)
127
128
# HERC optimization with custom parameters
129
w_herc = hc_port.optimization(
130
model='HERC',
131
codependence='spearman',
132
covariance='ledoit',
133
obj='MinRisk',
134
rm='CVaR',
135
linkage='complete'
136
)
137
138
print("HRP Weights:")
139
print(w_hrp.T)
140
print("\nNCO Weights:")
141
print(w_nco.T)
142
print("\nHERC Weights:")
143
print(w_herc.T)
144
145
# Visualize clustering
146
ax = rp.plot_dendrogram(
147
returns=returns,
148
codependence='pearson',
149
linkage='ward'
150
)
151
152
# Plot clustered correlation matrix
153
ax = rp.plot_clusters(
154
returns=returns,
155
codependence='pearson',
156
linkage='ward'
157
)
158
```
159
160
## Codependence Measures
161
162
- **pearson**: Pearson correlation coefficient
163
- **spearman**: Spearman rank correlation
164
- **abs_pearson**: Absolute Pearson correlation
165
- **abs_spearman**: Absolute Spearman correlation
166
- **distance_corr**: Distance correlation
167
- **mutual_info**: Mutual information
168
- **tail**: Lower tail dependence index
169
170
## Linkage Methods
171
172
- **single**: Single linkage (minimum distance)
173
- **complete**: Complete linkage (maximum distance)
174
- **average**: Average linkage (UPGMA)
175
- **weighted**: Weighted average linkage (WPGMA)
176
- **centroid**: Centroid linkage (UPGMC)
177
- **median**: Median linkage (WPGMC)
178
- **ward**: Ward variance minimization
179
- **DBHT**: Direct Bubble Hierarchical Tree