Python for Finance: Analyze Big Financial Data

(Elle) #1
ext

Behavior if x not in knot sequence (0 extrapolate, 1 return 0, 2 raise ValueError)

Applied to the current example, this translates into the following:


In  [ 44 ]: ipo =   spi.splrep(x,   f(x),   k= 1 )
In [ 45 ]: iy = spi.splev(x, ipo)

As Figure 9-11 shows, the interpolation already seems really good with linear splines (i.e.,


k=1):


In  [ 46 ]: plt.plot(x, f(x),   ‘b’,    label=‘f(x)’)
plt.plot(x, iy, ‘r.’, label=‘interpolation’)
plt.legend(loc= 0 )
plt.grid(True)
plt.xlabel(‘x’)
plt.ylabel(‘f(x)’)

Figure 9-11. Example plot with linear interpolation

This can be confirmed numerically:


In  [ 47 ]: np.allclose(f(x),   iy)
Out[47]: True

Spline interpolation is often used in finance to generate estimates for dependent values of


independent data points not included in the original observations. To this end, let us pick a


much smaller interval and have a closer look at the interpolated values with the linear


splines:


In  [ 48 ]: xd  =   np.linspace(1.0,    3.0,     50 )
iyd = spi.splev(xd, ipo)

Figure 9-12 reveals that the interpolation function indeed interpolates linearly between


two observation points. For certain applications this might not be precise enough. In


addition, it is evident that the function is not continuously differentiable at the original


data points — another drawback:


In  [ 49 ]: plt.plot(xd,    f(xd),  ‘b’,    label=‘f(x)’)
plt.plot(xd, iyd, ‘r.’, label=‘interpolation’)
plt.legend(loc= 0 )
plt.grid(True)
plt.xlabel(‘x’)
plt.ylabel(‘f(x)’)
Free download pdf