Sign in

Stochastic processes

Random quantities that evolve in time or over an input: random walks, Brownian motion and its relatives, and Gaussian processes.

Overview

A stochastic process is a whole collection of random variables, one for each time or input, tied together by rules about how they relate. The simplest is a random walk: start at zero and add a random step at each tick. Shrink the steps and speed up the clock in the right proportion and you get Brownian motion, a continuous jittery path. Variations add a trend, keep the path positive, or pull it back toward a mean. A Gaussian process takes a different view. It puts a probability distribution on functions themselves, by saying how strongly the values at any two inputs move together, and that lets you fit a curve to data with error bars.

A short history

Robert Brown described the irregular motion of particles in water in 1827. Louis Bachelier modelled stock prices as a random motion in his 1900 thesis, Albert Einstein explained Brownian motion physically in 1905, and Norbert Wiener gave it a rigorous mathematical construction in 1923. Gaussian processes entered prediction through kriging in mining geology in the 1950s and 1960s, and became a common machine learning tool in the 2000s.

How it works

  1. Random walk: start at a value and repeatedly add +s+s with probability pp or −s-s otherwise. The position is the running sum of the steps.
  2. Brownian motion: replace each step by an independent normal draw with mean μ Δt\mu\,\Delta t and variance σ2 Δt\sigma^{2}\,\Delta t, and accumulate.
  3. Geometric Brownian motion: simulate Brownian motion for the logarithm and exponentiate, which keeps the path positive.
  4. Ornstein-Uhlenbeck process: at each step move a fixed fraction of the way back toward a long-run mean, then add noise.
  5. Gaussian process prior: choose a kernel that gives the covariance between function values at any two inputs, build the covariance matrix and draw a correlated normal vector.
  6. Gaussian process posterior: condition that joint normal distribution on observed points to get a predicted mean and covariance at new inputs.

Watch out for

  • The spread of a random walk or Brownian motion grows without bound, like t\sqrt{t}. One path wandering far from zero is expected, not a sign of a trend.
  • Brownian increments scale with Δt\sqrt{\Delta t}, not Δt\Delta t. Scaling the noise by Δt\Delta t is a common bug that makes paths far too smooth.
  • The average of geometric Brownian motion grows at rate μ\mu, but a typical path grows at μ−σ2/2\mu - \sigma^{2}/2. With high volatility most paths can fall while the average rises.
  • Exact Gaussian process regression factorizes an n×nn \times n matrix, which costs on the order of n3n^{3} operations. It is impractical beyond a few thousand training points without approximations.
  • Kernel matrices are often close to singular. The jitter added to the diagonal makes the factorization succeed, and too little of it produces errors or noisy output.

Use cases

When to use it

Modelling noise that accumulates over time (prices, sensor drift, diffusion), building the forward process of diffusion models, and doing regression with calibrated uncertainty on small data sets.

In industry

Finance
The Black-Scholes option pricing model assumes the share price follows geometric Brownian motion.
Mining and geoscience
Kriging, which is Gaussian process regression, estimates ore grade or pollutant levels between drill holes and reports the uncertainty.
Machine learning
Bayesian optimisation uses a Gaussian process as a surrogate for an expensive function when tuning hyperparameters.
Physics and biology
Diffusion of molecules and animal movement paths are modelled as random walks and Brownian motion.

Choosing it: what must hold

  • A quantity indexed by time or by an input, where values at nearby indices are related.
  • A stated dependence structure: independent increments for a walk, or a covariance function for a Gaussian process.
  • For Gaussian process regression, a small or medium data set, because exact fitting cost grows with the cube of the number of points.

When to choose something else

IfUse instead
States are a finite set with fixed transition probabilitiesMarkov chains
You have a regularly sampled series with trend and seasonality to forecastTime series analysis
The data set is too large for an exact Gaussian processA sparse Gaussian process, or a tree or neural model

Math foundations

  1. Simple random walk

    Sn=∑i=1nξi,E[Sn]=n s (2p−1),Var⁡(Sn)=4 n s2 p (1−p)S_n = \sum_{i=1}^{n} \xi_i, \qquad \mathbb{E}[S_n] = n\,s\,(2p - 1), \qquad \operatorname{Var}(S_n) = 4\,n\,s^{2}\,p\,(1 - p)

    Each step ξi\xi_i is +s+s with probability pp and −s-s otherwise. Means and variances of independent steps add, so the standard deviation grows like n\sqrt{n}.

  2. Brownian motion with drift

    Xt+Δt−Xt∼N(μ Δt, σ2 Δt)X_{t + \Delta t} - X_t \sim \mathcal{N}\big(\mu\,\Delta t,\ \sigma^{2}\,\Delta t\big)

    Increments over separate time intervals are independent and normal. The variance, not the standard deviation, is proportional to elapsed time. This is the limit of a random walk with many tiny steps.

  3. Geometric Brownian motion

    St=S0exp⁡ ⁣((μ−12σ2) t+σWt),E[St]=S0 eμtS_t = S_0 \exp\!\Big(\big(\mu - \tfrac{1}{2}\sigma^{2}\big)\,t + \sigma W_t\Big), \qquad \mathbb{E}[S_t] = S_0\,e^{\mu t}

    The logarithm of StS_t is a Brownian motion, so StS_t stays positive and changes by random percentages. The correction −σ2/2-\sigma^{2}/2 is what makes the mean grow at exactly rate μ\mu.

  4. Ornstein-Uhlenbeck process

    Xt+Δt=m+(Xt−m) e−θΔt+σ1−e−2θΔt2θ ε,ε∼N(0,1)X_{t + \Delta t} = m + (X_t - m)\,e^{-\theta \Delta t} + \sigma \sqrt{\frac{1 - e^{-2\theta \Delta t}}{2\theta}}\ \varepsilon, \qquad \varepsilon \sim \mathcal{N}(0, 1)

    The exact one-step rule for the mean-reverting equation dX=θ(m−X) dt+σ dWdX = \theta(m - X)\,dt + \sigma\,dW. The gap to the mean decays by a fixed factor each step, and in the long run XX is normal with mean mm and variance σ2/(2θ)\sigma^{2}/(2\theta).

  5. RBF kernel

    k(x,x′)=σf2exp⁡ ⁣(−∥x−x′∥22 ℓ2)k(x, x') = \sigma_f^{2} \exp\!\left(-\frac{\lVert x - x' \rVert^{2}}{2\,\ell^{2}}\right)

    The covariance between function values at two inputs. Nearby inputs have almost the same value, and inputs further apart than a few length scales are almost unrelated. A Gaussian process is defined by saying that any finite set of function values is jointly normal with this covariance.

  6. Gaussian process posterior

    fˉ∗=K∗ (K+σn2I)−1y,Σ∗=K∗∗−K∗ (K+σn2I)−1K∗⊤\bar{f}_{*} = K_{*}\,\big(K + \sigma_n^{2} I\big)^{-1} y, \qquad \Sigma_{*} = K_{**} - K_{*}\,\big(K + \sigma_n^{2} I\big)^{-1} K_{*}^{\top}

    Conditioning a joint normal on the observed values. The mean is a weighted combination of the training targets, and the covariance is the prior covariance minus what the data explained. The template computes both with a Cholesky factorization.

Symbols

SnS_n
the position of the random walk after nn steps
s, ps,\ p
the step size and the probability of a step up
Xt, StX_t,\ S_t
the value of a continuous-time process at time tt
Δt\Delta t
the time between two simulated points (dt in the config)
μ, σ\mu,\ \sigma
the drift and the volatility
WtW_t
standard Brownian motion: zero drift and unit volatility
θ, m\theta,\ m
the speed of mean reversion and the long-run mean
k(x,x′)k(x, x')
the kernel: covariance between function values at xx and x′x'
ℓ, σf2\ell,\ \sigma_f^{2}
the kernel length scale and signal variance
KK
the kernel matrix between training inputs
K∗, K∗∗K_{*},\ K_{**}
the kernel matrices between test and training inputs, and among test inputs
yy
the observed training targets
σn2\sigma_n^{2}
the variance of the observation noise
fˉ∗, Σ∗\bar{f}_{*},\ \Sigma_{*}
the posterior mean and covariance at the test inputs

Worked by hand

First take a symmetric random walk with p=0.5p = 0.5 and step s=1s = 1 after n=100n = 100 steps. Then take standard Brownian motion (μ=0\mu = 0, σ=1\sigma = 1) with the default Δt=0.01\Delta t = 0.01 after 1000 steps, which is time t=10t = 10.

E[S100]=100×1×(2×0.5−1)=0\mathbb{E}[S_{100}] = 100 \times 1 \times (2 \times 0.5 - 1) = 0
Var⁡(S100)=4×100×12×0.5×0.5=100,sd⁡=10\operatorname{Var}(S_{100}) = 4 \times 100 \times 1^{2} \times 0.5 \times 0.5 = 100, \qquad \operatorname{sd} = 10
Var⁡(X10)=σ2 t=1×10=10,sd⁡=10≈3.16\operatorname{Var}(X_{10}) = \sigma^{2}\,t = 1 \times 10 = 10, \qquad \operatorname{sd} = \sqrt{10} \approx 3.16

After 100 fair steps the walk is typically about 10 away from the start, not 100 and not 0. The Brownian path at time 10 is typically about 3.2 away. In both cases the spread grows with the square root of elapsed time.

Visual example

Loading the example.

Try this

  • Press Draw again a few times on the random walk: the paths change, the band does not.
  • Switch to Brownian motion and give it a drift of 0.5. Watch the centre line outrun the widening band.
  • Choose Ornstein-Uhlenbeck and raise θ: the paths fall from 3 to the long run mean faster and the band levels off sooner.

Code sample

import numpy as np
from impl import StochasticProcesses
from config import StochasticProcessesConfig

sp = StochasticProcesses(StochasticProcessesConfig(n_steps=250, n_paths=1000, dt=1 / 250))
w = sp.brownian_motion()                       # (1000, 251); w[:, -1] has variance 1 (one unit of time)
s = sp.geometric_brownian_motion(start=100.0, drift=0.05, volatility=0.2)   # mean of s[:, -1] is 100 e^0.05

x = np.array([0.0, 1.0, 2.0])
mean, cov = sp.gp_posterior(x, np.sin(x), np.linspace(0, 2, 5))   # passes through the three points
Read the implementation (120 lines)
"""Stochastic processes: random walks, Brownian motion and relatives, Gaussian processes.

Simulators return whole paths as arrays (n_paths, n_steps + 1). Brownian motion, geometric Brownian motion and
the Ornstein-Uhlenbeck process are sampled from their exact transition laws, so the step size does not bias
them. The Gaussian process part draws functions from an RBF prior and computes the exact posterior given data.
"""
from __future__ import annotations

import math

import numpy as np

try:
    from .config import StochasticProcessesConfig
except ImportError:  # run from the template's own folder
    from config import StochasticProcessesConfig

class StochasticProcesses:
    """Path simulators and Gaussian process tools sharing one seeded generator (`self.rng`)."""

    def __init__(self, config: StochasticProcessesConfig | None = None) -> None:
        self.config = config or StochasticProcessesConfig()
        self.rng = np.random.default_rng(self.config.seed)

    def times(self) -> np.ndarray:
        """Time of every path point: 0, dt, 2 dt, ..., array (n_steps + 1,)."""
        return np.arange(self.config.n_steps + 1) * self.config.dt

    def _shape(self) -> tuple[int, int]:
        return self.config.n_paths, self.config.n_steps

    @staticmethod
    def _from_increments(increments: np.ndarray, start: float) -> np.ndarray:
        zeros = np.zeros((increments.shape[0], 1))
        return start + np.concatenate([zeros, np.cumsum(increments, axis=1)], axis=1)

    def random_walk(self, p_up: float = 0.5, step: float = 1.0, start: float = 0.0) -> np.ndarray:
        """Simple random walk: each step is +step with probability p_up, else -step.

        Returns array (n_paths, n_steps + 1). After n steps the mean is n step (2 p_up - 1) and the variance
        is 4 n step^2 p_up (1 - p_up).
        """
        if not 0 <= p_up <= 1:
            raise ValueError("p_up must lie in [0, 1]")
        moves = np.where(self.rng.random(self._shape()) < p_up, step, -step)
        return self._from_increments(moves, start)

    def brownian_motion(self, drift: float = 0.0, volatility: float = 1.0, start: float = 0.0) -> np.ndarray:
        """Brownian motion with drift: X_t = start + drift t + volatility W_t.

        Returns array (n_paths, n_steps + 1). Increments over dt are independent N(drift dt, volatility^2 dt).
        """
        dt = self.config.dt
        increments = drift * dt + volatility * math.sqrt(dt) * self.rng.normal(size=self._shape())
        return self._from_increments(increments, start)

    def geometric_brownian_motion(self, start: float = 1.0, drift: float = 0.0, volatility: float = 0.2) -> np.ndarray:
        """Geometric Brownian motion S_t = start exp((drift - volatility^2 / 2) t + volatility W_t).

        Always positive, with E[S_t] = start exp(drift t). Returns array (n_paths, n_steps + 1).
        """
        if start <= 0:
            raise ValueError("start must be positive")
        log_paths = self.brownian_motion(drift - 0.5 * volatility**2, volatility)
        return start * np.exp(log_paths)

    def ornstein_uhlenbeck(self, theta: float = 1.0, mean: float = 0.0, volatility: float = 1.0,
                           start: float = 0.0) -> np.ndarray:
        """Mean-reverting process dX = theta (mean - X) dt + volatility dW, sampled exactly.

        theta > 0 is the speed of reversion. The stationary distribution is N(mean, volatility^2 / (2 theta)).
        Returns array (n_paths, n_steps + 1).
        """
        if theta <= 0:
            raise ValueError("theta must be positive")
        decay = math.exp(-theta * self.config.dt)
        noise_std = volatility * math.sqrt((1.0 - decay**2) / (2.0 * theta))
        noise = noise_std * self.rng.normal(size=self._shape())
        paths = np.empty((self.config.n_paths, self.config.n_steps + 1))
        paths[:, 0] = start
        for t in range(self.config.n_steps):
            paths[:, t + 1] = mean + (paths[:, t] - mean) * decay + noise[:, t]
        return paths

    def poisson_process(self, rate: float = 1.0) -> np.ndarray:
        """Counting process N_t with independent Poisson(rate dt) increments. Returns array (n_paths, n_steps + 1)."""
        if rate <= 0:
            raise ValueError("rate must be positive")
        return self._from_increments(self.rng.poisson(rate * self.config.dt, size=self._shape()).astype(float), 0.0)

    def rbf_kernel(self, xa, xb) -> np.ndarray:
        """Squared-exponential kernel k(a, b) = signal_variance exp(-|a - b|^2 / (2 length_scale^2)).

        xa: array (n,) or (n, d); xb: array (m,) or (m, d). Returns array (n, m).
        """
        xa = np.asarray(xa, dtype=float).reshape(len(xa), -1)
        xb = np.asarray(xb, dtype=float).reshape(len(xb), -1)
        sq = (xa**2).sum(axis=1)[:, None] + (xb**2).sum(axis=1)[None, :] - 2.0 * xa @ xb.T
        return self.config.signal_variance * np.exp(-0.5 * np.maximum(sq, 0.0) / self.config.length_scale**2)

    def gp_sample(self, x, n_samples: int = 1) -> np.ndarray:
        """Draw functions from the zero-mean Gaussian process prior at inputs x. Returns array (n_samples, n)."""
        K = self.rbf_kernel(x, x)
        L = np.linalg.cholesky(K + max(self.config.jitter, 1e-10) * self.config.signal_variance * np.eye(len(K)))
        return (L @ self.rng.normal(size=(len(K), n_samples))).T

    def gp_posterior(self, x_train, y_train, x_test, noise_variance: float = 0.0) -> tuple[np.ndarray, np.ndarray]:
        """Gaussian process regression: the distribution of f(x_test) given noisy observations of f.

        x_train: array (n,) or (n, d); y_train: array (n,); x_test: array (m,) or (m, d).
        noise_variance: variance of the observation noise on y_train.
        Returns (mean array (m,), covariance array (m, m)).
        """
        y = np.asarray(y_train, dtype=float).ravel()
        K = self.rbf_kernel(x_train, x_train) + (noise_variance + self.config.jitter) * np.eye(y.size)
        K_star = self.rbf_kernel(x_test, x_train)
        L = np.linalg.cholesky(K)
        alpha = np.linalg.solve(L.T, np.linalg.solve(L, y))
        v = np.linalg.solve(L, K_star.T)
        return K_star @ alpha, self.rbf_kernel(x_test, x_test) - v.T @ v
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Create StochasticProcesses with StochasticProcessesConfig(n_paths=2000, n_steps=1000). Call random_walk and brownian_motion and compare the variance of the final column with the formulas. Call ornstein_uhlenbeck(theta=2.0, start=5.0) and check the late-time variance against σ2/(2θ)\sigma^{2}/(2\theta). Then fit gp_posterior to five points of a sine curve and plot the mean with two standard deviations from the diagonal of the covariance.

Check on learning

  1. Halve the time step of a Brownian simulation. By what factor must the standard deviation of each increment change, and what goes wrong if you scale it by Δt\Delta t?
    A way to think about it

    Variances of independent increments add. Work out the total variance at a fixed time for both scalings as the step count doubles.

  2. For geometric Brownian motion with μ=0.05\mu = 0.05 and σ=0.5\sigma = 0.5, the mean grows but most paths shrink. How can both hold?
    A way to think about it

    Compare μ\mu with μ−σ2/2\mu - \sigma^{2}/2. A few very large paths can lift an average that the median path never reaches.

  3. What happens to draws from a Gaussian process prior when the length scale is made very small, and when it is made very large?
    A way to think about it

    The kernel decides how far apart two inputs can be and still agree. Consider the limits where no pair agrees and where every pair does.

  4. Away from all training points, what do the Gaussian process posterior mean and variance return to, and why is that sensible?
    A way to think about it

    Look at K∗K_{*} when the test input is many length scales from the data. With no nearby evidence the prior is all that is left.

  5. An Ornstein-Uhlenbeck path and a Brownian path look alike over a short window. Which measurement over a long window tells them apart?
    A way to think about it

    Track the variance across many paths as time grows. One keeps growing in proportion to time and the other levels off.