In the process of cash flow mapping, in order to satisfy the conditions of present value and duration, the equation needs to be solved under certain constraints, but the results obtained by using the minimize or fsolve of scipy.optimize are different from those of excel solver(solver correct). Problem: Map a 425 day cash flow with a present value of 1 to maturities of 180 days, 360 days and 540 days.
"Known: the dates are 180,360,425,540(unit: day);
The variances corresponding to the above dates were 0.36,0.56,0.65,0.81, respectively; < br / > date vertex 180360540 rate of covariance matrix V for < br / >([[0.36, 0.36, 0.38], < br / > [0.36, 0.56, 0.51], < br / > [0.38, 0.51, 0.81]]) < br / > "for: The proportion of allocation(or weight) w = [(x, y, z)] translated into mathematical expressions: < br / > < br / > x + y + z = 1 < br / > 180 < em > 360 < / em > x + y + z - 540 *(x + y + z) * 425 = 0 < br / > wVw = 0.65
#1、用minimize
t1=180
t2=360
t=425
t3=540
var3=0.65
covMatrix=V #日期顶点t1、t2、t3处利率的协方差矩阵
fun=lambda x: np.power(var3-np.matmul(np.matmul(np.array([x[0],x[1],x[2]]),covMatrix),np.array([[x[0]],[x[1]],[x[2]]])),2)
cons=({'type':'eq','fun':lambda x:x[0]+x[1]+x[2]-1},
{'type':'eq','fun':lambda x:t1*x[0]+t2*x[1]+t3*x[2]-(x[0]+x[1]+x[2])*t}
)
x0=np.array([0.5,0.5,0])
res=optimize.minimize(fun,x0,constraints=cons)
结果:0.18,0.29,0.54 (不正确,不满足组合方差为0.65的条件)
excel结果:-0.23,1.09,0.13 (正确)
#2、用fsolve
def f(x):
return np.array([np.power(var3-np.matmul(np.matmul(np.array([[x[0],x[1],x[2]]]),covMatrix),np.array([[x[0],x[1],x[2]]]).T),2),
x[0]+x[1]+x[2]-1,
t1*x[0] + t2 * x[1] + t3 * x[2] - (x[0]+x[1]+x[2]) * t])
root=optimize.root(f,[0.5,0.5,0])
结果:Result from function call is not a proper array of floats.
I don't know what's wrong, thank you very much.
0 Answer
No answer yet
这家伙很懒,什么都没留下...