Stochastic Differential Equations (SDEs)

5 min read

1. Introduction to SDEs: Adding Noise to Deterministic Models

Welcome to step 9! 👋 Up until now, we’ve been living in a perfect, predictable universe. In our Ordinary Differential Equations (ODEs), if you drop a ball, you calculate exactly where it lands. If you model a population, it grows along a smooth curve.

But let’s be real. Life is messy. 🌪️

Stock markets crash based on tweets, biological cells jitter due to thermal noise, and sensors have static. To model reality, we can't just pretend the noise doesn't exist. We have to invite it in.

The Definition

A Stochastic Differential Equation (SDE) is essentially an ODE with a "random" term added to it.

The mathematical notation usually looks like this:

du=f(u,p,t)dt+g(u,p,t)dWdu = f(u,p,t)dt + g(u,p,t)dW

Here is the breakdown:

  1. f(u,p,t)dtf(u,p,t)dt: This is the Drift. It’s the deterministic part (the ODE part) that tells the system where it should go.
  2. g(u,p,t)dWg(u,p,t)dW: This is the Diffusion. It’s the noise scaling.
  3. dWdW: This represents the Wiener Process (or Brownian Motion). Think of it as a random variable that generates a Gaussian "kick" at every tiny time step.

Why do we need this?

If you use an ODE to model a bridge, you assume the wind is constant. If you use an SDE, you simulate the bridge buffering against random gusts of wind. In industry (Finance, Biology, Engineering), SDEs allow us to calculate risk and variance, not just averages.


2. Defining an SDEProblem: Drift and Diffusion Functions

In DifferentialEquations.jl, defining an SDE is surprisingly similar to an ODE. The only difference is that you need two functions instead of one.

The Two Functions

  1. Drift function (f): Describes the system's logic.
  2. Diffusion function (g): Describes how "loud" the noise is.

💡 Industry Tip: Always try to use the in-place form f(du, u, p, t) for both drift and diffusion to avoid memory allocation overheads, especially when running thousands of simulations (which you will do with SDEs).

Example: The Geometric Brownian Motion

Let's model a classic stock price evolution. The price trends up (drift) but fluctuates wildly (diffusion).

du=μudt+σudWdu = \mu u dt + \sigma u dW

Here, μ\mu is growth rate, and σ\sigma is volatility.

julia
using DifferentialEquations
using Plots

# 1. Define the Drift (Deterministic logic)
function drift_func!(du, u, p, t)
    μ = p[1]
    # The price grows by rate μ
    du[1] = μ * u[1]
end

# 2. Define the Diffusion (The Noise magnitude)
function diffusion_func!(du, u, p, t)
    σ = p[2]
    # The noise is proportional to the current price (u[1])
    # If the price is high, the swings are larger.
    du[1] = σ * u[1]
end

u0 = [1.0]             # Initial price
tspan = (0.0, 1.0)     # Time: 1 year
p = [1.5, 0.1]         # μ = 1.5, σ = 0.1

# 3. Define the SDE Problem
prob = SDEProblem(drift_func!, diffusion_func!, u0, tspan, p)

In this code, diffusion_func! doesn't create the random number. It just determines the magnitude of the random kick. The solver handles the randomness for you.


3. Understanding Diagonal vs. Non-Diagonal Noise Processes

This is where things get a bit spicy (and where most beginners get error messages). 🌶️

When you have a system of equations (multiple variables, e.g., Predator vs. Prey), the noise can act in different ways.

Diagonal Noise (The Easy One)

Each variable gets its own independent random noise.

  • The predator population has its own random flu season.
  • The prey population has its own random food shortage.

In code, du and u are vectors. The solver assumes that if u has 2 elements, there are 2 independent Wiener processes (dW1,dW2dW_1, dW_2). The diffusion function g calculates how dW1dW_1 affects u1u_1 and how dW2dW_2 affects u2u_2.

Non-Diagonal Noise (The Correlations)

What if one random event affects both variables?

  • A forest fire (one random event) kills both Predators and Prey.

This means the noise terms are mixed. To handle this, your diffusion function g needs to output a Matrix, not a Vector.

Practical Rule: DifferentialEquations.jl assumes Diagonal Noise by default (where the output of g matches the shape of u). If you need Non-Diagonal noise (correlations), you must explicitly define a noise_rate_prototype matrix.

For 90% of basic use cases (and this guide), we stick to Diagonal Noise. It is computationally cheaper and easier to reason about.


4. Simulating, Solving, and Visualizing Stochastic Trajectories

Solving an SDE is not like solving an ODE. Because there is randomness, one solution is just one possible reality.

If you run the code below once, you get one path. If you run it again, you get a completely different path.

Solving a Single Path

julia
# SOSRI is a strong, stable solver for SDEs
sol = solve(prob, SOSRI()) 

plot(sol, title="Stock Price (One Possible Reality)", label="Trajectory")

The Monte Carlo Simulation (Ensemble Problems)

In the industry, nobody cares about one simulation. They care about the probability distribution. We need to simulate the universe 1,000 times to see the average outcome and the "worst-case scenario."

We use EnsembleProblem for this. It is highly optimized in Julia to run in parallel.

julia
# 1. Wrap the SDE problem in an EnsembleProblem
ensemble_prob = EnsembleProblem(prob)

# 2. Solve it 100 times
# trajectories=100 : How many universes we simulate
sim = solve(ensemble_prob, SOSRI(), trajectories=100)

# 3. Visualize the "Spaghetti Plot"
plot(sim, linealpha=0.4, title="100 Possible Futures")

What just happened?

  1. We created a "multiverse" wrapper.
  2. We solved the SDE 100 times.
  3. We plotted all of them with low opacity (linealpha).

The resulting graph usually looks like a bundle of spaghetti. The dense center is the "likely" outcome, and the stray lines at the top and bottom represent the outliers (tail risks).

Analyzing the Results

You can now calculate statistics on your simulation sim.

julia
using Statistics

# Get the final value of the 5th simulation
val = sim[5][end] 

# Calculate the mean of all simulations at the final time point
final_values = [s[end][1] for s in sim]
mean_outcome = mean(final_values)

println("Average expected price: $mean_outcome")

Summary

  1. SDEs = Drift (Logic) + Diffusion (Noise).
  2. Define f(du,u,p,t) and g(du,u,p,t).
  3. Use SDEProblem.
  4. Diagonal noise is the default (noise per variable).
  5. Ensemble simulations are mandatory for meaningful SDE analysis. Don't trust a single run!

References & Further Reading

Challenge

Challenge: Modeling Stock Price with Geometric Brownian Motion

Your task is to model the price of a single stock over one year using the Geometric Brownian Motion (GBM) model and prepare it for a Monte Carlo simulation. The Stochastic Differential Equation for GBM is given by:

dS = μS dt + σS dW

Where:

  • S is the stock price.
  • μ is the drift (expected return).
  • σ is the volatility.
  • W is a Wiener Process.

Using the provided initial parameters and variables in the editor, complete the following steps:

  1. Define the in-place drift function, gbm_drift!, which corresponds to the μS term of the equation.
  2. Define the in-place diffusion function, gbm_diffusion!, which corresponds to the σS term.
  3. Construct an SDEProblem named sde_prob using your drift and diffusion functions, the initial condition, time span, and parameters.
  4. Create an EnsembleProblem named ensemble_prob based on your sde_prob to run 500 trajectories.

Expected result

Your final code should correctly define the two functions and the two problem types. A correct solution will have:

  1. A gbm_drift! function that correctly calculates μ * u and assigns it to du using the in-place form du[1] = ....
  2. A gbm_diffusion! function that correctly calculates σ * u and assigns it to du using the in-place form du[1] = ....
  3. An SDEProblem instance named sde_prob that is correctly constructed with gbm_drift!, gbm_diffusion!, the initial condition u0, the tspan, and the parameters p.
  4. An EnsembleProblem instance named ensemble_prob that takes sde_prob as its first argument and includes the keyword argument trajectories=500.
julia

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.