I am trying to solve an optimization problem in python using the gurobi solver.
Problem background: I can buy and sell goods on a market with given Prices P for a series of time steps. For a start, I can only buy/sell one good and my warehouse has storage capacity for up to 2 goods at a time. I decided to add a Variables x for each time step that can either be -1 (buy), 0 (do nothing) or 1 (sell). The restriction thus is that the sum over all x[i] in each time step has to be >=-2 and <=0 (“never sell more than you have bougth before)
I manged to run the following code:
P =[1,3,5,4,5,2,2,4,6]
x = m.addVars(6,lb=-1, ub=1, vtype=GRB.INTEGER, name="x")
m.addConstr((quicksum(x[i] for i in range(len(P))) <=0), name=("con.format(i)"))
m.addConstr((quicksum(x[i] for i in range(len(P))) >=-2), name=("Const1"))
m.setObjective(quicksum(x[i]*P[i] for i in range(len(P))) , GRB.MAXIMIZE)
However, the result of the optimization {0: -1.0, 1: -1.0, 2: 1.0, 3: 1.0, 4: 1.0, 5: -1.0, 6: -1.0, 7: 0.0, 8: 1.0}
shows that the only the overall solution meets the requirements, but in between, the algorithm sells more good than it had purchased before (e.g. periode 5).
So, I need to adapt my code in a way that it introduces a contraint for each time step [i], which ensures that the sum of all privious steps [1 to i] also meet the constrains.
I found some similar problem (e.g. here: Gurobi Python: how to write nested sum in a constraint) but none could help me with my specific problem of how to calculate the interim sums in each step. However, I hope you can!
Thanks in advance and best regards!