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:
Here is the breakdown:
- : This is the Drift. It’s the deterministic part (the ODE part) that tells the system where it should go.
- : This is the Diffusion. It’s the noise scaling.
- : 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
- Drift function (
f): Describes the system's logic. - 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).
Here, is growth rate, and is volatility.
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 (). The diffusion function g calculates how affects and how affects .
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.jlassumes Diagonal Noise by default (where the output ofgmatches the shape ofu). If you need Non-Diagonal noise (correlations), you must explicitly define anoise_rate_prototypematrix.
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
# 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.
# 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?
- We created a "multiverse" wrapper.
- We solved the SDE 100 times.
- 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.
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
- SDEs = Drift (Logic) + Diffusion (Noise).
- Define
f(du,u,p,t)andg(du,u,p,t). - Use
SDEProblem. - Diagonal noise is the default (noise per variable).
- 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:
Sis the stock price.μis the drift (expected return).σis the volatility.Wis a Wiener Process.
Using the provided initial parameters and variables in the editor, complete the following steps:
- Define the in-place drift function,
gbm_drift!, which corresponds to theμSterm of the equation. - Define the in-place diffusion function,
gbm_diffusion!, which corresponds to theσSterm. - Construct an
SDEProblemnamedsde_probusing your drift and diffusion functions, the initial condition, time span, and parameters. - Create an
EnsembleProblemnamedensemble_probbased on yoursde_probto run 500 trajectories.
Expected result
Your final code should correctly define the two functions and the two problem types. A correct solution will have:
- A
gbm_drift!function that correctly calculatesμ * uand assigns it toduusing the in-place formdu[1] = .... - A
gbm_diffusion!function that correctly calculatesσ * uand assigns it toduusing the in-place formdu[1] = .... - An
SDEProbleminstance namedsde_probthat is correctly constructed withgbm_drift!,gbm_diffusion!, the initial conditionu0, thetspan, and the parametersp. - An
EnsembleProbleminstance namedensemble_probthat takessde_probas its first argument and includes the keyword argumenttrajectories=500.