具有超越的多变量标准偏差用于相关

时间:2017-11-04 16:29:12

标签: python pandas numpy

所以我有一个多变量框架,其中我有3个不同权重的变量和一系列变量,如:

import numpy as np
weights = np.array([-2.61540125, -0.2480875, -0.2737325])
var = np.array([[0.00660683, -0.03470032, -0.02153846],
                [0.00458204, -0.02614379, -0.02830189],
                [-0.00098619, -0.00671141,  0.0032362],
                [0.00175217, -0.02591793, -0.01217039],
                [0.00077738,  0.00886918,  0.00821355],
                [0.00077677, -0.02197802,  0.00100000]])

我可以使用np.dot轻松计算标准偏差:

cov = np.cov(var.T)
standard_deviation = np.sqrt(weights.T.dot(cov).dot(weights))
standard_deviation

Out: 
0.0044526680008974574

但是我想覆盖相关矩阵并假设所有变量的相关性为1,并根据该假设找出标准差。是否有任何简单的矩阵运算我可以用numpy来做到这一点?我可以用循环来做,但我觉得这样效率不高

结果应该是:

0.015335270585229297

我这样做是为了达到它:

def stdev(weights, corr, stdev):
    total = 0.0
    for i in range(0, len(weights)):
        for j in range(0, len(weights)):
            if i < j:
                total = total + weights[i] * stdev[i] * weights[j] * stdev[j] * corr[i, j]
            else:
                total = total + weights[i] * stdev[i] * weights[j] * stdev[j] * corr[j, i]
    return total ** 0.5

cor_one = np.ones(var.shape)
stdev = pd.DataFrame(var).std(ddof=1)
stdev(weights, cor_one, stdev) 

0 个答案:

没有答案