edgekit

Conditional expectation

Part I treated as a passing tool; this chapter makes it the main character. The idea unfolds as a ladder — condition on an event, then on a value, then realise the whole family of values assembles into a random variable — and once you see as an object in its own right, three of the most useful theorems in probability fall out almost for free: the tower property, the law of total variance, and the fact that is the best possible predictor of from . The same machinery, pointed at a process instead of a pair, becomes first-step analysis — the one-line solver for “how long until…” questions — and Wald’s identity for random sums.

Intuition — a best guess that is itself random

Before observing anything, your best guess for is the single number . After observing , your best guess depends on what you saw: it is a rule, “if , guess .” Feed the random into that rule and the guess itself becomes random: . Everything in this chapter is a consequence of taking that seriously. Average the guess over what you might see and you recover the unconditional answer (tower property). Split ’s uncertainty into “scatter around the guess” plus “scatter ofthe guess” and you get the law of total variance. Ask which function of predicts with least squared error and the answer is — this same object. One definition, three theorems, and a technique (condition on the first step) that dissolves whole families of problems.

The ladder: event, value, random variable#

Rung 1 — conditioning on an event. For an event with , the conditional expectation of a discrete is the ordinary expectation under the renormalised measure of the axioms chapter:

A number. For a fair die, .

Rung 2 — conditioning on a value. Take and let range. Each value of produces a number, so we have built an ordinary function,

the regression function of on — the same object estimated from data in regression & inference. (In the continuous case the sum becomes an integral against the conditional density from joint distributions; nothing conceptual changes.)

Rung 3 — conditioning on the random variable. Now compose the function with the random input:

This is the step that upgrades conditioning from a computation to a concept. is a random variable — a function of and of nothing else. Before is revealed you do not know which best guess you will make, but you know the complete rule; the rule evaluated at the random observation is . Being a random variable, it has a distribution, an expectation, a variance — and interrogating those is precisely what the next two sections do.

!Pitfall — E[X | Y] is not E[X] with Y “plugged in”

Two confusions account for most errors with this object. First: is not obtained by taking the number and decorating it with a — it is a genuinely different object, computed from the conditional distribution, and it varies with whenever and are dependent (it collapses to the constant exactly when knowing tells you nothing about the mean of ). Second: keep (a number, one per ) distinct from (a random variable). Identities relate objects of the same type: the tower property below equates two numbers, and , by first averaging the random guess over . Writing which type each expression has — number or function of — catches sign-level blunders before they happen, including the two-envelope trap at the end of this chapter.

The tower property (Adam’s law)#

The first thing to ask of the random variable is: what is its expectation? The answer is the law of iterated expectations, previewed in joint distributions and proved properly here:

Proof — swap the order of summation

Discrete case. is the function , so its expectation is a weighted average of the numbers :

The factors cancel, the sum over marginalises the joint, and nothing else happens — the theorem is bookkeeping. In words: an average of averages, weighted correctly. Group outcomes by the value of , average within each group, then average the group means weighted by group probabilities: you must recover the grand mean, because every outcome is counted exactly once with its original weight. It is the expectation-level version of the law of total probability.

The tower property is the licence behind every “condition on something helpful” computation: to find a hard unconditional expectation, choose a that makes the conditional answer easy, then average. First-step analysis below is this strategy industrialised. It also composes: conditioning on more information first and less information second gives — the form that powers every martingale argument in martingales & optional stopping.

Scatter of simulated X, Y pairs with the conditional mean curve E[Y|X=x] drawn through the cloud and the flat dashed line at the unconditional mean E[Y]
E[Y|X] is a function — the best-guess curve threading the cloud, tracking the local mean of Y at each x. The flat dashed line is the single number E[Y]. The tower property is the statement that averaging the curve over the distribution of X lands exactly on the flat line: iterated expectation made visible.

The law of total variance (Eve’s law)#

The second question: how does the variance of relate to the conditional world? Define the conditional variance — again a random variable, a function of . Then:

Proof — expand both second moments with the tower property

Apply the tower property to : , using the definition of conditional variance inside. Subtract (tower again):

The bracketed term is exactly the variance of the random variable — the proof only works because rung 3 of the ladder made that a legitimate object. Intuition: total scatter = average scatter within groups + scatter between the group means. Both terms are non-negative, so conditioning never increases expected variance: — information can only help, on average.

Quant lens — decomposing PnL variance across regimes

Let be a strategy’s daily PnL and the market regime: calm with probability (mean , standard deviation ) and stressed with probability (mean , standard deviation ). Tower: . Eve: within-group ; between-group . Total , of which is within-regime — the risk lives inside the stressed regime’s fat volatility, not in the drift difference between regimes. That is the generic shape of trading risk: regime shifts move the mean a little and the volatility a lot, so hedging the mean exposure to regimes barely dents the variance. The decomposition also explains why mixtures grow fat tails — here has kurtosis well above 3 despite being conditionally Gaussian — the statistical engine behind regime detection and the vol-mixing story in time-series statistics. The simulation below verifies both identities on a three-regime version.

The best predictor: least squares lives here#

Suppose you must predict using any function whatsoever — linear, polynomial, a lookup table — and you are scored by mean squared error. The minimiser is the conditional expectation:

Proof — the error decomposes like Pythagoras

Write and split the error: . Square and take expectations; the cross term dies by the tower property, because for any function ,

since given , is a constant and by definition. Hence

and the second term is non-negative, zero exactly when (almost surely). Geometrically: the prediction residual is orthogonal to every function of — conditional expectation is a projection, and the display is Pythagoras.

This is why is called the regression function: every supervised method that minimises squared error — ordinary least squares in regression & inference, trees, neural networks — is an estimate of this one theoretical object from finite data. OLS restricts to linear functions and therefore finds the best linear approximation to the curve; when the true is nonlinear the gap between them is real, predictable, and exploitable (Problem 5 makes it exactly on a toy example). The irreducible floor, , is Eve’s within-group term: no model, however flexible, predicts away the scatter that survives conditioning.

First-step analysis: condition on the first move#

Point the tower property at a process: to compute an expected duration, condition on the first step, whose conditional answers are one step closer to done. The memoryless structure that makes this exact is the subject of Markov chains; here are the three canonical computations.

Flips until the first head. Let be the expected number of fair flips. Condition on flip one: with probability you are done in 1; with probability you spent 1 flip and — by the fresh-start property — face the original problem again:

One line replaces the geometric series of common distributions.

Worked example — HH takes 6 flips, HT takes 4

HH. Track progress: state 0 (no useful history) with expected remaining time , state 1 (last flip was H) with . Condition on the next flip in each state:

The first equation gives ; substituting the second, , so (and ).

HT. Same states: again, but now from state 1 a tail finishes and a head keeps you in state 1 — a head can never hurt an HT-hunter:

Why the asymmetry, when both patterns have probability in any two given flips? Look at what failure costs. Hunting HH in state 1, a tail demolishes you back to state 0 — all progress lost. Hunting HT in state 1, the failing flip is a head, which leaves you exactly where you were: progress toward HT never resets. Self-overlapping patterns recycle their near-misses into rivals’ progress, not their own — the same overlap arithmetic ( vs ) that the betting-team martingale of martingales & optional stopping reads off ABRACADABRA. First-step analysis and the martingale argument are two roads to one truth.

Random sums: Wald’s identity and Eve on N#

Many quantities are sums with a random number of terms: total insurance claims in a year, total PnL over a random number of trades, total offspring in a branching process. Let be i.i.d. with mean and variance , let be a non-negative integer random variable independent of the , and set . Condition on : and , so tower and Eve give

The mean formula is Wald’s identity in its independent- form; the remarkable upgrade — it survives when is a stopping time that peeks at the as they arrive — is proved in martingales & optional stopping. The variance formula is pure Eve: within-group scatter from the terms themselves, between-group scatter from not knowing how many there are. Note the second term vanishes when : for a zero-edge book, uncertainty in the number of trades adds nothing to PnL variance. For Poisson with rate , both pieces merge into the compound-Poisson formula (Poisson processes), worked with numbers in Problem 2.

A closing teaser on misusingthe machinery. Two envelopes, one holding twice the other; you hold one. The seductive computation — “the other contains or with probability each, so its conditional expectation is , so always switch” — silently assumes that given your envelope contains , both cases are equally likely for every , which no genuine prior on the amounts can satisfy. It is a type error on the ladder: a statement about that was never derived from any joint distribution. The full dissection, including priors under which switching genuinely is right for some , is in probability paradoxes.

tower_and_eve.py
import numpy as np

rng = np.random.default_rng(21)
n = 1_000_000

# Daily PnL from a 3-regime mixture: calm / choppy / crisis
p     = np.array([0.60, 0.30, 0.10])   # regime probabilities
mu    = np.array([0.08, 0.00, -0.50])  # conditional means E[X|R]
sigma = np.array([0.60, 1.20, 3.00])   # conditional vols  sd(X|R)

regime = rng.choice(3, size=n, p=p)
pnl = rng.normal(mu[regime], sigma[regime])

# Tower property: E[X] = E[ E[X|R] ] = sum_k p_k mu_k
lhs_mean = pnl.mean()
rhs_mean = p @ mu
print(f"tower:  E[X] sim = {lhs_mean:+.4f}   E[E[X|R]] = {rhs_mean:+.4f}")

# Eve's law: Var(X) = E[Var(X|R)] + Var(E[X|R])
within  = p @ sigma**2                 # E[Var(X|R)]
between = p @ (mu - rhs_mean)**2       # Var(E[X|R])
print(f"eve:    Var(X) sim = {pnl.var():.4f}   "
      f"within {within:.4f} + between {between:.4f} = {within + between:.4f}")

# Same decomposition estimated from the sample, group by group
p_hat  = np.bincount(regime) / n
m_hat  = np.array([pnl[regime == k].mean() for k in range(3)])
v_hat  = np.array([pnl[regime == k].var()  for k in range(3)])
print(f"sample: within {p_hat @ v_hat:.4f} + "
      f"between {p_hat @ (m_hat - lhs_mean)**2:.4f}")
# Theory: E[X] = -0.0020, Var(X) = 1.5480 + 0.0288 = 1.5768 --
# 98% of the variance is within-regime, and the mixture's kurtosis
# (try from scipy.stats import kurtosis) is far above Gaussian.

Practice problems#

Five problems that test whether the ladder, the two laws, and first-step conditioning are actually usable — each yields to writing down what is being conditioned on.

Problem 1 — two consecutive sixes

Roll a fair die repeatedly. What is the expected number of rolls until you first see two sixes in a row?

Solution. First-step analysis with two states: (last roll not a six) and (last roll a six). Conditioning on the next roll:

The first gives ; substituting the second, , so (and ). The general pattern for a success probability : two in a row costs , matching the overlap rule (the pattern “66” overlaps itself in “6”). Lesson: name the progress states, condition on one step, and the recursion does the rest — no distributions required.

Problem 2 — total insurance claims

Claims arrive in a year as , independent of claim sizes with mean (in thousands). Find the mean and variance of the total payout .

Solution. Wald: . Eve with (exponential: variance = mean²) and : — equivalently the compound-Poisson shortcut , standard deviation . Note the two variance sources contribute equally here (): random claim count is as risky as random claim size. Lesson: never bolt onto by guesswork — Eve dictates the exact weights.

Problem 3 — a die, then coins: two-stage conditioning

Roll a fair die to get , then flip fair coins. Find the mean and variance of the number of heads .

Solution. Given , , so and . Tower: . Eve:

Sanity checks: larger than a fixed- binomial’s (die uncertainty adds between-group variance), and both pieces are visibly non-negative. Lesson: two-stage experiments are not harder than one-stage ones — they are one conditioning away from being routine.

Problem 4 — the larger of two dice, by conditioning

Roll two fair dice. Compute by conditioning on the first die.

Solution. Given the first die shows , the max is if the second lands in and otherwise equals the second die: . The six conditional answers are — a genuinely varying function of the first roll, i.e. the random variable in the flesh. Tower-average them:

agreeing with the tail-sum route via from order statistics. Lesson: when a joint quantity resists direct attack, condition on one coordinate — the conditional answers are one-dimensional, and the tower property stitches them back together.

Problem 5 — beating every linear predictor

Let be uniform on and . Find the best predictor of from , the best linear predictor, and both mean squared errors.

Solution. The best predictor is — it predicts perfectly, MSE . The best linear predictor needs , and by symmetry — so the best line is the flat constant , with MSE . Here and are uncorrelated yet completely dependent: correlation sees only the linear shadow of the regression function. Lesson: “no correlation” never means “no predictability” — a nonlinear can carry an entire signal that every linear model scores as zero, which is exactly the gap nonlinear features exist to close in regression & inference.

Next: the other great labour-saving principle — arguments that finish before computation starts because relabelling cannot change an answer: exchangeability, symmetric sampling, and why uniform random positions are so often the whole solution. Symmetry & exchangeability.