为什么我不能在scipy.optimize SLSQP中迭代地附加新约束?

时间:2017-09-15 02:09:38

标签: python-3.x numpy optimization scipy iteration

scipy.optimize中的SLSQP方法接受可以包含在列表中的约束。但是,我正在编写的程序类型没有一组可以硬编码的约束。 以下列表是所述资产类型出现在“主”证券清单中的指数。

us_stock_indices = [0, 4, 12, 15, 19, 23]
intl_stock_indices = [1, 2, 18, 20, 21, 24]
us_bond_indices = [3, 5, 7, 8, 11, 16, 17]
intl_bond_indices = [14, 22]
alternative_indices = [6, 13]
hedge_fund_indices = [9, 10]

此问题的限制主要是将每种给定资产类型的总百分比保持在特定窗口内(例如,我只希望优化的对冲基金证券百分比占投资组合的0%至10%)

cons = [{'type': 'ineq', 'fun': lambda x: target_risk_level - .08}, {'type': 'eq', 'fun': lambda x: np.sum(x) - 1},
    {'type': 'ineq', 'fun': lambda x: np.sum([x[i] for i in us_stock_indices]) - .17}, {'type': 'ineq', 'fun': lambda x: .37- np.sum([x[i] for i in us_stock_indices])},
    {'type': 'ineq', 'fun': lambda x: np.sum([x[i] for i in intl_stock_indices]) - .08}, {'type': 'ineq', 'fun': lambda x: .28- np.sum([x[i] for i in intl_stock_indices])},
    {'type': 'ineq', 'fun': lambda x: np.sum([x[i] for i in .35]) - us_bond_min}, {'type': 'ineq', 'fun': lambda x: .6- np.sum([x[i] for i in us_bond_indices])},
    {'type': 'ineq', 'fun': lambda x: np.sum([x[i] for i in intl_bond_indices]) - .02}, {'type': 'ineq', 'fun': lambda x: .2 - np.sum([x[i] for i in intl_bond_indices])},
    {'type': 'ineq', 'fun': lambda x: np.sum([x[i] for i in alternative_indices]) - 0}, {'type': 'ineq', 'fun': lambda x: .1- np.sum([x[i] for i in alternative_indices])},
    {'type': 'ineq', 'fun': lambda x: np.sum([x[i] for i in hedge_fund_indices]) - 0}, {'type': 'ineq', 'fun': lambda x: .1- np.sum([x[i] for i in hedge_fund_indices])}]

以下代码按总投资组合的权重划分不同的帐户类型(Trust,IRA和Roth)。因此,例如,信托账户中证券的最终加权(或total_array的索引0)需要等于.41646367

account_weight_array = [0.41646367, 0.42259312, 0.16094321]
total_array = [['SCHB', 'INTF', 'EMGF', 'SCHR', 'LRGF', 'TFI', 'PGX'], ['CORP', 'SCHZ', 'QSPIX', 'AQMIX', 'LALDX', 'FNDX', 'BKLN', 'PCY', 'SPLV', 'SCHP', 'ZROZ'], ['FNDF', 'PSLDX', 'FNDC', 'SCHF', 'EMLC', 'FNDX', 'FNDE']]

for i in np.arange(3):
    cons.append({'type': 'eq', 'fun': lambda x: np.sum([x[r] for r in np.arange(len(total_array[i]))]) - account_weighting_array[i]})

终止消息是“LSQ子问题中的线性子矩阵C”。但是,理论上应该完全相同的以下代码可以起作用:

cons.append({'type': 'eq', 'fun': lambda x: np.sum([x[r] for r in np.arange(len(total_array[0]))]) - account_weighting_array[0]})
cons.append({'type': 'eq', 'fun': lambda x: np.sum([x[r] for r in (np.arange(len(total_array[1]))]) - account_weighting_array[1]})
cons.append({'type': 'eq', 'fun': lambda x: np.sum([x[r] for r in (np.arange(len(total_array[2]))]) - account_weighting_array[2]})

我不明白为什么运行for-或while循环不起作用,但是在单独的代码行上手动执行。在两种情况下,我只是在列表中添加一个新元素。奇怪的是,当我只是让代码构建约束列表(“cons”)并打印它时,您可以看到新对象已成功添加,但出于某种原因,当我运行优化时,它将无法识别它

0 个答案:

没有答案