使用numpy创建对角线矩阵返回零平方矩阵

2024-06-16 10:42:07 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,我试图用变量s1创建一个对角矩阵,但似乎得到了一个零平方矩阵。如果可以的话,我也尝试将函数crweights()中创建的变量调用到test()中,但没有成功。非常感谢你的帮助。你知道吗

import random as r
import numpy as np
import matplotlib.pyplot as plt

def crweights():
    ##Creates empty arrays for calculations##
    x = np.array([])
    y = np.array([])
    z = np.array([])
    nuport = np.array([])
    sigmaport = np.array([])
    ratio = np.array([])

    ##Below values are given in the question##
    sigma = [0.2,0.15,0.1]
    nu = [0.3,0.2,0.1]
    rho = [[1,-0.3,-0.5],[-0.3,1,-0.6],[-0.5,-0.6,1]]
    rho = np.array(rho).reshape(3,3)
    s1 = np.diag([0.2,0.15,0.1])####This is not working###
    r1 = rho*rho
    vcv = np.dot(s1,r1,s1)
    ##Below code created random weights for the portfolio##
    for i in range(10000):
        a = r.uniform(0,1)
        b = r.uniform(0,1-a)
        c = 1-(a+b)
        x = np.append(x,a)
        y = np.append(y,b)
        z = np.append(z,c)

        ## Below code computes return of the portfolio, SD of the portfolio and ratio for locating minium variance portfolio##
    for j in range(10000):
        nport = x[j]*nu[0]+y[j]*nu[1]+z[j]*nu[2]
        sp = np.sqrt(np.square(x[j])*np.square(sigma[0])+np.square(y[j])*np.square(sigma[1])+np.square(x[2])*np.square(sigma[2])+2*x[0]*x[1]*sigma[0]*sigma[1]*rho[0,1]+2*x[0]*x[2]*sigma[0]*sigma[2]*rho[0,2]+2*x[1]*x[2]*sigma[1]*sigma[2]*rho[1,2])
        nuport = np.append(nuport,nport)
        sigmaport = np.append(sigmaport,sp)
        p = nport/sp
        ratio = np.append(ratio,p)
    return nuport,sigmaport,ratio,s1;


k,l,m,j1 = crweights()

## The code below plots graph##
plt.scatter(k,l)
plt.show()
print(j1)
## The code below gives the location of MVP##
print(min(m))

np.diag doesn't work in the function


Tags: theinfornpcodearraysigmanu
1条回答
网友
1楼 · 发布于 2024-06-16 10:42:07

您正在覆盖s1,因为np.dot(s1, r1, s1)等价于np.dot(s1, r1, out=s1),后者将覆盖s1。你知道吗

我猜你的意思是s1.dot(r1).dot(s1)

相关问题 更多 >