如何解决如何解决 Python 中的非线性编程问题?
我有如下所述的非常简单的模型:
假设:
CW = [1.004455981050443,0.9937806249035503,0.9963341786199054,1.000775606323324,1.0006315883554697]
# Suppose That these are Percent of return of each bond
我想解决这个优化问题并确定 bi 的值。
如何用 Python 编写这个问题?
更新:
假设我想解决我投资组合中的一个优化问题。
我的最终目标是确定投资组合中每个债券的投资权重(0 到 1 之间的数量)。
我的投资组合债券:
我写了这段代码来解决这个优化:
from scipy.optimize import minimize
import math as mt
CW = [0.9862898856860483,0.9944441063388774,0.9934069612349462,0.9952892270523128,0.9951914282293151] # Suppose That these are Percent of return of each bond
def Objective(x):
x1 = x[0]
x2 = x[1]
x3 = x[2]
x4 = x[3]
x5 = x[4]
fin = (- (mt.log10(CW[0]* x1))) + (- (mt.log10(CW[1]* x2))) + (- (mt.log10(CW[2]* x3))) + (- (mt.log10(CW[3]* x4))) + (- (mt.log10(CW[4]* x5)))
return fin
def Equality_Constraint(x):
x1 = x[0]
x2 = x[1]
x3 = x[2]
x4 = x[3]
x5 = x[4]
return x1 + x2 + x3 + x4 + x5 - 1
bounds_x1 = (0,1)
bounds_x2 = (0,1)
bounds_x3 = (0,1)
bounds_x4 = (0,1)
bounds_x5 = (0,1)
Bounds = [bounds_x1,bounds_x2,bounds_x3,bounds_x4,bounds_x5]
Constraint1 = {'type' : 'eq','fun': Equality_Constraint}
Constraint = [Constraint1]
x0 = [0.2,0.2,0.2] #This is an initial Value
Result = minimize(Objective,x0,method='SLSQP',bounds=Bounds,constraints=Constraint)
print(Result)
输出
fun: 3.510281934983529
jac: array([-2.17147237,-2.17147237,-2.17147234])
message: 'Optimization terminated successfully'
nfev: 6
nit: 1
njev: 1
status: 0
success: True
x: array([0.2,0.2])
问题来了!因为它说我应该将总资金的 20% 用于 bound1,20% 用于 bound2 等等。但事实并非如此!投资的百分比(权重)应该不同!导致我的债券 4 = 0.9952892270523128 的回报,这是每个债券的回报之间的最佳回报CW 列表! 求解器的结果表明所有权重都应为 0.2,这是最佳解决方案!但这似乎不正确!他们应该是不同的权重! 现在有人可以帮我找出问题出在哪里吗?或者如何通过解决优化问题获得正确的权重?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。