我正在尝试为随机生成的投资组合计算投资组合值,例如收益,标准差。但是,在计算标准偏差时出现错误
试图将numpy数组转换为矩阵,但仍然无法正常工作。
for i in range(no_of_portfolios):
#Select random weights and normalize to set the sum to 1
weights = np.array(np.random.random(no_of_assets))
weights /= np.sum(weights)
print("Weights are before reshaping",weights,np.shape(weights))
np.reshape(weights,(3,1))
print("Weights are after reshaping",weights,np.shape(weights))
#Calculate the return and standard deviation for every step
portfolio_return = np.sum(mean_returns * weights)
portfolio_std_dev = np.sqrt(np.dot(weights.T,np.dot(v_cov, weights)))
#Store all the results in a defined array
v_simulation_res[0,i] = portfolio_return
v_simulation_res[1,i] = portfolio_std_dev
v_cov is [[ 0.04 -0.009 -0.01 ]
[-0.009 0.0225 -0.009 ]
[-0.01 -0.009 0.01 ]]
no_of_portfolios = 10
no_of_assets = 3
mean_returns = np.matrix([[0.3],[0.2],[0.1]])
vol_arr = np.matrix([[0.2],[.15],[0.1]])
rho_arr = np.matrix([[1,-0.3,-0.5],[-0.3,1,-0.6],[-0.5,-0.6,1]])
对于资产权重的每种组合,我都希望为Portfolio_std_dev获得一个数字,即10个值(每行一个)
我遇到错误:
ValueError: shapes (3,) and (1,3) not aligned: 3 (dim 0) != 1 (dim 0)
可能是因为weights数组的形状为(3,0),但不确定如何修复它。
答案 0 :(得分:0)
np.reshape(weights,(3,1))
print(“重量在重塑之后”,weights,np.shape(weights))
np.reshape返回整形数组。它没有改变。所以,我不确定您在这里做什么,但我猜您错过了形状变化吗?如果要更改形状,请分配权重。