Conditional distributions, hierarchical models and copulas
Conditional densities, Bayes’ theorem for densities, and hierarchical models that first generate a latent variable and then data. Copulas separate marginals from dependence (Sklar’s theorem) and reveal why correlation does not fully describe joint risk in the tails.
After this lesson you can
Calculate conditional densities and posteriors using Bayes’ theorem for densities.
Build hierarchical models and mixtures and obtain their marginal laws by integrating out the latent variable.
State Sklar’s theorem and simulate Gaussian, t and Clayton copulas with arbitrary marginals.
Calculate rank correlations and tail-dependence coefficients and explain their invariance.
Explain why conditioning on probability-zero events requires greater care.
Two seemingly distant situations call for the same tools.
A generative model with a hidden variable. A variational autoencoder generates an image in two steps: draw a code z∼N(0,I), then draw the image x from a law depending on z. The image density, needed for maximum-likelihood training, is not written down anywhere: it is the integral p(x)=∫p(x∣z)p(z)dz over every possible code. The inverse question, which code produced this image, is a conditional density p(z∣x) obtained by dividing by that same integral. All learning with latent variables, from Gaussian mixtures to diffusion models, involves managing integrals and ratios like these.
Two assets falling together. You have daily returns for two stocks. Each individually fits a heavy-tailed law well, and their dependence seems moderate: correlation 0.5. You want the probability that both fall together among their 0.1% worst days. With modeled marginals and measured correlation the answer seems settled. It is not. If you join the two marginals with the dependence of a bivariate normal with correlation 0.5, when A is in its worst thousandth of days the probability that B is too is 5.4%. If instead you join them using a bivariate t with 4 degrees of freedom and the same parameter 0.5, which leaves the marginals and Kendall’s τ unchanged (and, with normal marginals, a Pearson correlation of 0.49 versus 0.50), it is 26%: almost five times larger. The missing information is not correlation but the shape of dependence, and copulas are the tool that isolates it.
The lesson follows an arc:
Conditional densities. What f(y∣x) means when P(X=x)=0, and how to obtain the chain rule, the law of total probability and Bayes’ theorem for densities.
Hierarchical models and mixtures. Generate a latent variable and then data; which marginal law results from integrating out the latent variable, and why a heavy-tailed law such as Student’s t is a Gaussian with uncertain scale.
Copulas and Sklar’s theorem. Separate marginals and dependence, construct tailored joint laws and simulate them.
Tails and ranks. Why Pearson correlation misleads, and what tail dependence and rank correlations measure.
A warning. Conditioning on a probability-zero event depends on how that event is approached. This introduces the next lesson on conditional expectation.
Conditional density: slice and renormalize
Let (X,Y) be a random vector with X∈Rp, Y∈Rq and joint density f(x,y) with respect to Lebesgue measure (joint laws and density come from earlier lessons). By Fubini–Tonelli, X has marginal density fX(x)=∫f(x,y)dy. Conditional probabilities of events, P(B∣A)=P(A∩B)/P(A), require P(A)>0, and here the event {X=x} has probability zero. The natural way out is what one would do with a sample: take the fixed slice x of the joint and renormalize it to integrate to one.
The numerator f(x,y), as a function of y, is the slice. Its area is fX(x), not 1: dividing by fX(x) renormalizes it. The figure shows this with four joint laws sharing the same marginal X∼N(0,1).
InteractiveSlice and renormalize
Joint density f(x,y) (stronger color means higher density)
What Y sees at slice x=x0
unnormalized slice f(x0,y)
conditional f(y∣x0)
marginal fY(y)
E[Y∣X=x]
Joint law
Slice area, fX(x0)0.1942
E[Y∣X=x0]0.960
sd(Y∣X=x0)0.600
Modes of f(y∣x0)1
P(Y>1∣X=x0) versus P(Y>1)0.473 / 0.159
With a joint Gaussian, the conditional is another Gaussian: the mean shifts to ρx0 and variance drops to 1−ρ2, independently of x0.
Heat map of a joint density f(x,y). Drag the orange line (or touch the map) to choose x0. On the right, the slice f(x0,y) is dashed and the conditional density f(y∣x0) is the same curve scaled by 1/fX(x0), now with area 1; the marginal fY is gray. The map's magenta curve is E[Y∣X=x] and the dashed band is ± one standard deviation. Start with the correlated Gaussian and increase ρ: the mean shifts and the spread falls. Switch to the banana (what does correlation say here?), the funnel (what changes with x if not the mean?) and the cross (what does the conditional mean describe?).
Three things the figure shows and the rest of the section formalizes:
The conditional is distinct from the marginal. With ρ=0.8 and x0=1.2, knowing X=1.2 shifts the law of Y to a bell centered on 0.96 with standard deviation 0.6, compared with marginal N(0,1).
The mean does not tell the whole story. The funnel has E[Y∣X=x]=0 for every x yet X controls the dispersion of Y. The cross has the same constant conditional mean and a bimodal conditional law.
The slice area is a density.fX(x0) is the number to divide by, and the quantity divided changes from one x0 to another: in the tails of X the slice is tiny and the conditional is stretched considerably.
Why this is the correct definition
There are two justifications, one geometric and one exact. For the geometric one, with real X (p=1): if fX(x)>0 and the functions s↦∫Bf(s,y)dy and s↦fX(s) are continuous at x (for example, it suffices that f is continuous and dominated near x by a function integrable in y), conditioning on a narrow band X∈[x,x+h] makes sense, and as h→0
because numerator and denominator, divided by h, tend to ∫Bf(x,y)dy and fX(x) by continuity. The exact justification does not require continuity:
Proof
Since fX is integrable, the set N={fX=∞} has Lebesgue measure zero, so P(X∈/SX)=∫{fX=0}fX(x)dx+∫NfX(x)dx=0. By Tonelli, P(X∈A,Y∈B)=∫A∫Bf(x,y)dydx, and the outer integral can ignore N. If fX(x)=0, then f(x,y)=0 for almost every y and the inner integrand is zero, as is (∫Bf(y∣x)dy)fX(x) regardless of the value assigned to the conditional. If x∈SX, f(x,y)=f(y∣x)fX(x) by definition. Substitute.
∎
The function x↦∫Bf(y∣x)dy behaves as “P(Y∈B∣X=x)”: averaged against the law of X it returns the joint probability. This is the regular conditional distribution constructed generally in the next lesson without requiring densities. Two cautions: density f is defined only up to sets of measure zero, so f(y∣x) is defined only for almost every x with respect to the law of X; and f(y∣x) is not f(x∣y).
Chain rule, total probability and Bayes
The three identities you will use constantly follow directly from the definition.
Proof
(1) This is the definition written in both orders. The version with n variables follows by applying it repeatedly: f(x1,…,xn)=f(x1,…,xn−1)f(xn∣x1,…,xn−1) and iterate. (2) Integrate (1) over x. (3) Divide f(x,y)=f(y∣x)fX(x) by fY(y) and substitute (2). (4) The variables are independent if and only if f(x,y)=fX(x)fY(y), which divided by fX(x) gives f(y∣x)=fY(y); the converse is (1).
∎
These are the continuous versions of total probability and Bayes’ theorem from the conditioning lesson, with integrals replacing sums. The denominator in Bayes’ rule, fY(y), is the evidence (or marginal likelihood): it can almost never be calculated, and much of approximate Bayesian inference consists of avoiding it.
Hierarchical models: generate the latent variable and then data
A hierarchical model (or latent-variable model) is specified in stages: a law p(z) for the latent variable Z and a conditional law p(x∣z) for the data. By the chain rule the joint is p(z,x)=p(z)p(x∣z), from which come the two required quantities:
p(x)=∫p(x∣z)p(z)dz(marginal, o evidencia),p(z∣x)=p(x)p(x∣z)p(z)(posterior).
To simulate no integral is needed: draw z∼p(z) and then x∼p(x∣z); if you discard z what remains is a sample from p(x). This generative reading, called ancestral sampling, is why such models are useful: describe a mechanism and the integrals remain implicit. There is no guarantee that the integral has a closed form, which is where approximate methods come in.
The formula Var(X)=E[Var(X∣Z)]+Var(E[X∣Z]) just used (within variance plus between variance) is the law of total variance, proved in the next lesson. The general lesson now is: integrating out a latent variable widens the marginal law. In the VAE that integral has no closed form because p(x∣z) is parameterized by a neural network, motivating the variational bound in the generative-models module.
Mixtures: weighted sums of densities
When the latent variable only decides which law in a family applies, the hierarchical model is a mixture.
With a discrete label, Bayes’ theorem gives the component posterior, called the responsibilities:
P(J=k∣X=x)=∑jπjfj(x)πkfk(x).
Moments of a mixture are obtained by conditioning on the label:
Proof
Expectation is linear in the mixture: E[X]=∑kπkE[X∣J=k]. For the second moment, E[X2]=∑kπk(σk2+μk2), and subtracting μ2=∑kπkμ2 leaves ∑kπkσk2+∑kπk(μk2−μ2). The last term equals ∑kπk(μk−μ)2 because ∑kπkμk=μ.
∎
The two terms are “within” plus “between” component variance: a mixture is always at least as dispersed as the average of its components.
Student’s t, a Gaussian with uncertain scale
The practically most important special case of a continuous mixture uses a scale as its latent variable. Let W>0 be a random precision and, given W=w, X∼N(0,1/w). These are Gaussian scale mixtures. They always have heavier tails than a normal:
Proof
Given W, X is normal with variance 1/W and fourth moment 3/W2. Taking expectations, Var(X)=E[E[X2∣W]]=E[1/W] and E[X4]=3E[W−2]. The inequality is Jensen’s inequality for s↦s2 applied to 1/W: E[(1/W)2]≥(E[1/W])2, with equality if and only if 1/W is constant.
∎
With W∼Gamma(ν/2,ν/2), the mixture is exactly a Student t:
The proof is an unnormalized gamma integral, which you work out in the guided exercise. Its interpretation is interesting: a heavy tail is not just greater dispersion; it is uncertainty about scale. When W is almost always 1 but occasionally tiny (small precision means a very wide Gaussian), the mixture is a normal bell with a trail of distant values.
InteractiveStudent's t as a Gaussian mixture
Densities: each thin curve is N(0,1/wk)
Precisions wk come from Gamma(ν/2,ν/2)
Gaussians N(0,1/wk)
average of the K
exact tν density
N(0,1)
density of W and sampled precisions
L1 distance on [−6,6] between the mixture and t0.0829
Each thin blue curve is a Gaussian N(0,1/wk) with precision wk drawn from a Gamma(ν/2,ν/2) (blue ticks in the right panel). The magenta curve is the average of the first K; the gray dashed curve is the exact tν density. Raise K to 2000: the average approaches the t and the L1 distance falls. Turn on the logarithmic axis to see where everything happens: in the tails. Lower ν to 1 (the Cauchy) and raise it to 30 (almost normal). Which Gaussians sustain the tail?
With the mixture in view all moments of t follow. Since 1/W is inverse gamma with mean ν/(ν−2) for ν>2 and E[W−2]=ν2/((ν−2)(ν−4)) for ν>4:
Var(X)=ν−2ν(ν>2),curtosis en exceso=ν−43(ν−2)−3=ν−46(ν>4).
For ν≤2 the variance is infinite and for ν≤4 the fourth moment is infinite: the heavy tail is visible in how many moments exist. With ν=3, the probability of ∣X∣>4 is 2.8% versus 0.006% for the standard normal, about 440 times greater. The fact that t3 has variance 3 does not explain the difference: even measured in standard deviations, exceeding four has probability 0.62% with t3 versus 0.006% with the normal, nearly a hundred times more.
A consequence returns in the tails section. If two variables share the same latent scale, (X1,X2)=(Z1,Z2)/W with correlated Gaussians (Z1,Z2), each not only has heavy tails: when W is small, both shoot up together. Sharing a latent scale introduces tail dependence.
Copulas: separating marginals from dependence
Earlier sections construct joint laws by conditioning. Another way to approach dependence asks what part of a joint law does not depend on the marginals. Consider describing two assets: typically you model each return separately, with its heavy-tailed law, and then “glue” them together. Pearson correlation seems like the glue, but it is not: it is a number depending on the marginals (as exact numbers below show), it does not determine the joint law, and it cannot even take every value in [−1,1] for fixed marginals.
Copulas exploit the fact that, for continuous variables, the probability integral transform turns each marginal uniform. What remains after that operation, the joint law of the two uniforms, is pure dependence.
The result that makes sense of it all is Sklar’s theorem. We prove it for continuous marginals, the case that matters here, and discuss the general case at the end.
Sklar’s theorem says that every joint law is marginals plus a copula, and every pair (marginals, copula) gives a joint law. The two pieces may be chosen separately.
Proof
(1), continuous case. By the probability integral transform, U=F(X) and V=G(Y) are uniform on (0,1). Let C be the joint distribution function of (U,V): it is a copula by definition. We still need {X≤x}={F(X)≤F(x)} almost surely. One inclusion is obvious because F is increasing. If F(X)≤F(x) but X>x, then F is constant on [x,X], and the probability that X falls in an interval of constancy of F is zero. Thus H(x,y)=P(U≤F(x),V≤G(y))=C(F(x),G(y)). Uniqueness is immediate: F and G are onto (0,1) because they are continuous, so the equality determines C throughout [0,1]2.
(2). Let (U,V) have distribution function C and let F−1,G−1 be the quantile functions, satisfying F−1(u)≤x⟺u≤F(x). With X=F−1(U) and Y=G−1(V),
P(X≤x,Y≤y)=P(U≤F(x),V≤G(y))=C(F(x),G(y)),
and the marginals are P(X≤x)=C(F(x),1)=F(x) and analogously for Y. This holds for arbitrary F and G, including those with atoms.
∎
The proof of (2) is also a simulation recipe: to generate (X,Y) with marginals F, G and copula C, draw (U,V)∼C and apply the quantiles, (F−1(U),G−1(V)). This is the two-dimensional inverse transform. With atoms, C is no longer unique (it is determined only on RanF×RanG) and several copulas are compatible; the general existence proof requires interpolation or randomizing jumps (Rüschendorf, 2009).
Copula density and conditionals
If C is twice differentiable, its density is c(u,v)=∂2C/∂u∂v and, differentiating H(x,y)=C(F(x),G(y)),
f(x,y)=c(F(x),G(y))fX(x)fY(y),y por tantof(y∣x)=c(F(x),G(y))fY(y).
The copula density is the correction factor by which the joint departs from independence, and is the same quantity as in the first section: the conditional is the marginal multiplied by c. For independent variables, c≡1. For the Gaussian copula with correlation ρ, writing a=Φ−1(u) and b=Φ−1(v), the ratio of the bivariate normal density to the product of its marginals gives
cρ(u,v)=1−ρ21exp(−2(1−ρ2)ρ2(a2+b2)−2ρab).
Properties justifying the name
The copula does not depend on the marginals. If α,β are strictly increasing, (α(X),β(Y)) has the same copula as (X,Y) (proved in the Spearman exercise). Copulas capture what survives any monotone rescaling. If one is decreasing, the copula is reflected: C(u,v)↦u−C(u,1−v).
Fréchet–Hoeffding bounds. Every copula satisfies W(u,v)≤C(u,v)≤M(u,v), with W=max(u+v−1,0) and M=min(u,v). The upper bound is P(U≤u,V≤v)≤min(P(U≤u),P(V≤v)); the lower, P(U≤u,V≤v)≥1−P(U>u)−P(V>v). M is the copula of (X,α(X)) with α increasing (perfect positive dependence), W that of (X,β(X)) with β decreasing, and Π(u,v)=uv that of independence.
Four copulas to think with
Each family provides a different geometry of the unit square. The first two come from Gaussians, the last two from a latent variable.
Copula
Parameter
Kendall’s τ
Tail dependence
How to simulate
Gaussian
ρ∈(−1,1)
π2arcsinρ
λL=λU=0
Φ(Lε), with LL⊤=R
Student’s t
ρ, ν>0
π2arcsinρ
λL=λU=2Tν+1(−1+ρ(ν+1)(1−ρ))
Tν(Lε/W/ν), W∼χν2
Clayton
θ>0
θ+2θ
λL=2−1/θ, λU=0
latent gamma (below)
Gumbel
θ≥1
1−θ1
λL=0, λU=2−21/θ
latent positive stable
The Gaussian and t copulas are those of multivariate normal and t laws: C(u,v)=P(Z1≤Φ−1(u),Z2≤Φ−1(v)) for normal (Z1,Z2) with correlation ρ (and similarly for tν, whose copula retains the shared latent scale from the previous section). Clayton and Gumbel are Archimedean, C(u,v)=ψ(ψ−1(u)+ψ−1(v)), with ψ(t)=(1+t)−1/θ and ψ(t)=exp(−t1/θ) respectively. Archimedean copulas arise from a hierarchical model:
Proof
Given V=s, P(Uj≤u∣V=s)=P(Ej≥sψ−1(u))=e−sψ−1(u), because ψ is decreasing. The two events are conditionally independent, so P(U1≤u,U2≤v∣V=s)=e−s(ψ−1(u)+ψ−1(v)). Averaging over V and using ψ(t)=E[e−tV] gives ψ(ψ−1(u)+ψ−1(v)). With v=1, ψ−1(1)=0 and P(U1≤u)=u.
∎
For Clayton, ψ(t)=(1+t)−1/θ is the Laplace transform of a Gamma(1/θ,1). For Gumbel, ψ(t)=e−t1/θ is that of a positive stable law with index 1/θ. In both cases dependence comes from a single shared latent variableV (in finance and survival analysis, a frailty factor common to all assets), exactly like the shared scale of t.
InteractiveCopula sculptor
Copula space: (U,V)=(F(X),G(Y))
Data space (X,Y) with selected marginals
Same calibration criterion in all four copulas (click one to select it)
lower corner [0,0.1]2 (joint crashes)
upper corner (joint rises)
other points
Parameterize by
Pearson r (data)0.600
Spearman ρS0.596
Kendall τ0.426
Copula λL / λU0.66 / 0.00
Lower corner (8 expected under independence)45
Upper corner12
The four copulas give the same r with τ of 0.39, 0.40, 0.46, 0.38: equal linear correlation, different structures.
On the left, the sample in copula space (U,V); on the right, the same sample with your chosen marginals. The corners [0,0.1]2 (orange) and [0.9,1]2 (aqua) are highlighted in both views. Below, four copulas calibrated to the same Pearson correlation (or the same τ). Set normal marginals, r=0.6, and cycle through the thumbnails: which copula places more points in the corners? Next choose ‘Kendall's τ’, which fixes the copula, change a marginal to lognormal and see what happens to r and what does not happen to ρS and τ. Back in Pearson mode, with one normal and one lognormal marginal, raise r to 0.9: can it reach it?
Three observations. With fixed Pearson correlation, the four clouds are completely different: the Gaussian barely accumulates points in the corners (with normal marginals it is the familiar ellipse), t has corners in both tails, Clayton only in the lower and Gumbel only in the upper. With fixed copula (τ mode), changing a marginal to lognormal changes r but leaves rank coefficients unchanged; in Pearson mode the reverse happens, because to maintain r the widget must change the copula, and with it ρS and τ. With one normal and one lognormal marginal, Pearson correlation cannot exceed 1/e−1=0.763 however dependent the variables: this is the second defect of Pearson correlation, discussed in the rank section.
Tail dependence
If simultaneous extreme events matter (two failures or two assets crashing together), the relevant information lies in the square’s corners.
λL is “the probability that B is among its worst days when A is, in the limit where being there becomes ever rarer.” It is a property of the copula, not of the marginals: changing the marginals (for example, to heavy tails) does not change it, so a Gaussian copula with t marginals still has λ=0.
Proof
(1)C(q,q)=(2q−θ−1)−1/θ=q(2−qθ)−1/θ, and C(q,q)/q→2−1/θ as q→0.
(2) Let Z1,Z2 be standard normals with correlation ρ<1 and z<0. On event {Z1≤z,Z2≤z} we have Z1+Z2≤2z, and Z1+Z2∼N(0,2(1+ρ)). Therefore
P(Z1≤z)P(Z1≤z,Z2≤z)≤Φ(z)Φ(κz),κ=1+ρ2>1.
Since Φ(z)∼φ(z)/∣z∣ as z→−∞ (Mills ratio), the ratio on the right behaves like e−(κ2−1)z2/2/κ→0. This is the joint-tail exponent, z2/(1+ρ), strictly greater than the marginal exponent z2/2. The upper tail is identical by symmetry.
(3) The t copula is symmetric in its two arguments, so dqdC(q,q)=2P(V≤q∣U=q), and by L’Hôpital’s rule λL=limq→02P(V≤q∣U=q) when the limit exists. With (Y1,Y2) of the bivariate t, the conditional of Y2 given Y1=y is a tν+1 with location ρy and scale (ν+y2)(1−ρ2)/(ν+1). For y=z→−∞, the standardized argument tends to z(1−ρ)/(∣z∣(1−ρ2)/(ν+1))=−(ν+1)(1−ρ)/(1+ρ), and the probability to the value of Tν+1 at that point.
∎
With ρ=0.5 and ν=4, λ=0.253; with ν=10 it falls to 0.082 and with ν=30 to 0.003. As ν→∞ the t approaches the Gaussian and λ→0, but the limit is misleading: with ν=30 the coefficient is only 0.003 and yet, in the worst 0.01% of days, t still assigns twice the joint-crash probability of the Gaussian. A small λ does not mean the effect is negligible at thresholds that matter.
InteractiveJoint crashes
Gaussian copula: corner [0,0.01]2
t copula with ν=4.0: the same corner
Probability that B falls given A falls in its worst 10−k, versus threshold k=−log10q (horizontal axis)
Gaussian (exact)
t (exact)
independence (q)
simulation (at least 10 events)
current threshold
P(B falls∣A falls), Gaussian0.0543
P(B falls∣A falls), t0.2635
Ratio t / Gaussian4.86×
Joint-crash days per 100,000 simulated (Gaussian / t)8 / 22
Expected joint crashes in 10 years (2,500 days)0.136 / 0.659
t limit λ (Gaussian: 0)0.253
The Gaussian copula underestimates joint risk by a factor of 4.9: with the same correlation ρ and marginals, the models disagree on what matters in a crisis.
Two assets with the same correlation ρ: one modeled with a Gaussian copula and the other with a t copula. Simulate 100000 days under each model. Above, the lower corner of the copula square with joint-crash days (red) inside the dashed square. Below, the probability that B crashes given that A crashes, against threshold k=−log10q: exact curves (quadrature) and simulated points. Lower the threshold to k=4. The Gaussian falls toward zero; the t flattens at its λ. Then raise ν and see the t curve move toward the Gaussian, though very slowly. At what threshold does the ratio of t to Gaussian exceed 10?
With ρ=0.5 and ν=4, the exact probabilities of B falling when A falls in its worst q are:
q
Gaussian
t with ν=4
Ratio
10%
0.324
0.384
1.2
1%
0.129
0.288
2.2
0.1%
0.054
0.263
4.9
0.01%
0.023
0.256
11.0
In the center the two models are almost indistinguishable and would be calibrated identically on everyday data. The difference only appears where there are few data to choose between them. In frequency terms, with ρ=0.5 the Gaussian model expects 0.14 joint-crash days in each asset’s worst thousandth every ten years, and t expects 0.66: around five times more.
Rank correlations
Pearson correlation measures linear dependence and depends on the marginals. Rank correlations measure only monotone dependence and are calculated from ranks, so monotone rescaling does not affect them.
They have three properties Pearson does not.
Proof
(1)U=F(X) and V=G(Y) are uniform, with mean 1/2 and variance 1/12, hence ρS=12E[UV]−3. Also, by the tail formula for nonnegative variables, E[UV]=∬P(U>u,V>v)dudv=∬(1−u−v+C(u,v))dudv. Since ∬(1−u−v)dudv=1−21−21=0, this leaves E[UV]=∬C and ρS=12∬C−3. (Independence check: ∬uv=1/4 and ρS=0.) For τ: concordance of (X,Y) with (X′,Y′) is equivalent to that of (U,V) with (U′,V′) because F and G are increasing (almost surely), so it depends only on C.
(2) Proved in the guided exercise: (Fα(α(X)),Gβ(β(Y)))=(F(X),G(Y)).
(3) Let Z1,Z2 be normals with correlation ρ and W1,W2 standard normals independent of each other and of Z. Since Φ(Z1)=P(W1≤Z1∣Z1), E[Φ(Z1)Φ(Z2)]=P(Z1−W1≥0,Z2−W2≥0). The pair (Z1−W1,Z2−W2) is normal with variances 2 and covariance ρ, that is, correlation ρ/2. By Sheppard’s orthant formula, P(ambos≥0)=41+2π1arcsin2ρ, and ρS=12(41+2π1arcsin2ρ)−3=π6arcsin2ρ. For τ, apply the same formula to (Z1−Z1′,Z2−Z2′), normal with correlation ρ: P(concordantes)=2(41+2π1arcsinρ) and τ=2P(concordantes)−1=π2arcsinρ.
∎
Invariance (2) is exactly what Pearson lacks. With standard normals Z1,Z2 of correlation ρ, Corr(Z1,Z2)=ρ, but for lognormals eZ1,eZ2, using E[eZ1+Z2]=e1+ρ and Var(eZ)=e(e−1),
Corr(eZ1,eZ2)=e(e−1)e1+ρ−e=e−1eρ−1.
With ρ=0.8 this gives 0.713, while ρS=π6arcsin0.4=0.786 and τ=π2arcsin0.8=0.590 do not change. There is a second defect: the minimum correlation two lognormals can have is −1/e=−0.368 (attained by (eZ,e−Z)), so not every value of [−1,1] is attainable for fixed marginals, and the maximum is 1 only if the two marginals are of the same type (equal up to location and scale). Spearman and Kendall do not have this problem: since they depend only on the copula, and copulas W and M give −1 and 1, any value of [−1,1] is attainable for any pair of continuous marginals.
Rank coefficients are also used for estimation. Inverting ρ=sin(πτ/2) using the sample τ gives an estimator of ρ in a multivariate t or Gaussian that does not depend on marginal tails and is much more stable with heavy tails, as shown in the libraries section.
A warning: conditioning on a probability-zero event
The first section’s conditional density conditions on {X=x}, a probability-zero event, and seemed unsurprising. It is only because we fixed the conditioning variable from the start: coordinate X. When the event is described differently, the answer changes, for good reason.
Let X,Y be independent standard normals and condition on “Y=X”. There are two natural ways to enclose that event in a family of positive-probability events and take the limit:
Constant-width band:{∣Y−X∣<ε}. This conditions on variable D=Y−X at D=0. Since (X,D) is normal with Cov(X,D)=−1 and Var(D)=2, X∣D=0∼N(0,21).
Wedge:{∣Y/X−1∣<ε}, equivalent to ∣Y−X∣<ε∣X∣. This conditions on R=Y/X at R=1. Under the change (x,r)↦(x,rx) with Jacobian ∣x∣, the joint density of (X,R) is ∣x∣φ(x)φ(rx) and, at r=1, f(x∣R=1)∝∣x∣e−x2, a density with a gap at 0 (normalized, ∣x∣e−x2).
These are two different laws for the same event. E∣X∣ equals 0.564 in the first case and 0.886 in the second.
Interactive‘Y = X’ is not one event, but many
Two ways to approach the diagonal y=x
Law of X within each region versus its limit as ε→0
band and its histogram
band limit: N(0,1/2)
wedge and its histogram
wedge limit: ∣x∣e−x2
Points in the band / wedge11580 / 6862
E∣X∣ in the band (limit 0.564)0.577
E∣X∣ in the wedge (limit 0.886)0.906
P(∣X∣<0.25) in band / wedge (limits 0.276 / 0.061)0.262 / 0.059
It is the same event, {Y=X}, yet two reasonable approximations give different limiting laws. Probability conditioned on a null event is determined by the partition (the variable) used to enclose it.
(X,Y) are independent standard normals. In blue, the constant-width band ∣Y−X∣<ε; in orange, the wedge ∣Y−X∣<ε∣X∣, which admits more points farther from the origin. On the right, the histogram of x in each region (solid) and its limiting law (dashed). Narrow ε: both regions approach the diagonal and yet the histograms do not resemble each other. Look at the probability of ∣X∣<0.25: it tends to 0.276 for the band and 0.061 for the wedge.
The wedge weights regions with large ∣x∣ more heavily because its width grows with ∣x∣: this is the Jacobian. This is the Borel–Kolmogorov paradox, whose classical form conditions on a great circle of a sphere: the conditional law on a meridian differs from that obtained on the equator. The lesson is a hygiene rule: conditioning on a probability-zero event makes sense only relative to a variable (more precisely, a σ-algebra). The formula f(y∣x)=f(x,y)/fX(x) conditions on variable X, and when changing coordinates one must say which variable is held fixed. The next lesson’s conditional expectation does this correctly: it conditions on a σ-algebra and defines the conditional law as an object determined only almost surely.
Implementation from scratch
Start with the mechanics of hierarchical models: simulate the latent variable and data and compare frequencies with this lesson’s exact formulas.
[ ]Hierarchical models: Gamma–Poisson and t as a mixtureBrowser
import numpy as np
from scipy import stats
rng = np.random.default_rng(7)
n = 200_000
# Gamma-Poisson: Lambda ~ Gamma(3, tasa 1/2) y X | Lambda ~ Poisson(Lambda)
a, b = 3.0, 0.5
lam = rng.gamma(shape=a, scale=1 / b, size=n)
x = rng.poisson(lam)
print("media y varianza:", round(x.mean(), 3), round(x.var(), 3), " teoría:", a / b, a / b + a / b**2)
p_nb = b / (1 + b) # scipy: nbinom(r, p) tiene P(X=k) = C(k+r-1, k) p^r (1-p)^k
for k in [0, 1, 5, 15]:
print(f"P(X={k}): simulada {np.mean(x == k):.4f} binomial negativa {stats.nbinom.pmf(k, a, p_nb):.4f} Poisson(6) {stats.poisson.pmf(k, 6):.4f}")
# el posterior de Lambda dado X = 10 es Gamma(a + 10, b + 1): comprobación por rechazo
sel = lam[x == 10]
print("E[Lambda | X=10]: simulada", round(sel.mean(), 3), " Gamma(13, 1.5):", (a + 10) / (b + 1), f"({len(sel)} muestras)")
# la t como mezcla: W ~ Gamma(nu/2, tasa nu/2), X = Z / sqrt(W)
nu = 3.0
w = rng.gamma(nu / 2, 2 / nu, size=n)
t_mix = rng.standard_normal(n) / np.sqrt(w)
print("KS entre la mezcla y t(3):", round(stats.kstest(t_mix, stats.t(nu).cdf).statistic, 4))
print("P(|X| > 4): mezcla", round(np.mean(np.abs(t_mix) > 4), 4), " t exacta", round(2 * stats.t.cdf(-4, nu), 4), " normal", round(2 * stats.norm.cdf(-4), 6))
The negative binomial and gamma posterior emerge from the simulation without a single integral, and the gamma scale mixture reproduces t with a Kolmogorov–Smirnov statistic of 0.0015, on the order of sampling error. Now the four copula samplers. Only Φ and Φ−1 (ndtr, ndtri) and the cdf t are used; the rest is the lesson’s recipe: Cholesky for ellipticals and a shared latent variable for Archimedeans. To check each sampler, Kendall’s τ is estimated from scratch (using every pair) and compared with the table’s theoretical formula.
[ ]Four copula samplers from scratchBrowser
import numpy as np
from scipy.special import ndtr, ndtri
from scipy import stats
def sample_gaussian(R, n, rng):
L = np.linalg.cholesky(R)
Z = rng.standard_normal((n, len(R))) @ L.T
return ndtr(Z)
def sample_t(R, nu, n, rng):
L = np.linalg.cholesky(R)
Z = rng.standard_normal((n, len(R))) @ L.T
W = rng.chisquare(nu, size=(n, 1)) / nu # una escala por fila, compartida por las columnas
return stats.t.cdf(Z / np.sqrt(W), nu)
def sample_clayton(theta, n, d, rng):
V = rng.gamma(1 / theta, 1.0, size=(n, 1)) # latente gamma
E = rng.exponential(size=(n, d))
return (1 + E / V) ** (-1 / theta) # U_j = psi(E_j / V)
def sample_gumbel(theta, n, d, rng):
al = 1 / theta # latente estable positiva (Kanter)
T = rng.uniform(0, np.pi, size=(n, 1)); E0 = rng.exponential(size=(n, 1))
V = np.sin(al * T) / np.sin(T) ** (1 / al) * (np.sin((1 - al) * T) / E0) ** ((1 - al) / al)
E = rng.exponential(size=(n, d))
return np.exp(-(E / V) ** al)
def kendall_tau(x, y):
sx = np.sign(x[:, None] - x[None, :]); sy = np.sign(y[:, None] - y[None, :])
m = len(x)
return (sx * sy).sum() / (m * (m - 1))
def ranks(v):
r = np.empty(len(v)); r[np.argsort(v)] = np.arange(1, len(v) + 1)
return r
def spearman(x, y):
return np.corrcoef(ranks(x), ranks(y))[0, 1]
rng = np.random.default_rng(1)
m = 1500
R = np.array([[1, .6], [.6, 1]])
muestras = {
"gaussiana rho=0.6": (sample_gaussian(R, m, rng), 2 / np.pi * np.arcsin(.6)),
"t(3) rho=0.6": (sample_t(R, 3, m, rng), 2 / np.pi * np.arcsin(.6)),
"Clayton theta=2": (sample_clayton(2.0, m, 2, rng), 2 / (2 + 2)),
"Gumbel theta=2": (sample_gumbel(2.0, m, 2, rng), 1 - 1 / 2),
}
for nombre, (U, tau) in muestras.items():
ks = max(stats.kstest(U[:, j], "uniform").statistic for j in range(2))
print(f"{nombre:18s} tau empírica {kendall_tau(U[:, 0], U[:, 1]):.3f} teórica {tau:.3f} Spearman {spearman(U[:, 0], U[:, 1]):.3f} KS uniforme {ks:.3f}")
The four empirical τ agree with theoretical values within sampling error (about 0.02 with m=1500), and the column marginals are uniform. The two ellipticals give the same τ because they share ρ; Clayton and Gumbel with θ=2 also share it (0.5), with opposite tail structures. It remains to apply arbitrary marginals and see what changes.
[ ]Pearson changes with marginals; Spearman does notBrowser
Spearman is the same across all five rows, 0.785 (the theoretical value is 0.786), because all five use the same U and the marginals are increasing. Pearson ranges from 0.80 with normals to 0.46 with two lognormals of σ=2, where the estimate is also unreliable (theory gives 0.44): with marginals this skewed the sample variance of a lognormal product is enormous.
Now the tails. Simulate 5⋅105 pairs from three copulas with the same Kendall τ, 1/3: the Gaussian and t with the same parameter ρ=0.5, and Clayton calibrated to that τ, and count the fraction of times that when A falls in its worst q so does B; the exact value comes from quadrature of the conditional formula.
[ ]Tail dependence: empirical versus exactBrowser
from scipy import integrate
n = 500_000
R5 = np.array([[1, .5], [.5, 1]])
tau5 = 2 / np.pi * np.arcsin(.5)
th = 2 * tau5 / (1 - tau5) # Clayton con la misma tau de Kendall
modelos = {"gaussiana": sample_gaussian(R5, n, rng), "t(4)": sample_t(R5, 4, n, rng), "Clayton": sample_clayton(th, n, 2, rng)}
def exacto(modelo, q):
if modelo == "gaussiana": # C(q,q) = int phi(x) Phi((z - rho x)/sqrt(1-rho^2)) dx
z = stats.norm.ppf(q)
return integrate.quad(lambda x: stats.norm.pdf(x) * stats.norm.cdf((z - .5 * x) / np.sqrt(.75)), -np.inf, z)[0] / q
if modelo == "t(4)": # Y2 | Y1 = y es t_5 con la escala de la lección
z = stats.t.ppf(q, 4)
f = lambda y: stats.t.pdf(y, 4) * stats.t.cdf((z - .5 * y) / np.sqrt((4 + y * y) * .75 / 5), 5)
return integrate.quad(f, -np.inf, z)[0] / q
return (2 * q ** (-th) - 1) ** (-1 / th) / q
print(f"{'q':>6s}" + "".join(f"{k:>28s}" for k in modelos))
for q in [0.1, 0.01, 0.001]:
fila = ""
for k, Uk in modelos.items():
emp = np.mean((Uk[:, 0] <= q) & (Uk[:, 1] <= q)) / q
fila += f" {emp:8.4f} (exacto {exacto(k, q):.4f})"
print(f"{q:6.3f}{fila}")
The columns confirm the figure. The Gaussian falls with q (0.32, 0.13, 0.054) and t flattens near λ=0.253; Clayton stays around 2−1/θ=0.5 (θ=1). At q=0.001 there are only about 130 coincidences of t, so the simulation differs by a few percentage points from quadrature: the noise of counting rare events.
The professional version
For real use, there is no need to write samplers. SciPy provides multivariate normals and t, rank coefficients and integration; for complete copulas (maximum-likelihood fitting, Frank, vine copulas) statsmodels.distributions.copula and specialized packages exist. Here SciPy is used for the most practically important part: estimating correlation of a heavy-tailed t.
Task
SciPy
Multivariate normal / t
stats.multivariate_normal, stats.multivariate_t
Kendall’s τ, ρS
stats.kendalltau, stats.spearmanr
Marginals: cdf, quantile
dist.cdf, dist.ppf
Pseudo-observations
stats.rankdata(x) / (len(x) + 1)
[ ]Estimate ρ with heavy tails: Pearson versus Kendall inversionBrowser
rng = np.random.default_rng(3)
Rr = np.array([[1, .6], [.6, 1]])
rep, nn = 300, 400
rp, rt = [], []
for _ in range(rep):
X = stats.multivariate_t(loc=[0, 0], shape=Rr, df=3).rvs(size=nn, random_state=rng)
rp.append(np.corrcoef(X[:, 0], X[:, 1])[0, 1])
rt.append(np.sin(np.pi * stats.kendalltau(X[:, 0], X[:, 1])[0] / 2)) # rho = sin(pi tau / 2)
print("rho verdadero 0.6")
print(" Pearson: media", round(np.mean(rp), 3), " desviación típica", round(np.std(rp), 3))
print(" sin(pi tau / 2): media", round(np.mean(rt), 3), " desviación típica", round(np.std(rt), 3))
# pseudo-observaciones: la cópula empírica no necesita conocer las marginales
X = stats.multivariate_t(loc=[0, 0], shape=Rr, df=3).rvs(size=20000, random_state=rng)
Up = np.column_stack([stats.rankdata(X[:, j]) / (len(X) + 1) for j in range(2)])
q = 0.01
print("lambda_L empírico a q = 0.01 (pseudo-observaciones):", round(np.mean((Up[:, 0] <= q) & (Up[:, 1] <= q)) / q, 3))
With heavy tails (t with 3 degrees of freedom, n=400 and 300 repetitions), both estimators are approximately unbiased, but the one based on τ has standard deviation about two and a half times smaller (0.04 versus 0.10): one extreme observation dominates Pearson’s product of deviations, while in τ only the sign of its pairs matters, each weighted 1/(2n). The final block is the standard copula-fitting workflow: first ranks (pseudo-observations, U^=rango/(n+1), which eliminate the marginals), then the copula.
Common mistakes
Exercises
NumericPosterior of a component
In mixture 0.7N(0,1)+0.3N(3,1), calculate the posterior probability of the second component given x=2.
NumericVariance of a mixture
Let X∼21N(0,1)+21N(4,1). Calculate Var(X).
NumericTail of a Clayton copula
A Clayton copula has Kendall's τ equal to 0.5. What is its lower-tail dependence coefficient λL?
NumericPearson after exponentiation
Z1 and Z2 are standard normals with correlation 0.8. Calculate the Pearson correlation between eZ1 and eZ2.
QuizMore joint crashes
Three models for returns of two assets all have normal marginals and the same Kendall τ, 1/3 (that of a bivariate normal with correlation 0.5); their Pearson correlations are between 0.48 and 0.51. Which produces more extreme joint crashes (both in their worst 0.1%)?
QuizWhat is the law of $X$ given $Y = X$?
Let X,Y be independent standard normals. One person claims that, given event {Y=X}, the law of X is N(0,1/2); another says its density is ∣x∣e−x2. What is true?
QuizWhat is preserved and what is not
Which of these statements hold for variables with continuous marginals?
More than one answer may be correct.
ProofSpearman is invariant under increasing transformations
Prove: Let X,Y have continuous distribution functions F, G, and let α,β:R→R be strictly increasing and measurable. Then ρS(α(X),β(Y))=ρS(X,Y), where ρS(X,Y)=Corr(F(X),G(Y)).
0
Call Fα and Gβ the distribution functions of α(X) and β(Y). Since α is injective, α(X) has no atoms and Fα is continuous, so ρS(α(X),β(Y))=Corr(Fα(α(X)),Gβ(β(Y))).
Step 1 of 3. What is Fα(α(x)) for x∈R?
ProofStudent's t as a gamma mixture
Prove: If W∼Gamma(ν/2,ν/2) (shape and rate) and, given W=w, X∼N(0,1/w), then X has the density of a Student t with ν degrees of freedom: fν(x)=νπΓ(2ν)Γ(2ν+1)(1+νx2)−2ν+1.
0
Recall that N(0,1/w) has density w/(2π)e−wx2/2 and gamma has density Γ(ν/2)(ν/2)ν/2wν/2−1e−νw/2.
Step 1 of 4. How do you obtain the marginal density of X?
CodeGaussian copula sampler with marginals
Implement sample_gaussian_copula(R, ppfs, n, seed=0), returning an array of shape (n, d) with n samples of a vector with Gaussian copula of correlation matrix R (of d×d) and marginals given by quantile functions ppfs[j] (one per column: ppfs[j](u) receives an array in (0,1)). Use np.random.default_rng(seed) and Cholesky factorization; you may use scipy.special.ndtr as Φ. Do not call scipy.stats.multivariate_normal.
import numpy as np
from scipy.special import ndtr
def sample_gaussian_copula(R, ppfs, n, seed=0):
"""n muestras de un vector con cópula gaussiana de correlación R y marginales ppfs[j]."""
rng = np.random.default_rng(seed)
R = np.asarray(R, dtype=float)
d = R.shape[0]
# tu código: Z ~ N(0, R) con Cholesky; U = Phi(Z); X_j = ppfs[j](U_j)
return np.zeros((n, d))
Shift+Enter to run
Summary
Key idea
A joint law is marginals plus a copula (Sklar), and a conditional is a renormalized slice: Pearson correlation determines neither, and what decides joint risk in a crisis, tail dependence, is a property of the copula.
Conditional density.f(y∣x)=f(x,y)/fX(x) for fX(x)>0: the joint slice divided by its area. It gives the chain rule, total probability and Bayes for densities.
Hierarchical models and mixtures. Draw the latent variable and then the data; the marginal is ∫p(x∣z)p(z)dz and its variance is never less than the average conditional variance: Var(X)≥E[Var(X∣Z)]. Student’s t is a mixture of Gaussians with gamma precision: heavy tails are uncertainty about scale.
Copulas. Sklar: every joint law is H(x,y)=C(F(x),G(y)), with C unique if marginals are continuous, and every pair (marginals, copula) produces one. c(u,v) is the correction factor relative to independence, and Archimedean copulas are hierarchical models with a shared latent variable.
Tails.λL=limC(q,q)/q. Gaussian has λ=0 for ∣ρ∣<1; t has λ>0; Clayton has a lower tail and Gumbel an upper tail. At the same correlation, extreme joint risk differs by an increasing factor as the threshold falls.
Ranks.ρS and τ depend only on the copula and are invariant under increasing transformations; for the Gaussian, ρS=π6arcsin2ρ and τ=π2arcsinρ. Pearson is not invariant and its attainable range depends on the marginals.
Beware null events. Conditioning on {Y=X} gives different laws depending on the variable used to enclose it (band or wedge). The conditional law is defined relative to a σ-algebra, developed in the next lesson.