edgekit

Martingales & optional stopping

A martingale is a fair game made precise: given everything you know now, the expected next value is the current value. That single definition produces the most elegant machinery in probability — and some of the most useful in practice. The optional stopping theorem turns hard-looking questions (ruin probabilities, expected game lengths, waiting times for ABRACADABRA) into one-line equations; and its conditionsexplain, with full rigor, why no stop-loss, take-profit, or doubling scheme can conjure edge from a fair game. This chapter builds filtrations in plain language, proves optional stopping for bounded stopping times, solves gambler’s ruin both fair and biased, proves Wald’s identity, and walks the famous monkey-typing martingale.

Intuition — a fair game stays fair, no matter how cleverly you quit

Suppose each round of a game has zero expected profit. Can a clever exit rule— quit when ahead, double when behind, stop at the third loss — make the whole enterprise profitable? The optional stopping theorem says no, under conditions that amount to “you cannot wait forever and you cannot bet infinity.” Every apparent counterexample (the casino doubling system) works by violating exactly those conditions. For a trader the theorem is a null result of enormous value: if returns are a martingale, no overlay of stops and targets changes expectancy — so when a backtest improves after adding stops, the improvement came from non-martingale structure in the data (or from overfitting), never from the stop itself.

Filtrations, adaptedness, and the definition#

A filtration is simply the growing record of information: is everything observable by time (all coin flips so far, all prices so far). A process is adapted if is knowable at time — no peeking ahead. Then:

Replace with for a submartingale (favourable game, drifting up) and for a supermartingale (unfavourable — mnemonic: supermartingales are what casinos offer you). Iterating the definition and using the tower property (joint distributions) gives for every fixed — the content of optional stopping is extending this to random times.

The three examples that solve ninety percent of problems — all built from i.i.d. steps with :

  • The walk itself: if , then is a martingale: .
  • The compensated square: if additionally , then is a martingale — expand : the cross term dies by independence, the term contributes , cancelled by the compensator. This one measures time.
  • The exponential (Wald) martingale: for any where the MGF exists, is a martingale: . Choosing so that kills the denominator — the trick that cracks biased random walks below. Products of independent mean-one terms (e.g. gross return relatives of a zero-drift asset) are the same construction.

Worked check (by hand). Fair coin steps : , so is a martingale for every . For a biased walk with , , try : then , so

Quant lens — the martingale is the no-edge null

Weak-form market efficiency is the statement that (discounted) prices are a martingale with respect to the public filtration: , i.e. expected return conditional on the past is zero. Every systematic strategy is a claim that this fails for some computable conditioning — and every backtest evaluation implicitly tests against this null (stochastic processes, why backtests lie). The optional stopping theorem sharpens the null: under it, no entry rule, exit rule, stop, or target — however path-dependent — has positive expectancy. Edges must come from the conditional mean, never from the choreography around it. That is why entries, exits & stops treats stops as risk-shaping tools, not alpha sources.

Stopping times and the optional stopping theorem#

A stopping time is a random time whose arrival is decidable without foresight: for every . “First time the walk hits 10” is a stopping time; “the time the walk attains its eventual maximum” is not — you need the future to recognise it. (Most look-ahead bugs in backtests are, in this language, non-stopping-time exits.)

Proof — optional stopping for bounded stopping times

Suppose . Write the stopped value as a telescoping sum of increments taken only while the game is still running:

The crucial observation: — whether you are still playing at step was decided yesterday. So by the tower property,

and summing gives . Cases (b) and (c) follow by applying this to (always bounded) and passing to the limit — dominated convergence for (b), and for (c) the bound , integrable since . The proof is the trading statement: a stopped fair game is a sum of fair bets, each scaled by a decision made before the bet resolves.

!Counterexample — the doubling (martingale) betting system

Bet $1 on a fair coin; on each loss, double the stake; stop at the first win, . At you have lost and won : wealth , always. Yet is a martingale with — so . Which hypothesis failed? is finite a.s. and even — but the increments are unbounded (stakes double) and the stopped process is unbounded below: before the redeeming win you are down , which exceeds any credit line with positive probability. The “sure profit” is financed by an infinitely deep pocket that no one has; impose any finite bankroll and the rare wipeout exactly cancels the frequent small wins. Every martingale betting system, risk parity doubling grid, or “average down until saved” scheme dies on this same rock.

Gambler’s ruin — fair and biased, via optional stopping#

The canonical application. Start at (integer), take steps, stop at = first hit of (ruin) or (target). The stopped walk is bounded in and is a.s. finite with finite mean, so optional stopping applies in all uses below.

Derivation — fair case: hit probability and expected duration

Hit probability. is a martingale, so . But , so with :

Duration. Now stop the martingale : , and , so

Start in the middle of : even odds and steps — the product form means games starting near an edge end fast, games starting centred last quadratically long.

Derivation — biased case via the (q/p)^S martingale

Now , , . Stop the martingale : gives , so

For the duration, stop the drift-compensated martingale : , hence

Worked numbers. , , : , , , so and . A 1% per-bet edge against you turns a 50/50 doubling shot into 40/60 — and the effect compounds catastrophically with distance: with the same tiny bias gives (Problem 4). Small edges, iterated, are destiny — the martingale-side proof of the casino arithmetic in LLN & the CLT.

Simulated gambler's ruin paths between absorbing barriers at zero and N, with the probability of reaching the target shown collapsing as the per-step bias turns negative
Gambler's ruin: random-walk paths between an absorbing floor (ruin) and ceiling (target). In the fair game the hit probability is the starting fraction k/N; with even a 1% per-step disadvantage the doubling probability collapses — (q/p)^S is the martingale that quantifies exactly how fast.

Wald’s identity#

Optional stopping applied to the drift-compensated walk deserves its own name, because it answers “how long, on average?” questions in one line.

Proof — Wald's identity

Let be i.i.d. with , and a stopping time with . Then

Write . The event is decided by alone, hence independent of . Taking expectations term by term (Fubini, justified by ):

the last step being the tail-sum formula for expectations (random variables & moments).

Worked example. Roll a fair die until the running total first reaches at least 300. Wald: . The stopped total is 300 plus a small overshoot (renewal theory puts the average overshoot near ), so rolls. The quant reading of Wald: expected P&L of a stopped strategy = (edge per trade) × (expected number of trades). Zero edge in, zero expectation out — whatever the stopping rule; and with positive edge, the way to earn more is to make — time in the game — larger, not to choreograph exits.

The ballot problem#

Theorem (Bertrand). In an election where A receives votes and B receives votes, counted in uniformly random order,

Sketch. The count is a lattice path of s and s ending at . Paths that touch zero after the first step can be reflectedabout the axis up to their first zero, giving a bijection between “bad” paths starting with an A-vote and all paths starting with a B-vote; a short count then leaves the fraction never tied. With : only — even a landslide winner usually gets caught at least once. The reflection principle and its first-passage consequences are developed in random walks & Brownian motion; the martingale proof (via the backwards martingale ) is a beautiful second look.

ABRACADABRA — the monkey-typing martingale#

A monkey types i.i.d. uniform capital letters. What is the expected number of keystrokes until ABRACADABRA first appears? First-step recursions (Markov chains) work but drown in states. The martingale solution is one of the prettiest arguments in probability.

The betting-team argument, step by step

Just before each keystroke , a new gambler arrives with $1 and bets it on “the next letter is A.” Odds are fair (26-to-1 payout): winners hold $26 and let it ride on “next is B,” then “R,”… through the whole word; losers leave broke. Every individual bet is fair, so the team’s total wealth minus total stakes-paid-in is a martingale with bounded increments; the first-appearance time has finite mean, so optional stopping (condition c) applies: = .

Now count the wealth at the moment ABRACADABRA completes. The gambler who started 11 letters ago rode the full word: . But she is not alone — any newer gambler whose partial ride matches a suffix of ABRACADABRA that is also a prefix survives too. The overlaps of ABRACADABRA with itself are ABRA (length 4) and A (length 1): the gambler 4 letters in holds , the one 1 letter in holds . Everyone else is broke. Hence

The general rule: over all such that the length- prefix equals the length- suffix (including the full word). Self-overlap makes patterns slower to appear, because near-misses recycle progress for the pattern’s rivals, not for it — the same reason HH takes 6 fair-coin flips on average while HT takes only 4 (overlaps: vs ).

Azuma’s inequality is the concentration bound for martingales with bounded increments : — Hoeffding generalised to dependent-but-fair increments, and the rigorous form of “a zero-edge book with per-day risk limits cannot drift far” (tail bounds).

Sample paths of Brownian motion fanning out from zero with spread growing like the square root of time
Continuous-time martingale par excellence: Brownian motion. Both W_t and W_t^2 - t are martingales, so every discrete argument in this chapter — ruin probabilities via E[W_tau], durations via the compensated square — transfers verbatim to barrier-hitting problems for BM (see Problem 5).
ost_checks.py
import numpy as np

rng = np.random.default_rng(11)

def ruin(p, k, N, reps=20_000):
    """Simulate gambler's ruin: return (P(hit N first), E[steps])."""
    wins, steps = 0, 0
    for _ in range(reps):
        s, t = k, 0
        while 0 < s < N:
            s += 1 if rng.random() < p else -1
            t += 1
        wins += (s == N)
        steps += t
    return wins / reps, steps / reps

P, ET = ruin(0.50, k=10, N=20)
print(f"fair:   P(win)={P:.3f} (theory 0.500)   E[tau]={ET:.1f} (theory 100.0)")
P, ET = ruin(0.49, k=10, N=20)
print(f"biased: P(win)={P:.3f} (theory 0.401)   E[tau]={ET:.1f} (theory ~99)")

# Pattern waiting times: HH vs HT for a fair coin (overlap rule: 6 vs 4)
def wait(pattern, reps=100_000):
    total = 0
    for _ in range(reps):
        h, n = "", 0
        while not h.endswith(pattern):
            h += "HT"[rng.integers(2)]
            n += 1
        total += n
    return total / reps

print(f"E[wait HH] = {wait('HH'):.2f} (theory 6)   E[wait HT] = {wait('HT'):.2f} (theory 4)")

Practice problems#

Problem 1 — the $10 gambler

You have $10, your opponent has $90. You bet $1 on fair coin flips until someone is broke. What is the probability you win everything?

Solution. Your wealth is a martingale stopped at or (bounded, so optional stopping applies cleanly): , so — your bankroll fraction, full stop. The slick framing to say out loud: a fair game preserves expected wealth, so probabilities of the two endings mustbe proportional to the distances, whatever the bet size pattern. Escalation to expect: “what if you can choose bet sizes?” Answer: still 0.1 — any adapted betting scheme keeps wealth a martingale (bold play changes the duration, not the probability, in a fair game).

Problem 2 — how long does the game last?

Same setup: $10 vs $90, fair $1 bets. What is the expected number of bets until someone is broke?

Solution. Stop (unit-variance steps): bets. The product structure is the discrete backbone of “variance measures time” — the same identity that gives stopped Brownian motion its clock (Problem 5), and why a fair book’s lifetime scales with the product of the distances to its risk limits, not their sum.

Problem 3 — ABRACADABRA vs ABC

Monkey, uniform letters. Which appears sooner on average: ABC, or the same-length-11 word with no self-overlap, ABRACADABRZ — and how do both compare to ABRACADABRA?

Solution. By the betting-team argument, expected time = sum of over self-overlap lengths (full word included). ABC has no proper overlaps: . An 11-letter word with no self-overlap: . ABRACADABRA adds its ABRA and A overlaps: longer than the overlap-free word of the same length, by a tiny relative amount with a crisp reason: when ABRACADABRA fails at the final A, the failing attempt cannot double as progress toward a fresh attempt, whereas its dangling ABRA-prefix survivors were counted as extra wealth the team must be paid for. The fair-coin miniature to quote: HH takes 6 flips, HT takes 4, even though both are 2-flip patterns with probability per placement.

Problem 4 — doubling a bankroll at a 1% disadvantage

You start with 100 units and bet 1 unit per round at win probability . What is the probability you reach 200 before 0?

Solution. Stop the martingale with :

Against the fair-game answer of 50%: a 1% per-bet edge deficit destroys 96% of your doubling chances, because the exponent compounds the bias over the whole distance — . Points to volunteer: betting bigger helps when the odds are against you (10-unit bets make this the problem: ) — minimising the number of times the house edge taxes you; and symmetrically, when you have the edge, small bets and long games make winning nearly certain. That is bankroll management in one martingale, and the bridge to position sizing and the Kelly criterion.

Problem 5 — Brownian motion hitting 1 before −2

is standard Brownian motion started at 0; is the first time it hits or . Find and .

Solution. Both discrete arguments transfer verbatim. is a martingale and the stopped process is bounded in : gives — probabilities inversely proportional to barrier distances. is also a martingale: , and , so . In general: hit before with probability , expected time — the continuous gambler’s ruin, and the exact expected lifetime of a bracket order (stop at , target at ) on a driftless diffusion. Note the expectancy check: — the bracket reshapes the distribution but cannot create edge, which is this whole chapter in one line.

Next: drop the fair-game requirement and keep only the memoryless structure — transition matrices, stationary distributions, and first-step analysis, the single most-used problem-solving technique: Markov chains.