我试图最小化一个基本上如下所示的函数:
实际上它有两个自变量,但由于x1+x2=1,它们并不是真正独立的。你知道吗
现在是目标函数
def calculatePVar(w,covM):
w = np.matrix(w)
return (w*covM*w.T) [0,0]
wnere w是每个资产的权重列表,covM是由pandas的.cov()返回的协方差矩阵
在这里调用优化函数:
w0 = []
for sec in portList:
w0.append(1/len(portList))
bnds = tuple((0,1) for x in w0)
cons = ({'type': 'eq', 'fun': lambda x: np.sum(x)-1.0})
res= minimize(calculatePVar, w0, args=nCov, method='SLSQP',constraints=cons, bounds=bnds)
weights = res.x
现在函数有一个明确的最小值,但minimize只会吐出初始值作为结果,它确实表示“优化已成功终止”。有什么建议吗?你知道吗
优化结果:
图片作为链接,因为我不符合要求!你知道吗
你的代码有一些混乱的变量,所以我只是清除了这些,简化了一些行,现在最小化工作正常。然而,现在的问题是:结果是否正确?它们有意义吗?这是你的判断:
更新:
根据你的评论,在我看来-也许-你的函数有多个极小值,这就是
scipy.optimize.minimize
被困在那里的原因。我建议scipy.optimize.basinhopping
作为一种替代方法,这将使用一个随机步骤来遍历函数的大多数极小值,而且它仍然很快。代码如下:输出:
相关问题 更多 >
编程相关推荐