Advanced Methods, Part 2: Dimension, Adjoints & Machine Learning#
Trees, grids and quadrature are exact and fast in one or two dimensions, and they stop working as the number of risk factors grows. Risk is a second problem of scale: a book has hundreds of inputs, and a bumped Greek for each one multiplies the cost. This page sets out the curse of dimensionality, the adjoint method that gives all the sensitivities for a small multiple of the cost of one price, and where machine-learning methods fit. It is the second of two pages on more advanced methods.
The curse of dimensionality#
A method that puts \(n\) points on each axis of a \(d\)-dimensional space needs \(n^d\) points. With 10 points per axis that is 100 for two dimensions, a million for six, and ten billion for ten. A tree, a finite difference grid and a tensor quadrature rule all grow this way. This is why a basket option on five stocks is already hard for a grid, and one on fifty is out of reach.
Monte Carlo is different. Its error is \(s/\sqrt{N}\) whatever the dimension, so adding an asset adds the cost of one more random number per path and nothing else. This is the decisive reason for its use for products that depend on many underlyings, and it explains why a method that is slow in one dimension is preferred in thirty. The caveat is that the number that matters is the effective dimension: a payoff that depends on a single combination of the assets is a one-dimensional problem however many assets there are, and a grid can exploit this when it knows the combination.
Adjoint differentiation#
A valuation function maps many inputs (curves, volatilities, spot prices, parameters) to one number, the price. Its Greeks are the derivatives of that number with respect to every input. There are two ways to get them by computer:
Bump and revalue changes one input at a time and reprices. For \(m\) inputs it costs \(m + 1\) prices.
Adjoint (reverse-mode algorithmic) differentiation runs the price once, forward, recording the intermediate values, and then runs backwards through the same calculation, applying the chain rule at each step. One backward sweep gives the derivatives with respect to all the inputs. In terms of the Jacobian of The Jacobian, a backward sweep gives one row, and a price has one row. Its cost is a small constant multiple of one price, usually between 2 and 5, whatever the number of inputs.
For a simulated path \(S_{i+1} = S_i \, e^{(r - \sigma_i^2/2) \Delta t + \sigma_i \sqrt{\Delta t} \, Z_i}\) and a payoff on the average of the path, the backward sweep passes an adjoint \(\bar{S}_i\), the sensitivity of the payoff to \(S_i\), from the end of the path to the start. At each step it adds a term to the adjoint of the volatility \(\bar\sigma_i\) and of the rate \(\bar r\). The adjoint at the start is the delta. If the volatility is a separate input for each month, the sweep gives the vega of each month at no extra cost.
The method gives pathwise derivatives, so it has the limits of Monte Carlo, Part 4: Greeks: it needs a payoff that is smooth along the path, or a smoothing of the payoff. In production it is done by an automatic differentiation tool and not by hand, which is the main engineering effort. The result is risk on a large book in minutes where bumping takes hours.
Machine learning#
Several methods that use neural networks have been proposed for pricing and risk.
Surrogate pricing. A network is trained on the outputs of a slow model, a Monte Carlo or a PDE, over a range of inputs, and then it prices in microseconds. It is used where the same model is called very many times, such as in a calibration or a risk scenario.
Neural network solvers of PDEs and deep BSDE methods. They solve the pricing equation directly in high dimension, without a grid. They are research tools, and not yet a replacement for the methods of this series.
Learned exercise policies. A network in place of the polynomial regression of Advanced Methods, Part 1: Least-Squares Monte Carlo.
They depend on the conventional methods: the training data come from one, and the test of the network is a comparison with one. They also add risks of their own. A network is accurate inside the range that it was trained on and can be badly wrong outside it, and its error is not controlled by a convergence theorem. For a controller they are a model like any other, with a validation that has to show the error over the whole range of use, and a monitor that tells when the inputs leave it.
Worked example#
The example prices a call on the geometric average of 1 to 6 correlated assets, where the closed form is known, by a tensor Gauss-Hermite rule with 10 points per axis and by 100,000 Monte Carlo paths. It then computes the delta, the rho and the vega to each of 12 monthly volatilities of an Asian call with 252 daily fixings, once by one adjoint sweep and once by bumping, and compares the cost.
Python code
"""Dimension and differentiation: tensor quadrature against Monte Carlo as assets are added, and an adjoint sweep for bucketed vega."""
import time
import numpy as np
from numpy.polynomial.hermite_e import hermegauss
from scipy.stats import norm
from common import K, R, S0, SIGMA, T
RHO = 0.3
DISC = np.exp(-R * T)
def geometric_basket_exact(d):
"""Closed form for a call on the geometric average of d equally volatile assets with common correlation."""
m = np.log(S0) + (R - 0.5 * SIGMA**2) * T
v = SIGMA**2 * T * (1 + (d - 1) * RHO) / d
d1 = (m + v - np.log(K)) / np.sqrt(v)
return DISC * (np.exp(m + 0.5 * v) * norm.cdf(d1) - K * norm.cdf(d1 - np.sqrt(v)))
def basket_payoff(z, d):
"""Discounted payoff from independent normals z (one row per point), after correlating them."""
corr = np.full((d, d), RHO) + (1 - RHO) * np.eye(d)
log_s = np.log(S0) + (R - 0.5 * SIGMA**2) * T + SIGMA * np.sqrt(T) * (z @ np.linalg.cholesky(corr).T)
return DISC * np.maximum(np.exp(log_s.mean(axis=1)) - K, 0)
def tensor_gauss_hermite(d, n):
"""Gauss-Hermite on every axis: n**d points, taken in blocks of n**4 to keep the memory small."""
nodes, weights = hermegauss(n)
weights = weights / np.sqrt(2 * np.pi)
inner = min(d, 4)
grids = np.meshgrid(*([nodes] * inner), indexing="ij")
block = np.stack([g.ravel() for g in grids], axis=1)
block_w = np.ones(1)
for _ in range(inner):
block_w = np.outer(block_w, weights).ravel()
total = 0.0
for head in np.ndindex(*([n] * (d - inner))):
head_w = np.prod(weights[list(head)])
z = np.hstack([np.tile(nodes[list(head)], (len(block), 1)), block])
total += head_w * np.sum(block_w * basket_payoff(z, d))
return total
STEPS, BUCKETS = 252, 12
def asian_forward(z, sigma_buckets, s0=S0, r=R):
"""Discounted Asian call payoff per path, with one volatility for each month. Returns the payoff, the average and the states."""
dt = T / STEPS
sig = np.repeat(sigma_buckets, STEPS // BUCKETS)
s = np.empty((z.shape[0], STEPS + 1))
s[:, 0] = s0
for i in range(STEPS):
s[:, i + 1] = s[:, i] * np.exp((r - 0.5 * sig[i] ** 2) * dt + sig[i] * np.sqrt(dt) * z[:, i])
avg = s[:, 1:].mean(axis=1)
return np.exp(-r * T) * np.maximum(avg - K, 0), avg, s
def asian_adjoint(z, sigma_buckets):
"""One backward sweep: the price and its derivatives with respect to S0, r and every monthly volatility."""
dt = T / STEPS
sig = np.repeat(sigma_buckets, STEPS // BUCKETS)
payoff, avg, s = asian_forward(z, sigma_buckets)
n = z.shape[0]
p_bar = np.exp(-R * T) * (avg > K)
s_bar = np.zeros(n)
sigma_bar = np.zeros(STEPS)
r_bar = -T * payoff.sum()
for i in range(STEPS - 1, -1, -1):
s_bar = s_bar + p_bar / STEPS # S_{i+1} enters the average
grown = s[:, i + 1]
sigma_bar[i] = np.sum(s_bar * grown * (-sig[i] * dt + np.sqrt(dt) * z[:, i]))
r_bar += np.sum(s_bar * grown * dt)
s_bar = s_bar * grown / s[:, i] # S_i feeds S_{i+1}
vega = sigma_bar.reshape(BUCKETS, STEPS // BUCKETS).sum(axis=1) / n
return payoff.mean(), s_bar.mean(), r_bar / n, vega
if __name__ == "__main__":
print("Geometric basket call on d correlated assets: tensor Gauss-Hermite with 10 nodes per axis against 100,000 Monte Carlo paths\n")
rng = np.random.default_rng(31)
print(f"{'Assets':>7} {'Quadrature points':>18} {'Quadrature error':>17} {'Monte Carlo error':>18} {'MC std error':>13}")
for d in (1, 2, 3, 4, 5, 6):
exact = geometric_basket_exact(d)
quad = tensor_gauss_hermite(d, 10)
pv = basket_payoff(rng.standard_normal((100_000, d)), d)
print(f"{d:>7} {10**d:>18,} {quad - exact:+17.2e} {pv.mean() - exact:+18.2e} {pv.std(ddof=1) / np.sqrt(len(pv)):13.2e}")
print(f"\nWith 10 nodes per axis, 10 assets would need {10**10:,} points and 50 assets {float(10**50):.0e}.")
# Bucketed vega of an Asian call: bump each of 12 monthly volatilities, or run one adjoint sweep.
n = 100_000
z = np.random.default_rng(5).standard_normal((n, STEPS))
base_sigma = np.full(BUCKETS, SIGMA)
asian_forward(z, base_sigma) # warm-up, so the timings below are comparable
start = time.perf_counter()
base = asian_forward(z, base_sigma)[0].mean()
t_base = time.perf_counter() - start
start = time.perf_counter()
price, delta, rho, vega_adj = asian_adjoint(z, base_sigma)
t_adj = time.perf_counter() - start
start = time.perf_counter()
vega_bump = np.array([(asian_forward(z, base_sigma + 1e-4 * (np.arange(BUCKETS) == k))[0].mean() - base) / 1e-4 for k in range(BUCKETS)])
delta_bump = (asian_forward(z, base_sigma, s0=S0 + 0.01)[0].mean() - base) / 0.01
rho_bump = (asian_forward(z, base_sigma, r=R + 1e-4)[0].mean() - base) / 1e-4
t_bump = time.perf_counter() - start
print(f"\nAsian call, {STEPS} daily fixings, {n:,} paths, price {price:.4f}")
print(f"{'Monthly bucket':>15} {'Vega, adjoint':>14} {'Vega, bump':>11}")
for k in range(BUCKETS):
print(f"{k + 1:>15} {vega_adj[k]:14.4f} {vega_bump[k]:11.4f}")
print(f"{'Total':>15} {vega_adj.sum():14.4f} {vega_bump.sum():11.4f}")
print(f"Delta: adjoint {delta:.5f}, bump {delta_bump:.5f}. Rho: adjoint {rho:.4f}, bump {rho_bump:.4f}")
print(f"Time: one price {t_base * 1e3:.0f}ms, adjoint sweep (price and 14 sensitivities) {t_adj * 1e3:.0f}ms, "
f"bumping (14 revaluations) {t_bump * 1e3:.0f}ms")
The output is:
Geometric basket call on d correlated assets: tensor Gauss-Hermite with 10 nodes per axis against 100,000 Monte Carlo paths
Assets Quadrature points Quadrature error Monte Carlo error MC std error
1 10 +3.24e-01 -3.61e-02 4.45e-02
2 100 -4.82e-02 +3.47e-03 3.49e-02
3 1,000 +3.07e-03 -3.31e-02 3.12e-02
4 10,000 -1.41e-04 -5.45e-04 2.94e-02
5 100,000 -4.02e-04 -3.07e-02 2.80e-02
6 1,000,000 -1.45e-05 -4.04e-02 2.72e-02
With 10 nodes per axis, 10 assets would need 10,000,000,000 points and 50 assets 1e+50.
Asian call, 252 daily fixings, 100,000 paths, price 5.2726
Monthly bucket Vega, adjoint Vega, bump
1 5.0813 5.0817
2 4.3327 4.3334
3 3.3312 3.3312
4 2.8223 2.8227
5 2.1918 2.1922
6 1.7049 1.7053
7 1.1838 1.1841
8 0.7244 0.7245
9 0.5077 0.5079
10 0.2497 0.2497
11 0.1014 0.1014
12 0.0170 0.0170
Total 22.2482 22.2509
Delta: adjoint 0.56092, bump 0.56106. Rho: adjoint 23.5790, bump 23.5802
Time: one price 978ms, adjoint sweep (price and 14 sensitivities) 3275ms, bumping (14 revaluations) 27981ms
Reading the output:
The number of quadrature points explodes. From 10 points for one asset to a million for six, and ten billion for ten. The Monte Carlo cost stays at 100,000 paths in every row.
The quadrature error is small here for a particular reason. The payoff depends on the assets only through their geometric average, which is a single normal variable, and the larger the number of assets, the smaller its variance. The grid is wasting nearly all its points on directions that do not matter, and it is still accurate. A payoff that depends on the assets in a different way for each, such as a worst-of option, would need all the points.
The Monte Carlo error is at its usual level in every dimension, with a standard error of 0.027 to 0.045 in all six rows. It does not depend on the number of assets.
The adjoint and the bump agree. The vega of each month matches to about 0.001, and the totals are 22.248 and 22.251. The vega falls from 5.1 in the first month to 0.017 in the last, since a rise in the volatility of the last month affects only the last few fixings.
The adjoint is much cheaper. One backward sweep took 3,275 ms, 3.3 times the time of a price at 978 ms, and gave the price and 14 sensitivities. Bumping 14 sensitivities took 27,981 ms, 8.5 times the adjoint. The gap grows with every extra input. Timings are indicative.
A valuation control view#
Know the effective dimension of the product: a method that is fine for a product with two factors may be unusable for one with five, and a grid that looks accurate on a payoff with low effective dimension says nothing about one that has high dimension.
Reconcile adjoint risk with bumped risk on a sample: and keep doing it. An adjoint that has a bug in one branch of the code can give numbers that look sensible. The bump is slow, and it is the independent check, as in the example.
Check what is differentiated: an adjoint of a Monte Carlo price with a discontinuous payoff gives the pathwise answer, which is wrong for a digital or a barrier. The smoothing used and its width are model choices.
Treat a machine-learning model as a model: validate it over the whole range of inputs it will see, not only on a test sample, and monitor the inputs for drift outside the range. Keep the conventional method as a benchmark that can be run on a sample every day.
Do not let the speed hide the error: a surrogate that is a thousand times faster is useful only if its error is known and well below the tolerance, in the regions that drive the risk.
Next, One Option, Five Numerical Methods brings the methods of the series together.