Discrete-time martingales
A martingale formalizes a fair game and is a powerful tool for calculations at random times. Study submartingales and supermartingales, the martingale transform as a discrete precursor of the Itô integral, Doob decomposition, optional stopping and its assumptions, Wald's identity, Doob's maximal inequality, and martingale convergence, with Pólya's urn and gambler's ruin as labs.
After this lesson you can
- Check whether a process is a martingale, submartingale or supermartingale and construct martingales from Markov chains and likelihoods.
- Calculate ruin probabilities and expected durations by applying optional stopping to suitable martingales.
- Identify when optional stopping fails and which assumption is violated in a doubling strategy.
- Bound a process maximum with Doob's inequality and use it in sequential tests.
- Apply the convergence theorem to Pólya's urn and likelihood ratios.
Before you start
A fair game and the clock you choose
If a bet is fair, knowing its history does not change the expected gain on the next step. Can a rule that changes bet size and decides when to stop make it favorable? One temptation is to double after each loss: a win would recover everything lost and leave one unit of profit. The figure adds finite capital and table limits to reveal the infrequent losses that offset small gains.
Without limits, the first win occurs almost surely and its time has mean 2. However, bets grow without bound and stopped capital does not form a uniformly integrable family: with probability the first bets are lost and cumulative loss is . Finite mean time alone does not justify exchanging stopping and expectation without care. With finite limits, a predictable strategy on fair bets preserves zero expectation; a finite sample of results need not show exactly zero.
The definition requires information and integrability
Checking is not enough: the condition requires that no available information predict a gain. It does not require independent increments. If square-integrable, martingale increments at different times are uncorrelated by conditioning; lack of correlation does not imply independence.
A submartingale replaces equality with ; a supermartingale uses . Both still require adaptation and integrability. A convex function of a martingale is a submartingale when its transform is integrable, by conditional Jensen.
Important examples:
- If are independent, integrable and mean zero, is a martingale in its natural filtration. With equally likely , is also one.
- If are independent and , their product is a nonnegative martingale. A sequential likelihood ratio is an example under the null law, provided the alternative is absolutely continuous with respect to the null at each finite horizon.
- For , is the Doob martingale by the tower property: updating a coherent prediction introduces no conditional drift.
- If is a chain and is harmonic, , then is a martingale whenever integrable. The function summarizes the solution to the first-step problem.
Betting without seeing the next outcome
A strategy is predictable if it is -measurable. The martingale transform is
If is bounded and integrable, each term is integrable and . Thus the transform is a martingale. Bets may depend on the entire past but not on the next increment. This is the discrete version of the predictable-integrand idea that will reappear in the Itô integral.
The Doob decomposition writes any adapted integrable process as , with and
is predictable and is a martingale by construction; the decomposition is unique because the predictable increment of is forced by conditional expectation. If is a submartingale, is increasing almost surely. For a square-integrable martingale, is its predictable quadratic variation and is a martingale.
Stopping is not just substituting a letter
The optional stopping theorem guarantees under sufficient assumptions, for example any of these:
- is bounded by a deterministic constant.
- and the increments of are uniformly bounded.
- almost surely and the family is uniformly integrable.
In the first case, . The indicator is -measurable because is a stopping time: the previous transform has zero expectation. In the second, gives integrable domination. In the third, almost-sure convergence of to and uniform integrability allow passage to the limit in .
The counterexample is fair and . This time is finite almost surely and , but . It does not contradict the theorem: and the stopped values do not form a uniformly integrable family. Almost-sure stopping is not enough. In the doubling strategy, the limit without capital or table constraints also requires unbounded bets and potentially arbitrary losses.
Ruin and duration by stopping
Let and with probabilities and . For , stop at . On this finite interval : from every state there is a uniformly positive probability of reaching a boundary within steps, and the tail is geometrically bounded by blocks.
If , optional stopping for gives , so the success probability is . The martingale , first applied to , yields : the term is bounded by and increases to . These steps justify the limit without blindly assuming equality at .
If and both are positive, is a martingale because . The stopped process is bounded on ; optional stopping gives
Solving reproduces the first-step formula from the preceding lesson. The exponential martingale must not be used at or , where the ratio ceases to make sense.
Wald’s identities express the same discipline for iid sums: if are iid integrable variables and is an integrable stopping time with respect to their natural filtration, . If additionally and , . The first follows by summing ; the indicator depends only on earlier increments, and the sum of its probabilities is . The second uses the isometry of centered increments and the limit at .
Control the maximum, not only the endpoint
Doob’s maximal inequality for a nonnegative submartingale states, for ,
To prove it, let be the first crossing before , or if none occurs. By bounded stopping of a submartingale, . The crossing event contributes at least times its probability, and the rest is nonnegative. For and , the corresponding inequality is .
If is a nonnegative martingale with , the bound holds uniformly over any finite horizon: . Letting grow and using continuity of probability for increasing events gives Ville’s inequality for inspection at any time, including an infinite horizon.
Convergence and a random limit
The martingale convergence theorem states, in particular, that a submartingale with converges almost surely to an integrable variable. For , define as the number of complete disjoint upcrossings of up to . Doob’s upcrossing inequality for a submartingale is
To understand it, is a nonnegative submartingale. A predictable strategy buys when reaches or less and sells when it reaches or more. Each complete crossing contributes at least , and an open purchase has nonnegative value because is zero at purchase. Increments of while the strategy is not holding a position form another predictable submartingale transform with nonnegative expectation; separating those gains from gives the bound. A formal proof using crossing times appears in the MIT notes.
The bound uniformly bounds the right-hand side. By monotone convergence, the total number of crossings of every rational interval is finite almost surely. Thus the path has a limit on the extended real line. Fatou and rule out that limit being infinite with positive probability and also show it is integrable.
Almost-sure convergence does not imply convergence of expectations. A uniformly integrable martingale does converge in and . For example, the nonnegative likelihood ratio under the null converges almost surely, but its limit may have expectation below one if the family is not uniformly integrable.
In Pólya’s urn, start with red and blue balls. At each step draw a ball, replace it and add another of the same color. The red proportion is a bounded martingale, so it converges almost surely and in . Its limit has law ; it is random even though each individual path stabilizes. The exact finite-time distribution is not that continuous beta law: the number of added red balls is beta-binomial.
To identify the limiting law, consider a particular sequence of draws with red. Its probability is , where is the rising product. This expression is also the integral of against the beta density: first draw and then draw independent colors with red probability to obtain the same probabilities for all finite sequences. In that construction, the strong law conditional on makes the proportion converge to . Since the laws of the complete sequences agree, the urn limit has the stated beta law.
Lab: ruin, Wald and compensation
Simulate paths until absorption at or without discarding long ones. The exact probability is calculated using the exponential martingale. Wald is checked with the sum of centered increments , whose variance per step is . The mean of should approach zero and the mean of its square ; both comparisons fluctuate due to Monte Carlo error.
import numpy as np
rng = np.random.default_rng(26051)
M, N, k, p = 30_000, 10, 3, 0.48
q = 1-p
capital = np.full(M, k, dtype=int)
tiempo = np.zeros(M, dtype=int)
activos = (capital > 0) & (capital < N)
while activos.any():
idx = np.flatnonzero(activos)
capital[idx] += np.where(rng.random(len(idx)) < p, 1, -1)
tiempo[idx] += 1
activos = (capital > 0) & (capital < N)
exito = (1-(q/p)**k)/(1-(q/p)**N)
centrada = capital - k - (p-q)*tiempo
print('éxito empírico y exacto:', round(np.mean(capital == N), 5), round(exito, 5))
print('media centrada:', round(centrada.mean(), 5))
print('segundo momento centrado:', round(np.mean(centrada**2), 5))
print('Wald: varianza por paso × tiempo medio:', round(4*p*q*tiempo.mean(), 5))
print('tiempo medio:', round(tiempo.mean(), 5))For in the fair walk, the conditional expected increment is at and at every other integer. Its compensator is the number of visits to zero before each step. The cell calculates residual and checks the mean of its increments grouped by the preceding state. The empirical comparison does not prove the martingale property; the conditional identity proves it for every state.
rng = np.random.default_rng(26052)
M, pasos = 40_000, 60
estado = np.zeros(M, dtype=int)
compensador = np.zeros(M, dtype=int)
sumas = np.zeros(2)
cuentas = np.zeros(2, dtype=int)
for t in range(pasos):
cero = estado == 0
incremento = np.where(rng.random(M) < .5, 1, -1)
siguiente = estado + incremento
delta_m = np.abs(siguiente) - np.abs(estado) - cero.astype(int)
sumas[0] += delta_m[cero].sum()
sumas[1] += delta_m[~cero].sum()
cuentas += [cero.sum(), (~cero).sum()]
compensador += cero
estado = siguiente
print('media residual condicionada a cero / no cero:', np.round(sumas/cuentas, 6))
print('media de |S|-A:', round(np.mean(np.abs(estado)-compensador), 5))
print('visitas previas a cero medias:', round(compensador.mean(), 5))Now simulate urns and compare their mean and variance with exact finite-time moments. If , the final proportion observed after draws has expectation and variance . The limiting variance is . Fitting a beta law to the finite distribution is an approximation: finite proportions lie on a discrete grid.
rng = np.random.default_rng(26053)
a, b, n, M = 2, 3, 500, 20_000
rojas = np.full(M, a, dtype=int)
for t in range(n):
rojas += rng.random(M) < rojas / (a+b+t)
proporcion = rojas / (a+b+n)
media = proporcion.mean()
varianza = proporcion.var(ddof=1)
escala = media*(1-media)/varianza - 1
ajuste = (media*escala, (1-media)*escala)
var_finita = n*a*b/((a+b)**2*(a+b+1)*(a+b+n))
var_limite = a*b/((a+b)**2*(a+b+1))
print('media empírica y teórica:', round(media, 5), a/(a+b))
print('varianza empírica, finita y límite:', round(varianza, 5), round(var_finita, 5), round(var_limite, 5))
print('beta ajustada por momentos a tiempo finito:', np.round(ajuste, 4))Lab: valid evidence under repeated inspection
Consider two groups with independent normal observations of variance one. For each pair, has law under the null. Under an alternative with mean , the likelihood ratio for the first observations is , with . Mixing those ratios with a proper prior gives another nonnegative martingale under the null:
The formula follows by completing the square and integrating a normal density. If stopping at the first , Ville controls the crossing probability under the null regardless of how often we inspect. Compare with repeating an ordinary two-sided Welch t-test at nominal level at every sample size: its t distribution with Welch degrees of freedom is an approximation, and the rule declaring success at the first significant result does not automatically preserve that level under repeated inspection.
from scipy.special import stdtr
rng = np.random.default_rng(26054)
M, horizonte, alpha, tau = 3_000, 100, 0.05, 0.5
x = rng.normal(size=(M, horizonte))
y = rng.normal(size=(M, horizonte))
z = (x-y)/np.sqrt(2)
suma_z = np.cumsum(z, axis=1)
t = np.arange(1, horizonte+1)
log_e = -.5*np.log1p(t*tau**2) + tau**2*suma_z**2/(2*(1+t*tau**2))
cruce_e = (log_e >= np.log(1/alpha)).any(axis=1)
sx, sy = np.cumsum(x, axis=1), np.cumsum(y, axis=1)
sx2, sy2 = np.cumsum(x*x, axis=1), np.cumsum(y*y, axis=1)
n = t[4:]
mx, my = sx[:, 4:]/n, sy[:, 4:]/n
vx = (sx2[:, 4:] - sx[:, 4:]**2/n)/(n-1)
vy = (sy2[:, 4:] - sy[:, 4:]**2/n)/(n-1)
vx, vy = np.maximum(vx, 0), np.maximum(vy, 0)
error2 = (vx+vy)/n
estadistico = (mx-my)/np.sqrt(error2)
grados = (vx+vy)**2/(vx**2/(n-1)+vy**2/(n-1))
p_valor = 2*stdtr(grados, -np.abs(estadistico))
cruce_t = (p_valor < alpha).any(axis=1)
print('cruce de la martingala:', int(cruce_e.sum()), '/', M, 'cota:', alpha)
print('rechazo por t repetido:', int(cruce_t.sum()), '/', M)
print('error estándar de frecuencia con p=alpha:', round(np.sqrt(alpha*(1-alpha)/M), 5))The evidence test uses the model’s known variance to construct the ratio; Welch’s test estimates variances. The comparison shows the effect of the stopping rule in this experiment; it does not establish a universal difference among all possible tests. Simulated crossing frequency can fall below or above the theoretical bound due to fluctuation; the bound concerns the true probability.
Exercises
More than one answer may be correct.
Step 1 of 3. Which sum is correct?
Step 1 of 3. What do you obtain by stopping S?
Step 1 of 3. Why is the chosen time a bounded stopping time?
doob_decomposition(P, f, path). P is a row transition matrix, f a vector of values, and path a trajectory of indices. Return arrays M and A, with A₀=0, increments Aₖ−Aₖ₋₁=(Pf−f)(path[k−1]), and Mₖ=f(path[k])−Aₖ.import numpy as np
def doob_decomposition(P, f, path):
passA martingale encodes absence of conditional drift relative to available information. Predictable strategies do not create expected gain, but taking a limit at stopping requires assumptions. The maximal inequality controls repeated inspection, and convergence explains both random urn limits and the risk of losing mass in expectation.