我正在使用 SCIPY 来优化使用远期价格的存储设施,交易期限为 1 年。根据每月价差(例如 3 月 21 日与 5 月 20 日价差)是否足够高以覆盖可变运营成本,可以从该设施注入和提取天然气。附图代表了问题(这里的值是任意的,与代码中的值不匹配;图片仅用于概念)
蓝色单元格是“变化的单元格”,SCIPY 将调整数量以实现利润最大化。需要为每个月单独设置约束。当我尝试在 SCIPY 中设置这些约束时出现错误。这是该问题的可重现版本:
import numpy as np
import scipy.optimize as opt
p= np.array([4, 5, 6.65, 12]) #p = prices
pmx = np.triu(p - p[:, np.newaxis]) #pmx = price matrix, upper triangular
q =np.triu(np.ones((4,4))) # q = quantity, upper triangular
def profit(q):
profit = -np.sum(q.flatten() * pmx.flatten())
return profit
bnds = (0,10)
bnds = [bnds for i in q.flatten()]
def cons1(q):
np.sum(q,axis=1) - 10
#def cons2(q):
# np.sum(q,axis=0) - 8
#con1 = {'type':'ineq','fun':cons1}
#con2 = {'type':'ineq','fun':cons2}
cons = [con1] # using only 1 constraint (con1) to test the model
#sol = opt.minimize(profit,q,method='SLSQP', bounds= bnds,constraints = cons)
sol = opt.minimize(profit,q,method='SLSQP', bounds= bnds)
sol
当我排除约束时,模型运行良好。当我添加其中一项约束时,得到的错误是:
AxisError: axis 1 is out of bounds for array of dimension 1
我认为这与我指定约束的方式有关……但我不确定。对于约束,我确实需要识别注入和取款并设置约束,如图所示。如有帮助,将不胜感激。谢谢!