Interest Rate Curve Build, Part 4: Regression Fits#
See also
Nelson and Siegel, “Parsimonious modeling of yield curves”, Journal of Business, 1987
Svensson, “Estimating and interpreting forward interest rates: Sweden 1992-1994”, NBER working paper, 1994
Eilers and Marx, “Flexible smoothing with B-splines and penalties”, Statistical Science, 1996
The bootstrap in Interest Rate Curve Build, Part 1: Instruments & Bootstrapping and the global solver in Interest Rate Curve Build, Part 3: Global Solver & Jacobian make the curve reprice its inputs. That is right for the curve that values the trades that those inputs hedge. It is not always what is wanted. If the quotes are noisy, an exact fit reproduces the noise. If the data is sparse, there is nothing to reprice at the dates in between. And if the aim is a smooth reference curve, or a stable forward curve for scenarios, a curve that is allowed to miss the inputs a little can be far better behaved.
A regression fit takes this approach. It chooses a curve from a family with a few parameters, and finds the member that is closest to the data in the least-squares sense. This page starts with what the regression is fitted to, which is mostly government bond prices and swap spreads. It then covers the regression itself, three families (Nelson-Siegel, Svensson and a penalised spline), the effect of weights, and the cost of the misfit.
What the curve is fitted to#
The bootstrap in Interest Rate Curve Build, Part 1: Instruments & Bootstrapping uses cash, FRAs, futures and swaps, one instrument at each pillar. A regression fit is used where there are many more instruments than pillars, or where the instruments are not the ones that the curve will be used to price. The main inputs are as follows.
Input |
Quoted as |
Why it is used |
|---|---|---|
Government coupon bonds (Treasuries, gilts, bunds) |
Clean price or yield |
There are many of them, at many maturities, and they trade often. They give a dense, nearly risk-free curve, and the curve is the base for pricing other bonds. |
Treasury bills and STRIPS (zero-coupon) |
Price or yield |
A zero-coupon price is a discount factor directly, so it gives a zero rate with no bootstrap. They can trade away from coupon bonds because of liquidity and tax, so they are often down-weighted or left out. |
Swaps (overnight index) |
Par rate |
A regression is used to smooth swap quotes that are noisy or have gaps, or to produce a reference curve. A curve that has to value swaps is not fitted this way. |
Swap spreads |
Swap rate less government yield, in basis points |
They link the swap curve to the government curve, so that a dense government curve can fill gaps in the swap quotes. See below. |
Government bonds#
A bond is a bundle of cash flows, so its price is the sum of the cash flows discounted with the curve. For a bond with an annual coupon rate \(c\) paid twice a year, maturity \(T\) and a price per 100, valued on a coupon date so that there is no accrued interest:
Each bond gives one equation, and there are many more bonds than the three to six parameters of a family. The fit chooses the parameters that make the model prices as close as possible to the market prices. Two points matter in practice.
Weights. A price error means very different things for different bonds. The change in a bond’s price for a change in its yield is its duration times its price, so a price error of 0.03 on a six-month bond is about 6 basis points of yield, and on a 20 year bond is about 0.2. Fitting prices with equal weights therefore sacrifices the short bonds. The usual remedy is to weight each price error by one over the duration squared, which makes the fit close to a fit of the yields. The example below shows the effect.
Which bonds. The most recently issued bonds (“on the run”) are the most liquid and can trade at a premium to older bonds of the same maturity, so a fit may use only some of them, or add a term for the premium. Bonds that are special in the repo market, or close to maturity, are often removed.
Swap spreads#
A swap spread is the difference between the swap rate and the yield on a government bond of the same maturity. With \(s(T)\) the swap rate and \(y(T)\) the government par yield:
In markets such as the US, long-dated swap spreads have been negative for years, which is often attributed to the balance sheet cost of holding government bonds. The spread is not a constant, but it is usually much smoother than either curve, because the government curve and the swap curve share most of their shape. That is what makes the following approach work:
Fit the government curve to the large set of bond prices.
Observe the swap spread at the few tenors where the swap rate is quoted, using the fitted government yield.
Regress a smooth function on those spreads.
The swap rate at any other tenor is the fitted government yield plus the fitted spread.
The curve is then built from a dense, liquid curve and a small, smooth correction, and not from a few sparse swap quotes. The method fails if the spread has jumps, for example where the government curve has an on-the-run effect at one maturity. The day count and compounding of swap rates and bond yields differ, so in practice both are put on a common basis before the spread is taken. The example below takes them to be the same, to keep the point clear.
Multiple linear regression#
If the curve is a weighted sum of fixed basis functions, \(z(t) = \sum_k \beta_k \phi_k(t)\), then fitting it to observations \(y_i = z(t_i)\) is a multiple linear regression:
The columns of \(X\) are the basis functions evaluated at the observation dates, and \(\varepsilon\) is the part of the data that the curve does not explain. The weighted least-squares solution is in closed form, from the normal equations:
There is no iteration and no starting point, and the answer is unique. That is the difference from the global solve in Interest Rate Curve Build, Part 3: Global Solver & Jacobian, where the instruments are nonlinear functions of the unknowns and the solver has to iterate.
The weights \(W\) say how much each observation matters. A liquid maturity with a narrow bid-offer spread can be given a large weight, and a thinly traded one a small weight.
What makes it linear#
Whether the regression is linear depends on what is modelled and what is fitted. Writing the zero rate as a sum of basis functions, \(z(t) = \sum_k \beta_k \phi_k(t)\), the fit is linear when the data are zero rates or forward rates, because a zero rate is an average of forward rates and both are linear in the same coefficients. It is not linear if the data are bond prices, par swap rates or yields, since a price depends on \(D(t) = e^{-z(t)\,t}\), which is nonlinear in the coefficients. A fit of Nelson-Siegel or Svensson to bond prices is therefore a nonlinear least squares and needs an iterative solver, of the kind in Interest Rate Curve Build, Part 3: Global Solver & Jacobian, with the decay chosen by a grid.
There is a way to make bond prices linear. If the discount function itself is written as a sum of basis functions, \(D(t) = \sum_k b_k B_k(t)\) with \(b_0 = 1\), then the price of every bond is a linear function of the coefficients:
and the fit is a multiple linear regression of the market prices on the columns \(X\), solved in one step. This is the approach of McCulloch (1971), who fitted the discount function with a spline. It needs no starting point. Its weakness is that a spline for the discount function has no built-in smoothness for the forward rates, which are a derivative of it, so the forwards can be rough. The weights are chosen in the same way as before, with one over the duration squared. The example below uses both approaches. The other examples on this page fit zero rates, which are available from a bootstrapped curve, so that the regression stays linear and the families can be compared on their own.
Three families#
Nelson-Siegel#
The zero rate is
The three betas have a meaning. \(\beta_0\) is the long-run level, which is the limit as \(t \to \infty\). \(\beta_0 + \beta_1\) is the rate at the short end, as \(t \to 0\). \(\beta_2\) sets the size of a hump, at a maturity that depends on the decay \(\lambda\). Once \(\lambda\) is fixed, \(z(t)\) is linear in the betas. \(\lambda\) itself enters nonlinearly, so it is chosen by a grid search, with a regression at each value, and the best one is kept.
The curve has at most one hump or one trough, so it is stable but can only describe simple shapes.
Svensson#
Svensson adds a second hump with its own decay \(\lambda_2\):
There are four betas and two decays. The grid search is now over two decays, and it keeps the pair with the smallest error. Central banks use these two families to fit curves to government bond prices: the ECB publishes euro-area yield curves with the Svensson model, for example.
Penalised spline#
A spline is built from local basis functions \(B_k(t)\), each one non-zero over a few knots, so that \(z(t) = \sum_k c_k B_k(t)\). With many coefficients the fit can follow almost any shape, and it will follow the noise too. A penalty on the roughness of the coefficients holds it back. With the penalty on the second difference \(D_2 c\) of the coefficients, the fit is
The solution is again in closed form. The penalty \(\lambda\) is the dial between fit and smoothness. When it is zero the spline follows the data as closely as its knots allow, and when it is large the curve tends to a straight line. The effective number of parameters is the trace of the matrix that maps the data to the fitted values, \(\operatorname{tr}\left[ (B^\top W B + \lambda D_2^\top D_2)^{-1} B^\top W B \right]\), which falls from the number of coefficients to two (a line) as \(\lambda\) grows. The Bank of England fits gilt curves with a spline whose penalty varies with maturity.
Worked example 1: the families on zero rates#
The first example is a clean test of the families. It uses the nine zero rates of the swap-only curve from Interest Rate Curve Build, Part 1: Instruments & Bootstrapping. These zero rates are themselves the output of a bootstrap, so this is not how a curve is fitted in practice, and the second example below uses bond prices and swap spreads. The first example fits Nelson-Siegel and Svensson by least squares, repeats the Nelson-Siegel fit with weights, fits the penalised spline for five penalties, and values three par swaps on the fitted curves. A last test uses 30 noisy annual par rates from a known curve. The quotes are invented and the noise is simulated.
Python code
"""Regression fits of the zero curve: Nelson-Siegel, Svensson and a penalised spline, fitted by least squares."""
import numpy as np
from scipy.interpolate import BSpline
from curve_example import PAR_RATES, PILLARS, bootstrap
from curve_global_example import N, par_rates, payer_pv
def _g(t, decay):
x = np.where(t > 0, t / decay, 1e-9)
return (1.0 - np.exp(-x)) / x, np.exp(-x)
def ns_basis(t, decay):
"""Nelson-Siegel: level, slope and hump columns. The decay is fixed, so z(t) is linear in the betas."""
t = np.atleast_1d(np.asarray(t, dtype=float))
g, e = _g(t, decay)
return np.column_stack([np.ones_like(t), g, g - e])
def svensson_basis(t, decay1, decay2):
"""Svensson adds a second hump with its own decay."""
t = np.atleast_1d(np.asarray(t, dtype=float))
g, e = _g(t, decay2)
return np.column_stack([ns_basis(t, decay1), g - e])
KNOTS = np.array([1, 1, 1, 1, 3, 6, 10, 15, 22, 30, 30, 30, 30], dtype=float) # cubic B-spline on 1Y to 30Y
def spline_basis(t):
"""Cubic B-splines. Times outside 1Y to 30Y use the end values, so the curve is flat beyond them."""
t = np.clip(np.atleast_1d(np.asarray(t, dtype=float)), KNOTS[0], KNOTS[-1] - 1e-9)
return BSpline.design_matrix(t, KNOTS, 3).toarray()
class ZeroCurve:
"""A curve defined by a zero-rate function z(t) = basis(t) @ coef."""
def __init__(self, basis, coef):
self.basis, self.coef = basis, coef
def zero(self, t):
return self.basis(np.atleast_1d(np.asarray(t, dtype=float))) @ self.coef
def df(self, t):
t_array = np.atleast_1d(np.asarray(t, dtype=float))
values = np.exp(-self.zero(t_array) * t_array)
return values if np.ndim(t) else values[0]
def regress(x, y, w=None, penalty=None, lam=0.0):
"""Weighted, optionally penalised, least squares: solve (X'WX + lam P'P) b = X'Wy.
Returns the coefficients and the effective number of parameters, trace((X'WX + lam P'P)^-1 X'WX).
"""
w = np.ones(len(y)) if w is None else np.asarray(w, dtype=float)
xtwx = x.T @ (w[:, None] * x)
a = xtwx + (lam * penalty.T @ penalty if penalty is not None else 0.0)
coef = np.linalg.solve(a, x.T @ (w * y))
return coef, float(np.trace(np.linalg.solve(a, xtwx)))
def fit_ns(times, y, w=None, decays=np.linspace(0.5, 10.0, 96)):
"""Regression for the betas at each decay on a grid. Keep the decay with the smallest weighted error."""
w = np.ones(len(y)) if w is None else np.asarray(w, dtype=float)
best = None
for decay in decays:
x = ns_basis(times, decay)
coef, _ = regress(x, y, w)
sse = np.sum(w * (x @ coef - y) ** 2)
if best is None or sse < best[0]:
best = (sse, coef, decay)
_, coef, decay = best
return ZeroCurve(lambda t: ns_basis(t, decay), coef), decay
def fit_svensson(times, y, decays=np.linspace(0.5, 12.0, 24)):
best = None
for d1 in decays:
for d2 in decays:
if d2 <= 1.5 * d1:
continue
x = svensson_basis(times, d1, d2)
coef, _ = regress(x, y)
sse = np.sum((x @ coef - y) ** 2)
if best is None or sse < best[0]:
best = (sse, coef, d1, d2)
_, coef, d1, d2 = best
return ZeroCurve(lambda t: svensson_basis(t, d1, d2), coef), (d1, d2)
def fit_spline(times, y, lam):
"""Penalised spline: the penalty is on the second difference of the coefficients."""
x = spline_basis(times)
n = x.shape[1]
second_difference = np.diff(np.eye(n), 2, axis=0)
coef, dof = regress(x, y, penalty=second_difference, lam=lam)
return ZeroCurve(spline_basis, coef), dof
def zero_rates(curve, times):
times = np.asarray(times, dtype=float)
return -np.log(curve.df(times)) / times
def annual_forwards(curve, years):
return np.array([np.log(curve.df(t - 1) / curve.df(t)) for t in range(1, years + 1)])
if __name__ == "__main__":
quotes = np.array(PAR_RATES)
base = bootstrap()
times = np.array(PILLARS, dtype=float)
z = zero_rates(base, times)
# 1. Ordinary least squares: Nelson-Siegel (3 betas) and Svensson (4 betas).
ns, ns_decay = fit_ns(times, z)
sv, (sv_d1, sv_d2) = fit_svensson(times, z)
print(f"1. Nelson-Siegel (decay {ns_decay:.1f}Y) and Svensson (decays {sv_d1:.1f}Y and {sv_d2:.1f}Y), ordinary least squares")
print(f" {'Pillar':>6} {'NS zero err':>12} {'SV zero err':>12} {'NS par err':>11} {'SV par err':>11}")
ns_par, sv_par = par_rates(ns, PILLARS), par_rates(sv, PILLARS)
for i, m in enumerate(PILLARS):
print(f" {m:>5}Y {(zero_rates(ns, m) - z[i]) * 1e4:9.2f} bp {(zero_rates(sv, m) - z[i]) * 1e4:9.2f} bp "
f"{(ns_par[i] - quotes[i]) * 1e4:8.2f} bp {(sv_par[i] - quotes[i]) * 1e4:8.2f} bp")
rms = lambda c: np.sqrt(np.mean((zero_rates(c, times) - z) ** 2)) * 1e4
print(f" RMS zero error: NS {rms(ns):.2f} bp, Svensson {rms(sv):.2f} bp")
# 2. Weights: count the 5Y to 10Y points five times as much.
weights = np.where((times >= 5) & (times <= 10), 5.0, 1.0)
ns_w, _ = fit_ns(times, z, weights)
print("\n2. Nelson-Siegel with the 5Y, 7Y and 10Y points weighted 5 times:")
print(f" {'Pillar':>6} {'Equal weights':>14} {'Weighted':>10}")
for i, m in enumerate(PILLARS):
print(f" {m:>5}Y {(zero_rates(ns, m) - z[i]) * 1e4:11.2f} bp {(zero_rates(ns_w, m) - z[i]) * 1e4:7.2f} bp")
# 3. Penalised spline: the penalty trades fit for smoothness.
print("\n3. Penalised cubic spline, nine zero rates, nine coefficients:")
print(f" {'Penalty':>9} {'Effective parameters':>21} {'RMS zero error':>15} {'Worst par error':>16}")
for lam in (1e-4, 1e-3, 1e-2, 1e-1, 1.0):
sp, dof = fit_spline(times, z, lam)
worst = np.max(np.abs(par_rates(sp, PILLARS) - quotes)) * 1e4
print(f" {lam:9.0e} {dof:21.2f} {rms(sp):12.2f} bp {worst:13.2f} bp")
# 4. What the misfit costs: PV of 100 million par payer swaps, valued on the fitted curves.
sp, _ = fit_spline(times, z, 1e-2)
print("\n4. PV of a 100 million par payer swap on each fitted curve (0 on the bootstrapped curve):")
print(f" {'Swap':>6} {'Nelson-Siegel':>14} {'Svensson':>10} {'Spline (1e-2)':>14}")
for m in (5, 10, 20):
strike = par_rates(base, [m])[0]
pv = lambda c: N * payer_pv(c, m, strike)
print(f" {m:>5}Y {pv(ns):14,.0f} {pv(sv):10,.0f} {pv(sp):14,.0f}")
# 5. Noisy quotes: 30 annual par rates from a known smooth curve, with 0.5bp of noise on each.
rng = np.random.default_rng(7)
truth = ZeroCurve(lambda t: svensson_basis(t, 2.0, 8.0), np.array([0.0400, -0.0050, -0.0120, 0.0100]))
years = np.arange(1, 31)
noisy = par_rates(truth, years) + rng.normal(0.0, 0.5e-4, len(years))
exact = bootstrap(list(years), noisy)
z_noisy = zero_rates(exact, years)
fit_ns_noisy, _ = fit_ns(years.astype(float), z_noisy)
fit_sv_noisy, _ = fit_svensson(years.astype(float), z_noisy)
fit_sp_noisy, dof = fit_spline(years.astype(float), z_noisy, 1e-5)
z_true = zero_rates(truth, years)
error = lambda c: np.sqrt(np.mean((zero_rates(c, years) - z_true) ** 2)) * 1e4
jaggedness = lambda c: np.std(np.diff(annual_forwards(c, 30))) * 1e4
print("\n5. Thirty annual par rates from a known smooth curve, 0.5bp of noise on each quote:")
print(f" {'':<26} {'RMS zero error vs truth':>24} {'Year-to-year forward change':>28}")
for name, curve in (("Bootstrap (exact fit)", exact), ("Nelson-Siegel (3 betas)", fit_ns_noisy),
("Svensson (4 betas)", fit_sv_noisy), (f"Penalised spline ({dof:.0f} coef.)", fit_sp_noisy),
("True curve", truth)):
err = "-" if curve is truth else f"{error(curve):.2f} bp"
print(f" {name:<26} {err:>24} {jaggedness(curve):25.2f} bp")
1. Ordinary least squares#
1. Nelson-Siegel (decay 1.1Y) and Svensson (decays 4.0Y and 7.0Y), ordinary least squares
Pillar NS zero err SV zero err NS par err SV par err
1Y 0.42 bp -0.35 bp 0.44 bp -0.37 bp
2Y -1.75 bp 0.62 bp -1.78 bp 0.62 bp
3Y 0.98 bp 0.15 bp 0.95 bp 0.16 bp
5Y 4.25 bp -0.73 bp 4.16 bp -0.74 bp
7Y 2.34 bp -0.25 bp 2.42 bp -0.32 bp
10Y -3.66 bp 1.47 bp -3.02 bp 1.21 bp
15Y -13.66 bp -1.96 bp -11.69 bp -1.53 bp
20Y -5.65 bp 1.33 bp -6.03 bp 1.01 bp
30Y 16.72 bp -0.27 bp 9.61 bp 0.44 bp
RMS zero error: NS 7.74 bp, Svensson 1.00 bp
The curve in this example has a trough at 5 years, a hump at 15 years and a fall to 30 years. Nelson-Siegel has one bend, so it misses the hump by up to 14 basis points in the zero rate. Svensson has a second bend and follows the shape to within 2 basis points, with an RMS error of 1.0 basis point against 7.7 for Nelson-Siegel. Both fits are smooth, and neither reprices the swaps exactly: the par rate errors are as large as 12 basis points for Nelson-Siegel and 1.5 for Svensson.
Left: the Nelson-Siegel, Svensson and spline fits against the bootstrapped curve. Right: the one-year forward rates from 30 noisy quotes. The exact bootstrap oscillates, and the spline stays close to the true curve.#
2. Weights#
2. Nelson-Siegel with the 5Y, 7Y and 10Y points weighted 5 times:
Pillar Equal weights Weighted
1Y 0.42 bp 1.21 bp
2Y -1.75 bp -3.18 bp
3Y 0.98 bp -1.35 bp
5Y 4.25 bp 2.22 bp
7Y 2.34 bp 1.33 bp
10Y -3.66 bp -3.47 bp
15Y -13.66 bp -12.38 bp
20Y -5.65 bp -3.82 bp
30Y 16.72 bp 19.10 bp
Counting the 5, 7 and 10 year points five times as much nearly halves the errors at 5 and 7 years, from 4.25 to 2.22 and from 2.34 to 1.33 basis points. The errors move elsewhere: they grow at 1, 2, 3 and 30 years. With three parameters the total misfit cannot be removed, only shared out, and the weights decide where it falls. That is the reason to set them from the bid-offer spreads of the instruments and to record them.
3. The penalty#
3. Penalised cubic spline, nine zero rates, nine coefficients:
Penalty Effective parameters RMS zero error Worst par error
1e-04 7.97 0.02 bp 0.19 bp
1e-03 7.76 0.13 bp 0.26 bp
1e-02 6.77 0.65 bp 1.18 bp
1e-01 5.23 1.64 bp 3.27 bp
1e+00 3.83 4.41 bp 7.03 bp
As the penalty rises from \(10^{-4}\) to 1, the effective number of parameters falls from about 8 to under 4 and the curve gets smoother, and the error against the data rises from 0.02 to 4.4 basis points. A spline with a tiny penalty almost interpolates the zero rates, and even then the par rates are off by 0.2 basis points. That is because the spline and the log-linear bootstrap interpolate the dates between pillars differently, such as the 4 and 6 year payment dates of the swaps. This is the effect of the interpolation rule from Interest Rate Curve Build, Part 1: Instruments & Bootstrapping, seen from the other side.
4. What the misfit costs#
4. PV of a 100 million par payer swap on each fitted curve (0 on the bootstrapped curve):
Swap Nelson-Siegel Svensson Spline (1e-2)
5Y 186,684 -33,083 6,135
10Y -248,729 99,731 49,480
20Y -839,600 139,465 90,919
A par swap is worth zero on the curve that it was built from, so every number here is a misvaluation caused by the fit. For scale, one basis point on the 10 year swap rate is worth about 82,000 on 100 million. The Nelson-Siegel curve misvalues the 10 year swap by about three basis points, or 249,000, and the 20 year swap by 840,000. The Svensson and spline curves are much closer, but they are still wrong at 10 years by about 1.2 and 0.6 basis points, or 100,000 and 49,000. A trading book cannot be valued on a curve like this, since each of these numbers would be a P&L error against the hedges.
5. Noisy quotes#
The last test is a simulation. It takes a known smooth Svensson curve, generates 30 annual par swap rates from it, and adds 0.5 basis points of random noise to each quote, which is about the size of a bid-offer spread. It then builds the curve three ways and compares each with the truth.
5. Thirty annual par rates from a known smooth curve, 0.5bp of noise on each quote:
RMS zero error vs truth Year-to-year forward change
Bootstrap (exact fit) 0.64 bp 30.43 bp
Nelson-Siegel (3 betas) 1.55 bp 5.83 bp
Svensson (4 betas) 0.34 bp 5.72 bp
Penalised spline (9 coef.) 0.35 bp 5.71 bp
True curve - 5.78 bp
The exact fit tracks the noise. The bootstrap reprices every noisy quote, and the result is a zero curve that is only 0.64 basis points from the truth, but a forward curve that oscillates, with a typical year-to-year change of 30 basis points against 5.8 for the true curve. The right-hand panel of the figure shows it. Small errors in the par rates are magnified in the forward rates at long maturities, because each discount factor depends on all the earlier ones.
The regression fits average out the noise. The Svensson and spline fits have a smoothness that matches the true curve and zero rate errors of about a third of a basis point, which is half the error of the exact fit.
Too few parameters gives a bias. Nelson-Siegel is smooth but its error against the truth, 1.55 basis points, is more than the exact fit’s, because three parameters cannot describe the true shape. The choice of family is model risk.
The test favours the regression. The true curve is a Svensson curve, so the Svensson fit is in the right family, which flatters it. A market curve belongs to no simple family, so the real advantage will be smaller. The point is the pattern: too few parameters gives bias, and too many, as in the exact fit, gives noise.
Worked example 2: bond prices and swap spreads#
The second example uses the inputs that a regression is really fitted to. It simulates 18 Treasury bonds with maturities from 6 months to 30 years and semi-annual coupons set to the nearest eighth of a percent. The prices come from a known Svensson curve plus random noise of 0.03 per 100, which is about the size of a bid-offer. All the bonds are valued on a coupon date, so there is no accrued interest. The fits are then scored against the market prices and against the true curve. Every number is simulated.
Python code
"""Regression fits to government bond prices, and a swap curve built as Treasuries plus a fitted swap spread."""
import numpy as np
from scipy.interpolate import BSpline
from scipy.optimize import brentq, least_squares
from curve_regression_example import ZeroCurve, ns_basis, regress, svensson_basis
# A "true" Treasury zero curve, used to make the bond prices and to score the fits.
TRUTH = ZeroCurve(lambda t: svensson_basis(t, 2.0, 8.0), np.array([0.0400, -0.0050, -0.0120, 0.0100]))
MATURITIES = np.array([0.5, 1, 1.5, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 17, 20, 25, 30])
PRICE_NOISE = 0.03 # about 1/32 of a point, a typical bid-offer
YEARS = np.arange(1, 31)
def times(maturity):
return np.arange(0.5, maturity + 1e-9, 0.5)
def par_yield(curve, maturity):
"""Semi-annual par yield of the curve."""
return 2.0 * (1.0 - curve.df(maturity)) / curve.df(times(maturity)).sum()
def bond_prices(curve, coupons):
"""Price per 100 of semi-annual coupon bonds, valued on a coupon date so there is no accrued interest."""
return np.array([100.0 * (c / 2 * curve.df(times(T)).sum() + curve.df(T)) for T, c in zip(MATURITIES, coupons)])
def bond_yield(price, maturity, coupon):
t = times(maturity)
f = lambda y: 100.0 * (coupon / 2 * np.sum((1 + y / 2) ** (-2 * t)) + (1 + y / 2) ** (-2 * maturity)) - price
return brentq(f, -0.05, 0.30)
def duration(maturity, coupon, y=0.04):
t = times(maturity)
cash = np.full(len(t), coupon / 2 * 100.0)
cash[-1] += 100.0
pv = cash * (1 + y / 2) ** (-2 * t)
return (t * pv).sum() / pv.sum()
# The linear model: the discount function itself is a cubic spline, D(t) = sum_k b_k B_k(t) with b_0 = 1.
KNOTS = np.concatenate([[0.0] * 4, [1, 2, 4, 7, 10, 15, 20], [30.0] * 4])
class SplineDiscount:
def __init__(self, coefficients):
self.spline = BSpline(KNOTS, coefficients, 3)
def df(self, t):
values = self.spline(np.clip(np.atleast_1d(np.asarray(t, dtype=float)), 0.0, 30.0 - 1e-9))
return values if np.ndim(t) else values[0]
def spline_design(coupons):
"""Row j gives the bond's price as a linear function of the spline coefficients."""
rows = []
for T, c in zip(MATURITIES, coupons):
b_coupons = BSpline.design_matrix(np.clip(times(T), 0, 30 - 1e-9), KNOTS, 3).toarray()
b_final = BSpline.design_matrix(np.array([min(T, 30 - 1e-9)]), KNOTS, 3).toarray()[0]
rows.append(100.0 * (c / 2 * b_coupons.sum(axis=0) + b_final))
return np.array(rows)
def fit_spline_prices(coupons, prices, weights):
"""Weighted multiple linear regression of price on the spline columns, with D(0) = 1 fixed."""
x = spline_design(coupons)
coef, _ = regress(x[:, 1:], prices - x[:, 0], weights)
return SplineDiscount(np.concatenate([[1.0], coef]))
def fit_parametric(coupons, prices, weights, family, decay_grid):
"""Nelson-Siegel or Svensson by nonlinear least squares on prices: betas by an iterative solver, decays by a grid."""
best, start = None, np.array([0.04, -0.005, -0.01, 0.0][: 3 if family == "ns" else 4])
for decays in decay_grid:
basis = (lambda t, d=decays: ns_basis(t, d[0])) if family == "ns" else (lambda t, d=decays: svensson_basis(t, d[0], d[1]))
fun = lambda b: np.sqrt(weights) * (bond_prices(ZeroCurve(basis, b), coupons) - prices)
fit = least_squares(fun, start)
if best is None or fit.cost < best[0]:
best = (fit.cost, ZeroCurve(basis, fit.x))
return best[1]
NS_GRID = [(d,) for d in np.linspace(0.5, 8.0, 16)]
SV_GRID = [(d1, d2) for d1 in (1.0, 2.0, 3.0, 4.0) for d2 in (6.0, 8.0, 10.0, 14.0)]
# Swap spreads: the swap par rate less the Treasury par yield of the same maturity (same conventions, for simplicity).
QUOTED = np.array([2, 5, 10, 30]) # the only swap tenors that are quoted
UNQUOTED = [3, 7, 15, 20]
def spread_true(t):
return -0.0010 - 0.0040 * (1.0 - np.exp(-np.asarray(t, dtype=float) / 8.0))
def swap_true(t):
return par_yield(TRUTH, t) + spread_true(t)
def spread_basis(t):
t = np.atleast_1d(np.asarray(t, dtype=float))
return np.column_stack([np.ones(len(t)), 1.0 - np.exp(-t / 8.0)])
def fit_swap_spread(treasury, seed=21):
"""Quote swaps with 0.3bp of noise, subtract the fitted Treasury yield, and regress the spread on a smooth shape."""
noise = np.random.default_rng(seed).normal(0.0, 0.3e-4, len(QUOTED))
swap_quotes = np.array([swap_true(t) for t in QUOTED]) + noise
spread_quotes = swap_quotes - np.array([par_yield(treasury, t) for t in QUOTED])
coef, _ = regress(spread_basis(QUOTED), spread_quotes)
return swap_quotes, coef
def swap_estimate(treasury, coef, t):
return par_yield(treasury, t) + float(spread_basis(t) @ coef)
def scores(curve, coupons, prices):
fitted = bond_prices(curve, coupons)
yield_error = [bond_yield(f, T, c) - bond_yield(p, T, c) for f, p, T, c in zip(fitted, prices, MATURITIES, coupons)]
zero = lambda c: -np.log(c.df(YEARS.astype(float))) / YEARS
forwards = np.log(np.concatenate([[1.0], curve.df(YEARS.astype(float))])[:-1] / curve.df(YEARS.astype(float)))
return (np.sqrt(np.mean((fitted - prices) ** 2)),
np.sqrt(np.mean(np.square(yield_error))) * 1e4,
np.sqrt(np.mean((zero(curve) - zero(TRUTH)) ** 2)) * 1e4,
np.std(np.diff(forwards)) * 1e4)
if __name__ == "__main__":
rng = np.random.default_rng(5)
coupons = np.round(np.array([par_yield(TRUTH, T) for T in MATURITIES]) / 0.00125) * 0.00125 # to the nearest 1/8%
clean = bond_prices(TRUTH, coupons)
weights = 1.0 / np.array([duration(T, c) for T, c in zip(MATURITIES, coupons)]) ** 2
print(f"1. The inputs: {len(MATURITIES)} Treasury bonds, semi-annual coupons, price noise {PRICE_NOISE} per 100")
print(f" {'Maturity':>9} {'Coupon':>8} {'Price':>8} {'Duration':>9} {'Weight':>8}")
for T, c, p, w in list(zip(MATURITIES, coupons, clean, weights))[::3]:
print(f" {T:>8.1f}Y {c:8.3%} {p:8.3f} {duration(T, c):9.2f} {w:8.3f}")
methods = {
"Nelson-Siegel, unweighted": lambda c, p: fit_parametric(c, p, np.ones(len(p)), "ns", NS_GRID),
"Nelson-Siegel, weighted": lambda c, p: fit_parametric(c, p, weights, "ns", NS_GRID),
"Svensson, weighted": lambda c, p: fit_parametric(c, p, weights, "sv", SV_GRID),
"Spline on D(t), weighted": lambda c, p: fit_spline_prices(c, p, weights),
}
trials = 25
results = {name: [] for name in methods}
for _ in range(trials):
prices = clean + rng.normal(0.0, PRICE_NOISE, len(clean))
for name, fit in methods.items():
results[name].append(scores(fit(coupons, prices), coupons, prices))
print(f"\n2. Fits to bond prices, average over {trials} simulated sets of noisy prices:")
print(f" {'':<27} {'Price err':>10} {'Yield err':>10} {'Zero err vs truth':>18} {'Forward roughness':>18}")
for name, rows in results.items():
m = np.mean(rows, axis=0)
print(f" {name:<27} {m[0]:10.3f} {m[1]:7.2f} bp {m[2]:15.2f} bp {m[3]:15.2f} bp")
truth_rough = np.std(np.diff(np.log(np.concatenate([[1.0], TRUTH.df(YEARS.astype(float))])[:-1] / TRUTH.df(YEARS.astype(float))))) * 1e4
print(f" {'True curve':<27} {'':>10} {'':>10} {'':>18} {truth_rough:15.2f} bp")
# 3. Swap spreads: the swap curve as the Treasury curve plus a smooth spread, fitted to a few swap quotes.
prices = clean + np.random.default_rng(9).normal(0.0, PRICE_NOISE, len(clean))
treasury = fit_parametric(coupons, prices, weights, "sv", SV_GRID)
swap_quotes, coef = fit_swap_spread(treasury)
print("\n3. Swap spread regression: swap rates quoted at 2Y, 5Y, 10Y and 30Y only")
print(f" Fitted spread = {coef[0] * 1e4:+.1f}bp {coef[1] * 1e4:+.1f}bp x (1 - exp(-t/8)); the true spread is -10.0bp -40.0bp x (1 - exp(-t/8))")
print(f" {'Tenor':>6} {'Treasury':>9} {'Spread':>9} {'Swap rate':>10} {'True':>8} {'Error':>8} {'Linear interpolation error':>28}")
for t in UNQUOTED:
estimate = swap_estimate(treasury, coef, t)
interpolated = np.interp(t, QUOTED, swap_quotes)
print(f" {t:>5}Y {par_yield(treasury, t):9.4%} {float(spread_basis(t) @ coef):+9.4%} {estimate:10.4%} "
f"{swap_true(t):8.4%} {(estimate - swap_true(t)) * 1e4:+6.2f}bp {(interpolated - swap_true(t)) * 1e4:+24.2f}bp")
The inputs#
1. The inputs: 18 Treasury bonds, semi-annual coupons, price noise 0.03 per 100
Maturity Coupon Price Duration Weight
0.5Y 3.500% 100.005 0.50 4.000
2.0Y 3.500% 99.995 1.95 0.263
5.0Y 3.750% 100.199 4.60 0.047
8.0Y 3.875% 99.963 6.95 0.021
12.0Y 4.000% 99.877 9.65 0.011
20.0Y 4.125% 100.284 13.87 0.005
Every third bond is shown. The weight is one over the duration squared, so the six-month bond gets about 800 times the weight of the 20 year bond. That is the ratio between how much a price error means for each of them in yield terms.
Fits to the prices#
Four fits are made, and the whole experiment is repeated for 25 different sets of noise. The numbers are averages.
2. Fits to bond prices, average over 25 simulated sets of noisy prices:
Price err Yield err Zero err vs truth Forward roughness
Nelson-Siegel, unweighted 0.066 6.29 bp 2.55 bp 6.59 bp
Nelson-Siegel, weighted 0.127 1.48 bp 1.84 bp 5.47 bp
Svensson, weighted 0.031 0.95 bp 0.51 bp 5.81 bp
Spline on D(t), weighted 0.020 0.57 bp 0.59 bp 6.20 bp
True curve 5.78 bp
Left: the yield error of each fit, bond by bond, for one of the simulated sets of prices. Right: the swap curve from the Treasury fit and a fitted swap spread, against linear interpolation of the four swap quotes.#
Weights decide where the error goes. The unweighted Nelson-Siegel fit has the smaller price error, 0.066 against 0.127, but its yield error is 6.3 basis points against 1.5. In the left-hand panel it is the short bonds that suffer, with the six-month bond about 20 basis points off in yield. The unweighted fit counts a price error of 0.1 on a six-month bond the same as 0.1 on a 20 year bond, but in yield terms the first is 20 basis points and the second is 0.07. Fit the quantity whose errors you care about.
The right family matters more than the method. Nelson-Siegel has one bend and cannot follow the true curve, with a zero rate error of 1.8 basis points even when weighted. The four-parameter Svensson fit gets 0.5 basis points, and its price error, 0.031, is at the level of the noise that was added, 0.03. A fit whose residuals are no bigger than the noise has explained everything that is explainable.
The linear spline does as well, without iteration. Regressing the prices on the spline columns is a single matrix solution, and gives a yield error of 0.57 basis points and a zero error of 0.59, as good as Svensson. Its price error, 0.020, is below the noise because it has 10 coefficients for 18 prices and uses some of the freedom to follow the noise. Its forwards are slightly rougher than the true curve, 6.2 against 5.8 basis points of year-to-year change, which is the cost of having no smoothness built in. A penalty on the coefficients, as in the penalised spline above, would reduce it.
Forward roughness is a check on the family. The weighted Nelson-Siegel fit is too smooth (5.5 basis points of year-to-year change in the forwards, against 5.8 for the true curve) and the unweighted one is too rough (6.6). Svensson is close to the true curve at 5.8.
Swap spread regression#
The last part uses the Svensson fit from one noisy set of prices as the Treasury curve. The swap curve is the Treasury curve plus a smooth spread of -10 basis points at the short end, widening to -50 at the long end, which is invented. Only four swap rates are quoted, at 2, 5, 10 and 30 years, each with 0.3 basis points of noise. The spread at each of those tenors is the swap rate less the fitted Treasury par yield. A two-parameter regression, a level and a term in \(1 - e^{-t/8}\), is fitted to the four spreads, and the swap rate at the other tenors is the fitted Treasury yield plus the fitted spread. The alternative is to interpolate the swap quotes linearly.
3. Swap spread regression: swap rates quoted at 2Y, 5Y, 10Y and 30Y only
Fitted spread = -9.9bp -40.0bp x (1 - exp(-t/8)); the true spread is -10.0bp -40.0bp x (1 - exp(-t/8))
Tenor Treasury Spread Swap rate True Error Linear interpolation error
3Y 3.5576% -0.2237% 3.3339% 3.3376% -0.37bp +1.42bp
7Y 3.8308% -0.3318% 3.4990% 3.4971% +0.19bp -1.52bp
15Y 4.0633% -0.4371% 3.6262% 3.6255% +0.07bp -4.07bp
20Y 4.1010% -0.4656% 3.6354% 3.6370% -0.16bp -3.52bp
The Treasury curve supplies the shape. The swap curve rises and then flattens between 10 and 30 years, which a straight line between the 10 and the 30 year quotes cannot capture. Linear interpolation is wrong by 4.1 basis points at 15 years and 3.5 at 20. The Treasury fit and the spread are within 0.4 basis points at every tenor.
The spread is the only thing that has to be estimated, and four quotes are enough for a two-parameter function. The fitted spread, -9.9 and -40.0 basis points, is very close to the true -10 and -40, because it is smooth.
This flatters the method. The spread function in the regression has the same form as the true one, and the Treasury curve has no on-the-run effects. A real spread has kinks and changes over time, and the error would be larger. The test says that the idea works when the spread is smooth, and not that the numbers will be this good.
Choosing the method#
Aspect |
Bootstrap |
Global least squares |
Regression fit |
|---|---|---|---|
Reprices the inputs |
Exactly |
Exactly if there are no more quotes than unknowns, otherwise approximately |
No |
Number of parameters |
One per instrument |
Chosen by the knots |
Few, such as three or four, or controlled by a penalty |
Solved by |
One step per pillar |
Iterations of Gauss-Newton or Levenberg-Marquardt |
Normal equations, one step |
Handles noisy or overlapping quotes |
No |
Yes, by weights and a penalty |
Yes, by averaging |
Forward rates |
Can oscillate, with a sawtooth at the pillars |
Depends on the interpolation and the penalty |
Smooth by construction |
Risk by input |
By bumping, or by the inverse of a triangular matrix |
From the Jacobian |
Poorly defined, because the betas are not instruments |
Typical use |
Liquid curves with one instrument per pillar |
Production curve sets for pricing and risk |
Government bond curves fitted to bond prices, swap curves built from a government curve plus a fitted swap spread, smooth reference curves, scenarios and checks |
Practical points#
Choice of data: what is linear depends on what is modelled and what is fitted. A zero rate or forward rate model is linear when fitted to zero or forward rates, and a discount function model is linear when fitted to bond prices. A zero rate model fitted to bond prices, par rates or yields is nonlinear and needs an iterative solver. Fit the quantity whose errors you care about, and weight for it. For bond prices that means about one over the duration squared.
Grid search for the decay: the decay enters nonlinearly, and a coarse grid can miss the best value. A finer grid or a local optimiser gives a better fit, and the grid and the tolerance belong to the methodology.
Extrapolation: a parametric family extrapolates by construction, beyond the last data point, and Nelson-Siegel tends to its long-run level. A spline is held flat in this example. The choice is an assumption and needs its own control.
Stability over time: the betas and the decays are refitted each day, and large jumps can come from a change in the data and not in the market. Plotting them over time is a good check.
Number of data points: a fit needs more observations than parameters, and enough spread across the maturities. Nine points for a six-parameter Svensson fit is thin.
A valuation control view#
Know what the curve is for. A curve that does not reprice its inputs is not suitable for valuing the trades that those inputs hedge. If a regression curve is used for a reference, a scenario or a stress, the repricing error is a known limitation and it has to be documented. Quantify it as in the table above, in PV, and compare it with the bid-offer spread.
A reasonableness check on the bootstrap. A smooth regression curve is a good independent check on an exact curve. A quote that sits far from the smooth curve is a candidate for a stale or an erroneous input, and it can be flagged for review. This is the same idea as IPV for a price, applied to a curve input.
Check the bond inputs. Bond prices should come from an independent source at the same time, on the same bid, mid or offer basis. A bond with a large residual in the fit is either a stale price or a genuinely rich or cheap bond, for example one that is special in repo, and the two need different responses. Removing a bond from the fit is a judgement that is recorded.
Watch the spread and its basis. A swap curve built as a government curve plus a spread inherits the errors of both. The spread should be reviewed against its own history, and the day count and compounding conversions between swap rates and bond yields are a common source of a constant offset. A jump in the fitted spread at one tenor is a flag for an input or a methodology problem.
Family and parameters as model risk. Different families and different penalties give different curves, as the Nelson-Siegel and Svensson fits show. The range of values between plausible choices is an indication of model uncertainty and a candidate for a reserve. See Prudent Valuation: Requirements.
Reproducibility. The grid, the weights, the penalty and the knots are all part of the method, and a different choice gives a different curve. They are documented and version-controlled. See Governance: Model Risk, Accountability and Data.
Monitoring. The parameters, the residuals by maturity and the effective number of parameters are tracked over time, with limits.
Fit to the purpose. Where the curve feeds fair value, the level assessment and the reserves are linked to the quality of the fit. See Fair-Value Hierarchy: Levels 1, 2 & 3.