首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当通过lambda调用函数时,尺寸是错误的。

当通过lambda调用函数时,尺寸是错误的。
EN

Stack Overflow用户
提问于 2021-03-16 10:51:41
回答 1查看 27关注 0票数 0

我对下面的代码片段有问题,在这里我优化了一个函数(最小化了波动性)。

代码语言:javascript
复制
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)

带有错误消息

代码语言:javascript
复制
<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)

如果我创建一个独立的权重矩阵,例如

代码语言:javascript
复制
weights = np.matrix([[1, 1, 1, 1, 1]])
risk = np.dot(weights, np.dot(V, weights.T))

但是当我在原来的函数中转换时,这是行不通的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-17 10:53:47

下列问题解决了这个问题

代码语言:javascript
复制
V = np.squeeze(np.asarray(V))
esg_constraint = {'type': 'eq', 'fun': lambda weights: np.dot(weights, esgarr).sum() - prescribed_esg}

我还编辑了这个函数

代码语言:javascript
复制
def risk_measure(covMatrix, weights):
    risk = np.dot(weights.T, np.dot(covMatrix, weights))
    return risk
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66653737

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档