Skip to content

Instantly share code, notes, and snippets.

@khuyentran1401
Created December 23, 2019 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khuyentran1401/e271a4e40b25cbceb36851cb226c369d to your computer and use it in GitHub Desktop.
Save khuyentran1401/e271a4e40b25cbceb36851cb226c369d to your computer and use it in GitHub Desktop.
pip install mip==1.4.2
from mip.model import *
"""* c[i] is the return of each stock
* a[t][i] is the investment of each stock for year t
* b[t] is the total investment limit each year
with i = 0, 1, 2, 3, 4;
> t = 0, 1, 2
"""
c = [90, 120, 100, 80, 130]
b = [45, 60, 50]
a = [[10, 15, 12, 9, 13],
[20, 15, 25, 15, 10],
[15, 20, 20, 15, 10]]
T, I = range(len(b)),range(len(c))
a[0][1]
"""Create an empty Mixed Integer Linear Programmning problem. The optimization sense is set to Maximize and the selected sovler is set to Cbc (Coin-or branch and cut)"""
m = Model(sense = MAXIMIZE,solver_name=CBC)
"""Create variables with *add_var()*
Crate a vector of variables with n binary decision variables (n = 5) indicating whether a stock is selected or not.
"""
names = ['A','B','C','D','E']
x = [[m.add_var(name = names[i], var_type=BINARY) for i in I] for t in T]
sum(x[t][i] for i in I for t in T)
"""> Objective is to maximize the total return
> Use *xsum()* for summation expressions
"""
m.objective = maximize(xsum(c[i] * x[t][i] for i in I for t in T))
"""Add constraint in money available each year"""
for t in range(3):
m += xsum(a[t][i] * x[t][i] for i in I) <= b[t]
"""> Optimize() method executes the optimization of a formulation.
> optimize method returns the status (OptimizationStatus) of the search.
> OPTIMAL if the search was concluded and the optimal solution was found.
"""
status = m.optimize()
if status == OptimizationStatus.OPTIMAL:
print('optimal solution cost {} found'.format(m.objective_value))
results = {}
for i in range(3):
results[i+1] = [m.vars[j].x for j in range(5*i,5*i+5)]
results
import pandas as pd
result = pd.DataFrame(data = results, index = ['A','B','C','D','E'])
result
"""Visualize the result"""
import matplotlib.pyplot as plt
result.plot(kind='bar', subplots = True, title = ['Year 1', 'Year 2', 'Year 3'])
plt.tight_layout()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment