我目前正在研究Python中的约束优化问题,虽然我能够制定我的问题,但我得到以下错误:'LSQ子问题中的奇异矩阵C'。
我相信这是因为我的两个约束(相等)不是连续的或者与它们相关的其他东西,因为优化器在没有它们的情况下工作。
以下是一个例子:
vol_tgt = 0.1
sign_vec =
---------------+----+
| XLK US Equity | 1 |
| XOP US Equity | 1 |
| KRE US Equity | 1 |
| KBE US EQUITY | 1 |
| XLK US EQUITY | 1 |
| XLE US EQUITY | 1 |
| XLF US EQUITY | 1 |
| XRT US EQUITY | 1 |
| XLU US EQUITY | 1 |
| XLY US EQUITY | 1 |
| XLV US EQUITY | 1 |
| STS FP EQUITY | 1 |
| STR FP EQUITY | 1 |
| STZ FP EQUITY | 1 |
| STW FP EQUITY | 1 |
| STQ FP EQUITY | 1 |
| STN FP EQUITY | -1 |
+---------------+----+
return_vec =
+---------------+--------------+
| XLK US Equity | 0.005951589 |
| XOP US Equity | 0.024262624 |
| KRE US Equity | 0.007112154 |
| KBE US EQUITY | 0.003097968 |
| XLK US EQUITY | 0.005951589 |
| XLE US EQUITY | 0.019948716 |
| XLF US EQUITY | 0.003813095 |
| XRT US EQUITY | -0.001202198 |
| XLU US EQUITY | 0.003021156 |
| XLY US EQUITY | 0.002821742 |
| XLV US EQUITY | 0.004961415 |
| STS FP EQUITY | 0.000827929 |
| STR FP EQUITY | 0.005422823 |
| STZ FP EQUITY | -0.003453351 |
| STW FP EQUITY | -0.001449392 |
| STQ FP EQUITY | 0.015776843 |
| STN FP EQUITY | 0.000937061 |
+---------------+--------------+
代码如下:
### define necessary functions ###
def optimization_function(weights,returns , vol_tgt, signs) :
return - np.sum(np.log(np.abs(weights))) #multiply by -1 since we wish to maximize but we give the problem
#to a minimizer
def portfolio_vol(weights,returns , vol_tgt, signs) : # inequality
portf_return = np.dot(weights.T,returns)
return np.sqrt(portf_return) - vol_tgt
def absolute_exposure(weights,returns , vol_tgt, signs) :
return np.sum(np.abs(weights)) - 1
def positive_weights(weights,returns , vol_tgt, signs) :
return float(np.sum(weights[signs == 1] <= 0))
def negative_weights(weights,returns , vol_tgt, signs) :
return float(np.sum(weights[signs == -1] >= 0))
weights = sp.fmin_slsqp(optimization_function,lol,args=(return_vec,vol_tgt,sign_vec,),
ieqcons = [portfolio_vol,],eqcons=[absolute_exposure,positive_weights,])
麻烦的功能是positive_weights和negative_weights。没有他们我没有问题。有办法解决这个问题吗?
提前谢谢。
答案 0 :(得分:1)
将这些表示为不平等约束似乎更为自然。例如,return weights[signs == 1].min()
并将其限制为非负。 (除非权重0和权重1e-308之间的区别实际上是至关重要的,在这种情况下我猜你可以在返回之前减去一个小数字。) - user2357112