Implementation of Nelson Siegel with Python

Fitting with Optimization

A simple way to fit a Nelson Siegel type curve is to define an error or loss function and then use the minimze function of the scipy library to find the coefficients that minize the error.

The following code defines the Nelson Siegel function, and creates a fit function, which defines an error function and runs the minimization.

import math from scipy.optimize import minimize def nelson_siegel(level, slope, shape, decay): def calc(time): factor = (1-math.exp(time/decay))/(time/decay) return (level + slope*factor +shape*(factor - math.exp(time/decay)) ) return calc def fit(data): def error(val): level = val[0] slope = val[1] shape = val[2] decay = val[3] total = 0 for time, rate in data: if time>0.0: nval = nelson_siegel(level, slope, shape, decay)(time) total += (rate-nval)*(rate-nval) pass pass return total init = [0.01,0.01,0.01,1] test_error = error([0.01, 0.01, 0.01, 1]) result = minimize(error, init) vals = [x.item() for x in result.x] test_error2 = error(vals) return vals

Using Quantlib

The quantlib library provides a method to create a Term Structure object that has been fit using the Nelson Siegel methodology.