Updated: Apr 12, 2026
| 12 min

The Random Walk: From Coin Flips to Stochastic Calculus

Discover how a simple coin flip evolves into the mathematics powering modern derivative pricing. From Binomial Trees to the Wiener Process and the Heat Equation; we handle all in Python.

Banner for the "Finding P values and false hope" series

Have you ever looked at a stock chart and thought it looked like the erratic path of a confused traveller? You are not far off. In quantitative finance, we use a concept called the Random Walk to model how prices move.

While financial markets can feel like pure noise, there is a deep, elegant mathematical structure beneath the surface. This post explores how a simple coin flip evolves into the complex calculus used by Wall Street to price risk. Specifically, we will trace a single thread: starting from a discrete Binomial Tree, letting the time steps shrink toward zero, and discovering that the result is the same equation physicists use to describe heat diffusing through a metal rod.

The Simplest Market: The Binomial Tree

Imagine a stock price that moves up or down by a fixed amount σ\sigma over a tiny interval of time hh.

At the start (t=0)(t=0), the price is S0S_{0}. After one step, there is a 50/50 chance it moves either up or down, landing at either S0+σS_{0} + \sigma or S0σS_{0} - \sigma. But as time goes on, something interesting happens. By the second step, there are four possible paths, but only three possible prices. Two of those paths lead right back to where you started (S0)(S_{0}), while only one path leads to the extreme high and one to the extreme low.

As we add more steps, the “middle” outcomes become much more likely than the extremes. This is the Binomial Distribution in action. We can track this using a probability function P(k,n)P(k, n), where kk is the number of net steps taken after nn intervals:

P(l,n)=(nl)(12)nP(l, n) = \binom{n}{l} \left(\frac{1}{2}\right)^n

where ll is the number of “up” steps and k=2lnk = 2l - n is the net displacement.

To understand the Binomial Tree, it helps to visualise it as a branching path, with each node representing a possible price at a specific point in time. The following Python script simulates a 10-step binomial tree. Instead of just calculating the final price, it tracks the probability distribution. Notice that as we move further into the future, the distribution of possible prices begins to resemble a Normal Distribution which is a preview of what is to come.

import numpy as np
import matplotlib.pyplot as plt
from scipy.special import comb

def binomial_tree_dist(S0, sigma, steps):
    """
    S0: Initial Stock Price
    sigma: Size of the price move
    steps: Number of time steps (n)
    """
    prices = []
    probabilities = []
    
    # After 'n' steps, there are n+1 possible price outcomes
    for l in range(steps + 1):
        # Calculate the net steps k = (number of ups) - (number of downs)
        # From the text: k = 2l - n
        k = 2 * l - steps
        
        # Final price: S = S0 + k * sigma
        S_final = S0 + k * sigma
        
        # Probability using the Binomial Theorem formula:
        # P(l, n) = (n! / (l!(n-l)!)) * (0.5)^n
        prob = comb(steps, l) * (0.5**steps)
        
        prices.append(S_final)
        probabilities.append(prob)
        
    return prices, probabilities

# Parameters
S0 = 100      # Starting Price
sigma = 2     # Step size
n_steps = 10  # Number of intervals

prices, probs = binomial_tree_dist(S0, sigma, n_steps)

# Plotting the results
plt.figure(figsize=(10, 6))
plt.bar(prices, probs, color='skyblue', edgecolor='navy', width=1.5)
plt.title(f"Probability Distribution After {n_steps} Steps")
plt.xlabel("Stock Price (S)")
plt.ylabel("Probability P(S, t)")
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()

The chart confirms that extreme outcomes (prices far from S0S_0) are vanishingly rare, while prices near the starting point are overwhelmingly likely. The distribution is already bell-shaped after just ten steps. This is not a coincidence, the Central Limit Theorem guarantees it.

From Discrete Steps to “The Flow”

What happens if we make those time steps hh smaller and smaller? Imagine the stock price ticking every millisecond, then every microsecond.

When we shrink these steps toward zero, the math shifts from simple counting to Partial Differential Equations (PDEs). By applying a Taylor series expansion to our probability model, we discover that the way a stock’s probability “spreads out” over time follows the exact same equation as heat moving through a metal rod; the Heat Equation:

Pt=σ222Px2\frac{\partial P}{\partial t} = \frac{\sigma^2}{2} \frac{\partial^2 P}{\partial x^2}

In this equation:

  • P(x,t)P(x,t) is the probability density of the stock being at position xx at time tt.
  • Pt\frac{\partial P}{\partial t} represents how the probability at a specific point changes over time.
  • 2Px2\frac{\partial^2 P}{\partial x^2} represents the curvature (concavity) of the probability distribution across space.
  • σ2\sigma^2 is the variance rate, which determines how fast the “diffusion” or spreading occurs.

In physics, this equation describes how smoke fills a room. In finance, it describes how uncertainty grows over time. The solution to this equation is the Gaussian (Normal Distribution), which confirms mathematically what we observed visually in the Binomial Tree chart above.

In a discrete model like a Binomial Tree, the stock price is “trapped” in specific time buckets hh and specific price levels σ\sigma. But in the real world, time does not just tick — it flows. When we take the continuous-time limit (letting h0h \to 0), three things happen simultaneously:

  1. Price jumps become microscopic: Instead of big leaps of size σ\sigma, the price “diffuses” smoothly.
  2. The Binomial becomes the Normal: The discrete probability of being at a certain “step” transforms into a continuous Probability Density Function.
  3. Difference equations become Differential equations: Instead of computing P(k,n+1)P(k,n+1) from P(k,n)P(k,n), we track the rate of change P/t\partial P / \partial t.

This is exactly how heat moves through a metal rod. If you heat one end, the “temperature” (the probability density) spreads out over time. In finance, the “heat source” is the starting stock price, and as time passes, the “warmth” (the cloud of possible prices), spreads out according to the volatility σ\sigma.

In the earlier Python example, we calculated specific probabilities at discrete price levels. In the “Flow” example below, we simulate a single path of Geometric Brownian Motion (GBM). We are not just looking at the final destination; we are looking at the continuous journey itself.

import numpy as np
import matplotlib.pyplot as plt

# Parameters
S0 = 100      # Initial price
T = 1.0       # Total time (1 year)
mu = 0.05     # Drift (average annual return)
sigma = 0.2   # Volatility (the "diffusion" constant)
steps = 252   # Trading days (making h = 1/252)
dt = T / steps

# 1. THE DISCRETE STEP (Random Walk)
# We generate random "shocks" from a normal distribution.
# This represents the limit of the binomial tree's coin flips.
np.random.seed(42)
shocks = np.random.normal(0, np.sqrt(dt), steps)

# 2. THE FLOW (Integration)
# We accumulate these shocks over time to build the price path.
path = [S0]
for z in shocks:
    # Change in price = Price * (Expected Return + Randomness)
    # This is the discretized version of a Stochastic Differential Equation (SDE):
    # dS = S * (mu*dt + sigma*dW)
    dS = path[-1] * (mu * dt + sigma * z)
    path.append(path[-1] + dS)

# Plotting the "Flow"
plt.figure(figsize=(10, 5))
plt.plot(path, label="Stock Price Path (The Flow)")
plt.axhline(S0, color='red', linestyle='--', alpha=0.5, label="Starting Price")
plt.title("Continuous Stock Price Simulation (Geometric Brownian Motion)")
plt.xlabel("Time Steps (h)")
plt.ylabel("Price (S)")
plt.legend()
plt.show()

Analysing both the code and the result, we can draw three key observations:

  • The Shock (z)(z): In the binomial tree, this was a hard +1+1 or 1-1. Here, it is a draw from N(0,dt)N(0, dt). This is the Wiener Process increment, the mathematical formalisation of a “random nudge.”
  • The Diffusion: Notice how the path is jagged but continuous. It does not teleport between prices; each step is infinitesimally small.
  • The Drift: The mu * dt term adds a small, consistent upward push at each step (representing the expected return), which is why the path trends upward over the year. If you set mu = 0, the path would have no directional bias.

If you ran this simulation 10,000 times and plotted where the paths ended, you would recover the exact Bell Curve predicted by the Heat Equation. The connection is exact, not approximate.

Enter the Wiener Process

The limit of this “infinite coin flipping” is what mathematicians call a Wiener Process (or Standard Brownian Motion). It is the fundamental building block of modern continuous-time finance, and the object that makes Black-Scholes possible.

To understand the Wiener Process, you have to stop thinking about a “tree” with fixed branches and start thinking about a “cloud” of infinite possibilities. While a binomial tree says “the price can be here or there,” the Wiener Process says “the price can be anywhere on a continuous spectrum,” but with a very specific probability of landing in certain spots.

A stochastic process W(t)W(t) is a Wiener process if it satisfies three defining properties:

  1. The Anchor (W(0)=0)(W(0) = 0): It always starts at zero. In finance, we typically write S(t)=S0+σW(t)S(t) = S_0 + \sigma W(t) to shift it to a starting price S0S_0.

  2. Stationary and Normal Increments: The change over any time interval (ts)(t - s) is normally distributed. Specifically:

    W(t)W(s)N(0, ts)W(t) - W(s) \sim \mathcal{N}(0,\ t - s)

    This is the “magic” of the process: the variance of the move equals the length of time that has passed. Wait twice as long, and the uncertainty (variance) doubles. This σ2t\sigma^2 \propto t relationship is the fingerprint of diffusion.

  3. Independence of the Past: The move from t=2t = 2 to t=3t = 3 is completely independent of what happened from t=1t = 1 to t=2t = 2. The process has no “memory.” This is called the Markov property and is what makes the math tractable.

The Python script below visualises the “Cloud” of uncertainty. It does not simulate just one path; it simulates 1,000 different futures for the same starting point. This lets us observe diffusion in real time.

import numpy as np
import matplotlib.pyplot as plt

# Parameters
T = 1.0             # Total time (e.g., 1 year)
N = 500             # Number of time steps
dt = T / N          # Size of each tiny time increment
n_simulations = 1000 # Number of random paths to simulate

# Create a time axis
t = np.linspace(0, T, N)

# Generate increments: dW = Z * sqrt(dt), where Z ~ N(0,1)
# We generate all random shocks at once for efficiency.
shocks = np.random.normal(0, np.sqrt(dt), size=(n_simulations, N))

# Calculate the Wiener Process paths (Cumulative sum of shocks)
# axis=1 sums across the time steps for each simulation
W = np.cumsum(shocks, axis=1)

# Plotting the "Cloud"
plt.figure(figsize=(12, 6))
for i in range(100):  # Plot first 100 paths for clarity
    plt.plot(t, W[i, :], lw=0.5, alpha=0.3, color='blue')

# Plot the theoretical "Spread" (2 Standard Deviation lines)
# Since Var[W(t)] = t, the std dev at time t is sqrt(t)
plt.plot(t, 2 * np.sqrt(t), color='red', ls='--', label='±2 Standard Deviations (95% band)')
plt.plot(t, -2 * np.sqrt(t), color='red', ls='--')

plt.title("The Wiener Process: 1,000 Possible Futures")
plt.xlabel("Time (t)")
plt.ylabel("W(t)")
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

The interactive chart above shows the 2σ upper boundary of the Wiener Process (2t2\sqrt{t}). This growing curve is the mathematical shape of the “cone of uncertainty”: 95% of all paths will remain within this band at any given time. Three observations are worth dwelling on:

  • The Cone of Uncertainty: The red dashed lines grow proportionally to t\sqrt{t}, not linearly. Uncertainty does not scale with time — it scales with the square root of time. Doubling the forecast horizon widens the cone by only a factor of 21.41\sqrt{2} \approx 1.41.
  • Infinite Jaggedness: If you were to “zoom in” on any part of the individual blue paths, they would look just as jagged as the whole. This property is called self-similarity, and it means the Wiener Process is continuous everywhere but differentiable nowhere. The traditional notion of “velocity” (dW/dtdW/dt) does not exist.
  • No Mean Reversion: Even though the average of all 1,000 paths is zero, any individual path can drift very far and stay there indefinitely. The process has no pull back to the centre; it only responds to the next random shock.

This “cloud” of paths is precisely how quantitative analysts run Monte Carlo simulations to price insurance contracts, stock options, and structured products. If the current price is S0S_0, they model S(t)=S0+σW(t)S(t) = S_0 + \sigma W(t) and average the payoff across thousands of simulated futures.

Why Does It Matter?

The chain we have built is not just mathematical elegance (Binomial Tree → Heat Equation → Wiener Process). It is the load-bearing structure beneath trillions of dollars of financial contracts.

If we assume stock prices follow this kind of “diffusion,” we can calculate the exact probability of a price reaching a given level by a given date. This is the core insight that Fischer Black, Myron Scholes, and Robert Merton exploited in 1973 to derive the Black-Scholes equation, which won the Nobel Prize and transformed global options markets overnight.

More practically, every tool we have built in this series relies on this foundation:

  • The stock return distribution from Chapter 5 is the fingerprint of Geometric Brownian Motion.
  • The Monte Carlo paths used in VaR (Chapter 8) are just Wiener Process trajectories.
  • The option pricing formulas explored in Chapter 7 are closed-form solutions to the Heat Equation with appropriate boundary conditions.

The next time you see a jagged line on a trading screen, remember: you are not just looking at prices, you are watching a physical process of information diffusing through the world, governed by the same laws that move heat through a room. The randomness is not the noise obscuring some deeper signal; in quantitative finance, the randomness is the signal.

⚠️ Financial Education Disclaimer

The models and Python code provided in this post (including Geometric Brownian Motion and the Wiener Process) are for educational and research purposes only.

  • Not Financial Advice: This content does not constitute professional financial or investment advice.
  • Model Limitations: Real-world stock prices exhibit “Fat Tails,” volatility clustering, and jumps that are not captured by standard Brownian Motion. GBM is a useful approximation, not a complete description of reality.
  • Risk Warning: Trading financial instruments involves the risk of significant capital loss. Always consult a qualified financial professional before making investment decisions.