The Jacobian#

A model turns inputs into outputs: curve parameters into zero rates, a volatility surface into prices, a set of quotes into the parameters of a calibrated model. The Jacobian is the matrix of all the first derivatives of such a map, and it is the object that sits behind Newton’s method for several unknowns, least-squares fitting, the standard errors of a calibration, and the translation of risk from one set of variables to another, which is how risk is transformed from zero rates to par rates and rebucketed into hedging buckets. The pages of this series use it without naming it, as the vega in a root search, the matrix \(J^\top J\) in a fit, or a risk bucket. This page sets it out in one place, shows how it is computed and what its quality does to a solver, and shows what its singular values say about what the data determine.

Definition#

For a map \(f : \mathbb{R}^n \to \mathbb{R}^m\) the Jacobian at \(x\) is the \(m \times n\) matrix

\[J_{ij}(x) = \frac{\partial f_i}{\partial x_j}(x)\]

so that for a small change \(\delta\), \(f(x + \delta) \approx f(x) + J(x)\,\delta\). Column \(j\) is the change in all the outputs for a unit change in input \(j\), and row \(i\) is the gradient of output \(i\). For a single output, \(m = 1\), it is the gradient, as a row. The Hessian of a function is the Jacobian of its gradient. Maps compose by the chain rule,

\[J_{g \circ f}(x) = J_g\big( f(x) \big)\, J_f(x)\]

which is how the risk of a price to a model parameter and the risk of a parameter to a market quote combine into the risk of the price to the quote.

Where it is used#

Uses of the Jacobian in the series#

Use

Formula

Page

Newton’s method for \(f(x) = 0\) with \(n\) equations

\(x_{k+1} = x_k - J(x_k)^{-1} f(x_k)\)

Root Finding: Implied Volatility

Gauss-Newton and Levenberg-Marquardt

gradient \(J^\top r\), step \((J^\top J + \lambda D)\,\delta = -J^\top r\)

Regression and Fitting, Part 3: Non-linear Regression

Standard errors and identifiability

\(\operatorname{Cov}(\hat\theta) \approx \hat\sigma^2 (J^\top J)^{-1}\), singular values of \(J\)

Regression and Fitting, Part 3: Non-linear Regression

Calibration, and risk through a calibration

\(\partial\theta/\partial q = (J^\top J)^{-1} J^\top\)

Calibration

Adjoint differentiation

one row of \(J\) per backward sweep

Advanced Methods, Part 2: Dimension, Adjoints & Machine Learning

Transforming and rebucketing risk

\(r_q = J^\top r_x\), \(r_B = W^\top r_q\)

this page

Newton’s method for a system#

For \(n\) equations in \(n\) unknowns, replace \(f\) near \(x_k\) by its linearisation, \(f(x_k) + J(x_k)\,\delta = 0\), and solve for the step. Each iteration is one linear solve with the Jacobian (Numerical Linear Algebra). With the exact Jacobian the convergence is quadratic near a root. If the Jacobian is only approximate, the convergence slows. A Jacobian that is frozen at the start (the chord method) gives linear convergence, and quasi-Newton updates of the Jacobian, such as Broyden’s, give something in between. The scalar case is the Newton step of Root Finding: Implied Volatility, with the vega as the Jacobian.

Risk through a calibration#

Suppose parameters \(\theta\) are found from market quotes \(q\) by solving \(F(\theta, q) = 0\). By the implicit function theorem, the change in the parameters for a change in a quote is

\[\frac{\partial\theta}{\partial q} = -\left( \frac{\partial F}{\partial\theta} \right)^{-1} \frac{\partial F}{\partial q}\]

For an exact fit, \(F = g(\theta) - q\), this is \(J^{-1}\). For a least-squares fit with small residuals it is \((J^\top J)^{-1} J^\top\). The risk of a price \(V(\theta)\) to the quotes is then \(\nabla_\theta V \cdot \partial\theta/\partial q\). This is the sensitivity to the market quote that bumping the quote and recalibrating would give, from one linear solve and without the recalibrations.

Transforming and rebucketing risk#

Risk is a gradient, \(r_x = \partial V / \partial x\), in the variables \(x\) that the model uses. A risk system reports it in the variables that the traders hedge with: par swap rates and not zero rates, option quotes and not model parameters, quarters and not months. If the model variables are a function of the reporting variables, \(x = g(q)\), with Jacobian \(J = \partial x / \partial q\), the chain rule gives the risk in the new variables:

\[r_q = J^\top r_x, \qquad r_x = J^{-\top} r_q \;\text{ when } J \text{ is square and invertible}\]

The transformation has four properties that make it a check as well as a calculation.

  • Profit and loss does not depend on the coordinates. To first order, \(\Delta V = r_x^\top \Delta x = r_x^\top J\,\Delta q = r_q^\top \Delta q\). A risk report in two coordinate systems must give the same explained profit and loss for the same move.

  • A parallel move is not the same in both systems. The sum of the risks is the sensitivity to a parallel shift of the variables in that system, so the totals of \(r_x\) and \(r_q\) differ.

  • A structure in the map is a structure in the transformation. In a bootstrap the zero rate at a maturity depends only on the par rates up to it, so \(J\) is lower triangular and \(r_q\) is found by a back substitution, with no inverse.

  • Covariances transform the same way. If \(\Sigma_q\) is the covariance of the quotes, the covariance of the model variables is \(J \Sigma_q J^\top\), and a value at risk from \(r_x\) and \(J\Sigma_q J^\top\) equals the one from \(r_q\) and \(\Sigma_q\).

Rebucketing reduces many nodes to a few hedging buckets. Collect the interpolation weights in a matrix \(W\), with one row per node and one column per bucket, so that a move of the buckets \(\Delta b\) moves the nodes by \(\Delta q = W\,\Delta b\). The weights are the Jacobian of the nodes with respect to the buckets, and the bucketed risk is

\[r_B = W^\top r_q\]

If each row of \(W\) sums to one, the total is conserved, \(\mathbf{1}^\top r_B = \mathbf{1}^\top r_q\), since a parallel move of the buckets is a parallel move of the nodes. The profit and loss agrees when the scenario can be written through the buckets, \(r_q^\top W\,\Delta b = r_B^\top \Delta b\). A move that is not of that form, such as a local move of one node between two buckets, leaves a residual. If the hedges are instruments at the bucket nodes, the node risk that is left is \(r_q - E\,r_B\), where \(E\) places each bucket’s risk on its own node. The residual sums to zero and its profit and loss is the basis risk of the bucket hedge. Different weights, linear in the rate, in the discount factor or with a kernel, give different hedges with the same total.

The same calculation moves risk between any two systems that are linked by a map: model parameters to market quotes by the implicit Jacobian above, a volatility surface in strike and expiry to a coarse grid, months of a commodity curve to quarters and years (Commodity Pricing, Part 1: Forward Curves & Swaps), and a book of positions to the hedge instruments, by solving \(H^\top h = -r_q\) for the notionals \(h\), where \(H\) is the Jacobian of the hedge instruments.

Computing a Jacobian#

Ways of computing the Jacobian#

Method

Cost

Accuracy and cautions

Forward difference

\(n + 1\) evaluations

Error \(O(h)\) plus round-off \(\varepsilon/h\). Best step \(\sqrt{\varepsilon}\) of the variable (Numerical Differentiation)

Central difference

\(2n\) evaluations

Error \(O(h^2)\). Best step \(\varepsilon^{1/3}\)

Complex step

\(n\) evaluations

Full precision, with a step of \(10^{-30}\). Needs code that accepts complex numbers

Analytic

one evaluation, with the formulas

Exact, and fast. Needs the derivation, and a test against a difference

Algorithmic differentiation, forward

\(n\) sweeps, a small multiple of one evaluation each

Exact, one column per sweep

Algorithmic differentiation, reverse (adjoint)

\(m\) sweeps

Exact, one row per sweep. For a price, \(m = 1\), the whole gradient costs a small multiple of one price (Advanced Methods, Part 2: Dimension, Adjoints & Machine Learning)

The choice follows the shape of the map. A map from many inputs to a few outputs, such as a price that depends on hundreds of market quotes, is differentiated by reverse mode. A map from a few parameters to many outputs, such as a curve fitted to dozens of quotes, is cheaper by forward mode or by a difference.

Scaling and conditioning#

The singular value decomposition \(J = U \Sigma V^\top\) shows which combinations of inputs the outputs respond to. A large singular value is a direction that the data determine well, and a small one a direction that they do not, so the ratio \(\kappa(J) = \sigma_{\max}/\sigma_{\min}\) is a measure of identifiability, and \(\kappa(J^\top J) = \kappa(J)^2\) is what the normal equations suffer (Numerical Linear Algebra). The columns have the units of their variables, so the singular values change if a variable is rescaled, from a rate to a basis point or from years to months. The comparison of two sets of data for the same parameters is not affected, and the comparison of parameters with different units has to use a scale that is meaningful, such as the standard deviation or a typical size.

Worked example#

The example uses the Nelson-Siegel curve of Regression and Fitting, Part 3: Non-linear Regression, with 12 zero rates and 4 parameters \((\beta_0, \beta_1, \beta_2, \tau)\), so the Jacobian of the rates with respect to the parameters is 12 by 4. First it computes the Jacobian four ways and compares each with the analytic form. Second it uses Newton’s method to fit the curve exactly through four rates, with the analytic Jacobian, a finite-difference Jacobian and a Jacobian that is frozen at the start. Third it compares the singular values and the standard errors for all the maturities and for those up to five years. Finally it fits the curve to noisy quotes, and finds the sensitivity of the 30-year rate to each quote, with the implicit Jacobian and by bumping each quote and refitting.

Python code
"""The Jacobian: how to compute it, what its quality does to Newton's method, what its singular values say, and risk through a fitted curve."""
import numpy as np
from scipy.optimize import least_squares

from regression_nonlinear_example import MATURITIES, TRUE, nelson_siegel


def ns_jacobian(t, p):
    """Analytic Jacobian of the Nelson-Siegel zero rates with respect to (b0, b1, b2, tau)."""
    b0, b1, b2, tau = p
    x = t / tau
    e = np.exp(-x)
    l1 = (1 - e) / x
    l2 = l1 - e
    dl1_dx = (x * e - (1 - e)) / x**2
    dl1_dtau = -(x / tau) * dl1_dx
    dl2_dtau = dl1_dtau - x * e / tau
    return np.column_stack([np.ones_like(t), l1, l2, b1 * dl1_dtau + b2 * dl2_dtau])


def fd_jacobian(f, p, h, central=False):
    p = np.asarray(p, dtype=float)
    base = f(p)
    cols = []
    for j in range(len(p)):
        step = np.zeros_like(p)
        step[j] = h
        cols.append((f(p + step) - f(p - step)) / (2 * h) if central else (f(p + step) - base) / h)
    return np.column_stack(cols)


def complex_step_jacobian(t, p, h=1e-30):
    p = np.asarray(p, dtype=complex)
    cols = []
    for j in range(len(p)):
        q = p.copy()
        q[j] += 1j * h
        x = t / q[3]
        e = np.exp(-x)
        l1 = (1 - e) / x
        cols.append(((q[0] + q[1] * l1 + q[2] * (l1 - e)).imag) / h)
    return np.column_stack(cols)


def run_newton(f, jac_fn, p0, mode, steps=10):
    p = np.array(p0, dtype=float)
    out = [np.linalg.norm(f(p))]
    j0 = jac_fn(p)
    for _ in range(steps):
        j = j0 if mode == "chord" else jac_fn(p)
        p = p - np.linalg.solve(j, f(p))
        out.append(np.linalg.norm(f(p)))
    return p, out


if __name__ == "__main__":
    t = MATURITIES
    p_true = TRUE
    print(f"Nelson-Siegel parameters b0 {p_true[0]:.3f}, b1 {p_true[1]:.3f}, b2 {p_true[2]:.3f}, tau {p_true[3]}; {len(t)} maturities")

    print("\n1. The Jacobian of the 12 zero rates with respect to the 4 parameters, four ways. Largest error against the analytic Jacobian")
    exact = ns_jacobian(t, p_true)
    f = lambda p: nelson_siegel(t, p)
    print(f"   {'Method':<28} {'evaluations':>12} {'largest error':>14}")
    for name, evals, jac in (
        ("Forward difference, h 1e-2", 5, fd_jacobian(f, p_true, 1e-2)),
        ("Forward difference, h 1e-6", 5, fd_jacobian(f, p_true, 1e-6)),
        ("Forward difference, h 1e-12", 5, fd_jacobian(f, p_true, 1e-12)),
        ("Central difference, h 1e-5", 8, fd_jacobian(f, p_true, 1e-5, central=True)),
        ("Complex step, h 1e-30", 4, complex_step_jacobian(t, p_true)),
    ):
        print(f"   {name:<28} {evals:12d} {np.max(np.abs(jac - exact)):14.1e}")
    print("   Column of the Jacobian for tau (change in each zero rate for a unit change in tau, in basis points):")
    print("   " + " ".join(f"{v * 1e4:7.2f}" for v in exact[:, 3]))

    print("\n2. Newton's method for four equations in four unknowns: fit the curve exactly through 4 rates (0.5, 2, 7, 20 years), start b = (4%, -1%, -1%, 1.5)")
    t4 = np.array([0.5, 2.0, 7.0, 20.0])
    target = nelson_siegel(t4, p_true)
    g = lambda p: nelson_siegel(t4, p) - target
    start = [0.04, -0.01, -0.01, 1.5]
    print(f"   {'Iteration':>9} {'analytic Jacobian':>19} {'finite difference 1e-6':>24} {'frozen at the start':>21}")
    runs = {
        "analytic": run_newton(g, lambda p: ns_jacobian(t4, p), start, "full"),
        "difference": run_newton(g, lambda p: fd_jacobian(g, p, 1e-6), start, "full"),
        "frozen": run_newton(g, lambda p: ns_jacobian(t4, p), start, "chord"),
    }
    for k in range(9):
        print(f"   {k:9d} {runs['analytic'][1][k]:19.2e} {runs['difference'][1][k]:24.2e} {runs['frozen'][1][k]:21.2e}")
    print(f"   Solution from Newton: {np.round(runs['analytic'][0], 5)}; condition number of the Jacobian at the solution {np.linalg.cond(ns_jacobian(t4, runs['analytic'][0])):.1e}")

    print("\n3. What the singular values of the Jacobian say: all 12 maturities against the 6 up to 5 years")
    print(f"   {'Maturities used':<22} {'singular values':<44} {'condition':>10}")
    for name, mask in (("All 12", t > 0), ("Up to 5 years (6)", t <= 5)):
        jm = ns_jacobian(t[mask], p_true)
        sv = np.linalg.svd(jm, compute_uv=False)
        print(f"   {name:<22} {np.array2string(sv, precision=4, floatmode='fixed'):<44} {sv[0] / sv[-1]:10.1f}")
        if name.startswith("Up"):
            vt = np.linalg.svd(jm)[2]
            print(f"   Right singular vector of the smallest singular value (b0, b1, b2, tau): {np.round(vt[-1], 3)}")
    sd = 1e-4
    for name, mask in (("All 12", t > 0), ("Up to 5 years (6)", t <= 5)):
        jm = ns_jacobian(t[mask], p_true)
        se = sd * np.sqrt(np.diag(np.linalg.inv(jm.T @ jm)))
        print(f"   Standard errors for 1bp of noise, {name:<18}: b0 {se[0] * 100:.4f}%, b1 {se[1] * 100:.4f}%, b2 {se[2] * 100:.4f}%, tau {se[3]:.3f}")

    print("\n4. Risk through a fitted curve: fit to the 12 quotes, then the change in the 30-year rate for a 1bp bump in each quote")
    rng = np.random.default_rng(21)
    quotes = nelson_siegel(t, p_true) + rng.normal(0, 0.0001, t.size)
    fit = least_squares(lambda p: nelson_siegel(t, p) - quotes, [0.04, 0.0, 0.0, 2.0], method="lm")
    j = ns_jacobian(t, fit.x)
    dtheta_dq = np.linalg.solve(j.T @ j, j.T)
    grad30 = ns_jacobian(np.array([30.0]), fit.x)[0]
    implicit = grad30 @ dtheta_dq
    bumped = np.zeros(t.size)
    for i in range(t.size):
        q = quotes.copy()
        q[i] += 1e-4
        refit = least_squares(lambda p: nelson_siegel(t, p) - q, fit.x, method="lm", xtol=1e-15, ftol=1e-15)
        bumped[i] = nelson_siegel(np.array([30.0]), refit.x)[0] - nelson_siegel(np.array([30.0]), fit.x)[0]
    print(f"   {'Quote':>6} {'implicit Jacobian':>19} {'bump and refit':>16}   (change in the 30-year rate in bp for 1bp in the quote)")
    for i in range(t.size):
        print(f"   {t[i]:6.2f} {implicit[i]:19.4f} {bumped[i] * 1e4:16.4f}")
    print(f"   Sum of the sensitivities {implicit.sum():.4f}; largest difference between the two methods {np.max(np.abs(implicit - bumped * 1e4)):.1e}")
    print(f"   Work: one {j.shape[1]}x{j.shape[1]} solve for all {t.size} sensitivities, against {t.size} refits")

The output is:

Nelson-Siegel parameters b0 0.048, b1 -0.020, b2 -0.015, tau 2.5; 12 maturities

1. The Jacobian of the 12 zero rates with respect to the 4 parameters, four ways. Largest error against the analytic Jacobian
   Method                        evaluations  largest error
   Forward difference, h 1e-2              5        7.6e-06
   Forward difference, h 1e-6              5        7.6e-10
   Forward difference, h 1e-12             5        3.9e-05
   Central difference, h 1e-5              8        6.2e-13
   Complex step, h 1e-30                   4        2.2e-16
   Column of the Jacobian for tau (change in each zero rate for a unit change in tau, in basis points):
     -1.12   -2.44   -5.46  -11.89  -17.67  -25.34  -28.23  -27.40  -22.04  -17.29  -13.97  -11.66

2. Newton's method for four equations in four unknowns: fit the curve exactly through 4 rates (0.5, 2, 7, 20 years), start b = (4%, -1%, -1%, 1.5)
   Iteration   analytic Jacobian   finite difference 1e-6   frozen at the start
           0            5.61e-03                 5.61e-03              5.61e-03
           1            1.45e-03                 1.45e-03              1.45e-03
           2            3.05e-04                 3.05e-04              3.01e-04
           3            1.90e-05                 1.90e-05              1.71e-04
           4            3.24e-08                 3.24e-08              8.13e-05
           5            1.26e-13                 1.28e-13              2.97e-05
           6            1.10e-17                 1.39e-17              1.48e-05
           7            7.76e-18                 7.76e-18              5.72e-06
           8            1.90e-17                 1.04e-17              2.50e-06
   Solution from Newton: [ 0.048 -0.02  -0.015  2.5  ]; condition number of the Jacobian at the solution 4.3e+03

3. What the singular values of the Jacobian say: all 12 maturities against the 6 up to 5 years
   Maturities used        singular values                               condition
   All 12                 [3.8773e+00 9.8442e-01 2.8385e-01 1.0140e-03]     3823.8
   Up to 5 years (6)      [3.0761e+00 4.4646e-01 5.0894e-02 7.6602e-05]    40156.8
   Right singular vector of the smallest singular value (b0, b1, b2, tau): [ 0.006 -0.006 -0.002  1.   ]
   Standard errors for 1bp of noise, All 12            : b0 0.0132%, b1 0.0192%, b2 0.0797%, tau 0.099
   Standard errors for 1bp of noise, Up to 5 years (6) : b0 0.7455%, b1 0.7580%, b2 0.3155%, tau 1.305

4. Risk through a fitted curve: fit to the 12 quotes, then the change in the 30-year rate for a 1bp bump in each quote
    Quote   implicit Jacobian    bump and refit   (change in the 30-year rate in bp for 1bp in the quote)
     0.25             -0.0578           -0.0586
     0.50             -0.0087           -0.0086
     1.00              0.0513            0.0509
     2.00              0.0729            0.0728
     3.00              0.0324            0.0337
     5.00             -0.0702           -0.0704
     7.00             -0.1155           -0.1162
    10.00             -0.0754           -0.0731
    15.00              0.0975            0.0996
    20.00              0.2556            0.2556
    25.00              0.3690            0.3698
    30.00              0.4487            0.4519
   Sum of the sensitivities 1.0000; largest difference between the two methods 3.1e-03
   Work: one 4x4 solve for all 12 sensitivities, against 12 refits

Reading the output:

  • The step size decides the quality of a difference Jacobian. The forward difference has an error of 7.6e-6 at \(h = 10^{-2}\), 7.6e-10 at \(10^{-6}\), and 3.9e-5 at \(10^{-12}\), where round-off has taken over. The central difference reaches 6.2e-13 with 8 evaluations, and the complex step 2.2e-16 with 4. A column of the Jacobian is also a result: a unit change in \(\tau\) moves the 7-year rate by 28 basis points and the 3-month rate by 1.

  • A good Jacobian gives quadratic convergence, and the exact one is not required. Newton’s method with the analytic Jacobian reduces the residual from 5.6e-3 to 1.3e-13 in 5 iterations, with the residual falling faster at each step, 1.9e-5, then 3.2e-8, then 1.3e-13, as the number of correct digits roughly doubles. The finite-difference Jacobian with \(h = 10^{-6}\) gives the same residuals to three digits. The error of the Jacobian only needs to be small, since it enters as a correction to the step and not as an error in the answer.

  • A frozen Jacobian converges linearly. With the Jacobian of the start, the residual is 3.0e-4 after 2 iterations, and then falls by a factor of about 2 each time, 2.5e-6 after 8, against machine precision after 5 for Newton. It saves the cost of the Jacobian and pays in iterations, which is a good bargain only when the Jacobian is expensive and the start is close.

  • The singular values show what the data determine. With all 12 maturities the condition number of the Jacobian is 3,800. With only the six up to 5 years it is 40,000, ten times larger, and the standard errors for 1 basis point of noise are 56 times larger for \(\beta_0\) (0.75% against 0.013%) and 13 times for \(\tau\). The weakest direction is mostly \(\tau\), which is the scaling of that column, and the comparison between the two data sets does not depend on it.

  • The Jacobian gives the risk through the fit without refitting. The sensitivity of the 30-year rate to each of the 12 quotes from one 4 by 4 solve agrees with the bump-and-refit result to 0.003 basis points per basis point, for example 0.4487 and 0.4519 for the 30-year quote. The difference is the second-order term that the \((J^\top J)^{-1} J^\top\) form leaves out, which is small because the residuals are about 1 basis point. The sensitivities add to 1.0000, as they must for a parallel move. The risk is not only in the 30-year quote: it is 0.37 for the 25-year quote, 0.26 for the 20-year quote, and negative, -0.12, for the 7-year quote, so the fit spreads a move in one quote across the whole curve.

Worked example: transforming and rebucketing risk#

The second example bootstraps an annual curve from ten par swap rates and values a set of cash flows with positive and negative signs. It finds the risk in zero rates, and transforms it to par rates with the Jacobian of the bootstrap, and compares the result with bumping each par rate and revaluing. It then rebuckets the par risk to 2, 5 and 10 years with linear weights, and compares the profit and loss of two moves of the curve with the explained profit and loss before and after hedging the buckets.

Python code
"""Transforming and rebucketing risk with the Jacobian: zero-rate risk to par-rate risk, risk in coarse hedging buckets, and profit and loss explain."""
import numpy as np

PAR = np.array([3.00, 3.20, 3.35, 3.50, 3.62, 3.72, 3.80, 3.87, 3.93, 3.98]) / 100
YEARS = np.arange(1, 11)
CASH_FLOWS = np.array([2.0, 1.0, 5.0, 3.0, -6.0, 4.0, 2.0, 8.0, -3.0, 20.0])
BUCKETS = [2, 5, 10]
BP = 1e-4


def discount(par):
    """Bootstrap annual discount factors from par swap rates, one maturity at a time."""
    d = np.zeros(len(par))
    annuity = 0.0
    for n in range(len(par)):
        d[n] = (1 - par[n] * annuity) / (1 + par[n])
        annuity += d[n]
    return d


def zero(par):
    return -np.log(discount(par)) / YEARS


def value(par):
    return CASH_FLOWS @ discount(par)


def jacobian(f, x, h=1e-6):
    cols = []
    for j in range(len(x)):
        step = np.zeros_like(x)
        step[j] = h
        cols.append((f(x + step) - f(x - step)) / (2 * h))
    return np.column_stack(cols)


def bucket_weights():
    """Linear interpolation weights of each par node on the buckets 2y, 5y and 10y. Each row sums to 1."""
    w = np.zeros((len(YEARS), len(BUCKETS)))
    for i, n in enumerate(YEARS):
        if n <= BUCKETS[0]:
            w[i, 0] = 1
        elif n >= BUCKETS[-1]:
            w[i, -1] = 1
        else:
            for b in range(len(BUCKETS) - 1):
                lo, hi = BUCKETS[b], BUCKETS[b + 1]
                if lo <= n <= hi:
                    w[i, b + 1] = (n - lo) / (hi - lo)
                    w[i, b] = 1 - w[i, b + 1]
    return w


if __name__ == "__main__":
    d = discount(PAR)
    z = zero(PAR)
    print("1. The curve: annual par swap rates, bootstrapped discount factors and zero rates")
    print(f"   {'Year':>5} {'par %':>7} {'discount factor':>16} {'zero %':>8} {'cash flow':>10}")
    for i, n in enumerate(YEARS):
        print(f"   {n:5d} {PAR[i] * 100:7.2f} {d[i]:16.6f} {z[i] * 100:8.4f} {CASH_FLOWS[i]:10.1f}")
    print(f"   Value of the cash flows: {value(PAR):.4f}")

    print("\n2. Risk of the cash flows to a 1 basis point rise in each rate: zero rates, and par rates by the Jacobian and by bumping")
    r_z = -YEARS * CASH_FLOWS * d
    j_zs = jacobian(zero, PAR)
    r_par = j_zs.T @ r_z
    r_bump = np.array([(value(PAR + h) - value(PAR - h)) / (2e-6) for h in np.eye(10) * 1e-6])
    print(f"   {'Year':>5} {'zero rate':>10} {'par rate (Jacobian)':>20} {'par rate (bump)':>16}")
    for i, n in enumerate(YEARS):
        print(f"   {n:5d} {r_z[i] * BP:10.5f} {r_par[i] * BP:20.5f} {r_bump[i] * BP:16.5f}")
    print(f"   {'Total':>5} {r_z.sum() * BP:10.5f} {r_par.sum() * BP:20.5f} {r_bump.sum() * BP:16.5f}")
    print(f"   Largest difference between the Jacobian and the bump: {np.max(np.abs(r_par - r_bump)) * BP:.1e}")
    print(f"   The Jacobian of the zero rates with respect to the par rates is lower triangular: largest entry above the diagonal {np.max(np.abs(np.triu(j_zs, 1))):.1e}")
    print(f"   Zero risk at 1 and 2 years: {r_z[0] * BP:.5f}, {r_z[1] * BP:.5f}; par risk at 1 and 2 years: {r_par[0] * BP:.5f}, {r_par[1] * BP:.5f}")

    print("\n3. Rebucketing the par risk into hedging buckets at 2, 5 and 10 years with linear interpolation weights")
    w = bucket_weights()
    r_b = w.T @ r_par
    print(f"   {'Year':>5} " + " ".join(f"{'w ' + str(b) + 'y':>7}" for b in BUCKETS) + f" {'par risk':>10} {'residual after hedge':>21}")
    placed = np.zeros(10)
    for b, nb in enumerate(BUCKETS):
        placed[nb - 1] = r_b[b]
    residual = r_par - placed
    for i, n in enumerate(YEARS):
        print(f"   {n:5d} " + " ".join(f"{x:7.3f}" for x in w[i]) + f" {r_par[i] * BP:10.5f} {residual[i] * BP:21.5f}")
    print(f"   Bucket risk (2y, 5y, 10y): " + " ".join(f"{x * BP:.5f}" for x in r_b) + f"; sum {r_b.sum() * BP:.5f}, total before {r_par.sum() * BP:.5f}")
    print(f"   Sum of the absolute node risks: {np.sum(np.abs(r_par)) * BP:.5f} before the hedge, {np.sum(np.abs(residual)) * BP:.5f} after hedging the three buckets; the residual sums to {residual.sum() * BP:.1e}")

    print("\n4. Profit and loss explain for two moves of the par curve (basis points)")
    shocks = {
        "Smooth: +5 at 1y falling to -4 at 10y": np.array([5, 4, 3, 2, 1, 0, -1, -2, -3, -4], dtype=float),
        "Local: +6 at 7y only": np.array([0, 0, 0, 0, 0, 0, 6, 0, 0, 0], dtype=float),
    }
    print(f"   {'Move':<40} {'full revaluation':>17} {'first order':>12} {'after bucket hedge':>19}")
    for name, s in shocks.items():
        dv = value(PAR + s * BP) - value(PAR)
        print(f"   {name:<40} {dv:17.5f} {r_par @ s * BP:12.5f} {residual @ s * BP:19.5f}")

The output is:

1. The curve: annual par swap rates, bootstrapped discount factors and zero rates
    Year   par %  discount factor   zero %  cash flow
       1    3.00         0.970874   2.9559        2.0
       2    3.20         0.938888   3.1530        1.0
       3    3.35         0.905683   3.3022        5.0
       4    3.50         0.870975   3.4535        3.0
       5    3.62         0.836278   3.5759       -6.0
       6    3.72         0.801924   3.6790        4.0
       7    3.80         0.768463   3.7623        2.0
       8    3.87         0.735725   3.8362        8.0
       9    3.93         0.703962   3.9003       -3.0
      10    3.98         0.673395   3.9542       20.0
   Value of the cash flows: 26.9907

2. Risk of the cash flows to a 1 basis point rise in each rate: zero rates, and par rates by the Jacobian and by bumping
    Year  zero rate  par rate (Jacobian)  par rate (bump)
       1   -0.00019             -0.00009         -0.00009
       2   -0.00019              0.00000          0.00000
       3   -0.00136             -0.00112         -0.00112
       4   -0.00105             -0.00078         -0.00078
       5    0.00251              0.00308          0.00308
       6   -0.00192             -0.00157         -0.00157
       7   -0.00108             -0.00065         -0.00065
       8   -0.00471             -0.00485         -0.00485
       9    0.00190              0.00273          0.00273
      10   -0.01347             -0.01578         -0.01578
   Total   -0.01955             -0.01904         -0.01904
   Largest difference between the Jacobian and the bump: 5.8e-13
   The Jacobian of the zero rates with respect to the par rates is lower triangular: largest entry above the diagonal 0.0e+00
   Zero risk at 1 and 2 years: -0.00019, -0.00019; par risk at 1 and 2 years: -0.00009, 0.00000

3. Rebucketing the par risk into hedging buckets at 2, 5 and 10 years with linear interpolation weights
    Year    w 2y    w 5y   w 10y   par risk  residual after hedge
       1   1.000   0.000   0.000   -0.00009              -0.00009
       2   1.000   0.000   0.000    0.00000               0.00110
       3   0.667   0.333   0.000   -0.00112              -0.00112
       4   0.333   0.667   0.000   -0.00078              -0.00078
       5   0.000   1.000   0.000    0.00308               0.00394
       6   0.000   0.800   0.200   -0.00157              -0.00157
       7   0.000   0.600   0.400   -0.00065              -0.00065
       8   0.000   0.400   0.600   -0.00485              -0.00485
       9   0.000   0.200   0.800    0.00273               0.00273
      10   0.000   0.000   1.000   -0.01578               0.00130
   Bucket risk (2y, 5y, 10y): -0.00110 -0.00086 -0.01708; sum -0.01904, total before -0.01904
   Sum of the absolute node risks: 0.03066 before the hedge, 0.01814 after hedging the three buckets; the residual sums to -1.4e-18

4. Profit and loss explain for two moves of the par curve (basis points)
   Move                                      full revaluation  first order  after bucket hedge
   Smooth: +5 at 1y falling to -4 at 10y              0.06301      0.06298            -0.00009
   Local: +6 at 7y only                              -0.00388     -0.00388            -0.00388

Reading the output:

  • The Jacobian gives the par risk, and agrees with the bump. Transforming the zero-rate risk by \(J^\top\) gives the par-rate risk to 6e-13, the same as bumping each par rate and revaluing the cash flows. The Jacobian is a property of the curve and is computed once, and it applies to every portfolio. A bump needs a revaluation of each portfolio for each rate.

  • The two coordinate systems tell different stories. The 2-year zero risk is -0.00019 and the 2-year par risk is zero. The 10-year par risk, -0.01578, is 17% larger than the 10-year zero risk, -0.01347, because a basis point on the 10-year par rate moves the 10-year zero rate by 1.17 basis points on an upward sloping curve. The totals, which are the effect of a parallel move, are -0.01955 for the zero rates and -0.01904 for the par rates, 2.7% apart, since a parallel move of the par rates is not a parallel move of the zero rates.

  • The structure of the bootstrap shows in the Jacobian. All the entries above the diagonal are zero, since the zero rate at a maturity depends only on the par rates up to it, and so the risk of a late cash flow is carried back to every earlier par rate.

  • Rebucketing conserves the total. The bucket risks of -0.00110, -0.00086 and -0.01708 add to -0.01904, the total before. The 10-year bucket holds the risk of the 6 to 10-year nodes that is allocated to it, and it is larger than the 10-year node alone.

  • A bucket hedge removes about 40% of the absolute node risk. The sum of the absolute node risks falls from 0.03066 to 0.01814 after hedging the three buckets with swaps at their own nodes. What remains is at the nodes between the buckets, for example -0.00485 at 8 years and +0.00273 at 9 years, and it sums to zero.

  • The hedge works for a smooth move and not for a local one. For a move that falls from +5 to -4 basis points, the full revaluation is 0.06301 and the first-order explain 0.06298, so the risk explains the move, and after the bucket hedge the profit and loss is -0.00009, almost nothing. For a move of 6 basis points at the 7-year node alone, the profit and loss is -0.00388, and it is the same after the hedge, since the hedging swaps at 5 and 10 years do not move. This is the basis risk of a bucket hedge, and a limit on bucket risk does not see it.

A valuation control view#

  • Test an analytic Jacobian against a difference: a wrong derivative gives a Newton iteration that converges slowly or not at all, and a risk report that is wrong with no sign of it. Compare each column with a central difference or a complex step.

  • Check the conditioning of the Jacobian of a calibration: a large condition number or a very small singular value says that some combination of parameters is not determined, whatever the fit looks like. See Calibration.

  • Ask how risk through a calibration is computed: bump and recalibrate, which costs one calibration per quote and depends on the tolerance of the optimiser, or the implicit Jacobian, which is exact for the calibrated model. The two should agree, and a difference points to a loose tolerance or a model that recalibrates to a different minimum.

  • Check that the risk adds up: the sensitivities of a rate to all the quotes should add to one for a parallel move. Sensitivities that do not add up show a bug in the transformation of risk.

  • Look at the sign and the spread of the risk: a fitted curve moves at maturities where the quote did not, with a sign that can be opposite. A hedge built from the risk in the quote bucket alone will miss it.

  • Use the right mode for the shape of the problem: a price with hundreds of inputs needs the reverse mode, and a bump of every input does not scale. See Advanced Methods, Part 2: Dimension, Adjoints & Machine Learning.

  • Reconcile transformed risk to a bump: a risk in par rates, quote vegas or hedge buckets that comes from a Jacobian should agree with a bump and revaluation of the same portfolio. A difference is a stale Jacobian, a curve rebuilt with different interpolation, or a bug.

  • Check that the profit and loss explain does not depend on the coordinates: the explained profit and loss from the node risk, the bucketed risk and the model-variable risk should agree for a move that the buckets can represent. Any gap is the residual, and it should be reported.

  • Use the Jacobian of the production curve: the one that includes the interpolation, the instruments and the conventions that the valuation uses. A Jacobian from a simplified curve moves the risk to the wrong nodes.

  • Document the bucketing: the nodes, the weights and the total that is conserved. Different weights give different hedges from the same risk, and a change in them moves the reported bucket risk with no change in the position.

  • Test the bucket hedge against local moves: the residual node risk, and its profit and loss on a move of a single node, is the basis risk that a bucket limit does not capture.

Next, Numerical Integration: Quadrature covers numerical integration, which prices an option from its density.