使用 numpy returns 零方矩阵创建对角矩阵

creating diagonal matrix using numpy returns zero square matrix

在下面的代码中,我试图创建一个带有变量 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

您正在覆盖 s1,因为 np.dot(s1, r1, s1) 等同于 np.dot(s1, r1, out=s1),后者将覆盖 s1

我猜你想做 s1.dot(r1).dot(s1)