Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add HRP optimizer #60

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions turingquant/optimizers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,85 @@
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import linkage, leaves_list


class HierarchicalRiskParity:
'''
Hierarchical risk parity is a portfolio optimization algorithm that uses unsupervised learning (machine learning).

Parâmetros:
cov_matrix (pd.DataFrame): Matrix de covariança de um portfólio.
'''
def __init__(self, cov_matrix: pd.DataFrame):

self._cov_matrix = cov_matrix
self._columns = cov_matrix.columns
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Se colocarem uma cov_matrix numpy não funciona, infelizmente esse typing nao faz verificação dinâmica


def optimize(self):

seriation_columns = self._matrix_seriation()

weights = self._recursive_bisection(seriation_columns)

named_weights = self._mount_weights(weights)

return named_weights

def _matrix_seriation(self):

dendogram = linkage(self._cov_matrix, 'ward')

seriation_columns = leaves_list(dendogram)

return seriation_columns

def _recursive_bisection(self, seriation_columns):

weights = pd.Series(1, index=seriation_columns)
parities = [seriation_columns]

while len(parities) > 0:
parities = [cluster[start:end]
for cluster in parities
for start, end in ((0, len(cluster) // 2), (len(cluster) // 2, len(cluster)))
if len(cluster) > 1]

for subcluster in range(0, len(parities), 2):

left_cluster = parities[subcluster]
right_cluster = parities[subcluster + 1]

vol_left_cluster = self._get_cluster_vol(left_cluster)
vol_right_cluster = self._get_cluster_vol(right_cluster)

alocation_factor = 1 - vol_left_cluster / \
(vol_left_cluster + vol_right_cluster)

weights[left_cluster] *= alocation_factor
weights[right_cluster] *= 1 - alocation_factor

return weights

def _get_cluster_vol(self, cluster_assets):

cov_matrix = self._cov_matrix.iloc[cluster_assets, cluster_assets]

inv_diagonal = 1 / np.diag(cov_matrix.values)
weights = inv_diagonal / \
np.sum(inv_diagonal)

cluster_vol = np.dot(weights, np.dot(
cov_matrix, weights))

return cluster_vol

def _mount_weights(self, weights):

weights.index = self._columns[weights.index]

return weights

class Markowitz:
'''
Otimizador baseado na Teoria Moderna do Portfólio, de Harry Markowitz.
Expand Down