【发布时间】:2020-09-23 02:48:17
【问题描述】:
基于来自 20 种资产的每日观察的大型数据集,我创建了一个包含(滚动)相关矩阵的字典。我使用日期索引作为字典的键。
我现在要做的(以一种有效的方式)是比较字典中的所有相关矩阵并将结果保存在一个新矩阵中。这个想法是比较一段时间内的相关结构。
import pandas as pd
import numpy as np
from scipy.cluster.hierarchy import linkage
from scipy.cluster.hierarchy import cophenet
key_list = dict_corr.keys()
# Create empty matrix
X = np.empty(shape=[len(key_list),len(key_list)])
key1_index = 0
key2_index = 0
for key1 in key_list:
# Extract correlation matrix from dictionary
corr1_temp = d[key1]
# Transform correlation matrix into distance matrix
dist1_temp = ((1-corr1_temp)/2.)**.5
# Extract hierarchical structure from distance matrix
link1_temp = linkage(dist1_temp,'single')
for key2 in key_list:
corr2_temp = d[key2]
dist2_temp = ((1-corr2_temp)/2.)**.5
link2_temp = linkage(dist2_temp,'single')
# Compare hierarchical structure between the two correlation matrizes -> results in 2x2 matrix
temp = np.corrcoef(cophenet(link1_temp),cophenet(link2_temp))
# Extract from the resulting 2x2 matrix the correlation
X[key1_index, key2_index] = temp[1,0]
key2_index =+ 1
key1_index =+1
我很清楚使用两个 for 循环可能是效率最低的方法。
所以我很感谢任何有用的评论如何加快计算!
最好的
【问题讨论】:
标签: python pandas numpy scipy hierarchical-clustering