Lot constraints for portfolio optimization-- how to enforce lot constraints on number of stocks
回答済みHi,
I am new to Gurobi and in portfolio optimization while using Python, I am trying to force a lot constraints-- meaning there if n number of stocks are selected then they should at least be x%(5%).
Here is the code:
import gurobipy as gp
from gurobipy import GRB
from math import sqrt
# Create an empty model
m = gp.Model('portfolio')
# Add matrix variable for the stocks
x = m.addMVar(len(stocks),name="x")
# y = m.addMVar(len(stocks),name="y",vtype=GRB.BINARY)
# y = m.addVar()
cons= np.diag(np.full(len(stocks),.05))
# Objective is to minimize risk (squared). This is modeled using the
# covariance matrix, which measures the historical correlation between stocks
portfolio_risk = x @ sigma @ x
m.setObjective(portfolio_risk, GRB.MINIMIZE)
# Fix budget with a constraint
m.addConstr(x.sum() == 1, 'budget')
# number of stocks to be 10 and if stock is selected then it should be at least 5%
y = m.addVar()
m.addConstr( y == gp.norm(x,0))
m.addConstr(y == 10, 'cardinal')
cons= np.diag(np.full(len(stocks),.05))
m.update()
# m.addConstr( x - cons@y >= 0, 'constraintname1')
# Adding cardinal constraint-- limit portfolio to only 5 stocks
# Verify model formulation
m.write('portfolio_selection_optimization.lp')
# Optimize model
m.optimize()
print(x.X)
print('Obj: %g' % m.ObjVal)
-
正式なコメント
This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum. Or why not try our AI Gurobot?. -
Hi Rajeev,If the lot constraints should ensure 1) \(n\) stocks are selected and 2) if a stock is selected, its investment value is \(\geq 0.05\), then you just need to change the type of the \(x\) variables from continues to semi-continuous, forcing variables \(x\) to take a value of 0, or a value between the specified lower and upper bounds. Specifically, you need to define the \(x\) variables as:
x = m.addMVar(len(stocks), vtype=GRB.SEMICONT, lb=0.05, name="x")
Your explanation of the lot constraints is not super clear to me. I inferred the above meaning from your code. If this does not represent the constraints you are looking for to implement, please clarify.Best regards,Maliheh0 -
Thanks a lot, Maliheh! It works and solved my problem-- made me learn as I am very new to Gurobi.
Regards,
Raj
0
投稿コメントは受け付けていません。
コメント
3件のコメント