Take a look at CIR model// Nelson_Siegel Model calibration
********************************************************************************************
import numpy as np from scipy.stats import norm from pylab import plot, show, xlabel, ylabel, title # since every next step is related to the previous one, so we can only do this in a recursive manner
def brownian(delta,loc,dt): scale=loc*delta+1e-6 increment=norm.rvs(loc=0, scale=scale) return increment
def main(): u=0.07 a=6.3 delta=0.1 T=100.0 N=500 dt=T/N path_num=20 starting_point=0.12 x0=np.zeros((path_num,N+1)) x0[:,0]=starting_point timespace=np.linspace(0,T,N+1)
#print x0
for x in range(path_num): for i in range(1,N+1):
x0[x][i]=x0[x][i-1]+a*(u-(x0[x][i-1]))*dt+brownian(delta,x0[x][i-1],dt)
#print x0
for k in range(path_num): plot(timespace, x0[k])
xlabel("time (s)") title("CIR Model") ylabel ("interest rate") show()
main()
import numpy as np import pandas as pd import scipy.optimize as sciopt from math import *
beta_guess=np.asarray([0.87,2.09,3.11]) observation=data.shape[0] def Nelson_Siegel(beta): alpha=1.0 T=np.asarray([10.0,5.0,2.0,1.0]) beta_0,beta_1,beta_2=beta termstructure=beta_0+beta_1*((1-np.exp(-1*alpha*T))/(alpha*T))+beta_2*((1-(1+alpha*T)*np.exp(-1*alpha*T))/(alpha*T)) return termstructure
def residual(beta,data): err=data-Nelson_Siegel(beta) return err
for k in range(observation): data_k=data[k] betals=sciopt.leastsq(residual,beta_guess,args=(data_k)) b=np.asarray(betals) print b
result=opt.minimize(rosenbrock,x_0,method="nelder-mead",options={"xtol":1e-8,"disp":True}) print type(result) print result