-
-
Save khuyentran1401/e271a4e40b25cbceb36851cb226c369d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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