简体   繁体   English

计算 python 中的一系列相关矩阵(如 DataFrames、pandas)之间的差异

[英]Calculating the differences between series of correlation matrixes (as DataFrames, pandas) in python

From a series of DataFrames that contain daily log returns of a large number of stocks, eg:来自包含大量股票每日日志回报的一系列 DataFrame,例如:

data_list = [data_2015, data_2016, data_2017, data_2018, data_2019, data_2020]

The task at hand is to compute the change in the correlations between each successive year, eg:手头的任务是计算每个连续年份之间相关性的变化,例如:

data_2015.corr() - data_2016.corr()

It is the element-wise differences / changes that is needed.需要的是元素方面的差异/更改。 A simple for loop gives really bad answers and I am stuck一个简单的 for 循环给出了非常糟糕的答案,我被卡住了

for i in data_list:
    j = i +1
        
    a = (i).corr()
    b = (j).corr()
    
    print(a-b)

An stylized example would work something as follows:一个程式化的示例将按如下方式工作:

#import pandas and numpy
import numpy as np
import pandas as pd


#create four symmetric matrices with 1 on the diagonal as correlation matrix
np.random.seed(39)

b = np.random.randint(-100,100,size=(4,4))/100
b_symm = (b + b.T)/2
b = np.fill_diagonal(b_symm, 1)

c = np.random.randint(-100,100,size=(4,4))/100
c_symm = (c + c.T)/2
c = np.fill_diagonal(c_symm, 1)

d = np.random.randint(-100,100,size=(4,4))/100
d_symm = (d + d.T)/2
d = np.fill_diagonal(d_symm, 1)

e = np.random.randint(-100,100,size=(4,4))/100
e_symm = (e + e.T)/2
e = np.fill_diagonal(e_symm, 1)

#convert to DataFrame
data_2015 = pd.DataFrame(b_symm)
data_2016 = pd.DataFrame(c_symm)
data_2017 = pd.DataFrame(d_symm)
data_2018 = pd.DataFrame(e_symm)

#print DataFrames
print(data_2015)
print(data_2016)
print(data_2017)
print(data_2018)

#print intended result(s)
print("Change in correlations 2015-16",'\n',data_2015-data_2016,'\n')
print("Change in correlations 2016-17",'\n',data_2016-data_2017,'\n')
print("Change in correlations 2017-18",'\n',data_2017-data_2018,'\n')

If I understand correctly you want to access consecutive pairs of elements of data_list so you can calculate the differences in their correlations?如果我理解正确,您想访问data_list的连续元素对,以便计算它们相关性的差异? There are many ways to do it, a somewhat ugly but at least transparent way is as follows有很多方法可以做到,一个有点难看但至少透明的方法如下

for i in range(len(data_list)-1):
        
    a = data_list[i+1].corr()
    b = data_list[i].corr()
    
    print(a-b)

a more Pythonian way to write this would be一种更 Pythonian 的写法是

for a,b in zip(data_list[1:],data_list[:-1]):
    print(a.corr()-b.corr())

or even simply甚至简单地

[print(a.corr() - b.corr()) for a,b in zip(data_list[1:],data_list[:-1])]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM