Path simulation: numerical methods for SDEs
Derive Euler-Maruyama and Milstein, distinguish strong and weak convergence, use exact transitions when available, refine paths with bridges, diagnose instability and simulate jump diffusions.
After this lesson you can
- Derive Euler-Maruyama and Milstein from the Itô-Taylor expansion.
- Measure strong and weak orders with the same Brownian noise refined over successive grids.
- Choose exact simulation or discretization according to the model and quantity to estimate.
- Diagnose and address stiffness, superlinear coefficients and CIR positivity.
- Simulate Merton jump diffusion and compare the return law with a Gaussian.
- Explain multilevel Monte Carlo and when it reduces cost for a given accuracy.
Before you start
- 26Stochastic differential equationLinear SDEsOrnstein-Uhlenbeck processCIR process and Feller conditionBrownian bridgeCompound Poisson processItô's lemmaGeometric Brownian motion
- 09Explicit and implicit Euler methodsRunge-Kutta methodsEmpirical order-of-convergence verificationStiffness and implicit methodsRegion of absolute stabilityMonte Carlo estimatorMonte Carlo error and confidence intervals
- 00Pseudorandom generators and independent streams
One path is not a distribution
You want to estimate portfolio risk, generate interest-rate scenarios or integrate an equation that produces samples in a diffusion model. Even with a well-defined SDE, its explicit solution is usually unknown. A time grid turns the integral equation into finite operations, but introduces error.
Before measuring it, decide what is compared. Two paths driven by independent noise differ even when both are exact. To measure approximation of the same scenario, generate fine increments and sum those belonging to each coarse interval. Each curve then uses the same Brownian motion.
From Itô-Taylor to two integrators
Consider the autonomous scalar equation . On interval , freezing coefficients inside the integral gives the Euler-Maruyama scheme
The normals are independent across intervals and paths. In particular, their standard deviation is , not .
To improve the stochastic term, expand to first order in the dominant variation: . The iterated integral is calculated by Itô:
Substituting it yields scalar Milstein:
Term is the quadratic-variation correction. In multiple dimensions iterated integrals and Lévy areas can arise: this scalar formula does not replace them without further assumptions. Higham develops both methods, convergence and stability.
Two questions, two errors
Strong convergence compares an approximation and solution coupled to the same noise, for example . Order means for small , with constant independent of . Weak convergence compares expectations, , for a declared class of functions . Checking one function is insufficient to prove general weak order.
With suitable regularity and moments, Euler typically has strong order and weak order ; scalar Milstein has strong order . These are theorems under assumptions, not promises for arbitrary coefficients or functionals. Additive diffusion can improve Euler’s strong order. For a smooth European payoff its expectation matters; for paired paths, dynamic hedging or pathwise learning, strong fidelity matters. A continuous barrier additionally requires resolving crossings between nodes.
For , , and , the exact expectation is and Euler’s is . Weak bias for is known without Monte Carlo. A bias estimate uses paired differences ; its standard error measures sampling uncertainty, not discretization. If bias is smaller than this noise, fitting a line to logarithms of absolute values does not identify the order. With this particular bias is zero on every grid.
To check strong order without Monte Carlo noise, for this GBM define . One-step moments give , and . Their combination has leading term proportional to if : the square root has order . Here we keep ; later you will generalize the argument to an arbitrary horizon.
For example, with , expanding logarithms of the two factors gives
Multiply by , exponentiate and combine : constant terms cancel, leaving . The constant is strictly positive for . This calculation proves the order for the example, not every SDE.
When to simulate exactly
On a grid, exact simulation avoids transition error: use the Gaussian OU transition, exponential GBM solution and noncentral chi-square CIR transition. OU and CIR formulas are in the previous lesson. Exactness at nodes does not imply observing the entire continuous path.
Stability, positivity and superlinear drift
For deterministic equation , Euler’s factor is and damps only if . An implicit scheme has factor and removes that restriction for . With noise, stability also depends on diffusion and the chosen notion of stability.
Numerical stability can fail even for a well-behaved SDE. In , explicit Euler applies ; for large it can throw the next value much farther away. A tamed alternative replaces with ; the implicit one solves , a strictly increasing equation with a unique real root. Neither is exact and both have discretization error.
Events dominating an expectation can be so rare that a finite sample contains none. Hutzenthaler, Jentzen and Kloeden prove strong and weak divergence of Euler for a class of superlinear coefficients. We do not infer that general result from one simulation. In CIR, ceases to make sense if Euler produces a negative state; truncating or projecting changes the method and its law. An exact transition at nodes avoids that problem when available.
Bridges and barriers
Bridge interpolation preserves already sampled endpoints. For standard Brownian motion between , the conditional probability of crossing an upper barrier during interval is
If an endpoint already reaches the barrier, . Given the nodes, bridges of different intervals are independent: averaging gives an unbiased estimator of continuous probability, with Monte Carlo uncertainty. The fine grid can also miss crossings. For log-GBM with constant coefficients apply the formula to the logarithm, with in the denominator. Neither an arbitrary diffusion nor a jump automatically admits that correction.
Jumps and multilevel Monte Carlo
In Merton’s jump diffusion, take independent and Poisson with intensity . If , the solution is
Compensation makes . Price jumps are multiplicative: a log jump multiplies price by . Log-return variance is and its excess kurtosis is
Excess does not always increase with : with and it reaches a maximum at and then decreases. If jumps are almost surely zero there is no excess kurtosis. Compare the histogram and quantile plot with a normal of equal mean and variance; matching moments does not guarantee equal tails.
In the figure jumps have zero mean and continuous log drift is ; in the previous parameterization this amounts to choosing . Thus changes in intensity also change expected price growth. Tail comparison uses theoretical return mean and variance for that configuration.
For a costly expectation, multilevel Monte Carlo writes . Each difference couples fine and coarse grids with the same noise; if its variance decreases, fewer samples are needed at expensive levels. Final-grid bias remains. Cost depends on bias, variance and per-level cost rates: it is not always . Giles develops these conditions.
Among libraries, sdeint integrates Itô and Stratonovich SDEs; Diffrax provides JAX integrators; torchsde works with PyTorch and GPU. Its repository is archived. Check stochastic convention, noise type and version compatibility before comparing results.
Lab: integrators and coupling
Methods receive an increment matrix: independent rows and time columns. Do not reset the seed inside the path loop. The implicit method uses bisection for the monotone root of ; it is validated by its residual. The tamed method is explicitly declared.
import numpy as np
def euler(x0, dw, h, drift, diffusion):
x=np.full(dw.shape[0],float(x0))
for d in dw.T:
x=x+h*drift(x)+diffusion(x)*d
return x
def milstein(x0, dw, h, drift, diffusion, derivative):
x=np.full(dw.shape[0],float(x0))
for d in dw.T:
x=x+h*drift(x)+diffusion(x)*d+.5*diffusion(x)*derivative(x)*(d*d-h)
return x
def tamed(x0,dw,h,sigma):
x=np.full(dw.shape[0],float(x0))
for d in dw.T:
b=-x**3
x=x+h*b/(1+h*np.abs(b))+sigma*d
return x
def implicit_cubic(x0,dw,h,sigma):
x=np.full(dw.shape[0],float(x0))
max_residual=0.
for d in dw.T:
c=x+sigma*d
lo=np.minimum(c,0.); hi=np.maximum(c,0.)
for _ in range(52):
y=(lo+hi)/2
left=y+h*y**3<c
lo=np.where(left,y,lo); hi=np.where(left,hi,y)
y=(lo+hi)/2
max_residual=max(max_residual,float(np.max(np.abs(y+h*y**3-c))))
x=y
return x,max_residual
rng=np.random.default_rng(2701)
dw=rng.normal(size=(1000,32))/np.sqrt(32)
imp,residuo=implicit_cubic(1.,dw,1/32,.6)
domado=tamed(1.,dw,1/32,.6)
assert residuo<1e-10 and np.isfinite(domado).all()
print("residuo implícito máximo, medias implícita y domada:",
residuo,imp.mean(),domado.mean())For each path we refine a single realization. Coarse columns are sums of contiguous blocks, so their variance is the coarse step. The strong-error curve uses the same exact terminal solution at every level.
mu,sigma,T=.2,.5,1.
m,nfine=4000,128
fine=rng.normal(size=(m,nfine))*np.sqrt(T/nfine)
exact=np.exp((mu-sigma**2/2)*T+sigma*fine.sum(axis=1))
hs=[]; rms_e=[]; rms_m=[]
for n in (8,16,32,64,128):
h=T/n
coarse=fine.reshape(m,n,nfine//n).sum(axis=2)
ye=euler(1.,coarse,h,lambda x:mu*x,lambda x:sigma*x)
ym=milstein(1.,coarse,h,lambda x:mu*x,lambda x:sigma*x,
lambda x:np.full_like(x,sigma))
rms_e.append(np.sqrt(np.mean((ye-exact)**2)))
rms_m.append(np.sqrt(np.mean((ym-exact)**2)))
hs.append(h)
delta=ye-exact
bias=(1+mu*h)**n-np.exp(mu*T)
print("n, RMS Euler, RMS Milstein, sesgo exacto, sesgo estimado, error estándar:",
n,rms_e[-1],rms_m[-1],bias,delta.mean(),delta.std(ddof=1)/np.sqrt(m))
print("pendientes fuertes observadas:",
np.polyfit(np.log(hs),np.log(rms_e),1)[0],
np.polyfit(np.log(hs),np.log(rms_m),1)[0])Slopes are estimates from this sample, not guarantees. Grids share paths and their errors are correlated. A confidence interval requires resampling whole paths, not treating each level as an independent observation.
from scipy.stats import norm
m=50000; dt=.4
theta,level,vol,x0=.8,1.,.6,.3
phi=np.exp(-theta*dt)
ou=level+phi*(x0-level)+vol*np.sqrt(-np.expm1(-2*theta*dt)/(2*theta))*rng.normal(size=m)
ou_mean=level+phi*(x0-level)
ou_var=vol**2*(-np.expm1(-2*theta*dt))/(2*theta)
assert abs(ou.mean()-ou_mean)<5*np.sqrt(ou_var/m)
gbm=x0*np.exp((mu-sigma**2/2)*dt+sigma*np.sqrt(dt)*rng.normal(size=m))
gbm_mean=x0*np.exp(mu*dt)
gbm_var=x0**2*np.exp(2*mu*dt)*np.expm1(sigma**2*dt)
assert abs(gbm.mean()-gbm_mean)<5*np.sqrt(gbm_var/m)
kappa,level,vol,x0=1.2,.05,.4,.05
c=vol**2*(-np.expm1(-kappa*dt))/(4*kappa)
nu=4*kappa*level/vol**2
nc=np.exp(-kappa*dt)*x0/c
cir=c*rng.noncentral_chisquare(nu,nc,size=m)
cir_mean=level+(x0-level)*np.exp(-kappa*dt)
cir_var=2*c*c*(nu+2*nc)
assert np.all(cir>=0) and abs(cir.mean()-cir_mean)<5*np.sqrt(cir_var/m)
print("OU media observada y teórica:",ou.mean(),ou_mean)
print("GBM media observada y teórica:",gbm.mean(),gbm_mean)
print("CIR media observada y teórica:",cir.mean(),cir_mean)These mean checks, with tolerance of five theoretical standard errors, are a reproducible alarm, not a complete proof of equal distributions.
Local lab: one million paths
This lab requires local Python with NumPy, SciPy, PyTorch and torchsde installed. The full experiment processes one million paths in batches; for a quick check enable environment variable ORYON_SHORT=1 before running. It uses CUDA if available and CPU otherwise. All three OU implementations receive literally the same increments and the torchsde method uses a noise provider specific to this fixed grid: it is not valid for adaptive steps.
For Merton each jump mark is also shared; torchsde integrates the continuous log-return component and jumps are added afterward. NumPy and PyTorch evaluate the terminal solution while torchsde takes successive steps: they are different algorithms. Exact OU mean and covariance show the combination of Monte Carlo error and Euler bias. Timing ratios compare only each implementation’s computation, exclude generation and transfers, and depend on hardware and load. Do not extrapolate them to another machine or mistake them for a complete performance measure.
# Ejecuta: python -m pip install torch torchsde scipy numpy
# Para comprobar rápidamente: define ORYON_SHORT=1 en tu entorno.
# Experimento completo: 1.000.000 de trayectorias, procesadas por bloques.
import os
import time
import numpy as np
import torch
import torchsde
from scipy.linalg import expm, solve_continuous_lyapunov
N = 8192 if os.environ.get('ORYON_SHORT') == '1' else 1_000_000
BLOCK = 2048 if os.environ.get('ORYON_SHORT') == '1' else 8192
STEPS = 64
DT = 1.0 / STEPS
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
DTYPE = torch.float64
print('trayectorias, bloque, pasos, dispositivo:', N, BLOCK, STEPS, DEVICE)
rng = np.random.default_rng(2627)
# dX = A X dt + G dW con dos fuentes brownianas independientes.
A = np.array([[-0.8, 0.3], [-0.4, -0.6]])
G = np.array([[0.5, 0.0], [0.2, 0.35]])
X0 = np.array([1.0, -1.0])
At = torch.tensor(A, dtype=DTYPE, device=DEVICE)
Gt = torch.tensor(G, dtype=DTYPE, device=DEVICE)
class OU(torch.nn.Module):
noise_type = 'general'
sde_type = 'ito'
def f(self, t, y):
return y @ At.T
def g(self, t, y):
return Gt.expand(y.shape[0], -1, -1)
class BrownianoEnMalla:
"""Solo para Euler no adaptativo en esta malla: los incrementos son explícitos."""
levy_area_approximation = 'none'
def __init__(self, dw):
self.dw = dw
self.shape = dw.shape[1:]
self.dtype = dw.dtype
self.device = dw.device
def __call__(self, ta, tb=None, return_U=False, return_A=False):
if tb is None or return_U or return_A:
raise ValueError('Se requieren intervalos de malla sin áreas de Lévy')
i, j = round(float(ta) / DT), round(float(tb) / DT)
if j != i + 1 or not (0 <= i < STEPS):
raise ValueError('El integrador pidió una partición distinta de la malla fijada')
return self.dw[i]
def numpy_euler(dw):
x = np.broadcast_to(X0, (dw.shape[1], 2)).copy()
for k in range(STEPS):
x = x + x @ A.T * DT + dw[k] @ G.T
return x
def torch_euler(dw):
x = torch.tensor(X0, dtype=DTYPE, device=DEVICE).expand(dw.shape[1], -1).clone()
for k in range(STEPS):
x = x + x @ At.T * DT + dw[k] @ Gt.T
return x
def torchsde_euler(dw):
x = torch.tensor(X0, dtype=DTYPE, device=DEVICE).expand(dw.shape[1], -1).clone()
# DT=1/64 es exacto en binario. No usar adaptive=True con este proveedor.
ts = torch.tensor([0.0, 1.0], dtype=DTYPE, device=DEVICE)
return torchsde.sdeint(OU(), x, ts, bm=BrownianoEnMalla(dw),
method='euler', dt=DT, adaptive=False)[-1]
def sincronizar():
if DEVICE.type == 'cuda':
torch.cuda.synchronize()
total_np = total_torch = total_sde = 0.0
max_torch = max_sde = 0.0
sum_x = np.zeros(2)
sum_xx = np.zeros((2, 2))
for start in range(0, N, BLOCK):
b = min(BLOCK, N - start)
# El mismo array se pasa a las tres implementaciones; igual semilla no bastaría.
dw_np = rng.normal(0.0, np.sqrt(DT), size=(STEPS, b, 2))
begin = time.perf_counter()
reference = numpy_euler(dw_np)
total_np += time.perf_counter() - begin
dw_t = torch.from_numpy(dw_np).to(DEVICE)
sincronizar(); begin = time.perf_counter()
manual = torch_euler(dw_t)
sincronizar(); total_torch += time.perf_counter() - begin
begin = time.perf_counter()
library = torchsde_euler(dw_t)
sincronizar(); total_sde += time.perf_counter() - begin
manual_np = manual.cpu().numpy()
library_np = library.cpu().numpy()
max_torch = max(max_torch, np.max(np.abs(manual_np - reference)))
max_sde = max(max_sde, np.max(np.abs(library_np - reference)))
sum_x += reference.sum(axis=0)
sum_xx += reference.T @ reference
del dw_np, dw_t, manual, library, manual_np, library_np, reference
empirical_mean = sum_x / N
empirical_cov = (sum_xx - N * np.outer(empirical_mean, empirical_mean)) / (N - 1)
phi = expm(A)
P = solve_continuous_lyapunov(A, -(G @ G.T))
exact_mean = phi @ X0
exact_cov = P - phi @ P @ phi.T
euler_mean = np.linalg.matrix_power(np.eye(2) + A * DT, STEPS) @ X0
print('OU: máxima diferencia NumPy/PyTorch y NumPy/torchsde:', max_torch, max_sde)
print('OU: media simulada, media Euler, media continua exacta:', empirical_mean, euler_mean, exact_mean)
print('OU: covarianza simulada y continua exacta:', empirical_cov, exact_cov)
print('OU: cocientes tiempo PyTorch/NumPy y torchsde/NumPy, solo cómputo:',
total_torch / total_np, total_sde / total_np)
print('Los cocientes dependen de dispositivo, tamaño de bloque y carga; no incluyen transferencia ni generación.')
assert max_torch < 1e-9 and max_sde < 1e-9
# Merton exacto a T=1. Los saltos se generan aparte: torchsde integra EDEs continuas.
mu, sigma, intensity, jump_mu, jump_sd = 0.08, 0.25, 0.6, -0.12, 0.3
kappa = np.exp(jump_mu + jump_sd**2 / 2) - 1
class LogMertonContinuo(torch.nn.Module):
noise_type = 'diagonal'
sde_type = 'ito'
def f(self, t, y):
return torch.ones_like(y) * (mu - intensity * kappa - sigma**2 / 2)
def g(self, t, y):
return torch.ones_like(y) * sigma
mean_returns = 0.0
mean_prices = 0.0
max_jump_diff = 0.0
max_jump_sde_diff = 0.0
total_jump_np = total_jump_torch = total_jump_sde = 0.0
for start in range(0, N, BLOCK):
b = min(BLOCK, N - start)
dw_np = rng.normal(0.0, np.sqrt(DT), size=(STEPS, b, 1))
counts = rng.poisson(intensity, size=b)
# Cada marca de salto se comparte literalmente; las sobrantes se enmascaran.
marks = rng.normal(jump_mu, jump_sd, size=(int(counts.max()), b))
mask = np.arange(marks.shape[0])[:, None] < counts[None, :]
begin = time.perf_counter()
z = dw_np.sum(axis=0)[:, 0] # B_1, a partir de incrementos compartidos
jumps = np.where(mask, marks, 0.0).sum(axis=0)
log_return = (mu - intensity * kappa - sigma**2 / 2) + sigma * z + jumps
prices = np.exp(log_return)
total_jump_np += time.perf_counter() - begin
dw_t = torch.from_numpy(dw_np).to(DEVICE)
mt = torch.from_numpy(marks).to(DEVICE)
mask_t = torch.from_numpy(mask).to(DEVICE)
sincronizar(); begin = time.perf_counter()
zt = dw_t.sum(dim=0)[:, 0]
jt = torch.where(mask_t, mt, 0.0).sum(dim=0)
rt = (mu - intensity * kappa - sigma**2 / 2) + sigma * zt + jt
price_t = torch.exp(rt)
sincronizar(); total_jump_torch += time.perf_counter() - begin
# La EDE del log-retorno continuo es aditiva; los saltos se agregan aparte.
initial = torch.zeros((b, 1), dtype=DTYPE, device=DEVICE)
ts = torch.tensor([0.0, 1.0], dtype=DTYPE, device=DEVICE)
begin = time.perf_counter()
continuous = torchsde.sdeint(LogMertonContinuo(), initial, ts,
bm=BrownianoEnMalla(dw_t), method='euler',
dt=DT, adaptive=False)[-1][:, 0]
jump_sde = torch.where(mask_t, mt, 0.0).sum(dim=0)
rt_sde = continuous + jump_sde
price_sde = torch.exp(rt_sde)
sincronizar(); total_jump_sde += time.perf_counter() - begin
rt_np = rt.cpu().numpy()
price_np = price_t.cpu().numpy()
rt_sde_np = rt_sde.cpu().numpy()
price_sde_np = price_sde.cpu().numpy()
max_jump_diff = max(max_jump_diff, np.max(np.abs(rt_np - log_return)), np.max(np.abs(price_np - prices)))
max_jump_sde_diff = max(max_jump_sde_diff, np.max(np.abs(rt_sde_np - log_return)), np.max(np.abs(price_sde_np - prices)))
mean_returns += np.sum(log_return)
mean_prices += np.sum(prices)
del dw_np, dw_t, z, counts, marks, mask, zt, mt, mask_t, jt, jump_sde, rt, price_t, continuous, rt_sde, price_sde, rt_np, price_np, rt_sde_np, price_sde_np, initial, ts, log_return, prices, jumps
print('Merton: diferencias máximas NumPy/PyTorch y NumPy/torchsde:', max_jump_diff, max_jump_sde_diff)
print('Merton: log-retorno medio muestral y teórico:', mean_returns / N,
mu - intensity * kappa - sigma**2 / 2 + intensity * jump_mu)
print('Merton: precio medio muestral y teórico:', mean_prices / N, np.exp(mu))
print('Merton: cocientes tiempo PyTorch/NumPy y torchsde/NumPy, solo cómputo:', total_jump_torch / total_jump_np, total_jump_sde / total_jump_np)
print('NumPy y PyTorch suman incrementos y evalúan la fórmula terminal; torchsde integra 64 pasos: los algoritmos son distintos.')
print('Los tres tiempos incluyen sumas de incrementos o integración y aplicación de marcas, no generación ni transferencias.')
assert max_jump_diff < 1e-9 and max_jump_sde_diff < 1e-9
if DEVICE.type == 'cuda':
torch.cuda.empty_cache()npm run lab and open the connection link.Exercises
Step 1 of 3. What is the principal variation of Xₛ−Xₜ in the stochastic integral?
Step 1 of 3. Which moments occur in E[(Yₜ−Xₜ)²]?
import numpy as np
def strong_order_estimate(scheme,sde,exact,dts,m=1200,bootstrap=160,seed=27):
passCouple grids to compare paths, separate bias from Monte Carlo noise and choose the scheme for the quantity needed. Exact transition at nodes and continuous crossing are different questions.
print("pasos de Milstein:",100)
print("coeficiente del error cuadrático de Euler para mu=.2, sigma=.5:",
.5*.5**4*np.exp(2*.2+.5**2))