edgekit

Bayesian inference

The frequentist chapter kept insisting that a p-value is not the probability the hypothesis is true. Bayesian inference is the framework in which that probability exists: treat the unknown parameter as a random variable, encode what you believed before the data as a prior, and let Bayes’ theorem convert data into an updated belief. This chapter derives — not merely states — the three classic conjugate updates (beta–binomial, normal–normal, gamma–Poisson), pins down exactly how credible intervals differ from confidence intervals, and connects posterior means, MAP, and MLE through loss functions.

Intuition — inference as bookkeeping on beliefs

You already reason this way at the desk. You believe a strategy has a small edge (prior). It wins seven of its next ten trades (likelihood). You now believe in it a bit more — but not as much as the raw 70% hit rate suggests, because ten trades is nothing (posterior: a compromise, weighted by how much information each side carries). Bayes’ theorem is the unique consistent arithmetic for that compromise. The entire chapter is one identity applied relentlessly: , with the normalising constant left to fend for itself.

Bayes for parameters#

Let be the unknown parameter and the data. The four objects of Bayesian inference:

The evidence is a constant in , so in practice you work with and normalise at the end — the engine of every derivation below. Two structural properties fall out immediately:

  • Sequential updating.Today’s posterior is tomorrow’s prior. Processing observations one at a time, or all at once, gives the identical posterior — multiply the likelihoods and the order of multiplication cannot matter. Bayesian learning is streaming by construction.
  • Prediction. The posterior predictive for a new observation averages the model over remaining parameter uncertainty: — fatter-tailed than any single- forecast, because it prices in not knowing .
A sequence of posterior densities for a coin's heads probability, starting flat and sharpening around the true value as flips accumulate
Sequential Bayesian updating: a flat prior over a coin's heads probability sharpens flip by flip. Each posterior becomes the next prior; the batch answer and the one-at-a-time answer coincide exactly. Information accumulates as the density narrows — the Bayesian picture of the law of large numbers.

Conjugacy I — beta–binomial, derived#

A prior is conjugateto a likelihood when the posterior stays in the prior’s family — updating reduces to updating a few hyperparameters. The workhorse example: a coin (a trade’s win indicator) with unknown heads probability .

Derivation — Beta prior + binomial data ⇒ Beta posterior

Take prior , density , and observe heads in flips, likelihood . Multiply and keep only -dependence:

That is precisely the kernel of a Beta density, so — no integration required —

The hyperparameters act as pseudo-counts: the prior behaves like imaginary heads and imaginary tails already seen. The posterior mean exposes the compromise explicitly:

A weighted average of prior mean and sample frequency, with weights proportional to pseudo-counts vs real counts. As the data weight tends to 1 and the posterior mean approaches the MLE — priors wash out under data.

Worked numeric: prior (mean 0.5, worth 4 pseudo-flips), observe 7 wins in 10 trades. Posterior: , mean — pulled from the raw 0.700 toward 0.5 by exactly the ratio of pseudo-data to total data. Posterior standard deviation : the hit rate is known to roughly ±12% — still very little.

Beta prior, scaled binomial likelihood, and resulting Beta posterior for a coin's heads probability on one axis
Beta prior, binomial likelihood, Beta posterior — the conjugate triangle. The posterior sits between prior and likelihood, closer to whichever carries more effective observations. With pseudo-counts a + b = 4 against n = 10 real flips, the data get 10/14 of the vote.

Conjugacy II — normal–normal and precision weighting#

Now estimate a mean — a strategy’s true daily edge — from observations with known, and prior . Define precision = 1/variance; the result is cleanest in that currency.

Derivation — complete the square, get precision-weighted shrinkage

The likelihood depends on the data only through . The log-posterior is, up to constants,

Expand and collect the quadratic and linear terms in :

A quadratic log-density is a Gaussian, with precision equal to the coefficient of and mean equal to (linear coefficient)/(precision):

Read it twice. Precisions add: certainty accumulates linearly in information. And the posterior mean is a precision-weighted average of prior mean and sample mean — each source of information votes in proportion to how sure it is. Writing , the mean is : the data estimate shrunk toward the priorby a factor determined by relative noise. This is the same shrinkage that reappears as James–Stein and empirical Bayes in estimators & sampling, and as beta shrinkage in regression.

Worked numeric: prior (edge probably near zero), data with . Posterior precision , so ; posterior mean . The data are four times as precise as the prior, so the estimate moves 80% of the way from 0 to 1.2.

Prior, likelihood, and posterior Gaussians on one axis, with the posterior mean visibly between the prior and sample means, weighted toward the sharper density
Normal-normal updating: the posterior Gaussian sits between prior and likelihood, its mean the precision-weighted average and its precision the sum. The sharper curve pulls harder. Shrinkage is not a correction bolted on afterwards — it is what Bayes' theorem computes.

Conjugacy III — gamma–Poisson#

For count data — order arrivals, jump counts (Poisson processes) — with rate : take prior (shape , rate ), density , and observe counts with likelihood . Multiplying kernels:

Posterior mean : again pseudo-data — the prior is worth events over periods, blended with the observed events over periods. Worked numeric: a desk believes a venue sends roughly 20 fills/hour, worth two hours of pseudo-observation: . Watching 3 hours with 45 fills gives posterior , mean 17/hour, sd . The three conjugate families share one grammar:

LikelihoodConjugate priorPosterior updatePseudo-data reading
Binomial(n, θ)Beta(a, b)Beta(a + k, b + n − k)a heads, b tails already seen
Normal(θ, σ² known)Normal(μ₀, τ₀²)precision-weighted Normalprior ≈ σ²/τ₀² extra observations
Poisson(λ)Gamma(a, b)Gamma(a + Σx, b + n)a events over b periods

Credible vs confidence intervals — the exact difference#

A credible interval is a set with posterior probability 0.95: — a direct probability statement about the parameter, given your data and prior. A confidence interval makes a coverage promise about the procedure across hypothetical repetitions: before the data arrive. With flat priors and no constraints the two often coincide numerically, which breeds the confusion. They split apart the moment real prior information exists — most vividly, a support constraint:

Worked example — where the two intervals genuinely differ

Suppose is known (a variance, a capacity, a squared quantity), and one observation lands at . The standard 95% confidence interval is

which is mostly impossible values — and had occurred, the interval would contain no feasible value at all, while the procedure still boasts 95% coverage (it fails only in the 5% of samples like this one). The Bayesian answer with a flat prior on is the truncated normal . Its equal-tailed 95% credible interval solves at , giving approximately

Every value is feasible, and the interval concentrates just above zero — exactly what the evidence plus the constraint warrant. The confidence procedure is calibrated on average over samples; the credible interval is calibrated for the sample you actually have. A crisp way to phrase it: “the CI answers a question about the method, the credible interval answers a question about the parameter.”

Point estimates as loss functions — MAP vs MLE vs posterior mean#

Collapsing a posterior to one number is a decision, and decisions need a loss. Choosing the estimate to minimise expected posterior loss gives:

  • Squared loss ⇒ posterior mean. gives — the same L2-optimality as conditional expectation in joint distributions.
  • Absolute loss ⇒ posterior median. Balancing probability mass on each side.
  • 0–1 loss ⇒ MAP (posterior mode), the limit of rewarding only near-exact hits. And since , MAP with a flat prior is exactly the MLE of the previous part. A Gaussian prior turns MAP into ridge regression; a Laplace prior into lasso — regularisation is a prior in disguise.

For skewed posteriors the three disagree materially: in the Beta(9,5) example, mean 0.643, mode , median . For the heavy-tailed German-tank posterior in Problem 5, mean and median differ by 40%.

Priors — choice, Jeffreys, and sensitivity#

The prior is the framework’s cost of admission. Practical guidance:

  • Flat is not innocent. A uniform prior on is not uniform on or — “no information” is parameterisation-dependent. The Jeffreys prior (Fisher information from Cramér–Rao) fixes this by being invariant under reparameterisation; for a Bernoulli it is .
  • Sensitivity fades as grows. The data weight in every conjugate update above is ; report posterior conclusions under two or three plausible priors and show they agree before trusting them.
  • Empirical Bayes teaser. With many parallel problems (5,000 strategies, each with a hit rate), estimate the prior from the ensembleand shrink each estimate toward it — the James–Stein phenomenon operationalised. This is the statistically honest version of “compare each strategy to the population of strategies you tried.”

Checking a derivation by simulation#

Conjugacy claims are exactly checkable: sample from the prior, simulate data, keep the draws whose simulated data match the observed data. The surviving draws are samples from the posterior (this is rejection ABC — and the definition of conditioning). Verifying :

conjugacy_check.py
import numpy as np

rng = np.random.default_rng(11)
a, b, n, k = 2.0, 2.0, 10, 7

theta = rng.beta(a, b, size=2_000_000)     # draws from the prior
sims = rng.binomial(n, theta)              # each theta flips its own coin
post = theta[sims == k]                    # condition on the observed data

exact_mean = (a + k) / (a + b + n)         # Beta(9,5) mean = 0.6429
exact_var = ((a + k) * (b + n - k)) / ((a + b + n) ** 2 * (a + b + n + 1))
print(f"accepted draws:   {post.size}")
print(f"posterior mean:   {post.mean():.4f}   exact {exact_mean:.4f}")
print(f"posterior var:    {post.var():.5f}  exact {exact_var:.5f}")
print(f"P(theta > 0.5):   {(post > 0.5).mean():.4f}")

The empirical mean and variance land on the Beta(9,5) values to three decimals, and you get for free — the probability the strategy is better than a coin, a number no p-value will ever hand you.

Quant lens — Kelly under parameter uncertainty, regimes, and Thompson

Three places this machinery earns money. (1) Sizing. Kelly says bet of bankroll on an even-money edge — but you never know , only a posterior. Maximising expected log growth over the posterior predictive shrinks the bet: uncertainty about the edge behaves like extra variance, and overbetting an overestimated edge is ruinous while underbetting is merely slow (see bandits & allocation). Fractional Kelly is an informal posterior shrinkage. (2) Regimes. Beliefs about the current market state update by exactly the sequential Bayes rule above — the filter behind regime detection is this chapter running in a loop. (3) Exploration.Thompson sampling allocates capital to strategies by sampling each one’s posterior and backing the sampled winner — randomised exactly in proportion to the probability each strategy is best. See Bayesian methods for the applied toolkit.

Practice problems#

Problem 1 — posterior for a biased coin

With a uniform prior on , a coin shows 7 heads in 10 flips. Give the posterior, its mean, its mode, and the probability the next flip is heads.

Solution. Uniform = Beta(1,1), so the posterior is . Mean ; mode — equal to the MLE, as it must be under a flat prior. The predictive probability of heads is the posterior mean, , not 0.7: prediction integrates over uncertainty rather than plugging in the best guess, and the integral drags the answer toward 1/2. Distinguishing those two numbers crisply is the point of the question.

Problem 2 — Laplace's rule of succession

Derive: after observing successes in trials with a uniform prior, the probability the next trial succeeds is .

Solution. Posterior is by the beta–binomial derivation. The predictive is its mean:

The +1/+2 are the flat prior’s pseudo-counts (one imagined success, one imagined failure). Note the consequences: after n successes in n trials the answer is — a Bayesian never assigns probability 1 from finite data — and with n = 0 the rule gives 1/2. A strategy that is 3-for-3 has predictive win rate 4/5, not 1.

Problem 3 — a normal-normal update by hand

Prior: . You observe a sample mean of 1.2 with sampling variance 1. Posterior?

Solution. Work in precisions: prior 1/4, data 1. Posterior precision variance . Posterior mean = precision-weighted average:

Sanity checks worth stating explicitly: the posterior mean lies between 0 and 1.2, closer to the data (which are 4× more precise); the posterior variance (0.8) is smaller than boththe prior’s (4) and the data’s (1), because precisions add.

Problem 4 — would one more win change your mind?

A strategy has won 55 of 100 trades (uniform prior). It wins the next trade. How much does your estimate of its hit rate move? What if it had only ever traded twice, winning both?

Solution. Before: Beta(56, 46), mean . After: Beta(57, 46), mean — a move of 0.4%. In general one observation moves the posterior mean by : with n = 100 the belief is stiff. With 2-for-2, the mean jumps from to — 5 points — because the posterior is still wide. The key point: the same evidence moves beliefs by an amount inversely proportional to the information already held; anyone who re-sizes positions dramatically on one good week is running an n-of-5 posterior on an n-of-500 problem.

Problem 5 — Bayesian German tank

You see serial numbers 17, 42, 60 from a fleet numbered 1..N. With a flat prior on N, estimate N. Why do the posterior mean and median disagree so much?

Solution. The likelihood of observing 3 particular distinct serials is (approximately) for , zero below. With a flat prior, the posterior is on — a power law. Continuous approximation with :

The frequentist UMVU estimate (see estimators) sits near the posterior median, while the posterior mean is dragged to 120 by the heavy right tail — enormous fleets are improbable but not impossible, and squared loss cares about them. The disagreement is the loss-function lesson of this chapter in one number: report the median (or the whole posterior) when tails are heavy, and know which loss your estimate is optimising before you quote it.

Next: from beliefs about single parameters to the workhorse of empirical finance — fitting lines through noise, and knowing precisely when to trust the fitted slope. Regression & Gauss–Markov.