Quantitative Methods · Methods
4Stochastic Differential Equations
At 02:00 the overnight risk run stops. A square-root variance process, stepped forward one day at a time with the plain Euler scheme, produced a negative variance, the code took its square root, and a NaN propagated from one path into the book’s value and every limit that depends on it. It was not one unlucky path: with the desk’s calibrated parameters, three paths in four go negative within a year, and halving the time step four times over changes nothing. The model was not wrong, the scheme was, and the number that says so, the Feller ratio, is a one-line function of the parameters. This chapter sets out what a stochastic differential equation is and when it has a solution, the three diffusions the series uses most (geometric, mean-reverting and square-root), the generator that links them to partial differential equations, and the Feynman–Kac formula that turns an expectation into a PDE and back.
4.1 Existence, uniqueness and the Euler scheme
Definition 4.1 (Stochastic differential equation, strong and weak solutions)
A stochastic differential equation is
for measurable . A strong solution on a given probability space with a given Brownian motion is an adapted continuous process with . A weak solution is a pair on some filtered probability space satisfying the equation: the Brownian motion is part of the answer.
Theorem 4.2 (Existence and uniqueness)
If and , the equation has a unique strong solution, with .
Partial proof. Picard iteration : by the isometry and Doob’s inequality, , so the differences are bounded by and the iterates converge; Gronwall’s lemma gives uniqueness (Karatzas and Shreve, 1991, §5.2). ∎
The square-root coefficient is not Lipschitz at zero, which is why the square-root process needs its own theory below. Weak solutions matter because measure changes (chapter 5) produce them: the equation has a weak solution, a Brownian motion, but no strong one.
Definition 4.3 (Euler–Maruyama scheme)
The Euler–Maruyama scheme on the grid is , with independent standard normals.
It is the discrete Itô integral of Chapter 3: coefficients frozen at the left point. Under the Lipschitz conditions it converges as , pathwise at order and in law at order 1 (chapter 26 makes both orders precise). Its weakness is that it ignores the geometry of the state space: a Gaussian increment can carry a positive process below zero.
4.2 The workhorse diffusions
Definition 4.4 (Geometric Brownian motion)
A geometric Brownian motion solves ; by Example 3.8, , lognormal.
Definition 4.5 (Mean reversion, Ornstein–Uhlenbeck process, half-life)
A process shows mean reversion when its drift pulls it toward a level. The Ornstein–Uhlenbeck process is the Gaussian case , . The half-life of a mean-reverting process is the time after which the expected deviation from the level has halved.
Proposition 4.6 (The Ornstein–Uhlenbeck transition)
; given , is normal with mean and variance , tending to .
Proof. Itô’s formula on gives ; integrate, and use the isometry for the variance of the Wiener integral. ∎
The exact transition makes the Ornstein–Uhlenbeck process free to simulate at any step with no error (Figure 4.1), and its discrete sampling is an autoregression with coefficient (chapter 17). Spreads, funding bases and, in One Quant Book 6, short rates are modelled this way.
Definition 4.7 (Square-root process, Feller condition)
The square-root process is with and . The Feller condition is ; the ratio is the Feller ratio.
Theorem 4.8 (Feller)
The square-root process has a unique strong nonnegative solution. It never reaches zero if the Feller condition holds, and reaches zero with positive probability (and is instantly reflected) if it fails. Given , with noncentral chi-square with degrees of freedom and noncentrality , where ; its stationary law is .
Proof. Admitted here. ∎
Uniqueness uses the Yamada–Watanabe argument for Hölder- coefficients; the boundary classification is Feller’s (1951), the transition law is in Cox, Ingersoll and Ross (1985). The square-root process is the variance of the Heston model and the short rate of the CIR model (One Quant Books 5 and 6); stochastic-volatility fits to equity smiles typically want a high vol-of-vol and so violate the condition. The desk’s process has , and : a Feller ratio of 0.44, a stationary law with mean 0.04 and standard deviation 0.06, and 27.9% of its stationary mass below one tenth of the mean.
The plain Euler step from a small is Gaussian with mean and standard deviation : from one daily step goes negative with probability 3.6%, and a path spends many days near zero. Figure 4.2 counts the paths that produce a negative variance within a year: 75% at the desk’s parameters, and, what surprises most, the same 75% with four or sixteen steps a day. Refining cannot help, because the exact process itself comes arbitrarily close to zero on those paths; only a scheme that respects the boundary can. Even at a Feller ratio of exactly one, a quarter of the daily Euler paths go negative: the condition protects the process, not the scheme.
Two fixes are standard. The exact scheme samples the noncentral chi-square transition of Theorem 4.8 and is positive by construction. Full truncation (Lord, Koekkoek and van Dijk, 2010) keeps the Euler step but uses in both coefficients, reporting : it never takes the square root of a negative number, and its bias vanishes as . One Quant Book 5, chapter 23, adds the quadratic-exponential scheme used for Heston in production.
4.3 Generators and the Kolmogorov equations
Definition 4.9 (Infinitesimal generator)
The infinitesimal generator of a time-homogeneous diffusion is the operator on functions.
Proposition 4.10 (Dynkin’s formula)
For with compact support and a stopping time with , .
Proof. By Itô’s formula, , a martingale with bounded integrand; apply optional stopping at and let . ∎
Definition 4.11 (Kolmogorov equations, stationary distribution)
For , the Kolmogorov backward equation is with . The transition density of solves the Kolmogorov forward equation, also called the Fokker–Planck equation, . A stationary distribution of a Markov process is a law that, taken as the law of , is the law of every ; for a diffusion its density solves .
The backward equation looks at a payoff from where one stands; the forward equation pushes a density forward in time. For the Ornstein–Uhlenbeck process, integrates once to , whose solution is the density; for the square-root process, gives , the Gamma law of Theorem 4.8. When the Feller ratio is below one the exponent is negative and the density is infinite at zero (Figure 4.3).
4.4 Feynman–Kac
Theorem 4.12 (Feynman–Kac)
Let solve the equation of Definition 4.1, and continuous and of polynomial growth, and let of polynomial growth solve
Then .
Proof. With , Itô’s product rule gives . The growth conditions make the stochastic integral a martingale, so . ∎
The theorem runs both ways: an expectation can be computed by solving a PDE (chapter 27), and a PDE by simulating paths (chapter 26). Figure 4.4 collects the links. With itself an Ornstein–Uhlenbeck short rate and , is the price of a zero-coupon bond, and the PDE has the affine solution with and , found by substituting and matching the terms in . With , , and , the five-year price is 0.8343, and 20 000 simulated paths give . One Quant Book 6, chapter 7, turns this calculation into a model of the curve.
4.5 Tutorial: the overnight NaN
Goal. Reproduce the overnight failure, measure it against the Feller ratio, fix it two ways, and check the stationary law and a Feynman–Kac price. End state: Figures 4.1, 4.2 and 4.3 and the numbers of the weekend problem.
The schemes. The running project samples the square-root process exactly and by Euler, plain or with full truncation.
def sqrt_exact(v0: float, kappa: float, vbar: float, eta: float, T: float, n_steps: int, n_paths: int, seed: int) -> np.ndarray: """dv = kappa (vbar - v) dt + eta sqrt(v) dW sampled exactly: v_{k+1} = c chi'^2_d(lambda) with c = eta^2 (1 - e^{-kappa dt}) / (4 kappa), d = 4 kappa vbar / eta^2, lambda = v_k e^{-kappa dt} / c.""" rng = np.random.default_rng(seed) dt = T / n_steps c = eta**2 * (1 - math.exp(-kappa * dt)) / (4 * kappa) d = 4 * kappa * vbar / eta**2 v = np.empty((n_paths, n_steps + 1)) v[:, 0] = v0 for k in range(n_steps): lam = v[:, k] * math.exp(-kappa * dt) / c v[:, k + 1] = c * rng.noncentral_chisquare(d, np.maximum(lam, 1e-300)) return v def sqrt_euler(v0: float, kappa: float, vbar: float, eta: float, T: float, n_steps: int, n_paths: int, seed: int, scheme: str = "plain") -> np.ndarray: """Euler steps of the square-root process. 'plain' takes sqrt(v) and yields NaN after a negative value; 'full_truncation' (Lord, Koekkoek and van Dijk) uses v^+ in drift and diffusion and reports v^+.""" rng = np.random.default_rng(seed) dt = T / n_steps v = np.empty((n_paths, n_steps + 1)) v[:, 0] = v0 for k in range(n_steps): z = rng.standard_normal(n_paths) vk = v[:, k] if scheme == "plain" else np.maximum(v[:, k], 0.0) with np.errstate(invalid="ignore"): v[:, k + 1] = v[:, k] + kappa * (vbar - vk) * dt + eta * np.sqrt(vk) * math.sqrt(dt) * z return v if scheme == "plain" else np.maximum(v, 0.0)Listing 4.1. Exact and Euler steps of the square-root process. code/firm/mcengine/firm_mcengine.py The count: the share of plain-Euler paths that produce a negative variance, and a Feynman–Kac check by simulation.
def bond_price_mc(r0=0.03, kappa=0.5, rbar=0.04, sigma=0.01, T=5.0, n_steps=500, n_paths=20_000, seed=6): """E[exp(-int_0^T r dt)] under an Ornstein-Uhlenbeck short rate, by simulation (trapezoid rule).""" r = ou_exact(r0, kappa, rbar, sigma, T, n_steps, n_paths, seed) integral = (r[:, :-1] + r[:, 1:]).sum(axis=1) * 0.5 * T / n_steps d = np.exp(-integral) return float(d.mean()), float(d.std() / math.sqrt(n_paths)) def bond_price_pde(r0=0.03, kappa=0.5, rbar=0.04, sigma=0.01, T=5.0) -> float: """Feynman-Kac: u = exp(A(tau) - B(tau) r) solves u_t + kappa (rbar - r) u_r + sigma^2/2 u_rr - r u = 0, with B = (1 - e^{-kappa tau}) / kappa and A = (rbar - sigma^2 / (2 kappa^2)) (B - tau) - sigma^2 B^2 / (4 kappa).""" B = (1 - math.exp(-kappa * T)) / kappa A = (rbar - sigma**2 / (2 * kappa**2)) * (B - T) - sigma**2 * B**2 / (4 * kappa) return math.exp(A - B * r0)Listing 4.2. A zero-coupon price under an Ornstein–Uhlenbeck short rate, by simulation and by the PDE. code/methods/04-stochastic-differential-equations/python/qm_sde.py - Run
problem(),feller_table(),stationary_histograms()andfig_sde.py; the C++20 and Rust twins of the Euler and Ornstein–Uhlenbeck steps are incode/firm/mcengine/.
What to change next. Add the reflection scheme () and compare its one-year mean with the exact scheme’s; give the variance process a time-dependent level and check the generator’s prediction for .
4.6 Build: the Monte Carlo engine, stage two
Purpose. Step the diffusions every later chapter simulates, with the scheme each one needs, and never return a NaN.
Interface. euler_maruyama(mu, sigma, x0, T, n_steps, n_paths, seed); ou_exact(x0, kappa, xbar, sigma, T, n_steps, n_paths, seed); sqrt_exact(v0, kappa, vbar, eta, …); sqrt_euler(…, scheme) with plain or full_truncation; feller_ratio(kappa, vbar, eta). C++20 and Rust: ou_exact_path and sqrt_euler_path over the stage-one NormalStream.
Rules. Parameters in the series notation (, , , ); exact transitions where they exist; a scheme that can leave the state space is named as such and never the default.
Acceptance tests. Stationary mean and variance of both processes; Euler converges to the exact Ornstein–Uhlenbeck mean; the exact square-root scheme is nonnegative with the right moments; plain Euler fails at the desk’s parameters and full truncation never does, in all three languages.
Stretch. The quadratic-exponential scheme; a Milstein step (chapter 26).
Sources and further reading
- W. Feller, “Two singular diffusion problems”, Annals of Mathematics 54, 1951.
- J. C. Cox, J. E. Ingersoll and S. A. Ross, “A theory of the term structure of interest rates”, Econometrica 53, 1985.
- G. E. Uhlenbeck and L. S. Ornstein, “On the theory of the Brownian motion”, Physical Review 36, 1930.
- M. Kac, “On distributions of certain Wiener functionals”, Transactions of the AMS 65, 1949.
- R. Lord, R. Koekkoek and D. van Dijk, “A comparison of biased simulation schemes for stochastic volatility models”, Quantitative Finance 10, 2010.
4.7 Exercises
Exercise 4.1 ★
A spread follows an Ornstein–Uhlenbeck process with per year. What is its half-life in years and in trading days?
Solution
Solution of Exercise 4.1.
years, 87 trading days.
Exercise 4.2 ★
A stock follows a geometric Brownian motion with and . What is the probability that it is below its starting price after one year?
Solution
Solution of Exercise 4.2.
: the median grows at .
Exercise 4.3 ★
Write the generator of the Ornstein–Uhlenbeck process, apply it to , and deduce the ODE satisfied by .
Solution
Solution of Exercise 4.3.
; for , , so and .
Exercise 4.4 ★★
From the forward equation, find the stationary variance of the Ornstein–Uhlenbeck process with , .
Solution
Solution of Exercise 4.4.
gives a Gaussian density with variance .
Exercise 4.5 ★★
With Dynkin’s formula, compute for the square-root process with , , .
Solution
Solution of Exercise 4.5.
Dynkin with gives , so .
Exercise 4.6 ★★
Check the five-year zero-coupon price of the chapter (0.8343) from the formula for and .
Solution
Solution of Exercise 4.6.
; ; .
Exercise 4.7 ★★★
Coding. With negative_fraction, find the share of daily plain-Euler paths that go negative within a year when the Feller ratio is exactly one (), and the largest in the table for which it is below 1%.
Solution
Solution of Exercise 4.7.
24.5% at a Feller ratio of one: the condition keeps the exact process away from zero, not the Gaussian Euler step. In the table, (ratio 2.56) gives 0.08%, and (ratio 1.78) already 1.6%.
Exercise 4.8 ★★★
Find the flaw. “We floor the variance at zero after every Euler step, so the scheme is now exact.”
Solution
Solution of Exercise 4.8.
Flooring removes the NaN but not the error: every step that would have crossed zero is replaced by zero, which then has zero diffusion, so the scheme adds mass at zero and biases the law near the boundary. It is still a first-order Euler scheme, not the exact transition; check its moments against and the Gamma stationary law, or use the exact or full-truncation scheme.
4.8 Problem: The NaN in the Overnight Run
Problem 4.1
Weekend problem — a variance process that violates the Feller condition
The desk’s variance process is with , and , simulated for one year of 252 days.
Part I — The process.
- What is the Feller ratio? Is zero attainable?
- What are the stationary law, its mean and standard deviation?
- What share of the stationary mass lies below 0.004?
- What vol-of-vol would make the Feller ratio exactly one?
- What is the half-life of the expected variance’s return to ?
Part II — Plain Euler.
- From , what is the probability that one daily Euler step goes negative?
- What share of paths produce a negative variance within the year?
- With four and sixteen steps a day, and with weekly steps?
- Why does refining the step not help?
- What does one NaN do to a risk run that sums over paths?
Part III — Fixes.
- What minimum and one-year mean does the exact scheme give?
- What one-year mean does full truncation give, and on what share of steps is it at zero?
- Which of the two is biased, and how does the bias behave as ?
- What would reflection () do to the mean near zero?
- Why do production Heston engines use another scheme?
Part IV — Judgement.
- Should the desk impose the Feller condition in its calibration?
- What should an automated test of the simulation engine assert?
- What belongs in the model-review note about this incident?
- State the named result: the Feller ratio and the share of failing paths.
- In one sentence: what does the Feller condition protect, and what does it not?
Solution
Solution of Problem 4.1.
1. : below one, zero is attainable. 2. : mean 0.04, standard deviation . 3. 27.9%. 4. . 5. years. 6. . 7. 75.2% of 40 000 paths. 8. 75.3% with four steps a day, 74.6% with sixteen, 75.2% with weekly steps. 9. The exact process comes arbitrarily close to zero on those paths; from a small a Gaussian step of any length has a fixed chance of crossing, and more steps near zero means more chances. 10. It propagates through every sum and average into the book’s value, and a comparison with a NaN is false, so limit checks can pass silently. 11. Minimum 0 (never negative); one-year mean 0.0394 against . 12. Mean 0.0393; at zero on 5.2% of the steps. 13. The exact scheme has no discretisation bias; full truncation does, and its bias vanishes as . 14. Reflection turns every overshoot into a positive value of the same size, pushing mass up and biasing the mean upward near zero. 15. The exact sampler is slow and the Euler variants need small steps; the quadratic-exponential scheme (One Quant Book 5, chapter 23) is accurate at daily or larger steps. 16. No: the market’s smile asks for a high vol-of-vol, and imposing the condition would distort the fit to save a numerical scheme; fix the scheme. 17. No NaN and no negative variance on any seed; and against their closed forms; the stationary law against the Gamma density; convergence as the step is refined. 18. The root cause (plain Euler with a Feller ratio of 0.44), the size of the failure (75% of paths), the fix (exact or full truncation) and its validation, and the tests added. 19. Named result: the NaN in the overnight run: with a Feller ratio of 0.44, 75% of daily plain-Euler paths produce a negative variance within a year, whatever the step; the exact and full-truncation schemes produce none. 20. It keeps the exact process away from zero; it does not keep a Gaussian step from crossing it.
4.9 Interview questions
Interview question 4.1 ★ trader, researcher
Solve . What is the median of ?
Solution
Solution of Interview question 4.1.
; the median is , below the mean .
What the interviewer is looking for: Itô on and the lognormal law.
Interview question 4.2 ★ researcher
A spread mean-reverts with a half-life of 10 days. What is , and how much of today’s deviation is expected to remain after 30 days?
Solution
Solution of Interview question 4.2.
a day; after 30 days, three half-lives, remains.
What the interviewer is looking for: and half-lives.
Interview question 4.3 ★★ researcher, bank
What is the Feller condition, and what happens to a square-root process and to its simulation when it fails?
Solution
Solution of Interview question 4.3.
: then the drift near zero beats the diffusion and zero is never reached; otherwise the process touches zero and reflects. The law stays nonnegative either way, but an Euler step from near zero can go negative, and more so when the condition fails.
What the interviewer is looking for: the boundary classification and its numerical consequence.
Interview question 4.4 ★★ researcher, bank
State the Feynman–Kac formula and use it to write the PDE for under a geometric Brownian motion.
Solution
Solution of Interview question 4.4.
solves , . For and constant : .
What the interviewer is looking for: generator plus discounting, terminal condition.
Interview question 4.5 ★★ developer
The overnight Monte Carlo sometimes returns NaN. How do you find the cause and make it impossible?
Solution
Solution of Interview question 4.5.
Make the failure reproducible (log the seed and the path index), find the first non-finite value and the step that produced it, and read the scheme at that state. Then make it impossible: exact or boundary-respecting schemes, assertions on the state space inside the kernel, a test that runs many seeds and fails on any NaN, and aggregation that refuses non-finite inputs instead of propagating them.
What the interviewer is looking for: reproducibility, root cause, and invariants enforced in code.
Interview question 4.6 ★★★ researcher
What is the difference between a strong and a weak solution? Give an equation with one but not the other.
Solution
Solution of Interview question 4.6.
A strong solution is built on a given Brownian motion; a weak one only asks for some probability space carrying a process and a Brownian motion that satisfy the equation. Tanaka’s equation , , has weak solutions (any Brownian motion with ) but no strong one, because cannot be recovered from .
What the interviewer is looking for: the definitions and Tanaka’s example.