在下面的代码中,我试图创建一个变量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))
答案 0 :(得分:0)
您要覆盖s1
,因为np.dot(s1, r1, s1)
等效于np.dot(s1, r1, out=s1)
,它将覆盖s1
。
我猜你打算做s1.dot(r1).dot(s1)