首页 > 解决方案 > 如何计算两列内两组数据之间的相关性?

问题描述

我想先创建两列,然后用它LOG()来计算 columnPrice和 column的定期每日收益Adjusted Close。此后使用周期回报来计算周期每日回报之间的相关性。

我试过了

Combine_data['log_return'] = np.log(1 + Combine_data.pct_change)
Combine_data.head()

但它不工作。

Combine_data= pd.merge(XAU_USD,SP500, on='Date',suffixes= 
('(GOLD)','(SP500)'))
Combine_data.set_index('Date',inplace=True)
Combine_data.head()

这是我的输出的样子:

标签: pythonpandasmatplotlibjupyter-notebook

解决方案


您可以尝试如下:

ser1= (df['gold']+1).apply(np.log)
ser2= (df['silver']+1).apply(np.log)
np.corrcoef(ser1, ser2)

结果如下所示:

Out[431]: 
array([[1.        , 0.30121126],
       [0.30121126, 1.        ]])

考虑到数据是随机生成的,0.301 的相关性还不错:-)

Out[430]: 
          gold     silver        date
0   793.559641  19.112793  2019-08-23
1  1428.329390  17.758924  2019-08-24
2  1044.061092  17.962435  2019-08-25
3  1222.397539  17.638691  2019-08-26
4   890.945841  11.593497  2019-08-27
5  1224.616916  15.759736  2019-08-28
6  1059.684075  12.900665  2019-08-29
7  1147.011421  20.274250  2019-08-30
8   929.638993  12.244630  2019-08-31
9   515.545695  14.609073  2019-09-01

推荐阅读