I am doing a portfolio optimization using Gekko. I am using the returns per asset and its covariance matrix as input. The code I am trying is
# Initialize Model
m = GEKKO(remote=True)
#initialize variables
w=m.Array(m.Var,23)
for i in range(23):
w[i].value = 0.04347826
w[i].lower = 0.0
w[i].upper = 1.0
#Equations
m.Equation(0.18 >= (np.dot(w.T,np.dot(covariance_ar, w)))**0.5)
m.Equation(np.sum(w[0:23]) == 1.0)
m.Equation(w[7]+w[9]+w[11] >= (np.sum(w[7:13])*0.3))
m.Equation(w[7]+w[9]+w[11] <= (np.sum(w[7:13])*0.7))
m.Equation(w[11]+w[12] >= 0.0)
m.Equation(w[11]+w[12] <= (np.sum(w[7:13])*0.15))
#Objective
m.Obj(-(np.sum(return_ar.T @ w)))
#Solve simulation
m.solve() # solve on public server
#Results
for i in range(23):
print('w['+str(i)+']='+str(w[i].value))
return_ar is an array of returns of individual assets of shape (23,1) and covariance_ar is the covariance array of returns of shape (23,23)
Although the code ran succesfully with small number of weights, with 23 weight parameters it is throwing error Exception: @error: Max Equation Length....... APM model error: string > 15000 characters Consider breaking up the line into multiple equations
Can you help me to formulate the code constraint so that this works.
I couldn't run your code because it was missing values so I had to modify it with sample values.
This reproduces the same error that you observed. You can overcome the equation length limitation by redefining your
np.dot
functions with list comprehensions. Also, you need to use them.sum()
gekko function instead of the numpy function for summation.You can now use your values for
covariance_ar
andreturn_ar
. The reason this method works is that Gekko can break down the equations into smaller pieces that are solved individually. The length limitation for each equation of 15,000 characters is not just a processing limitation but also encourages better model formulation strategies that work well with sparse nonlinear programming solvers.