tgoop.com/data_notes/113
Create:
Last Update:
Last Update:
Насущная проблема инвесторов из РФ: лимит на продажу заблокированных активов 100 тысяч рублей, превышать который нельзя. Если таковых на бОльшую сумму, то возникает вопрос, какие активы продать, чтобы использовать лимит по-максимуму? С ответом поможет линейное программирование!
from ortools.linear_solver import pywraplp
def maximize_spending(L, prices, stock):
# Create a linear solver object
solver = pywraplp.Solver.CreateSolver('SCIP')
# Define variables
quantities = [solver.IntVar(0, stock[i], f'quantity_{i}') for i in range(len(prices))]
# Define objective function: maximize the total spending
objective = solver.Objective()
for i in range(len(prices)):
objective.SetCoefficient(quantities[i], prices[i])
objective.SetMaximization()
# Add constraint: total spending should not exceed the limit M
constraint_total_spending = solver.Constraint(0, L)
for i in range(len(prices)):
constraint_total_spending.SetCoefficient(quantities[i], prices[i])
# Solve the problem
status = solver.Solve()
if status == pywraplp.Solver.OPTIMAL:
total_spending = sum(quantities[i].solution_value() * prices[i] for i in range(len(prices)))
items_quantities = {f'I{i+1}': int(quantities[i].solution_value()) for i in range(len(prices))}
return total_spending, items_quantities
else:
return None
Пример использования: задаем наш лимит, количества бумаг и цену каждой. На выходе получим количества бумаг, для которых нужно подать заявку на продажу, чтобы использовать лимит по максимуму:
# Money limit
L = 100000
# Prices of items I1, I2, I3, I4
prices = [709.18, 11851.10, 1528.21, 9395.44]
# Quantities of items in stock Q1, Q2, Q3, Q4
stock = [17, 4, 19, 12]
total_spending, items_quantities = maximize_spending(L, prices, stock)
if total_spending is not None:
print("Maximum spending:", total_spending)
print("Items quantities:", items_quantities)
else:
print("No solution found.")
BY Data notes
Share with your friend now:
tgoop.com/data_notes/113