gpt4 book ai didi

python - 尝试使用 #gekko 最大化这个简单的非线性问题,但出现此错误

转载 作者:行者123 更新时间:2023-12-03 16:35:16 25 4
gpt4 key购买 nike

(@错误:未找到解决方案)

positions = ["AAPL", "NVDA", "MS","CI", "HON"]
cov = df_ret.cov()
ret = df_ret.mean().values
weights = np.array(np.random.random(len(positions)))

def maximize(weights):
std = np.sqrt(np.dot(np.dot(weights.T,cov),weights))
p_ret = np.dot(ret.T,weights)
sharpe = p_ret/std
return sharpe

a = GEKKO()
w1 = a.Var(value=0.2, lb=0, ub=1)
w2 = a.Var(value=0.2, lb=0, ub=1)
w3 = a.Var(value=0.2, lb=0, ub=1)
w4 = a.Var(value=0.2, lb=0, ub=1)
w5 = a.Var(value=0.2, lb=0, ub=1)

a.Equation(w1+w2+w3+w4+w5<=1)
weight = np.array([w1,w2,w3,w4,w5])

a.Obj(-maximize(weight))
a.solve(disp=False)

**** 试图弄清楚为什么它没有给出解决方案作为错误

# df_ret 是一个有 yield 的数据框(对于持仓的股票)

Df_ret looks like this

# 尝试最大化锐利比率

# w(1 to n) 是总和小于等于1的权重****

最佳答案

我不熟悉 GEKKO所以我真的帮不上那个包,但如果有人没有回答如何使用 GEKKO ,这是 scipy.optimize.minimize 的潜在解决方案:

from scipy.optimize import minimize
import numpy as np
import pandas as pd



def OF(weights, cov, ret, sign = 1.0):
std = np.sqrt(np.dot(np.dot(weights.T,cov),weights))
p_ret = np.dot(ret.T,weights)
sharpe = p_ret/std
return sign*sharpe


if __name__ == '__main__':

x0 = np.array([0.2,0.2,0.2,0.2,0.2])
df_ret = pd.DataFrame(np.array([[.001729, .014603, .036558, .016772, .001983],
[-0.015906, .006396, .012796, -.002163, 0],
[-0.001849, -.019598, .014484, .036856, .019292],
[.006648, .002161, -.020352, -.007580, 0.022083],
[-.008821, -.014016, -.006512, -.015802, .012583]]))
cov = df_ret.cov()
ret = df_ret.mean().values


minx0 = np.repeat(0, [len(x0)] , axis = 0)
maxx0 = np.repeat(1, [len(x0)] , axis = 0)
bounds = tuple(zip(minx0, maxx0))

cons = {'type':'ineq',
'fun':lambda weights: 1 - sum(weights)}
res_cons = minimize(OF, x0, (cov, ret, -1), bounds = bounds, constraints=cons, method='SLSQP')



print(res_cons)
print('Current value of objective function: ' + str(res_cons['fun']))
print('Current value of controls:')
print(res_cons['x'])

输出:
     fun: -2.1048843911794486
jac: array([ 5.17067784e+00, -2.36839056e-04, -6.24716282e-04, 6.56819057e+00,
2.45392323e-04])
message: 'Optimization terminated successfully.'
nfev: 69
nit: 9
njev: 9
status: 0
success: True
x: array([5.47832097e-14, 1.52927443e-01, 1.87864415e-01, 5.32258098e-14,
6.26433468e-01])
Current value of objective function: -2.1048843911794486
Current value of controls:
[5.47832097e-14 1.52927443e-01 1.87864415e-01 5.32258098e-14
6.26433468e-01]

此处添加符号参数是因为为了最大化目标函数,您只需最小化 OF*(-1)。我将默认值设置为 1(最小化),但我在 args 中传递 -1 来更改它。

关于python - 尝试使用 #gekko 最大化这个简单的非线性问题,但出现此错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61846319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com