If any one could help,I can't express the objective function, this is my code:
import numpy as np
def portfolio_return( weights, returns):
return weights.T @ returns
def portfolio_vol( weights, covmatrix):
return np.sqrt(weights.T @ covmatrix @ weights)
def sharp_ratio(er,covmat,w,rf = 0.01):
r_p = portfolio_return(w, er)/100
sigma_p = portfolio_vol(w,cov)/100
return (r_p-rf)/sigma_p
w = mdl.integer_var_list(5,5,30, 'w')
mdl.add_constraint(mdl.sum(w) == 100)
mdl.minimize(-sharp_ratio(quartered_er, cov,np.array(w)))
But i get this error:
loop of ufunc does not support argument 0 of type QuadExpr which has no callable sqrt method
You may use numpy for some computation after the solve but the constraints should be described with functions from docplex.
For instance, the quadratic example from the making optimization easy with python story
from docplex.mp.model import Model
mdl = Model(name='buses')
nbbus40 = mdl.integer_var(name='nbBus40')
nbbus30 = mdl.integer_var(name='nbBus30')
mdl.add_constraint(nbbus40*40 + nbbus30*30 >= 300, 'kids')
mdl.minimize(nbbus40**2*500 + nbbus30**2*400)
mdl.solve()
for v in mdl.iter_integer_vars():
print(v," = ",v.solution_value)
import numpy as np
print("We bring ",np.array(
[40,30])@np.array([nbbus40.solution_value,nbbus30.solution_value])
," kids to the zoo")
gives
nbBus40 = 4.0
nbBus30 = 5.0
We bring 310.0 kids to the zoo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.