Search code examples
pythonoptimizationmathematical-optimizationquantitative-financegekko

Is it possible to use gekko to do portfolio Optimisation?


I have been using my own simple code to do Monte Carlo simulations to create sample portfolios. While effective, I don’t feel like I’m getting the best results.

I am not a math major or anything. Is it possible to use gekko to solve for a certain portfolio like highest sharpe ratio or least variance, highest return etc?

Before I try to figure it out on my own I wanna know if it’s possible.

I have been looking online for code examples but I can’t seem to find anything. Is it possible ? Any ideas ?


Solution

  • It should be possible as long as you can describe the optimization problem mathematically with equations and an objective. Below is an example with 3 potential assets between 0 and 5 units and a total budget of 100. The objective is to maximize the mean of the Sharpe ratio. I'm not an expert on portfolio optimization so the equations or objective function are likely incorrect. It is an example of how to solve a related optimization problem with linear programming.

    from gekko import GEKKO
    m = GEKKO(remote=False)
    x = m.Array(m.Var,3,value=1,lb=0,ub=5)
    # asset price
    p = [5,10,6.2]
    # expected return on the asset
    Rp = [0.1,0.05,0.3]
    # risk free rate of return
    Rf = [0.01,0.02,0.01]
    # standard deviation of returns of the asset
    sigma = [0.1,0.2,0.15]
    
    # linear inequality constraint Ax<b
    A = [[3, 6, 1], [8, 4, 3], [2, 2, 2]]
    b = [30, 44, 35]
    m.axb(A,b,x=x,etype='<')
    
    # total budget
    m.Equation(m.sum(x)<100)
    
    # total assets purchased
    ta = m.Intermediate(m.sum(x))
    
    # maximize mean Sharpe ratio of portfolio
    m.Maximize(m.sum([x[i]*(Rp[i]-Rf[i])/sigma[i] for i in range(3)])/ta)
    
    m.options.solver = 1
    m.solve(disp=True)
    for i in range(3):
        print ('Asset ',i+1,x[i].value[0])
    print ('Objective: ' + str(-m.options.objfcnval))
    

    Gekko also allows nonlinear equations or objective functions with continuous or mixed integer decision variables. This particular example is a linear deterministic model with a unique solution.

    Asset  1 0.0
    Asset  2 0.29204291501
    Asset  3 5.0
    Objective: 1.8349195688
    

    If you want to include uncertainty then there are several strategies to do this such as simultaneously solving multiple instances of the model with sampling from the uncertainty distribution.