Regression and Fitting, Part 3: Non-linear Regression#

Many of the curves that valuation fits are not linear in their parameters: the Nelson-Siegel curve has a decay time \(\tau\) inside an exponential, the SVI smile has a location and a width, and every stochastic volatility model is a non-linear function of its parameters. There is no formula for the best fit. It is found by an iterative method from a starting point, and the answer can depend on the start, and on how much the data say about each parameter. This page sets out the Gauss-Newton and Levenberg-Marquardt methods, shows a fit that ends in a wrong local minimum, shows the trick of treating the linear parameters exactly, and measures how well the parameters are determined. It is the third of four pages on regression and fitting.

The model#

The model is \(y_i = f(x_i; \theta) + \varepsilon_i\) with a parameter vector \(\theta\), and the fit minimises the sum of squares of the residuals \(r_i(\theta) = f(x_i; \theta) - y_i\),

\[S(\theta) = \tfrac12 \sum_i r_i(\theta)^2\]

Let \(J\) be the Jacobian, \(J_{ij} = \partial r_i / \partial \theta_j\), the matrix of derivatives of the residuals with respect to the parameters (The Jacobian sets out how it is computed and what it shows). Near a minimum the Hessian of \(S\) is approximately \(J^\top J\), because the second-derivative terms are multiplied by residuals that are small. This gives two standard methods.

Gauss-Newton solves a linear least-squares problem at each step,

\[\left( J^\top J \right) \delta = -J^\top r, \qquad \theta \leftarrow \theta + \delta\]

and converges quickly when the start is close and the fit is good. Levenberg-Marquardt damps the step,

\[\left( J^\top J + \lambda\,\operatorname{diag}(J^\top J) \right) \delta = -J^\top r\]

with a \(\lambda\) that is raised when a step fails and lowered when it succeeds. For a large \(\lambda\) the step is a short move down the gradient, and for a small \(\lambda\) it is Gauss-Newton. It is the standard method, and it is more robust than Gauss-Newton, although it also finds only a local minimum (Optimisation).

Linear and non-linear parameters#

The Nelson-Siegel zero rate is

\[z(t) = \beta_0 + \beta_1 \frac{1 - e^{-t/\tau}}{t/\tau} + \beta_2 \left( \frac{1 - e^{-t/\tau}}{t/\tau} - e^{-t/\tau} \right)\]

It is linear in \(\beta_0, \beta_1, \beta_2\) for a fixed \(\tau\). So for each \(\tau\) the three betas are the solution of a linear regression, and what is left is a profile \(S(\tau)\) of a single variable. This is called variable projection. It reduces a four-dimensional search to a one-dimensional one that can be plotted and searched on a grid, and it shows whether there is more than one minimum.

Standard errors and identifiability#

At the solution the uncertainty of the parameters is approximated from the Jacobian, as in linear regression,

\[\operatorname{Cov}(\hat\theta) \approx \hat\sigma^2 \left( J^\top J \right)^{-1}, \qquad \hat\sigma^2 = \frac{\lVert r \rVert^2}{n - p}\]

If two parameters can be changed together with almost no change in the fit, \(J^\top J\) is nearly singular, their standard errors are large and their correlation is close to \(\pm 1\). The parameters are then weakly identified: the data do not determine them, and a small change in the data moves them a long way. The prices that depend on such a parameter inherit the uncertainty. The same applies to the calibration of a model in Calibration.

Worked example#

The example generates 12 zero rates from a Nelson-Siegel curve and adds 1 basis point of noise. It fits the four parameters by Levenberg-Marquardt from five starting values of \(\tau\), profiles the residual sum of squares in \(\tau\), and computes the standard errors from the Jacobian. Finally it repeats the fit for 300 noisy data sets, with all the maturities and with only those up to five years, and compares the fitted 30-year rate.

Python code
"""Non-linear regression: the Nelson-Siegel curve, starting points, the profile in tau, and identifiability."""
import numpy as np
from scipy.optimize import least_squares, minimize_scalar

MATURITIES = np.array([0.25, 0.5, 1, 2, 3, 5, 7, 10, 15, 20, 25, 30])
TRUE = np.array([0.048, -0.020, -0.015, 2.5])


def loadings(t, tau):
    x = t / tau
    slope = (1 - np.exp(-x)) / x
    return np.column_stack([np.ones_like(t), slope, slope - np.exp(-x)])


def nelson_siegel(t, params):
    return loadings(t, params[3]) @ params[:3]


def profile(t, y, tau):
    """For a given tau the betas are linear. Returns the betas and the residual sum of squares."""
    a = loadings(t, tau)
    beta, *_ = np.linalg.lstsq(a, y, rcond=None)
    return beta, np.sum((y - a @ beta) ** 2)


if __name__ == "__main__":
    rng = np.random.default_rng(21)
    t = MATURITIES
    y = nelson_siegel(t, TRUE) + rng.normal(0, 0.0001, t.size)
    print("Zero rates at 12 maturities from a Nelson-Siegel curve (b0 4.8%, b1 -2.0%, b2 -1.5%, tau 2.5) plus 1bp of noise")

    print("\n1. Levenberg-Marquardt on all four parameters from different starting values of tau")
    print(f"   {'Start tau':>9} {'b0 %':>8} {'b1 %':>8} {'b2 %':>8} {'tau':>9} {'RMSE (bp)':>10} {'evaluations':>12}")
    for tau0 in (0.1, 0.5, 2.0, 10.0, 50.0):
        r = least_squares(lambda p: nelson_siegel(t, p) - y, [0.04, 0.0, 0.0, tau0], method="lm")
        print(f"   {tau0:9.1f} {r.x[0] * 100:8.3f} {r.x[1] * 100:8.3f} {r.x[2] * 100:8.3f} {r.x[3]:9.3f} {np.sqrt(np.mean(r.fun**2)) * 1e4:10.3f} {r.nfev:12d}")

    print("\n2. The profile: for each tau the betas are a linear least-squares problem")
    print(f"   {'tau':>6} {'RSS (1e-8)':>11} {'condition number of the loadings':>34}")
    for tau in (0.2, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0):
        _, rss = profile(t, y, tau)
        print(f"   {tau:6.1f} {rss * 1e8:11.2f} {np.linalg.cond(loadings(t, tau)):34.1f}")
    grid = np.logspace(np.log10(0.1), np.log10(30), 300)
    rss = np.array([profile(t, y, tau)[1] for tau in grid])
    print("   local minima of the profile on a grid of 300 values of tau between 0.1 and 30:")
    for i in range(1, grid.size - 1):
        if rss[i] < rss[i - 1] and rss[i] < rss[i + 1]:
            local = minimize_scalar(lambda tau: profile(t, y, tau)[1], bounds=(grid[i - 1], grid[i + 1]), method="bounded", options={"xatol": 1e-8})
            print(f"   tau {local.x:7.4f}, RSS {local.fun * 1e8:7.2f}e-8, betas {np.round(profile(t, y, local.x)[0] * 100, 3)} %")

    print("\n3. Standard errors from the Jacobian, s^2 (J'J)^-1")
    r = least_squares(lambda p: nelson_siegel(t, p) - y, [0.04, 0.0, 0.0, 2.0], method="lm")
    s2 = np.sum(r.fun**2) / (t.size - 4)
    cov = s2 * np.linalg.inv(r.jac.T @ r.jac)
    se = np.sqrt(np.diag(cov))
    print(f"   {'':<8} {'b0':>9} {'b1':>9} {'b2':>9} {'tau':>9}")
    print(f"   {'estimate':<8} " + " ".join(f"{v:9.4f}" for v in (r.x[0] * 100, r.x[1] * 100, r.x[2] * 100, r.x[3])))
    print(f"   {'std err':<8} " + " ".join(f"{v:9.4f}" for v in (se[0] * 100, se[1] * 100, se[2] * 100, se[3])))
    corr = cov / np.outer(se, se)
    print(f"   correlation of b1 and b2 {corr[1, 2]:+.3f}, of b2 and tau {corr[2, 3]:+.3f}")

    print("\n4. Identifiability: the 30-year rate from 300 noisy fits, with all maturities and with maturities up to 5 years")
    print(f"   {'Data used':<22} {'mean 30y rate %':>16} {'std dev (bp)':>13} {'std dev of tau':>15}")
    truth = nelson_siegel(np.array([30.0]), TRUE)[0]
    for name, mask in (("All 12 maturities", t > 0), ("Up to 5 years (6 points)", t <= 5)):
        rates, taus = [], []
        for _ in range(300):
            yy = nelson_siegel(t, TRUE) + rng.normal(0, 0.0001, t.size)
            res = least_squares(lambda p: nelson_siegel(t[mask], p) - yy[mask], [0.04, -0.01, -0.01, 2.0], bounds=([-1, -1, -1, 0.1], [1, 1, 1, 60]))
            rates.append(nelson_siegel(np.array([30.0]), res.x)[0])
            taus.append(res.x[3])
        print(f"   {name:<22} {np.mean(rates) * 100:16.3f} {np.std(rates) * 1e4:13.1f} {np.std(taus):15.2f}")
    print(f"   true 30-year rate {truth * 100:.3f}%")

The output is:

Zero rates at 12 maturities from a Nelson-Siegel curve (b0 4.8%, b1 -2.0%, b2 -1.5%, tau 2.5) plus 1bp of noise

1. Levenberg-Marquardt on all four parameters from different starting values of tau
   Start tau     b0 %     b1 %     b2 %       tau  RMSE (bp)  evaluations
         0.1    4.822   -2.020   -1.460     2.627      0.853           84
         0.5    4.822   -2.020   -1.460     2.627      0.853           51
         2.0    4.822   -2.020   -1.460     2.627      0.853           41
        10.0    3.859   -1.096    3.703    13.389      1.669           62
        50.0    3.859   -1.096    3.703    13.389      1.669          108

2. The profile: for each tau the betas are a linear least-squares problem
      tau  RSS (1e-8)   condition number of the loadings
      0.2    12278.64                               36.7
      0.5     5064.27                               17.7
      1.0     1380.22                               13.8
      2.5       10.30                               13.7
      5.0       76.18                               18.3
     10.0       42.55                               36.2
     30.0       88.58                              207.3
   local minima of the profile on a grid of 300 values of tau between 0.1 and 30:
   tau  2.6272, RSS    8.74e-8, betas [ 4.822 -2.02  -1.46 ] %
   tau 13.3895, RSS   33.45e-8, betas [ 3.859 -1.096  3.703] %

3. Standard errors from the Jacobian, s^2 (J'J)^-1
                   b0        b1        b2       tau
   estimate    4.8222   -2.0203   -1.4597    2.6272
   std err     0.0146    0.0207    0.0853    0.1129
   correlation of b1 and b2 -0.772, of b2 and tau +0.905

4. Identifiability: the 30-year rate from 300 noisy fits, with all maturities and with maturities up to 5 years
   Data used               mean 30y rate %  std dev (bp)  std dev of tau
   All 12 maturities                 4.509           0.7            0.10
   Up to 5 years (6 points)            4.924          95.3            7.30
   true 30-year rate 4.508%
Left, the residual sum of squares of the Nelson-Siegel fit against tau, with two minima. Right, the two fitted curves, which pass close to the data up to 30 years and diverge beyond it

Reading the output:

  • The start decides the answer. Three of the five starts, with \(\tau\) of 0.1, 0.5 and 2.0, reach the right solution, with \(\tau = 2.63\) against a true 2.5, and a fit error of 0.85 basis points. The starts of 10 and 50 stop at \(\tau = 13.4\), with a fit error of 1.67 and a curvature coefficient of +3.7% instead of -1.5%. The optimiser reports success from both, and the two curves agree inside the data and diverge beyond the last point, as the figure shows.

  • The profile shows why. The residual sum of squares of the profile has two minima, at \(\tau\) of 2.63 and 13.39, with 8.7e-8 and 33.5e-8. A start to the right of the ridge between them slides into the wrong one. A one-dimensional grid of the profile finds both at no cost, and it is the way to start a fit.

  • The standard errors show which parameters are determined. The level \(\beta_0\) is known to 0.015 percentage points, 1.5 basis points, and the slope \(\beta_1\) to 0.021. The curvature \(\beta_2\) has 0.085, six times the level, and \(\tau\) has 0.113. The correlation of \(\beta_2\) and \(\tau\) is +0.905 and that of \(\beta_1\) and \(\beta_2\) is -0.772: the curvature and the decay time can trade off against each other.

  • Without long maturities the long end is not determined. With all 12 maturities, the fitted 30-year rate is 4.509%, for a true 4.508%, with a standard deviation of 0.7 basis points. With only the six maturities up to five years, the fit to the data is just as good, and the 30-year rate has a mean of 4.92% and a standard deviation of 95 basis points, with \(\tau\) ranging by 7.3. The data say nothing about the long end, and the model fills it in with an assumption.

A valuation control view#

  • Ask how the fit was started and whether other starts were tried: a fit that gives a different answer from another start is under-determined or has several minima. Look at the profile in the nonlinear parameters, or a grid of starting values.

  • Look at the standard errors and correlations, not only the fit error: a very small fit error with a large standard error on a parameter means that the parameter is not determined, and the quantities that depend on it are not either.

  • Check that the data cover where the curve is used: a fit to maturities up to five years says nothing reliable at 30 years. Where the model extrapolates, its form is making the assumption. See Interpolation, Part 2: Extrapolation.

  • Reduce the problem where you can: treat the linear parameters exactly, so that the search is over the few non-linear ones, and fix a parameter that the data cannot determine rather than let it float.

  • Watch for parameters that move from day to day with no change in the market: that is a flat valley in the fit, and the day-to-day change in the fitted curve is noise in a valuation.

Next, Regression and Fitting, Part 4: Least-Squares Fitting covers the choices that are common to all these fits: the weights, the loss function, the regularisation and the constraints.