Module contents
Lesson 26 of 31Core 115 min

Stochastic differential equations

Study stochastic differential equations, existence and uniqueness, strong and weak solutions, linear equations and canonical Ornstein-Uhlenbeck, CIR and Langevin models.

After this lesson you can

  • Prove existence and uniqueness under Lipschitz conditions using Picard iteration.
  • Solve scalar and vector linear SDEs and obtain mean and covariance.
  • Calculate Ornstein-Uhlenbeck transition and stationary laws and connect sampled OU to AR(1).
  • Analyze CIR, its Feller condition and transition law, and simulate it without violating positivity.
  • Explain why Langevin dynamics samples from e^{-U} and the role of temperature.

Before you start

Dynamics with perturbations

A particle may feel a force and thermal shocks; an interest rate may revert while receiving perturbations. A stochastic differential equation combines both effects:

dXt=b(t,Xt)dt+σ(t,Xt)dBt,Xt=X0+∫0tb(s,Xs)ds+∫0tσ(s,Xs)dBs.dX_t=b(t,X_t)dt+\sigma(t,X_t)dB_t,\qquad X_t=X_0+\int_0^t b(s,X_s)ds+\int_0^t\sigma(s,X_s)dB_s.

The second equality is the definition in the Itô convention. Drift describes first-order conditional displacement and diffusion its local quadratic variation; it does not replace a full conditional distribution with a single path. Explore the dynamics and move the date: exact transitions and numerical approximations are identified in the figure.

InteractiveWhat drift and diffusion do

dX = (c−X) dt + σ dB; X₀=1. We generate 256 paths with a reproducible seed and 240 steps up to T=3. Eight are shown; drag the marker or use the date control to change the histogram.

  • Paths shown
  • Histogram date

Distribution of the 256 paths at the selected date; the value at t=0 is deterministic.

Drift field b(x) for current parameters

Brownian, OU and geometric models use exact transitions at nodes. CIR uses Euler with projection to zero and the double well uses tamed Euler: both are approximations with step-dependent bias. Projections do not count actual boundary crossings. The other CIR figure uses exact transitions on the grid.

0.0
0.6
160
1
Time t2.000
Sample mean0.116
Sample deviation0.384
Compare paths, distribution and drift field of several models.

Existence, uniqueness and explosion

A sufficient condition for global existence and uniqueness on a finite horizon is that bb and σ\sigma are measurable in time, globally Lipschitz in state and satisfy a uniform linear-growth bound. With X0∈L2X_0\in L^2 and F0\mathcal F_0-measurable, and BB Brownian relative to that filtration, a continuous strong solution exists and is pathwise unique. These conditions are sufficient, not necessary.

Picard’s argument starts with Xt(0)=X0X^{(0)}_t=X_0 and defines X(k+1)X^{(k+1)} by substituting X(k)X^{(k)} in both integrals. For uk(t)=Esup⁡s≤t∣Xs(k+1)−Xs(k)∣2u_k(t)=E\sup_{s\le t}|X_s^{(k+1)}-X_s^{(k)}|^2, Cauchy-Schwarz controls the drift integral; Itô isometry and Doob’s maximal inequality control the stochastic integral. The Lipschitz assumption gives, with constant CC depending on the horizon and bounds,

uk+1(t)≤C∫0tuk(s) ds,uk(T)≤C0(CT)kk!.u_{k+1}(t)\le C\int_0^t u_k(s)\,ds, \qquad u_k(T)\le C_0\frac{(CT)^k}{k!}.

Differences form a convergent series in the supremum norm L2L^2; the limit satisfies the equation by continuity of the integrals. For two solutions with the same noise, the same estimate and Gronwall force their difference to zero. Without global control there can be explosion: the deterministic equation dX=X2dtdX=X^2dt, X0=1X_0=1, has Xt=1/(1−t)X_t=1/(1-t) only until time 1.

A strong solution is constructed adapted to the given noise and initial data; in a weak solution the probability space and driving Brownian motion are also chosen. The Tanaka equation dX=sign⁡(X)dBdX=\operatorname{sign}(X)dB, X0=0X_0=0, admits a weak solution but no strong solution relative to the natural filtration of the noise; the sign function is not Lipschitz at zero. See the ETH notes. Uniqueness in law and pathwise uniqueness are distinct statements.

Linear equations and Ornstein-Uhlenbeck

For the vector linear SDE with deterministic coefficients

dXt=(A(t)Xt+b(t))dt+G(t)dWt,dX_t=(A(t)X_t+b(t))dt+G(t)dW_t,

let Φ′(t)=A(t)Φ(t)\Phi'(t)=A(t)\Phi(t), Φ(0)=I\Phi(0)=I. Then

Xt=Φ(t)X0+Φ(t)∫0tΦ(s)−1b(s)ds+Φ(t)∫0tΦ(s)−1G(s)dWs.X_t=\Phi(t)X_0+\Phi(t)\int_0^t\Phi(s)^{-1}b(s)ds +\Phi(t)\int_0^t\Phi(s)^{-1}G(s)dW_s.

If X0X_0 is independent of the noise and has covariance P0P_0, the covariance is Φ(t)[P0+∫0tΦ(s)−1G(s)G(s)TΦ(s)−Tds]Φ(t)T\Phi(t)[P_0+\int_0^t\Phi(s)^{-1}G(s)G(s)^\mathsf T\Phi(s)^{-\mathsf T}ds]\Phi(t)^\mathsf T. With Gaussian or deterministic X0X_0 the process is Gaussian. Not every linear SDE with multiplicative diffusion has a Gaussian law: geometric Brownian motion is a counterexample.

The Ornstein-Uhlenbeck process, with θ>0\theta>0 and σ>0\sigma>0, satisfies dXt=θ(μ−Xt)dt+σdBtdX_t=\theta(\mu-X_t)dt+\sigma dB_t. Multiplying by eθte^{\theta t} gives

Xt+Δ∣Xt=x∼N ⁣(μ+e−θΔ(x−μ),σ22θ(1−e−2θΔ)).X_{t+\Delta}\mid X_t=x\sim N\!\left( \mu+e^{-\theta\Delta}(x-\mu), \frac{\sigma^2}{2\theta}(1-e^{-2\theta\Delta})\right).

The stationary law is N(μ,σ2/(2θ))N(\mu,\sigma^2/(2\theta)) and the half-life of an expected deviation is log⁡2/θ\log 2/\theta. On an equally spaced grid it is exactly an AR(1) with ϕ=e−θΔ\phi=e^{-\theta\Delta}. A finite fit can give ϕ^∉(0,1)\hat\phi\notin(0,1): then it does not represent a stable OU through −log⁡ϕ^/Δ-\log\hat\phi/\Delta. High frequency without a long horizon does not automatically eliminate bias in estimating reversion.

InteractiveOU on a grid

Model: dX=0.7(1−X)dt+0.8dB, with X₀=1. The exact Gaussian transition is simulated without Euler. Dates reach the last multiple of Δ not exceeding the requested horizon.

Each point compares one observation with the next; the chart shows up to 350 pairs for readability. The fit uses all pairs.

  • Observed pairs
  • Theoretical conditional mean
  • Fitted regression

Horizontal axis: Xᵢ. Vertical axis: Xᵢ₊₁. The transition is Xᵢ₊₁=1+φ(Xᵢ−1)+εᵢ, with φ=e^(−0.7Δ) and ε variance 0.8²(1−e^(−1.4Δ))/1.4. The fit estimates slope and intercept by regression and divides residual sum of squares by the number of transitions: this is conditional maximum-likelihood variance.

Since 0<estimated φ<1, we convert the regression to OU parameters using θ̂=−log(φ̂)/Δ and level ĉ/(1−φ̂). Estimates can differ from true parameters on a finite path.

As Δ decreases, φ approaches 1, but more observations over the same total time are not equivalent to observing a longer horizon. The fit depends on the sample and may be biased; changing Δ resimulates, so resulting paths are not subsamples of the same path.

0.20
20
Transitions100
Observed time20.00
Theoretical φ0.8694
Estimated φ0.7442
Theoretical innovation variance0.1116
Estimated residual variance0.1073
Estimated θ1.477
Estimated level0.511
Estimated σ0.843
Seed2626
Change observation frequency and compare the AR(1) estimate with the exact transition.

CIR and the zero boundary

The Cox-Ingersoll-Ross process satisfies dXt=κ(θ−Xt)dt+σXt dBtdX_t=\kappa(\theta-X_t)dt+\sigma\sqrt{X_t}\,dB_t, with positive parameters and X0>0X_0>0. The square root is not Lipschitz at zero, but the model has its own existence and uniqueness theory. Define α=2κθ/σ2\alpha=2\kappa\theta/\sigma^2. If α≥1\alpha\ge1, zero is inaccessible from a positive state; if 0<α<10<\alpha<1, it can be reached and the standard solution immediately leaves the boundary without becoming negative.

For Δ>0\Delta>0 the transition is exact:

Xt+Δ=cZ,Z∼χν′2(λ),c=σ2(1−e−κΔ)4κ,ν=4κθσ2,λ=e−κΔXtc.X_{t+\Delta}=cZ,\quad Z\sim\chi'^2_{\nu}(\lambda),\quad c=\frac{\sigma^2(1-e^{-\kappa\Delta})}{4\kappa},\quad \nu=\frac{4\kappa\theta}{\sigma^2},\quad \lambda=\frac{e^{-\kappa\Delta}X_t}{c}.

The stationary law is Gamma with shape α\alpha and scale σ2/(2κ)\sigma^2/(2\kappa). An exact sample at nodes does not reveal every possible contact with zero between dates. Careless Euler simulation can produce negative values; projecting them to zero changes the law and must be declared. The original paper by Cox, Ingersoll and Ross presents the rate model.

InteractiveThe CIR boundary

Each line is one of the first 12 paths, starting at X₀ = θ. The dashed line marks ε = 0.05θ = 0.0020. Being below ε at a node indicates proximity, not that zero was hit.

Time · vertical axis: X
  • Paths on grid
  • Threshold ε > 0

Bars: terminal values of the 500 paths at t = 5. Line: probabilities of the same intervals under the stationary gamma, not a curve fitted to terminal values. The process starts at θ, not in the stationary distribution: the two laws may differ at finite time. Values outside the axis count in readouts; the line also has mass outside the axis.

16 %0.0000.0890.178
Value at t = 5 · outside axis: 5 of 500 terminal values
  • Simulated terminal distribution
  • Stationary gamma

Model: dX = κ(θ−X)dt + σ√X dB, with positive parameters. The stationary law is Gamma with shape α = 2κθ/σ² and scale σ²/(2κ). When α < 1, its density diverges near zero; here interval probabilities are calculated using the CDF, including the first bar, without evaluating density at zero.

With X₀ > 0, zero is inaccessible if α ≥ 1; if 0 < α < 1 it can be reached and standard CIR leaves it instantaneously. A grid, even with exact transitions, does not reveal every crossing between nodes. Thus the percentage of nodes ≤ ε is not an estimated probability of hitting zero and depends on ε and the grid. If no proximity is observed, estimated standard error is zero, but this does not rule out positive probability.

We simulate 500 independent paths with 60 intervals and seed 2626. Each transition is a scaled noncentral chi-square, generated as an exact Poisson-gamma mixture; summing small-mean Poissons avoids underflow for large parameters. The curve joins nodes only for visualization. Reference: Malham and Wiese, chi-square CIR simulation.

1.5
0.04
0.30
Feller α = 2κθ/σ²1.333
Zero boundaryInaccessible
Nodes ≤ ε at least once54.2 %
Estimated standard error2.23 %
Sample terminal mean0.0382
Theoretical terminal mean0.0400
Seed2626
Compare exact grid transitions, proximity to zero and stationary distribution.

Langevin and temperature

One-dimensional overdamped Langevin dynamics is dXt=−U′(Xt)dt+2T dBtdX_t=-U'(X_t)dt+\sqrt{2T}\,dB_t, with T>0T>0. If e−U/Te^{-U/T} is integrable and appropriate boundary conditions hold, p∞(x)∝e−U(x)/Tp_\infty(x)\propto e^{-U(x)/T} is invariant: in the Fokker-Planck equation current −U′p∞−Tp∞′-U'p_\infty-Tp_\infty' vanishes. With additional ergodicity assumptions, the law converges to that distribution. Temperature changes both noise and concentration in the wells.

For U(x)=(x2−1)2/4U(x)=(x^2-1)^2/4, minima lie at −1-1 and 11 and the barrier at zero has height 1/41/4. Kramers’ law describes exponential growth of transition time in the low-temperature asymptotic regime; the prefactor and assumptions are detailed in Berglund and Gentz. At finite temperature this is an approximation, not an exact equality. If a simulation ends before reaching the other well, its time is censored.

InteractiveCrossing between wells

200 particles start at x=−1. Bars show their positions at the horizon; the curve is the stationary density of the continuous diffusion, not the initial distribution.

  • Simulated positions
  • Gibbs reference

Proportion that has not yet reached x=+1 at observed nodes. The curve ends at the chosen horizon; it does not assign arrival times to those still censored.

  • No observed arrival

Continuous model: dX=−U′(X)dt+√(2T)dB, U(x)=(x²−1)²/4. The Gibbs reference is proportional to exp(−U/T), numerically normalized on [−4,4]. Bars divide by 200 and each bin width, including when particles fall outside the chart.

The simulation uses tamed Euler with Δt=0.02: drift b is replaced at each step by b/(1+Δt|b|). This is an approximation with discretization bias and stationary distribution different from Gibbs. Crossings between nodes can be detected late or missed.

The restricted mean averages min(observed τ, horizon); for paths with no arrival it uses the horizon as a censoring time, not an actual arrival. The Kramers scale 2π exp[1/(4T)]/√2 approximates expected transition time between wells as T tends to zero; it is neither the restricted mean nor an exact equality at finite temperature.

0.18
40
1
Observed arrivals at +1170 / 200
Censored at horizon30 / 200
Mean restricted to horizon19.84
Asymptotic Kramers scale17.82
Outside histogram0
No observed arrival15.0 %
Compare the simulated distribution with Gibbs and distinguish observed arrivals from censoring.

Lab: exact vector OU and estimation

For constant Hurwitz AA, all eigenvalues have negative real parts. Stationary covariance PP solves AP+PAT+GGT=0AP+PA^\mathsf T+GG^\mathsf T=0. If Φ=eAΔ\Phi=e^{A\Delta}, the exact one-step innovation covariance is QΔ=P−ΦPΦTQ_\Delta=P-\Phi P\Phi^\mathsf T. Do not confuse this finite covariance with PP.

[ ]Vector covariance and exact transitionBrowser
import numpy as np
from scipy.linalg import expm, solve_continuous_lyapunov

rng=np.random.default_rng(2626)
A=np.array([[-.8,.3],[-.4,-.6]])
G=np.array([[.5,0.],[.2,.35]])
[email protected]
P=solve_continuous_lyapunov(A,-Q)
T=2.; Phi=expm(A*T)
P_T=P-Phi@[email protected]
x0=np.array([1.,-1.]); media=Phi@x0
print("autovalores de A y residuo Lyapunov:",np.linalg.eigvals(A),np.max(abs(A@[email protected]+Q)))
print("media y covarianza exactas al horizonte:",media,P_T)
print("covarianza estacionaria:",P)

replicas=5000; pasos=200; dt=T/pasos
euler=np.broadcast_to(x0,(replicas,2)).copy()
for _ in range(pasos):
    ruido=rng.normal(size=(replicas,2))
    euler += ([email protected])*dt + np.sqrt(dt)*([email protected])
print("media y covarianza Euler en malla fina:",
      euler.mean(axis=0),np.cov(euler,rowvar=False))
exactas=rng.multivariate_normal(media,P_T,size=replicas)
print("media y covarianza de transiciones exactas:",
      exactas.mean(axis=0),np.cov(exactas,rowvar=False))

Euler discretization is an approximation and the comparison includes Monte Carlo error. Equal moments alone do not prove equal laws. In the linear model with deterministic coefficients and fixed initial data, the exact solution is Gaussian.

An equally spaced OU transition is Gaussian regression with intercept. Its unrestricted maximum provides ϕ^\hat\phi, intercept and innovation variance. Transformation to stable OU parameters is valid only if 0<ϕ^<10<\hat\phi<1; we do not clip invalid estimates to make them appear admissible.

[ ]Exact maximum likelihood for scalar OUBrowser
def ou_mle(x,dt):
    x=np.asarray(x,dtype=float)
    if x.ndim!=1 or len(x)<4 or not np.all(np.isfinite(x)) or not np.isfinite(dt) or dt<=0:
        raise ValueError("serie finita y paso positivo")
    u=x[:-1]; v=x[1:]
    centro=u-u.mean()
    denom=np.dot(centro,centro)
    if denom<=0:
        raise ValueError("regresores constantes")
    phi=np.dot(centro,v-v.mean())/denom
    if not 0<phi<1:
        raise ValueError("el máximo AR no restringido no es un OU estable interior")
    intercepto=v.mean()-phi*u.mean()
    residual=v-intercepto-phi*u
    q=np.mean(residual**2)
    if q<=0 or not np.isfinite(q):
        raise ValueError("no hay máximo interior con varianza residual nula")
    theta=-np.log(phi)/dt
    mu=intercepto/(1-phi)
    sigma=np.sqrt(2*theta*q/(-np.expm1(-2*theta*dt)))
    return theta,mu,sigma

def simular_ou(m,pasos,dt,theta,mu,sigma,rng):
    phi=np.exp(-theta*dt)
    sd=sigma*np.sqrt(-np.expm1(-2*theta*dt)/(2*theta))
    caminos=np.empty((m,pasos+1)); caminos[:,0]=mu
    for i in range(pasos):
        caminos[:,i+1]=mu+phi*(caminos[:,i]-mu)+sd*rng.normal(size=m)
    return caminos

for horizonte in (5,60):
    caminos=simular_ou(400,int(horizonte/.1),.1,.7,1.,.8,rng)
    estimaciones=[]; invalidos=0
    for camino in caminos:
        try:
            estimaciones.append(ou_mle(camino,.1))
        except ValueError:
            invalidos+=1
    print("horizonte, válidos, no interiores y media de theta, mu, sigma:",
          horizonte,len(estimaciones),invalidos,np.mean(estimaciones,axis=0))

The printed means are conditional on the unrestricted AR maximum being interior. Short samples may yield estimates outside (0,1)(0,1); ignoring them also changes the summary. Constrained likelihood optimization with boundaries requires treating those cases, not silently replacing them with an interior value.

CIR transition without negative values

NumPy provides a sample from the noncentral chi-square law. We compare its first moment with the theoretical solution; positivity at discrete dates does not report every contact of the path with the boundary.

[ ]An exact CIR transitionBrowser
kappa,theta,sigma,x0,delta=1.2,.05,.4,.05,1.
c=sigma**2*(-np.expm1(-kappa*delta))/(4*kappa)
nu=4*kappa*theta/sigma**2
lam=np.exp(-kappa*delta)*x0/c
salida=c*rng.noncentral_chisquare(nu,lam,size=100000)
media=x0*np.exp(-kappa*delta)+theta*(-np.expm1(-kappa*delta))
print("CIR mínimo, media, error estándar y media teórica:",
      salida.min(),salida.mean(),salida.std(ddof=1)/np.sqrt(len(salida)),media)
print("parámetros de la ley no central:",c,nu,lam)

Exercises

ProofSolve Ornstein-Uhlenbeck
Prove: Solve dX=θ(μ−X)dt+σdB with θ>0 and X₀=x, and obtain its mean and variance.
0
Multiply Xₜ−μ by the deterministic factor e^{θt}.

Step 1 of 3. What is the differential of e^{θt}(Xₜ−μ)?

ProofWhy Picard converges
Prove: Outline existence and uniqueness for globally Lipschitz coefficients with linear growth and X₀∈L².
0
Define X^(k+1) by integrating coefficients evaluated at X^(k) and measure the difference with the supremum in L².

Step 1 of 3. Which tools control differences of the two integrals?

NumericHalf-life
An OU has θ=2. What is the half-life of an expected deviation from its level? Give four decimal places.
NumericStationary spread
For an OU with θ=2 and σ=0.5, what is the stationary standard deviation?
NumericA CIR boundary
For κ=1.5, θ=0.04 and σ=0.3, calculate 2κθ/σ². Give three decimal places.
QuizWhat a sufficient theorem tells you
Which statement about Lipschitz conditions, growth and existence is correct?
CodeFit an OU to equally spaced observations
Implement ou_mle(x,dt) using the exact Gaussian transition likelihood. Fit an AR(1) with intercept, use residual variance with divisor n and return θ, μ, σ. If the unrestricted AR maximum has φ outside (0,1), or data are invalid, raise ValueError.
import numpy as np

def ou_mle(x,dt):
  pass
Shift+Enter to run
Key idea

An SDE is an integral equation with explicit information and regularity. Exact solutions distinguish model properties, estimation uncertainty and discretization errors.

Check the numerical exercises after attempting them.

[ ]Exercise checkBrowser
print("vida media, desviación OU y razón CIR:",
      np.log(2)/2, .5/np.sqrt(2*2), 2*1.5*.04/.3**2)