【发布时间】:2021-03-16 10:51:41
【问题描述】:
我对以下代码 sn-p 有疑问,我在其中优化了一个函数(最小化波动)。
from scipy import optimize as sco
import numpy as np
def risk_measure(covMatrix, weights):
risk = np.dot(weights, np.dot(covMatrix, weights))
return risk
prescribed_esg = 6 # esg score between 0 and 10 used as threshold in the esg_constraint
# Covariance and return matrix
V = np.matrix([[84.76695659, 20.8854772, 20.62182415, 74.73652696, 14.35995947],
[20.8854772, 35.22429277, 12.95439707, 32.22912903, 12.96449085],
[20.62182415, 12.95439707, 44.02079739, 38.73627316, 9.46608475],
[74.73652696, 32.22912903, 38.73627316, 178.86640813, 33.40281336],
[14.35995947, 12.96449085, 9.46608475, 33.40281336, 32.38514103]])
R = np.matrix([[-0.32264539, -0.08469428, 1.27628749, -0.23207085, 0.21012106]]).T
# Mean ESG score of each company
esgarr = np.matrix([[8.24336898, 4.6373262, 8.30657754, 4.65406417, 3.43620321]]).T
# Bounds and constraints
N = len(R) # number of instruments
bounds = ((-10,10),)*N # allow shorting, bounds of stocks
constraints = {'type': 'eq', 'fun': lambda weights: weights.sum() - 1}
esg_constraint = {'type': 'eq', 'fun': lambda weights: np.dot(weights, esgarr) - prescribed_esg}
esgmvp = sco.minimize(lambda x: risk_measure(V, x), # function to be minimized
N * [1 / N], # initial guess
bounds=bounds, # boundary conditions
constraints =[constraints, esg_constraint], # equality constraints)
)
esgmvp_weights = list(esgmvp['x'])
esgmvp_risk = esgmvp['fun']
esgmvp_esg = np.dot(esgmvp_weights, esgarr)
带有错误信息
<ipython-input-252-0d6bf5d30ccf> in risk_measure(covMatrix, weights)
3
4 def risk_measure(covMatrix, weights):
----> 5 risk = np.dot(weights, np.dot(covMatrix, weights))
6 return risk
7
<__array_function__ internals> in dot(*args, **kwargs)
ValueError: shapes (5,) and (1,5) not aligned: 5 (dim 0) != 1 (dim 0)
如果我创建一个独立的权重矩阵,例如
weights = np.matrix([[1, 1, 1, 1, 1]])
risk = np.dot(weights, np.dot(V, weights.T))
但这在我的原始函数中转置时不起作用。
【问题讨论】: