要优化的功能:
def optimize(allocs, allStocksNormalized):
allocs = allStocksNormalized * allocs
postvalues = allocs * startvalue
portfolioValues = postvalues.sum(axis=1)
cumulativeReturns = (portfolioValues[-1] / portfolioValues[0]) - 1
return cumulativeReturns*-1
通话功能:
allocsGuess = [0.3,0.3,0.3,0.1]
cons = ({'type': 'eq', 'fun' : lambda inputs: 1 - (np.sum(abs(inputs)))})
bnds = [(0.0, 1.0), (0.0, 1.0), (0.0, 1.0), (0.0, 1.0)]
min_cum_return = optimizer.minimize(optimize, allocsGuess, args=(allStocksNormalized,) ,
method='SLSQP', bounds=bnds, constraints=cons,
options={'disp': True})
print("X = {}, Y = {}".format(min_cum_return.x,min_cum_return.fun))
现在返回这样的结果 -
X = [ 3.47499807e-14 1.00000000e+00 0.00000000e+00 0.00000000e+00], Y = -14.500342231347526
我想要以下条件的约束 -
正如我们所看到的,我从X数组得到的结果不符合任何一个标准。
如何改善这一点以使其有效?
答案 0 :(得分:1)
尝试以下操作:
bnds = ((0.0, 1.0), (0.0, 1.0), (0.0, 1.0), (0.0, 1.0))
绑定应该是一个元组