edgekit

Random variables & moments

A random variable turns outcomes into numbers, and everything you compute about it flows through a handful of objects: the CDF, the density or mass function, the quantile function, and the moments. This chapter builds each one, proves the workhorse identities — linearity of expectation, LOTUS, the tail-sum formula, the change-of-variables rule, the normal MGF — and finishes with the indicator-variable method, the single most valuable trick in quant probability.

Intuition — the object is the distribution, not the number

“Tomorrow’s return” is not a number; it is a menu of numbers with weights. A random variable is that menu made precise, and the skill of this chapter is moving fluently between its equivalent descriptions: the CDF when you want probabilities of intervals and quantiles (VaR is a quantile), the density when you want to integrate, the MGF when you want moments or sums, and — most powerful of all — a decomposition into indicator variables when you want an expectation without touching the distribution at all.

Random variables and the CDF#

Formally, a random variable is a function mapping each outcome to a number, measurable in the sense that events like belong to the σ-algebra of the axioms chapter — so they have probabilities. That technical condition rarely bites in practice; what matters is the object it licenses, the cumulative distribution function:

Every CDF has exactly three properties, and any function with them is a CDF:

  • Non-decreasing: — monotonicity of probability, since .
  • Limits: , — by continuity of probability along shrinking/growing events.
  • Right-continuous: as , because . Left limits can jump, and the jump at is exactly .

Interval probabilities read straight off: . A discrete variable concentrates mass on points, described by the PMF (the CDF is a staircase). A continuous variable has a density — the PDF — with and at every point: densities are rates of probability, and is legal on a narrow enough interval.

A probability density function above its cumulative distribution function, showing that area under the density equals the rise of the CDF and marking a quantile
The two faces of one distribution: area under the PDF over an interval (top) equals the rise of the CDF across it (bottom). The quantile function runs the CDF backwards — pick a probability on the vertical axis, read off the threshold. VaR is literally this arrow.

Running the CDF backwards gives the quantile function — the level that cuts off probability below. Quantiles are the language of risk: the 95% VaR of the applied probability chapter is of the loss distribution, and for continuous — the probability integral transform, proved in order statistics — grounds both simulation and p-values.

Transformations of random variables#

Given , what is ’s distribution? The robust method works through the CDF; for monotone it yields a clean formula.

Proof — the change-of-variables formula

Let be strictly increasing and differentiable, with inverse . Then

Differentiate with the chain rule:

For decreasing the inequality flips, producing a minus sign that the absolute value absorbs. General monotone case:

The Jacobian factor is conservation of probability: mass in a small interval must reappear in the image interval of width — where stretches, density thins. Non-monotone maps (like ) sum this over each monotone branch.

Worked example — from normal returns to lognormal prices

Let be a log return and the gross price relative. With and derivative :

— the lognormal density, the terminal distribution of geometric Brownian motion. The Jacobian is what skews it right: equal log-moves map to wider dollar intervals on the upside. Its mean–median gap is derived in the zoo.

Expectation, linearity, and LOTUS#

The expectation is the probability-weighted average:

defined whenever the sum/integral converges absolutely — a caveat with teeth, as the St. Petersburg and Cauchy examples below show. Its superpower is linearity: , with no independence assumption whatsoever.

Proof — linearity needs no independence

Discrete case; let be the joint PMF. By definition of the expectation of a function of ,

The inner sums collapse to the marginals and , leaving . The joint distribution — where all dependence lives — was summed out without ever being factored. This is why the indicator method later works on wildlydependent pieces, and why a book’s expected PnL is the sum of per-trade expectancies no matter how correlated the trades are (their risk is another story — joint distributions).

To average a function of you do not need the distribution of — the law of the unconscious statistician (LOTUS) lets you integrate against ’s own distribution:

It is a theorem, not a definition (its name is a joke about forgetting it needed proof), and note the trap it does not license: for nonlinear — the gap is Jensen’s inequality, quantified in inequalities & tail bounds, and it is the entire volatility-drag story ().

The tail-sum formula#

For a non-negative integer-valued variable there is a second, often far cleaner, route to the mean — summing the survival function:

Proof — swap the order of a double sum

Write , i.e. — the variable counts how many thresholds it clears. Take expectations and use linearity (fine for non-negative terms):

Equivalently: arrange the PMF as a table of repeated times and sum by columns instead of rows. The continuous analogue, proved the same way with Fubini, is — the mean is the area under the survival curve.

Worked example — geometric mean in two lines

Let be the number of trials to the first success, success probability . Then (the first trials all fail), so

No differentiation of power series, no algebra. The tail-sum route is worth internalising — it also cracks “expected maximum of dice” (Problem 2 below) and any problem where is easier than .

Variance, covariance, and higher moments#

Variance measures spread as expected squared deviation, with the computational identity obtained by expanding the square and applying linearity:

Its algebra, all one-line consequences of linearity:

  • — shifts do nothing, scales enter squared.
  • , where — variances add only when covariances vanish; that failure of linearity is diversification.

Standardised higher moments describe shape: skewness (asymmetry — negative skew is the many-small-wins, rare-big-loss profile) and kurtosis (tail weight — 3 for the normal, far above 3 for real returns). They are the moments where Sharpe ratios go blind, as the applied chapter shows on data.

Worked example — mean and variance of one die

; ; so , . For the sum of two independent dice: mean 7, variance — add means always, add variances because independent. Memorise ; dice problems are standard practice furniture.

Moment generating functions#

The MGF packs every moment into one function:

Proof sketch — moments from derivatives, and uniqueness

Expand the exponential and (where the expansion is justified) exchange expectation and sum:

Differentiate times, set , and the -th moment falls out. Uniqueness (stated, proof beyond scope): if the MGF is finite on an open interval around 0, it determines the distribution — two variables with the same MGF there are identically distributed. That, plus for independent variables, is why MGFs demolish sum-of-variables problems and drive the CLT proof in LLN & CLT.

Derivation — the normal MGF by completing the square

For :

because and the remaining integrand is a shifted normal density integrating to 1. Then for ,

Check the machinery: , , so . Set : — the lognormal mean, volatility drag surfacing through an MGF. When the MGF fails to exist (Student-t, Cauchy, lognormal for ), the characteristic function — always finite, always unique — takes over; it is the tool of record in the CLT chapter.

The indicator-variable method#

The most useful trick in this entire series. An indicator is 1 when occurs, else 0, and its expectation is a probability: . To find an expected count, write it as a sum of indicators and apply linearity — dependence between the events is irrelevant:

  • Matches (fixed points). A random permutation of items: , so the expected number of fixed points is — for every , despite the heavy dependence (compare the derangement count in counting & combinatorics).
  • Empty boxes. Throw balls into boxes uniformly: , so the expected number of empty boxes is — the bootstrap’s “36.8% of observations left out of a resample.”
  • Inversions. In a random permutation, each of the pairs is inverted with probability (symmetry), so the expected inversion count is .
Quant lens — expectancy decomposes; risk does not

Linearity over indicators is how a desk reasons about aggregates without modelling dependence: the expected number of stopped-out positions today is the sum of per-position stop probabilities; a book’s expectancy is the sum of per-trade edges (the math of edge) even when every trade loads on the same regime. But remember the boundary: the moment the question involves variance, drawdown, or tails, the vanished covariances return with interest — 100 correlated 1R bets have the expectancy of 100 trades and the risk of far fewer independent ones. Expected values need no correlation model; risk numbers are nothing but one.

A seeded simulation confirms three headline results — fixed points, the geometric tail-sum mean, and the empty-box fraction:

moments_checks.py
import numpy as np

rng = np.random.default_rng(11)
trials = 200_000

# 1) Expected fixed points of a random permutation of n = 52 items: exactly 1
n = 52
perms = np.argsort(rng.random((trials, n)), axis=1)
fixed = (perms == np.arange(n)).sum(axis=1)
print(f"E[fixed points] = {fixed.mean():.4f}   (theory 1)")

# 2) Geometric mean via simulation: trials to first six, p = 1/6
rolls = rng.geometric(1/6, size=trials)
print(f"E[rolls to a 6] = {rolls.mean():.4f}   (theory 6)")
# tail-sum check: sum_k P(X >= k) computed empirically
ks = np.arange(1, 61)
tail_sum = np.array([(rolls >= k).mean() for k in ks]).sum()
print(f"sum P(X >= k)   = {tail_sum:.4f}   (same number, by the tail-sum formula)")

# 3) Empty boxes: n balls in n boxes, expected empty fraction -> 1/e
m = 100
boxes = rng.integers(0, m, size=(trials // 10, m))
empty_frac = np.array([m - len(np.unique(row)) for row in boxes]).mean() / m
print(f"empty fraction  = {empty_frac:.4f}   ((1-1/m)^m = {(1 - 1/m)**m:.4f}, 1/e = {1/np.e:.4f})")

Practice problems#

Five classics of expectation — each has a grind-it-out route and a slick route; lead with the slick one.

Problem 1 — Expected rolls to see a 6

Roll a fair die repeatedly. How many rolls, on average, until the first 6?

Solution. Slick (first-step / memorylessness): let be the answer. The first roll either succeeds (probability ) or fails and — because the die has no memory — leaves you facing the identical problem, one roll poorer: . Systematic: geometric with , tail-sum gives . Be ready for the follow-up: after 10 non-sixes the expected number of additional rolls is still 6 (Problem 5) — contrast the all-even conditional of the axioms chapter, where conditioning on the future changed everything.

Problem 2 — Expected maximum of two dice

Roll two fair dice. What is the expected value of the larger one?

Solution. Tail-sum on : . So

Sanity checks worth running: above 3.5, below 6, and by the symmetry , — two answers for one. The CDF-of-the-max move generalises to any number of dice and to order statistics at large.

Problem 3 — Coupon collector, via indicators

Each cereal box contains one of coupon types, uniformly at random. How many boxes on average to collect all ? Evaluate for (rolling a die until every face appears).

Solution. Decompose into stages: with types already collected, each box is new with probability , so the stage is geometric with mean . Linearity across stages:

For : rolls. The last coupon alone costs boxes on average — completeness is expensive. Full treatment in the brainteaser canon.

Problem 4 — St. Petersburg: infinite mean, finite price

A fair coin is flipped until the first head; if it lands on flip you are paid . What is the fair price of this game?

Solution. — yet nobody pays more than about $20. The resolutions to present: (i) expectation means an absolutely convergent sum, and this one diverges — the “mean” is not a usable summary; (ii) any real counterparty is finitely capitalised — capping the bank at (~$1B) truncates the sum to 30, a ~$30 game; (iii) log utility (Bernoulli’s fix) gives a modest certainty equivalent — the concavity that drives Kelly sizing in position sizing. The quant moral: a payoff dominated by vanishingly rare astronomical outcomes has an expectation no realisable sample mean approaches — a first sighting of the fat-tail failures in LLN & CLT.

Problem 5 — Memorylessness, precisely

For geometric (trials to first success), show , and use it to re-derive .

Solution. Since ,

Past failures carry zero information — the process restarts at every trial. For the mean, condition on the first trial: , since after a failure the memoryless clock restarts. Solving gives . The geometric is the only discrete distribution with this property (the exponential is its continuous twin — uniqueness proved in the distribution zoo), and it is the clean rebuttal of the gambler’s fallacy: “due” is precisely what memorylessness forbids.

Next: the indicator method you just met deserves a chapter of its own — linearity of expectation as a first-class problem-solving tool, with the classic problems it demolishes. Expectation & the linearity trick.