Numerical Differentiation#

A derivative is needed whenever a sensitivity is: delta and gamma of an option, the Jacobian that a calibration uses, the slope that Newton’s method follows, the forward rate that comes from a discount curve. A formula is not always available, and a pricer that is a simulation or a grid can only be differentiated numerically, by bumping an input and revaluing. The choice of the bump size is a balance between two errors that go in opposite directions, and for a Monte Carlo pricer it is a matter of how the random numbers are used. This page sets out the finite-difference formulas and their errors, the complex step, and the bump-and-revalue Greeks of a simulation.

Finite differences#

From the Taylor expansion of \(f\) the standard formulas are

\[f'(x) \approx \frac{f(x + h) - f(x)}{h}, \qquad f'(x) \approx \frac{f(x + h) - f(x - h)}{2h}, \qquad f''(x) \approx \frac{f(x + h) - 2f(x) + f(x - h)}{h^2}\]

The truncation error comes from the terms that are dropped:

\[\text{forward: } \tfrac{h}{2} f''(x), \qquad \text{central: } \tfrac{h^2}{6} f'''(x), \qquad \text{second difference: } \tfrac{h^2}{12} f^{(4)}(x)\]

The central formula is accurate to order \(h^2\), and the forward formula only to order \(h\), for an extra function evaluation that is often shared with the value. The round-off error comes from the subtraction of two nearly equal numbers. If each value of \(f\) has a relative error of \(\varepsilon \approx 10^{-16}\), the error in the difference is about \(\varepsilon |f| / h\) for a first derivative and \(\varepsilon |f| / h^2\) for a second. It grows as \(h\) falls. The total error is smallest where the two are equal:

\[h_{opt} \sim \varepsilon^{1/2}\,|x| \text{ (forward)}, \qquad \varepsilon^{1/3}\,|x| \text{ (central)}, \qquad \varepsilon^{1/4}\,|x| \text{ (second difference)}\]

which is about \(10^{-8}\), \(5 \times 10^{-6}\) and \(10^{-4}\) of the level of \(x\), and a best attainable accuracy of about 8, 11 and 8 digits. For a pricer that is itself only accurate to \(10^{-6}\), as a grid or a tree is, \(\varepsilon\) is \(10^{-6}\), and the best step is much larger. A tree price also has a saw-tooth error that a small bump differentiates, and not the smooth price.

The complex step#

If \(f\) is an analytic function of a real variable, then

\[f(x + ih) = f(x) + ih f'(x) - \tfrac{h^2}{2} f''(x) - \dots \quad \Rightarrow \quad f'(x) \approx \frac{\operatorname{Im} f(x + ih)}{h}\]

with an error of order \(h^2\). There is no subtraction, so no cancellation, and \(h\) can be taken as small as \(10^{-30}\), giving the derivative to full machine precision. The cost is that the code must work with complex numbers, with no absolute value, comparison or branch on the input. It suits a closed form and a hand-written pricer, and not a library routine. It is also the simplest way to obtain a reference derivative to test another method against.

Greeks by bump and revalue#

With several inputs, the first derivatives of each output with respect to each input form the Jacobian, and a difference formula costs one extra evaluation per input, \(n + 1\) for the forward form and \(2n\) for the central one. How the matrix is built, and what it is used for, is the subject of The Jacobian.

The Greeks of a Monte Carlo price are usually found by bumping an input and revaluing,

\[\Delta \approx \frac{V(S_0 + h) - V(S_0 - h)}{2h}\]

and the estimate then has the noise of two simulations in the numerator, divided by \(2h\). With independent random numbers in the two valuations the noise does not cancel, the variance of the difference is twice the variance of one price, and the standard deviation of the delta grows as \(1/h\). With common random numbers, the same paths in both valuations, the noise in the two prices is almost the same and cancels in the difference. For a smooth payoff, such as a call, the variance of the difference is \(O(h^2)\), and the standard deviation of the delta does not depend on \(h\). For a payoff with a jump, such as a digital, only the paths close to the strike are changed by the bump, and the variance of the delta grows as \(h\) falls, as \(h^{-1/2}\). Smoothing the payoff, for instance a digital as a tight call spread, or using a pathwise or likelihood-ratio estimator, removes the problem, and the three methods are compared in Monte Carlo, Part 4: Greeks. Adjoint methods give all the sensitivities of a payoff in one pass (Advanced Methods, Part 2: Dimension, Adjoints & Machine Learning).

Worked example#

The example differentiates the benchmark call price of The Pricing Problem & the Benchmark, for which the exact delta and gamma are known. It measures the error of the forward, central and complex-step formulas as the step falls, the error of the second difference for gamma, and the noise of a Monte Carlo delta with independent and with common random numbers, for a call and for a digital.

Python code
"""Numerical differentiation: truncation against round-off, the complex step, and bump Greeks by Monte Carlo."""
import numpy as np
from scipy.special import erf

from common import K, R, S0, SIGMA, T, bs_greeks, bs_price


def bs_call(s, k=K, r=R, sigma=SIGMA, t=T):
    """Black-Scholes call that accepts a complex spot, so that the complex step can be used."""
    sd = sigma * np.sqrt(t)
    d1 = (np.log(s / k) + (r + 0.5 * sigma**2) * t) / sd
    d2 = d1 - sd
    cdf = lambda x: 0.5 * (1 + erf(x / np.sqrt(2)))
    return s * cdf(d1) - k * np.exp(-r * t) * cdf(d2)


def mc_delta(h, n, payoff, rng, common):
    """Central-difference delta from simulation, with common or independent random numbers for the two bumps."""
    z1 = rng.standard_normal(n)
    z2 = z1 if common else rng.standard_normal(n)
    st = lambda s, z: s * np.exp((R - 0.5 * SIGMA**2) * T + SIGMA * np.sqrt(T) * z)
    up, down = payoff(st(S0 + h, z1)).mean(), payoff(st(S0 - h, z2)).mean()
    return np.exp(-R * T) * (up - down) / (2 * h)


if __name__ == "__main__":
    delta, gamma, _ = bs_greeks()
    f = lambda s: float(bs_price(s=s))
    print(f"1. Delta of the benchmark call by three formulas, error against the closed form {delta:.10f}")
    print(f"   {'step h':>9} {'forward':>12} {'central':>12} {'complex step':>14}")
    for h in (1e-1, 1e-2, 1e-4, 1e-6, 1e-8, 1e-10, 1e-12, 1e-14):
        forward = (f(S0 + h) - f(S0)) / h - delta
        central = (f(S0 + h) - f(S0 - h)) / (2 * h) - delta
        cstep = bs_call(complex(S0, h)).imag / h - delta
        print(f"   {h:9.0e} {forward:12.2e} {central:12.2e} {cstep:14.2e}")
    print(f"   complex step with h = 1e-30: error {bs_call(complex(S0, 1e-30)).imag / 1e-30 - delta:.2e}")

    print(f"\n2. Gamma by the central second difference, closed form {gamma:.10f}")
    print(f"   {'step h':>9} {'error':>12}")
    for h in (1.0, 1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6):
        print(f"   {h:9.0e} {(f(S0 + h) - 2 * f(S0) + f(S0 - h)) / h**2 - gamma:12.2e}")

    print("\n3. Delta by bump and revalue with 100,000 paths, 50 repetitions: mean error and standard deviation")
    call = lambda s: np.maximum(s - K, 0)
    digital = lambda s: (s > K).astype(float)
    digital_delta = np.exp(-R * T) * np.exp(-0.5 * ((np.log(K / S0) - (R - 0.5 * SIGMA**2) * T) / (SIGMA * np.sqrt(T))) ** 2) / (np.sqrt(2 * np.pi) * SIGMA * np.sqrt(T) * S0)
    print(f"   {'Payoff':<10} {'bump h':>7} {'independent: mean error':>25} {'std dev':>9} {'common: mean error':>20} {'std dev':>9}")
    for name, payoff, exact in (("Call", call, delta), ("Digital", digital, digital_delta)):
        for h in (1.0, 0.1, 0.01):
            row = []
            for common in (False, True):
                rng = np.random.default_rng(7)
                runs = np.array([mc_delta(h, 100_000, payoff, rng, common) for _ in range(50)])
                row += [runs.mean() - exact, runs.std()]
            print(f"   {name:<10} {h:7.2f} {row[0]:25.5f} {row[1]:9.5f} {row[2]:20.5f} {row[3]:9.5f}")

The output is:

1. Delta of the benchmark call by three formulas, error against the closed form 0.5987063257
      step h      forward      central   complex step
       1e-01     9.66e-04    -7.25e-07       7.25e-07
       1e-02     9.67e-05    -7.25e-09       7.25e-09
       1e-04     9.67e-07     6.67e-12       7.24e-13
       1e-06     1.04e-08    -7.38e-09      -5.55e-16
       1e-08    -8.85e-07    -8.85e-07       0.00e+00
       1e-10    -3.02e-06    -3.02e-06      -8.88e-16
       1e-12    -8.96e-03    -5.40e-03       2.22e-16
       1e-14    -5.99e-01     1.12e-01       0.00e+00
   complex step with h = 1e-30: error -6.66e-16

2. Gamma by the central second difference, closed form 0.0193334058
      step h        error
       1e+00    -2.85e-06
       1e-01    -2.85e-08
       1e-02    -3.50e-10
       1e-03     1.44e-08
       1e-04     4.62e-07
       1e-05     6.44e-05
       1e-06     1.62e-02

3. Delta by bump and revalue with 100,000 paths, 50 repetitions: mean error and standard deviation
   Payoff      bump h   independent: mean error   std dev   common: mean error   std dev
   Call          1.00                  -0.00024   0.02975             -0.00016   0.00193
   Call          0.10                  -0.00123   0.29543             -0.00012   0.00191
   Call          0.01                  -0.01189   2.95212             -0.00012   0.00191
   Digital       1.00                  -0.00007   0.00123              0.00000   0.00030
   Digital       0.10                  -0.00057   0.01206              0.00007   0.00090
   Digital       0.01                  -0.00555   0.11958             -0.00001   0.00313

Reading the output:

  • Truncation and round-off are both visible. The forward error falls in proportion to \(h\), 9.7e-4 at \(h = 0.1\) and 9.7e-7 at \(10^{-4}\), until it reaches about 1e-8 at \(10^{-6}\). After that it grows, to 8.9e-7 at \(10^{-8}\) and to -0.60 at \(10^{-14}\), which is a delta of 0.0 and an error of 100%. The central formula falls as \(h^2\) to 6.7e-12 at \(10^{-4}\) and is then lost in round-off, 1.1e-1 at \(10^{-14}\).

  • The complex step has no round-off. Its error is 7.3e-7 at \(h = 0.1\), the same size as the central formula, and falls as \(h^2\). Below \(10^{-6}\) it is at machine precision, about 1e-15, down to \(h = 10^{-30}\).

  • The second difference is far more sensitive. The gamma error is best at \(h = 0.01\), 3.5e-10, and it grows after that, to 6.4e-5 at \(10^{-5}\) and 1.6e-2 at \(10^{-6}\), which is 84% of the gamma of 0.0193. A gamma computed with a step that was fine for delta can be noise.

  • Independent random numbers make a small bump useless. The standard deviation of the call delta is 0.030 at \(h = 1\), 0.295 at 0.1 and 2.95 at 0.01, which is 1/h, for a delta of 0.6. With common random numbers it is 0.0019 at all three, so the size of the bump does not matter, and the estimate for the smallest bump is over 1,000 times less noisy.

  • A digital is harder even with common random numbers. The standard deviation is 0.0003 at \(h = 1\), 0.0009 at 0.1 and 0.0031 at 0.01, and it rises as the bump falls. Only the paths within the bump of the strike matter, and there are fewer of them. For a digital, the bump has to be large enough to catch paths, and then it is a call spread, with a bias.

A valuation control view#

  • Compare the bump size with the precision of the pricer: for a closed form a bump of \(10^{-4}\) is fine. For a tree, a grid or a simulation, a bump below the precision of the price gives noise. Ask for the step and the evidence that the Greek is stable when it changes.

  • Check the Greeks in two ways: a bump with two different sizes, a central and a one-sided difference, and an analytic or complex-step reference where one exists. A Greek that depends on the bump is not a Greek.

  • Fix the random numbers in a bump-and-revalue: the same seeds and the same path construction in the base and the bumped runs. An unseeded bump of a simulation gives a risk number that changes from run to run.

  • Treat gamma and discontinuous payoffs with care: second differences amplify round-off and noise, and a digital or barrier has a delta that depends on how the jump is smoothed. See PDE Methods, Part 2: Implicit & Crank-Nicolson for the gamma that a grid gives at a kink.

  • State what is held fixed: a bump of a spot with the volatility surface held fixed in strike, or in moneyness, gives different deltas. A bump of a calibration input with and without recalibration gives different sensitivities. The definition belongs in the Greek.

Next, The Jacobian covers the derivatives of a map with several inputs and outputs, which is what Newton’s method for systems, a least-squares fit and the risk through a calibration use.