Module contents
Lesson 27 of 31Core 115 min

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

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.

InteractiveOne path, three solutions

GBM with X₀=1, dX=0.2Xdt+σXdB and horizon T=1. The exact solution is X(t)=exp[(0.2−σ²/2)t+σB(t)]. All three curves use the same Brownian motion; the exact path is drawn on 256 intervals and the methods on the selected grid. Segments between nodes are interpolations.

  • Exact GBM at nodes
  • Euler-Maruyama
  • Milstein

Final errors across 1200 paths: each value is √(mean of |approximate X − exact X|²). Both coordinates are decimal logarithms; the regression slope approximates strong order.

  • Euler RMS
  • Milstein RMS

Euler multiplies the state by 1+0.2Δt+σΔB. Milstein adds σ²((ΔB)²−Δt)/2 to the factor. Each coarse-grid increment sums the same fine increments; error is calculated against the solution on that same path, not an independent Brownian motion.

In this model theoretical strong orders are 1/2 for Euler and 1 for Milstein. Six-point slopes and delta-method approximate standard errors fluctuate with the sample and do not guarantee those values on each run. A single path does not establish convergence. See Higham, 2001.

4
0.5
Intervals n16
Step Δt0.06250
Euler RMS0.05672
Euler RMS standard error0.00214
Milstein RMS0.00979
Milstein RMS standard error0.00054
Observed Euler slope0.510
Observed Milstein slope0.958
Seed2627
Refine the grid and compare Euler, Milstein and the exact geometric Brownian solution.

From Itô-Taylor to two integrators

Consider the autonomous scalar equation dX=b(X)dt+σ(X)dBdX=b(X)dt+\sigma(X)dB. On interval [t,t+h][t,t+h], freezing coefficients inside the integral gives the Euler-Maruyama scheme

Yn+1=Yn+b(Yn)h+σ(Yn)ΔBn,ΔBn∼N(0,h).Y_{n+1}=Y_n+b(Y_n)h+\sigma(Y_n)\Delta B_n, \qquad \Delta B_n\sim N(0,h).

The normals are independent across intervals and paths. In particular, their standard deviation is h\sqrt h, not hh.

To improve the stochastic term, expand σ(Xs)\sigma(X_s) to first order in the dominant variation: σ(Xs)≃σ(Yn)+σ′(Yn)σ(Yn)(Bs−Bt)\sigma(X_s)\simeq\sigma(Y_n)+\sigma'(Y_n)\sigma(Y_n)(B_s-B_t). The iterated integral is calculated by Itô:

∫tt+h(Bs−Bt) dBs=(ΔBn)2−h2.\int_t^{t+h}(B_s-B_t)\,dB_s=\frac{(\Delta B_n)^2-h}{2}.

Substituting it yields scalar Milstein:

Yn+1=Yn+b(Yn)h+σ(Yn)ΔBn+12σ(Yn)σ′(Yn)((ΔBn)2−h).Y_{n+1}=Y_n+b(Y_n)h+\sigma(Y_n)\Delta B_n +\tfrac12\sigma(Y_n)\sigma'(Y_n)\big((\Delta B_n)^2-h\big).

Term −h-h 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 es(h)=(E∣YT−XT∣2)1/2e_{\rm s}(h)=(E|Y_T-X_T|^2)^{1/2}. Order pp means es(h)≤Chpe_{\rm s}(h)\le Ch^p for small hh, with constant independent of hh. Weak convergence compares expectations, ∣Ef(YT)−Ef(XT)∣≤Cfhq|E f(Y_T)-E f(X_T)|\le C_fh^q, for a declared class of functions ff. Checking one function is insufficient to prove general weak order.

With suitable regularity and moments, Euler typically has strong order 1/21/2 and weak order 11; scalar Milstein has strong order 11. 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.

InteractiveAccuracy of paths and expectations

GBM with X₀=1 and horizon 1. The five grids sum the same fine increments for each path; different paths receive independent noise. Strong error is the root mean squared terminal error. Paired bias estimates E[Euler X − exact X].

  • Strong RMS error
  • Exact weak bias
  • Absolute paired bias
  • Paired standard error

Exact bias comes from |(1+μ/n)ⁿ−e^μ|; Monte Carlo noise is calculated using paired differences, not independent samples. If bias is comparable to its standard error, its absolute value may rise or fall by chance and a logarithmic slope is no longer reliable. The plot floor 10⁻⁸ avoids logarithms of zero.

1024
0.20
0.50
Fine-grid steps128
Strong RMS error0.02053
Exact weak bias0.000191
Signed paired bias0.000282
Bias standard error0.000642
Compare exact weak bias, strong error and paired-estimation noise.

For dX=μXdt+σXdBdX=\mu Xdt+\sigma XdB, X0=1X_0=1, T=1T=1 and h=1/nh=1/n, the exact expectation is eμe^\mu and Euler’s is (1+μ/n)n(1+\mu/n)^n. Weak bias for f(x)=xf(x)=x is known without Monte Carlo. A bias estimate uses paired differences YT−XTY_T-X_T; 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 μ=0\mu=0 this particular bias is zero on every grid.

To check strong order without Monte Carlo noise, for this GBM define a=1+μha=1+\mu h. One-step moments give E[YT2]=(a2+σ2h)nE[Y_T^2]=(a^2+\sigma^2h)^n, E[YTXT]=[eμh(a+σ2h)]nE[Y_TX_T]=[e^{\mu h}(a+\sigma^2h)]^n and E[XT2]=e2μ+σ2E[X_T^2]=e^{2\mu+\sigma^2}. Their combination E(YT−XT)2E(Y_T-X_T)^2 has leading term proportional to hh if σ≠0\sigma\ne0: the square root has order 1/21/2. Here we keep T=1T=1; later you will generalize the argument to an arbitrary horizon.

For example, with c=2μ+σ2c=2\mu+\sigma^2, expanding logarithms of the two factors gives

log⁡(a2+σ2h)=ch−(μ2+2μσ2+12σ4)h2+O(h3),log⁡[eμh(a+σ2h)]=ch−12(μ+σ2)2h2+O(h3).\begin{aligned} \log(a^2+\sigma^2h)&=ch-(\mu^2+2\mu\sigma^2+\tfrac12\sigma^4)h^2+O(h^3),\\ \log[e^{\mu h}(a+\sigma^2h)]&=ch-\tfrac12(\mu+\sigma^2)^2h^2+O(h^3). \end{aligned}

Multiply by n=1/hn=1/h, exponentiate and combine E[YT2]−2E[YTXT]+E[XT2]E[Y_T^2]-2E[Y_TX_T]+E[X_T^2]: constant terms cancel, leaving 12σ4e2μ+σ2h+O(h2)\frac12\sigma^4e^{2\mu+\sigma^2}h+O(h^2). The constant is strictly positive for σ≠0\sigma\ne0. 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 dX=−λXdtdX=-\lambda Xdt, Euler’s factor is 1−λh1-\lambda h and damps only if 0<λh<20<\lambda h<2. An implicit scheme has factor 1/(1+λh)1/(1+\lambda h) and removes that restriction for λ,h>0\lambda,h>0. With noise, stability also depends on diffusion and the chosen notion of stability.

Numerical stability can fail even for a well-behaved SDE. In dX=−X3dt+σdBdX=-X^3dt+\sigma dB, explicit Euler applies x−hx3+σΔBx-hx^3+\sigma\Delta B; for large ∣x∣|x| it can throw the next value much farther away. A tamed alternative replaces b(x)hb(x)h with b(x)h/(1+h∣b(x)∣)b(x)h/(1+h|b(x)|); the implicit one solves y+hy3=x+σΔBy+hy^3=x+\sigma\Delta B, a strictly increasing equation with a unique real root. Neither is exact and both have discretization error.

InteractiveExplosions and alternatives

De 400 simulated paths, the Euler path with greatest amplitude is drawn; if one was interrupted, one of those is chosen. All three methods use the same noise increments.

  • Euler
  • Tamed
  • Implicit

Model dX=−X³dt+1.5 dB, X₀=0. Euler uses X−hX³+1.5ΔB; tamed Euler replaces drift with −X³/(1+h|X³|). The implicit scheme solves Y+hY³=X+1.5ΔB by bisection; the root is unique. The instability shown belongs to the scheme and does not mean this SDE explodes.

When |X| exceeds 10⁶, that Euler path is interrupted and counted: its second moment is not calculated. The chart omits points outside [−5,5], so a missing segment may be off scale. The other two means use all 400 paths; this visual selection does not represent a typical sample.

40
1
Step Δt0.250
Euler: interrupted paths16 / 400
Final mean X², EulerUnavailable
Final mean X², tamed1.322
Final mean X², implicit0.757
Compare schemes with the same noise and observe paths that leave the scale.

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, X\sqrt X 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 x,y<ax,y<a, the conditional probability of crossing an upper barrier aa during interval hh is

p=exp⁡[−2(a−x)(a−y)h].p=\exp\left[-\frac{2(a-x)(a-y)}{h}\right].

If an endpoint already reaches the barrier, p=1p=1. Given the nodes, bridges of different intervals are independent: averaging 1−∏i(1−pi)1-\prod_i(1-p_i) 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 σ2h\sigma^2h in the denominator. Neither an arbitrary diffusion nor a jump automatically admits that correction.

InteractiveWhat happens between observations

The figure selects the first path crossing at a fine node but not a coarse one: it is a selected example, not a typical sample. Lines between nodes are interpolations: even the fine grid can miss crossings.

  • Fine grid
  • Coarse grid
  • Barrier

We simulate 3000 paths with X₀ = 0 and Xₜ = μt + σBₜ on [0,1]. This equals log(Sₜ/S₀) for a constant-parameter GBM: if price drift is m, then μ = m − σ²/2. The corresponding price barrier is S₀eᵇ. The fine grid has 128 intervals and the coarse grid groups 8 of those same subintervals.

If both endpoints x,y are below b, bridge crossing probability between nodes is exp[−2(b−x)(b−y)/(σ²Δt)]; if either endpoint reaches b, it is 1. Constant drift disappears when conditioning on endpoints. We multiply non-crossing probabilities and average conditional crossing probability over the same paths. The bridge estimator removes monitoring bias for this model and barrier, but retains Monte Carlo error.

The continuous reference is Φ((μ−b)/σ) + exp(2μb/σ²) Φ((−μ−b)/σ). Φ is calculated by numerical integration of the normal tail. Standard errors are sample estimates; the bridge-minus-fine difference uses paired errors. If no crossing is observed, estimated standard error zero does not prove the event impossible. The fine count is no smaller than the coarse count because grids are nested; each estimate’s closeness to theory varies by sample.

1.0
0.0
1.0
8
Crossing at coarse nodes23.5 %
Crossing at fine nodes29.4 %
Bridges, coarse grid31.7 %
Theoretical continuous probability31.7 %
Coarse standard error0.77 %
Fine standard error0.83 %
Bridge standard error0.80 %
Bridges minus fine2.25 %
Standard error of difference0.30 %
Paths3000
Seed2627
Compare nested grids and conditional bridge probability.

Jumps and multilevel Monte Carlo

In Merton’s jump diffusion, take independent Ji∼N(mJ,sJ2)J_i\sim N(m_J,s_J^2) and Poisson NtN_t with intensity λ\lambda. If k=E(eJ)−1k=E(e^J)-1, the solution is

log⁡STS0=(μ−λk−12σ2)T+σBT+∑i=1NTJi.\log\frac{S_T}{S_0}=(\mu-\lambda k-\tfrac12\sigma^2)T+\sigma B_T+\sum_{i=1}^{N_T}J_i.

Compensation −λk-\lambda k makes E[ST]=S0eμTE[S_T]=S_0e^{\mu T}. Price jumps are multiplicative: a log jump JJ multiplies price by eJe^J. Log-return variance is T(σ2+λE[J2])T(\sigma^2+\lambda E[J^2]) and its excess kurtosis is

λE[J4]T(σ2+λE[J2])2.\frac{\lambda E[J^4]}{T(\sigma^2+\lambda E[J^2])^2}.

Excess does not always increase with λ\lambda: with σ>0\sigma>0 and E[J2]>0E[J^2]>0 it reaches a maximum at λ=σ2/E[J2]\lambda=\sigma^2/E[J^2] 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 −σ2/2-\sigma^2/2; in the previous parameterization this amounts to choosing μ=λk\mu=\lambda k. Thus changes in intensity also change expected price growth. Tail comparison uses theoretical return mean and variance for that configuration.

InteractiveA distribution with jumps

Cumulative log return of the path with most jumps among the first 30 replicates: it is selected to make jumps visible, not as a typical example.

  • Log return

Histogram of 1200 final returns versus the normal density with the same theoretical mean and variance.

  • Simulated Merton
  • Comparable normal

QQ: horizontal axis, normal quantiles; vertical axis, empirical return quantiles. The diagonal indicates matching quantiles.

  • Empirical quantiles
  • Equality

Model at T=1: R=−σ²/2+σB₁+ΣJ, σ=0.2, independent N~Poisson(λ) and J~N(0,s²). Jumps are grouped into 80 intervals with exact Poisson counts; their time within each interval is not drawn. The histogram divides by 1200 and bin width, including out-of-scale values in the denominator.

Theoretical excess kurtosis is 3λs⁴/(σ²+λs²)². It is zero when λ=0 and does not always grow with λ: for s>0 it reaches its maximum at λ=σ²/s² and then falls. Sample kurtosis is sensitive to extremes and can fluctuate; the QQ plot and histogram do not establish behavior across all tails.

0.7
0.40
1
Theoretical excess kurtosis2.327
Sample excess kurtosis1.577
Theoretical return variance0.1520
Jumps in selected path4
Outside histogram0
Change jump intensity and size, and compare returns with an equivalent normal.

For a costly expectation, multilevel Monte Carlo writes E[PL]=E[P0]+∑ℓ=1LE[Pℓ−Pℓ−1]E[P_L]=E[P_0]+\sum_{\ell=1}^L E[P_\ell-P_{\ell-1}]. 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 O(ε−2)O(\varepsilon^{-2}). 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 y+hy3=cy+hy^3=c; it is validated by its residual. The tamed method is explicitly declared.

[ ]Four scalar integratorsBrowser
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.

[ ]Order with nested incrementsBrowser
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.

[ ]Exact transitions and statistical validationBrowser
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.

[ ]Multidimensional OU and jumps in batchesLocal GPU
# 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()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofRecovering the Milstein term
Prove: For an autonomous scalar SDE with sufficiently regular coefficients, derive the Milstein correction from the local diffusion expansion.
0
In one step, approximate σ(Xₛ) around the initial value and retain the dominant stochastic variation.

Step 1 of 3. What is the principal variation of Xₛ−Xₜ in the stochastic integral?

ProofEuler's strong order for GBM
Prove: For X₀=1, dX=μXdt+σXdB, σ≠0, horizon T>0 and h=T/n, use moments to prove Euler's mean squared error is asymptotic to positive C h. Calculate C.
0
Let a=1+μh. Use independent increments and the same Brownian motion in the approximation and exact solution.

Step 1 of 3. Which moments occur in E[(Yₜ−Xₜ)²]?

NumericCompare step budgets
Suppose strong errors C/√n for Euler and C/n for Milstein, with the same constant C. How many steps does Milstein need for an error ten times smaller than Euler's with 100 steps?
QuizChoose the relevant accuracy
You want to estimate a European price, a continuous barrier and train with coupled paths. Which combination best reflects the quantities to control?
CodeEstimate order with nested paths
Implement strong_order_estimate(scheme,sde,exact,dts,m=1200,bootstrap=160,seed=27). Use horizon 1, dts=1/n with nested integer n. scheme(x0,dw,h,sde) receives increments by row and returns terminal values; exact(W,sde) receives terminal Brownian motion. Fit log(RMS) against log(h) and return slope and 95% percentile interval by resampling whole paths. Reject invalid grids.
import numpy as np

def strong_order_estimate(scheme,sde,exact,dts,m=1200,bootstrap=160,seed=27):
  pass
Shift+Enter to run
Key idea

Couple 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.

[ ]Check the numerical exercise and strong constantBrowser
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))