Module contents
Lesson 11 of 24Core 95 min

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.

Before you start

Motivation: the latent variable and the crisis

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)\vb{z} \sim \Normal(\vb{0}, \mat{I}), then draw the image x\vb{x} from a law depending on z\vb{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) ⁣dzp(\vb{x}) = \int p(\vb{x} \given \vb{z})\,p(\vb{z})\dd\vb{z} over every possible code. The inverse question, which code produced this image, is a conditional density p(z∣x)p(\vb{z} \given \vb{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.50.5. You want the probability that both fall together among their 0.1 %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.50.5, when AA is in its worst thousandth of days the probability that BB is too is 5.4 %5.4\,\%. If instead you join them using a bivariate tt with 44 degrees of freedom and the same parameter 0.50.5, which leaves the marginals and Kendall’s τ\tau unchanged (and, with normal marginals, a Pearson correlation of 0.490.49 versus 0.500.50), it is 26 %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:

  1. Conditional densities. What f(y∣x)f(y \given x) means when P(X=x)=0\Pr(X = x) = 0, and how to obtain the chain rule, the law of total probability and Bayes’ theorem for densities.
  2. 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 tt is a Gaussian with uncertain scale.
  3. Copulas and Sklar’s theorem. Separate marginals and dependence, construct tailored joint laws and simulate them.
  4. Tails and ranks. Why Pearson correlation misleads, and what tail dependence and rank correlations measure.
  5. 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)(X, Y) be a random vector with X∈RpX \in \R^p, Y∈RqY \in \R^q and joint density f(x,y)f(x, y) with respect to Lebesgue measure (joint laws and density come from earlier lessons). By Fubini–Tonelli, XX has marginal density fX(x)=∫f(x,y) ⁣dyf_X(x) = \int f(x, y)\dd y. Conditional probabilities of events, P(B∣A)=P(A∩B)/P(A)\Pr(B \given A) = \Pr(A \cap B)/\Pr(A), require P(A)>0\Pr(A) > 0, and here the event {X=x}\{X = x\} has probability zero. The natural way out is what one would do with a sample: take the fixed slice xx of the joint and renormalize it to integrate to one.

The numerator f(x,y)f(x, y), as a function of yy, is the slice. Its area is fX(x)f_X(x), not 1: dividing by fX(x)f_X(x) renormalizes it. The figure shows this with four joint laws sharing the same marginal X∼N(0,1)X \sim \Normal(0, 1).

InteractiveSlice and renormalize
Joint density f(x,y)f(x, y) (stronger color means higher density)
−2−1012−2−101234xy
What YY sees at slice x=x0x = x_0
density
  • unnormalized slice f(x0,y)f(x_0, y)
  • conditional f(y∣x0)f(y \given x_0)
  • marginal fY(y)f_Y(y)
  • E[Y∣X=x]\E[Y \given X = x]
Joint law
0.80
1.20
Slice area, fX(x0)f_X(x_0)0.1942
E[Y∣X=x0]\E[Y \given X = x_0]0.960
sd(Y∣X=x0)\mathrm{sd}(Y \given X = x_0)0.600
Modes of f(y∣x0)f(y \given x_0)1
P(Y>1∣X=x0)\Pr(Y > 1 \given X = x_0) versus P(Y>1)\Pr(Y > 1)0.473 / 0.159
With a joint Gaussian, the conditional is another Gaussian: the mean shifts to ρx0\rho x_0 and variance drops to 1−ρ21 - \rho^2, independently of x0x_0.
Heat map of a joint density f(x,y)f(x, y). Drag the orange line (or touch the map) to choose x0x_0. On the right, the slice f(x0,y)f(x_0, y) is dashed and the conditional density f(y∣x0)f(y \given x_0) is the same curve scaled by 1/fX(x0)1/f_X(x_0), now with area 1; the marginal fYf_Y is gray. The map's magenta curve is E[Y∣X=x]\E[Y \given X = x] and the dashed band is ±\pm one standard deviation. Start with the correlated Gaussian and increase ρ\rho: the mean shifts and the spread falls. Switch to the banana (what does correlation say here?), the funnel (what changes with xx 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:

  1. The conditional is distinct from the marginal. With ρ=0.8\rho = 0.8 and x0=1.2x_0 = 1.2, knowing X=1.2X = 1.2 shifts the law of YY to a bell centered on 0.960.96 with standard deviation 0.60.6, compared with marginal N(0,1)\Normal(0, 1).
  2. The mean does not tell the whole story. The funnel has E[Y∣X=x]=0\E[Y \given X = x] = 0 for every xx yet XX controls the dispersion of YY. The cross has the same constant conditional mean and a bimodal conditional law.
  3. The slice area is a density. fX(x0)f_X(x_0) is the number to divide by, and the quantity divided changes from one x0x_0 to another: in the tails of XX 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 XX (p=1p = 1): if fX(x)>0f_X(x) > 0 and the functions s↦∫Bf(s,y) ⁣dys \mapsto \int_B f(s, y)\dd y and s↦fX(s)s \mapsto f_X(s) are continuous at xx (for example, it suffices that ff is continuous and dominated near xx by a function integrable in yy), conditioning on a narrow band X∈[x,x+h]X \in [x, x + h] makes sense, and as h→0h \to 0

P(Y∈B∣X∈[x,x+h])=∫xx+h ⁣∫Bf(s,y) ⁣dy ⁣ds∫xx+hfX(s) ⁣ds  ⟶  ∫Bf(x,y)fX(x) ⁣dy,\Pr(Y \in B \given X \in [x, x + h]) = \frac{\int_x^{x+h}\!\int_B f(s, y)\dd y \dd s}{\int_x^{x+h} f_X(s)\dd s} \;\longrightarrow\; \int_B \frac{f(x, y)}{f_X(x)}\dd y,

because numerator and denominator, divided by hh, tend to ∫Bf(x,y) ⁣dy\int_B f(x, y)\dd y and fX(x)f_X(x) by continuity. The exact justification does not require continuity:

Proof

Since fXf_X is integrable, the set N={fX=∞}N = \{f_X = \infty\} has Lebesgue measure zero, so P(X∉SX)=∫{fX=0}fX(x) ⁣dx+∫NfX(x) ⁣dx=0\Pr(X \notin S_X) = \int_{\{f_X = 0\}} f_X(x)\dd x + \int_N f_X(x)\dd x = 0. By Tonelli, P(X∈A,Y∈B)=∫A∫Bf(x,y) ⁣dy ⁣dx\Pr(X \in A, Y \in B) = \int_A \int_B f(x, y)\dd y \dd x, and the outer integral can ignore NN. If fX(x)=0f_X(x) = 0, then f(x,y)=0f(x, y) = 0 for almost every yy and the inner integrand is zero, as is (∫Bf(y∣x) ⁣dy)fX(x)\big(\int_B f(y \given x)\dd y\big) f_X(x) regardless of the value assigned to the conditional. If x∈SXx \in S_X, f(x,y)=f(y∣x)fX(x)f(x, y) = f(y \given x) f_X(x) by definition. Substitute.

∎

The function x↦∫Bf(y∣x) ⁣dyx \mapsto \int_B f(y \given x)\dd y behaves as “P(Y∈B∣X=x)\Pr(Y \in B \given X = x)”: averaged against the law of XX it returns the joint probability. This is the regular conditional distribution constructed generally in the next lesson without requiring densities. Two cautions: density ff is defined only up to sets of measure zero, so f(y∣x)f(y \given x) is defined only for almost every xx with respect to the law of XX; and f(y∣x)f(y \given x) is not f(x∣y)f(x \given 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 nn variables follows by applying it repeatedly: f(x1,…,xn)=f(x1,…,xn−1) f(xn∣x1,…,xn−1)f(x_1, \dots, x_n) = f(x_1, \dots, x_{n-1})\,f(x_n \given x_1, \dots, x_{n-1}) and iterate. (2) Integrate (1) over xx. (3) Divide f(x,y)=f(y∣x)fX(x)f(x, y) = f(y \given x) f_X(x) by fY(y)f_Y(y) and substitute (2). (4) The variables are independent if and only if f(x,y)=fX(x)fY(y)f(x, y) = f_X(x) f_Y(y), which divided by fX(x)f_X(x) gives f(y∣x)=fY(y)f(y \given x) = f_Y(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)f_Y(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)p(z) for the latent variable ZZ and a conditional law p(x∣z)p(x \given z) for the data. By the chain rule the joint is p(z,x)=p(z) p(x∣z)p(z, x) = p(z)\,p(x \given z), from which come the two required quantities:

p(x)=∫p(x∣z) p(z) ⁣dz(marginal, o evidencia),p(z∣x)=p(x∣z) p(z)p(x)(posterior).p(x) = \int p(x \given z)\,p(z)\dd z \quad\text{(marginal, o evidencia)}, \qquad p(z \given x) = \frac{p(x \given z)\,p(z)}{p(x)} \quad\text{(posterior)}.

To simulate no integral is needed: draw z∼p(z)z \sim p(z) and then x∼p(x∣z)x \sim p(x \given z); if you discard zz what remains is a sample from p(x)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])\Var(X) = \E[\Var(X \given Z)] + \Var(\E[X \given 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)p(\vb{x} \given \vb{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)=πkfk(x)∑jπjfj(x).\Pr(J = k \given X = x) = \frac{\pi_k f_k(x)}{\sum_j \pi_j f_j(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]\E[X] = \sum_k \pi_k \E[X \given J = k]. For the second moment, E[X2]=∑kπk(σk2+μk2)\E[X^2] = \sum_k \pi_k(\sigma_k^2 + \mu_k^2), and subtracting μ2=∑kπkμ2\mu^2 = \sum_k \pi_k\mu^2 leaves ∑kπkσk2+∑kπk(μk2−μ2)\sum_k \pi_k\sigma_k^2 + \sum_k \pi_k(\mu_k^2 - \mu^2). The last term equals ∑kπk(μk−μ)2\sum_k \pi_k(\mu_k - \mu)^2 because ∑kπkμk=μ\sum_k \pi_k\mu_k = \mu.

∎

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 tt, a Gaussian with uncertain scale

The practically most important special case of a continuous mixture uses a scale as its latent variable. Let W>0W > 0 be a random precision and, given W=wW = w, X∼N(0,1/w)X \sim \Normal(0, 1/w). These are Gaussian scale mixtures. They always have heavier tails than a normal:

Proof

Given WW, XX is normal with variance 1/W1/W and fourth moment 3/W23/W^2. Taking expectations, Var⁡(X)=E[E[X2∣W]]=E[1/W]\Var(X) = \E[\E[X^2 \given W]] = \E[1/W] and E[X4]=3E[W−2]\E[X^4] = 3\E[W^{-2}]. The inequality is Jensen’s inequality for s↦s2s \mapsto s^2 applied to 1/W1/W: E[(1/W)2]≥(E[1/W])2\E[(1/W)^2] \ge (\E[1/W])^2, with equality if and only if 1/W1/W is constant.

∎

With W∼Gamma(ν/2,ν/2)W \sim \mathrm{Gamma}(\nu/2, \nu/2), the mixture is exactly a Student tt:

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 WW is almost always 11 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)\mathrm{N}(0, 1/w_k)
−4−20240.10.20.30.40.5
Precisions wkw_k come from Gamma(ν/2,ν/2)(\nu/2, \nu/2)
0.51.01.52.02.51.02.0
  • Gaussians N(0,1/wk)\mathrm{N}(0, 1/w_k)
  • average of the KK
  • exact tνt_\nu density
  • N(0,1)\mathrm{N}(0, 1)
  • density of WW and sampled precisions
3.0
12
L1L^1 distance on [−6,6][-6, 6] between the mixture and tt0.0829
P(∣X∣>4)\Pr(\abs{X} > 4): mixture / tνt_\nu / normal0.980 % / 2.801 % / 0.0063 %
Variance of tt, ν/(ν−2)\nu/(\nu - 2)3.000
Excess kurtosis, 6/(ν−4)6/(\nu - 4)∞
Each thin blue curve is a Gaussian N(0,1/wk)\Normal(0, 1/w_k) with precision wkw_k drawn from a Gamma(ν/2,ν/2)(\nu/2, \nu/2) (blue ticks in the right panel). The magenta curve is the average of the first KK; the gray dashed curve is the exact tνt_\nu density. Raise KK to 20002000: the average approaches the tt and the L1L^1 distance falls. Turn on the logarithmic axis to see where everything happens: in the tails. Lower ν\nu to 11 (the Cauchy) and raise it to 3030 (almost normal). Which Gaussians sustain the tail?

With the mixture in view all moments of tt follow. Since 1/W1/W is inverse gamma with mean ν/(ν−2)\nu/(\nu - 2) for ν>2\nu > 2 and E[W−2]=ν2/((ν−2)(ν−4))\E[W^{-2}] = \nu^2/((\nu-2)(\nu-4)) for ν>4\nu > 4:

Var⁡(X)=νν−2 (ν>2),curtosis en exceso=3(ν−2)ν−4−3=6ν−4 (ν>4).\Var(X) = \frac{\nu}{\nu - 2}\ (\nu > 2), \qquad \text{curtosis en exceso} = \frac{3(\nu-2)}{\nu-4} - 3 = \frac{6}{\nu - 4}\ (\nu > 4).

For ν≤2\nu \le 2 the variance is infinite and for ν≤4\nu \le 4 the fourth moment is infinite: the heavy tail is visible in how many moments exist. With ν=3\nu = 3, the probability of ∣X∣>4\abs{X} > 4 is 2.8 %2.8\,\% versus 0.006 %0.006\,\% for the standard normal, about 440440 times greater. The fact that t3t_3 has variance 33 does not explain the difference: even measured in standard deviations, exceeding four has probability 0.62 %0.62\,\% with t3t_3 versus 0.006 %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(X_1, X_2) = (Z_1, Z_2)/\sqrt{W} with correlated Gaussians (Z1,Z2)(Z_1, Z_2), each not only has heavy tails: when WW 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][-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)U = F(X) and V=G(Y)V = G(Y) are uniform on (0,1)(0, 1). Let CC be the joint distribution function of (U,V)(U, V): it is a copula by definition. We still need {X≤x}={F(X)≤F(x)}\{X \le x\} = \{F(X) \le F(x)\} almost surely. One inclusion is obvious because FF is increasing. If F(X)≤F(x)F(X) \le F(x) but X>xX > x, then FF is constant on [x,X][x, X], and the probability that XX falls in an interval of constancy of FF is zero. Thus H(x,y)=P(U≤F(x),V≤G(y))=C(F(x),G(y))H(x, y) = \Pr(U \le F(x), V \le G(y)) = C(F(x), G(y)). Uniqueness is immediate: FF and GG are onto (0,1)(0, 1) because they are continuous, so the equality determines CC throughout [0,1]2[0, 1]^2.

(2). Let (U,V)(U, V) have distribution function CC and let F−1,G−1F^{-1}, G^{-1} be the quantile functions, satisfying F−1(u)≤x  ⟺  u≤F(x)F^{-1}(u) \le x \iff u \le F(x). With X=F−1(U)X = F^{-1}(U) and Y=G−1(V)Y = G^{-1}(V),

P(X≤x,Y≤y)=P(U≤F(x),V≤G(y))=C(F(x),G(y)),\Pr(X \le x, Y \le y) = \Pr(U \le F(x), V \le G(y)) = C(F(x), G(y)),

and the marginals are P(X≤x)=C(F(x),1)=F(x)\Pr(X \le x) = C(F(x), 1) = F(x) and analogously for YY. This holds for arbitrary FF and GG, including those with atoms.

∎

The proof of (2) is also a simulation recipe: to generate (X,Y)(X, Y) with marginals FF, GG and copula CC, draw (U,V)∼C(U, V) \sim C and apply the quantiles, (F−1(U),G−1(V))(F^{-1}(U), G^{-1}(V)). This is the two-dimensional inverse transform. With atoms, CC is no longer unique (it is determined only on Ran⁡F×Ran⁡G\operatorname{Ran}F \times \operatorname{Ran}G) and several copulas are compatible; the general existence proof requires interpolation or randomizing jumps (Rüschendorf, 2009).

Copula density and conditionals

If CC is twice differentiable, its density is c(u,v)=∂2C/∂u ∂vc(u, v) = \partial^2 C/\partial u\,\partial v and, differentiating H(x,y)=C(F(x),G(y))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).f(x, y) = c\big(F(x), G(y)\big)\,f_X(x)\,f_Y(y), \qquad\text{y por tanto}\qquad f(y \given x) = c\big(F(x), G(y)\big)\,f_Y(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 cc. For independent variables, c≡1c \equiv 1. For the Gaussian copula with correlation ρ\rho, writing a=Φ−1(u)a = \Phi^{-1}(u) and b=Φ−1(v)b = \Phi^{-1}(v), the ratio of the bivariate normal density to the product of its marginals gives

cρ(u,v)=11−ρ2exp⁡ ⁣(−ρ2(a2+b2)−2ρab2(1−ρ2)).c_\rho(u, v) = \frac{1}{\sqrt{1 - \rho^2}}\exp\!\Big(-\frac{\rho^2(a^2 + b^2) - 2\rho ab}{2(1 - \rho^2)}\Big).

Properties justifying the name

  • The copula does not depend on the marginals. If α,β\alpha, \beta are strictly increasing, (α(X),β(Y))(\alpha(X), \beta(Y)) has the same copula as (X,Y)(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)C(u, v) \mapsto u - C(u, 1 - v).
  • Fréchet–Hoeffding bounds. Every copula satisfies W(u,v)≤C(u,v)≤M(u,v)W(u, v) \le C(u, v) \le M(u, v), with W=max⁡(u+v−1,0)W = \max(u + v - 1, 0) and M=min⁡(u,v)M = \min(u, v). The upper bound is P(U≤u,V≤v)≤min⁡(P(U≤u),P(V≤v))\Pr(U \le u, V \le v) \le \min(\Pr(U \le u), \Pr(V \le v)); the lower, P(U≤u,V≤v)≥1−P(U>u)−P(V>v)\Pr(U \le u, V \le v) \ge 1 - \Pr(U > u) - \Pr(V > v). MM is the copula of (X,α(X))(X, \alpha(X)) with α\alpha increasing (perfect positive dependence), WW that of (X,β(X))(X, \beta(X)) with β\beta decreasing, and Π(u,v)=uv\Pi(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.

CopulaParameterKendall’s τ\tauTail dependenceHow to simulate
Gaussianρ∈(−1,1)\rho \in (-1, 1)2πarcsin⁡ρ\frac{2}{\pi}\arcsin\rhoλL=λU=0\lambda_L = \lambda_U = 0Φ(Lε)\Phi(\mat{L}\vb{\varepsilon}), with LL⊤=R\mat{L}\mat{L}\T = \mat{R}
Student’s ttρ\rho, ν>0\nu > 02πarcsin⁡ρ\frac{2}{\pi}\arcsin\rhoλL=λU=2 Tν+1 ⁣(−(ν+1)(1−ρ)1+ρ)\lambda_L = \lambda_U = 2\,T_{\nu+1}\!\big(-\sqrt{\tfrac{(\nu+1)(1-\rho)}{1+\rho}}\big)Tν(Lε/W/ν)T_\nu\big(\mat{L}\vb{\varepsilon}/\sqrt{W/\nu}\big), W∼χν2W \sim \chi^2_\nu
Claytonθ>0\theta > 0θθ+2\frac{\theta}{\theta + 2}λL=2−1/θ\lambda_L = 2^{-1/\theta}, λU=0\lambda_U = 0latent gamma (below)
Gumbelθ≥1\theta \ge 11−1θ1 - \frac1\thetaλL=0\lambda_L = 0, λU=2−21/θ\lambda_U = 2 - 2^{1/\theta}latent positive stable

The Gaussian and tt copulas are those of multivariate normal and tt laws: C(u,v)=P(Z1≤Φ−1(u),Z2≤Φ−1(v))C(u, v) = \Pr(Z_1 \le \Phi^{-1}(u), Z_2 \le \Phi^{-1}(v)) for normal (Z1,Z2)(Z_1, Z_2) with correlation ρ\rho (and similarly for tνt_\nu, whose copula retains the shared latent scale from the previous section). Clayton and Gumbel are Archimedean, C(u,v)=ψ(ψ−1(u)+ψ−1(v))C(u, v) = \psi\big(\psi^{-1}(u) + \psi^{-1}(v)\big), with ψ(t)=(1+t)−1/θ\psi(t) = (1 + t)^{-1/\theta} and ψ(t)=exp⁡(−t1/θ)\psi(t) = \exp(-t^{1/\theta}) respectively. Archimedean copulas arise from a hierarchical model:

Proof

Given V=sV = s, P(Uj≤u∣V=s)=P(Ej≥s ψ−1(u))=e−sψ−1(u)\Pr(U_j \le u \given V = s) = \Pr(E_j \ge s\,\psi^{-1}(u)) = e^{-s\psi^{-1}(u)}, because ψ\psi is decreasing. The two events are conditionally independent, so P(U1≤u,U2≤v∣V=s)=e−s(ψ−1(u)+ψ−1(v))\Pr(U_1 \le u, U_2 \le v \given V = s) = e^{-s(\psi^{-1}(u) + \psi^{-1}(v))}. Averaging over VV and using ψ(t)=E[e−tV]\psi(t) = \E[e^{-tV}] gives ψ(ψ−1(u)+ψ−1(v))\psi\big(\psi^{-1}(u) + \psi^{-1}(v)\big). With v=1v = 1, ψ−1(1)=0\psi^{-1}(1) = 0 and P(U1≤u)=u\Pr(U_1 \le u) = u.

∎

For Clayton, ψ(t)=(1+t)−1/θ\psi(t) = (1 + t)^{-1/\theta} is the Laplace transform of a Gamma(1/θ,1)\mathrm{Gamma}(1/\theta, 1). For Gumbel, ψ(t)=e−t1/θ\psi(t) = e^{-t^{1/\theta}} is that of a positive stable law with index 1/θ1/\theta. In both cases dependence comes from a single shared latent variable VV (in finance and survival analysis, a frailty factor common to all assets), exactly like the shared scale of tt.

InteractiveCopula sculptor
Copula space: (U,V)=(F(X),G(Y))(U, V) = (F(X), G(Y))
Data space (X,Y)(X, Y) with selected marginals
−2.00.02.0−2.00.02.0
Same calibration criterion in all four copulas (click one to select it)
  • lower corner [0,0.1]2[0, 0.1]^2 (joint crashes)
  • upper corner (joint rises)
  • other points
Parameterize by
0.60
3.0
Pearson rr (data)0.600
Spearman ρS\rho_S0.596
Kendall τ\tau0.426
Copula λL\lambda_L / λU\lambda_U0.66 / 0.00
Lower corner (8 expected under independence)45
Upper corner12
The four copulas give the same rr 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)(U, V); on the right, the same sample with your chosen marginals. The corners [0,0.1]2[0, 0.1]^2 (orange) and [0.9,1]2[0.9, 1]^2 (aqua) are highlighted in both views. Below, four copulas calibrated to the same Pearson correlation (or the same τ\tau). Set normal marginals, r=0.6r = 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 rr and what does not happen to ρS\rho_S and τ\tau. Back in Pearson mode, with one normal and one lognormal marginal, raise rr to 0.90.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), tt has corners in both tails, Clayton only in the lower and Gumbel only in the upper. With fixed copula (τ\tau mode), changing a marginal to lognormal changes rr but leaves rank coefficients unchanged; in Pearson mode the reverse happens, because to maintain rr the widget must change the copula, and with it ρS\rho_S and τ\tau. With one normal and one lognormal marginal, Pearson correlation cannot exceed 1/e−1=0.7631/\sqrt{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\lambda_L is “the probability that BB is among its worst days when AA 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 tt marginals still has λ=0\lambda = 0.

Proof

(1) C(q,q)=(2q−θ−1)−1/θ=q (2−qθ)−1/θC(q, q) = (2q^{-\theta} - 1)^{-1/\theta} = q\,(2 - q^{\theta})^{-1/\theta}, and C(q,q)/q→2−1/θC(q, q)/q \to 2^{-1/\theta} as q→0q \to 0.

(2) Let Z1,Z2Z_1, Z_2 be standard normals with correlation ρ<1\rho < 1 and z<0z < 0. On event {Z1≤z,Z2≤z}\{Z_1 \le z, Z_2 \le z\} we have Z1+Z2≤2zZ_1 + Z_2 \le 2z, and Z1+Z2∼N(0,2(1+ρ))Z_1 + Z_2 \sim \Normal(0, 2(1 + \rho)). Therefore

P(Z1≤z,Z2≤z)P(Z1≤z)≤Φ(κz)Φ(z),κ=21+ρ>1.\frac{\Pr(Z_1 \le z, Z_2 \le z)}{\Pr(Z_1 \le z)} \le \frac{\Phi\big(\kappa z\big)}{\Phi(z)}, \qquad \kappa = \sqrt{\frac{2}{1 + \rho}} > 1.

Since Φ(z)∼φ(z)/∣z∣\Phi(z) \sim \varphi(z)/\abs{z} as z→−∞z \to -\infty (Mills ratio), the ratio on the right behaves like e−(κ2−1)z2/2/κ→0e^{-(\kappa^2 - 1)z^2/2}/\kappa \to 0. This is the joint-tail exponent, z2/(1+ρ)z^2/(1 + \rho), strictly greater than the marginal exponent z2/2z^2/2. The upper tail is identical by symmetry.

(3) The tt copula is symmetric in its two arguments, so  ⁣d ⁣dqC(q,q)=2 P(V≤q∣U=q)\frac{\dd}{\dd q}C(q, q) = 2\,\Pr(V \le q \given U = q), and by L’Hôpital’s rule λL=lim⁡q→02 P(V≤q∣U=q)\lambda_L = \lim_{q \to 0}2\,\Pr(V \le q \given U = q) when the limit exists. With (Y1,Y2)(Y_1, Y_2) of the bivariate tt, the conditional of Y2Y_2 given Y1=yY_1 = y is a tν+1t_{\nu+1} with location ρy\rho y and scale (ν+y2)(1−ρ2)/(ν+1)\sqrt{(\nu + y^2)(1 - \rho^2)/(\nu + 1)}. For y=z→−∞y = z \to -\infty, the standardized argument tends to z(1−ρ)/(∣z∣(1−ρ2)/(ν+1))=−(ν+1)(1−ρ)/(1+ρ)z(1 - \rho)/\big(\abs{z}\sqrt{(1 - \rho^2)/(\nu+1)}\big) = -\sqrt{(\nu+1)(1-\rho)/(1+\rho)}, and the probability to the value of Tν+1T_{\nu+1} at that point.

∎

With ρ=0.5\rho = 0.5 and ν=4\nu = 4, λ=0.253\lambda = 0.253; with ν=10\nu = 10 it falls to 0.0820.082 and with ν=30\nu = 30 to 0.0030.003. As ν→∞\nu \to \infty the tt approaches the Gaussian and λ→0\lambda \to 0, but the limit is misleading: with ν=30\nu = 30 the coefficient is only 0.0030.003 and yet, in the worst 0.01 %0.01\,\% of days, tt still assigns twice the joint-crash probability of the Gaussian. A small λ\lambda does not mean the effect is negligible at thresholds that matter.

InteractiveJoint crashes
Gaussian copula: corner [0,0.01]2[0, 0.01]^2
0.5 %0.5 %8 joint crashes
tt copula with ν=4.0\nu = 4.0: the same corner
0.5 %0.5 %22 joint crashes
Probability that BB falls given AA falls in its worst 10−k10^{-k}, versus threshold k=−log⁡10qk = -\log_{10} q (horizontal axis)
11.522.533.50.20.40.60.81λ of the t copula
  • Gaussian (exact)
  • tt (exact)
  • independence (qq)
  • simulation (at least 10 events)
  • current threshold
0.50
4.0
3.00 (q = 0.100 %)
P(B falls∣A falls)\Pr(B \text{ falls} \given A \text{ falls}), Gaussian0.0543
P(B falls∣A falls)\Pr(B \text{ falls} \given A \text{ falls}), tt0.2635
Ratio tt / Gaussian4.86×
Joint-crash days per 100,000 simulated (Gaussian / tt)8 / 22
Expected joint crashes in 10 years (2,500 days)0.136 / 0.659
tt limit λ\lambda (Gaussian: 00)0.253
The Gaussian copula underestimates joint risk by a factor of 4.9: with the same correlation ρ\rho and marginals, the models disagree on what matters in a crisis.
Two assets with the same correlation ρ\rho: one modeled with a Gaussian copula and the other with a tt copula. Simulate 100 000100\,000 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 BB crashes given that AA crashes, against threshold k=−log⁡10qk = -\log_{10} q: exact curves (quadrature) and simulated points. Lower the threshold to k=4k = 4. The Gaussian falls toward zero; the tt flattens at its λ\lambda. Then raise ν\nu and see the tt curve move toward the Gaussian, though very slowly. At what threshold does the ratio of tt to Gaussian exceed 1010?

With ρ=0.5\rho = 0.5 and ν=4\nu = 4, the exact probabilities of BB falling when AA falls in its worst qq are:

qqGaussiantt with ν=4\nu = 4Ratio
10 %10\,\%0.3240.3240.3840.3841.21.2
1 %1\,\%0.1290.1290.2880.2882.22.2
0.1 %0.1\,\%0.0540.0540.2630.2634.94.9
0.01 %0.01\,\%0.0230.0230.2560.25611.011.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\rho = 0.5 the Gaussian model expects 0.140.14 joint-crash days in each asset’s worst thousandth every ten years, and tt expects 0.660.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)U = F(X) and V=G(Y)V = G(Y) are uniform, with mean 1/21/2 and variance 1/121/12, hence ρS=12 E[UV]−3\rho_S = 12\,\E[UV] - 3. Also, by the tail formula for nonnegative variables, E[UV]=∬P(U>u,V>v) ⁣du ⁣dv=∬(1−u−v+C(u,v)) ⁣du ⁣dv\E[UV] = \iint \Pr(U > u, V > v)\dd u\dd v = \iint \big(1 - u - v + C(u, v)\big)\dd u\dd v. Since ∬(1−u−v) ⁣du ⁣dv=1−12−12=0\iint (1 - u - v)\dd u\dd v = 1 - \tfrac12 - \tfrac12 = 0, this leaves E[UV]=∬C\E[UV] = \iint C and ρS=12∬C−3\rho_S = 12\iint C - 3. (Independence check: ∬uv=1/4\iint uv = 1/4 and ρS=0\rho_S = 0.) For τ\tau: concordance of (X,Y)(X, Y) with (X′,Y′)(X', Y') is equivalent to that of (U,V)(U, V) with (U′,V′)(U', V') because FF and GG are increasing (almost surely), so it depends only on CC.

(2) Proved in the guided exercise: (Fα(α(X)),Gβ(β(Y)))=(F(X),G(Y))(F_\alpha(\alpha(X)), G_\beta(\beta(Y))) = (F(X), G(Y)).

(3) Let Z1,Z2Z_1, Z_2 be normals with correlation ρ\rho and W1,W2W_1, W_2 standard normals independent of each other and of ZZ. Since Φ(Z1)=P(W1≤Z1∣Z1)\Phi(Z_1) = \Pr(W_1 \le Z_1 \given Z_1), E[Φ(Z1)Φ(Z2)]=P(Z1−W1≥0, Z2−W2≥0)\E[\Phi(Z_1)\Phi(Z_2)] = \Pr(Z_1 - W_1 \ge 0,\ Z_2 - W_2 \ge 0). The pair (Z1−W1,Z2−W2)(Z_1 - W_1, Z_2 - W_2) is normal with variances 22 and covariance ρ\rho, that is, correlation ρ/2\rho/2. By Sheppard’s orthant formula, P(ambos≥0)=14+12πarcsin⁡ρ2\Pr(\text{ambos} \ge 0) = \frac14 + \frac{1}{2\pi}\arcsin\frac\rho2, and ρS=12(14+12πarcsin⁡ρ2)−3=6πarcsin⁡ρ2\rho_S = 12\big(\frac14 + \frac{1}{2\pi}\arcsin\frac\rho2\big) - 3 = \frac6\pi\arcsin\frac\rho2. For τ\tau, apply the same formula to (Z1−Z1′,Z2−Z2′)(Z_1 - Z_1', Z_2 - Z_2'), normal with correlation ρ\rho: P(concordantes)=2(14+12πarcsin⁡ρ)\Pr(\text{concordantes}) = 2\big(\frac14 + \frac{1}{2\pi}\arcsin\rho\big) and τ=2P(concordantes)−1=2πarcsin⁡ρ\tau = 2\Pr(\text{concordantes}) - 1 = \frac2\pi\arcsin\rho.

∎

Invariance (2) is exactly what Pearson lacks. With standard normals Z1,Z2Z_1, Z_2 of correlation ρ\rho, Corr⁡(Z1,Z2)=ρ\Corr(Z_1, Z_2) = \rho, but for lognormals eZ1,eZ2e^{Z_1}, e^{Z_2}, using E[eZ1+Z2]=e1+ρ\E[e^{Z_1 + Z_2}] = e^{1 + \rho} and Var⁡(eZ)=e(e−1)\Var(e^{Z}) = e(e - 1),

Corr⁡(eZ1,eZ2)=e1+ρ−ee(e−1)=eρ−1e−1.\Corr\big(e^{Z_1}, e^{Z_2}\big) = \frac{e^{1+\rho} - e}{e(e - 1)} = \frac{e^{\rho} - 1}{e - 1}.

With ρ=0.8\rho = 0.8 this gives 0.7130.713, while ρS=6πarcsin⁡0.4=0.786\rho_S = \frac6\pi\arcsin 0.4 = 0.786 and τ=2πarcsin⁡0.8=0.590\tau = \frac2\pi\arcsin 0.8 = 0.590 do not change. There is a second defect: the minimum correlation two lognormals can have is −1/e=−0.368-1/e = -0.368 (attained by (eZ,e−Z)(e^Z, e^{-Z})), so not every value of [−1,1][-1, 1] is attainable for fixed marginals, and the maximum is 11 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 WW and MM give −1-1 and 11, any value of [−1,1][-1, 1] is attainable for any pair of continuous marginals.

Rank coefficients are also used for estimation. Inverting ρ=sin⁡(πτ/2)\rho = \sin(\pi\tau/2) using the sample τ\tau gives an estimator of ρ\rho in a multivariate tt 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}\{X = x\}, a probability-zero event, and seemed unsurprising. It is only because we fixed the conditioning variable from the start: coordinate XX. When the event is described differently, the answer changes, for good reason.

Let X,YX, Y be independent standard normals and condition on “Y=XY = 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∣<ε}\{\abs{Y - X} < \eps\}. This conditions on variable D=Y−XD = Y - X at D=0D = 0. Since (X,D)(X, D) is normal with Cov⁡(X,D)=−1\Cov(X, D) = -1 and Var⁡(D)=2\Var(D) = 2, X∣D=0∼N(0,12)X \given D = 0 \sim \Normal(0, \tfrac12).
  • Wedge: {∣Y/X−1∣<ε}\{\abs{Y/X - 1} < \eps\}, equivalent to ∣Y−X∣<ε∣X∣\abs{Y - X} < \eps\abs{X}. This conditions on R=Y/XR = Y/X at R=1R = 1. Under the change (x,r)↦(x,rx)(x, r) \mapsto (x, rx) with Jacobian ∣x∣\abs{x}, the joint density of (X,R)(X, R) is ∣x∣φ(x)φ(rx)\abs{x}\varphi(x)\varphi(rx) and, at r=1r = 1, f(x∣R=1)∝∣x∣e−x2f(x \given R = 1) \propto \abs{x}e^{-x^2}, a density with a gap at 00 (normalized, ∣x∣e−x2\abs{x}e^{-x^2}).

These are two different laws for the same event. E∣X∣\E\abs{X} equals 0.5640.564 in the first case and 0.8860.886 in the second.

Interactive‘Y = X’ is not one event, but many
Two ways to approach the diagonal y=xy = x
(X, Y) iid N(0, 1)
Law of XX within each region versus its limit as ε→0\varepsilon \to 0
−2−10120.20.40.60.8
  • band and its histogram
  • band limit: N(0,1/2)\mathrm{N}(0, 1/2)
  • wedge and its histogram
  • wedge limit: ∣x∣ e−x2\abs{x}\,e^{-x^2}
0.35
Points in the band / wedge11580 / 6862
E∣X∣\E\abs{X} in the band (limit 0.5640.564)0.577
E∣X∣\E\abs{X} in the wedge (limit 0.8860.886)0.906
P(∣X∣<0.25)\Pr(\abs{X} < 0.25) in band / wedge (limits 0.2760.276 / 0.0610.061)0.262 / 0.059
It is the same event, {Y=X}\{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)(X, Y) are independent standard normals. In blue, the constant-width band ∣Y−X∣<ε\abs{Y - X} < \varepsilon; in orange, the wedge ∣Y−X∣<ε∣X∣\abs{Y - X} < \varepsilon\abs{X}, which admits more points farther from the origin. On the right, the histogram of xx in each region (solid) and its limiting law (dashed). Narrow ε\varepsilon: both regions approach the diagonal and yet the histograms do not resemble each other. Look at the probability of ∣X∣<0.25\abs{X} < 0.25: it tends to 0.2760.276 for the band and 0.0610.061 for the wedge.

The wedge weights regions with large ∣x∣\abs{x} more heavily because its width grows with ∣x∣\abs{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 σ\sigma-algebra). The formula f(y∣x)=f(x,y)/fX(x)f(y \given x) = f(x, y)/f_X(x) conditions on variable XX, 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 σ\sigma-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 tt with a Kolmogorov–Smirnov statistic of 0.00150.0015, on the order of sampling error. Now the four copula samplers. Only Φ\Phi and Φ−1\Phi^{-1} (ndtr, ndtri) and the cdf tt 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 τ\tau 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 τ\tau agree with theoretical values within sampling error (about 0.020.02 with m=1500m = 1500), and the column marginals are uniform. The two ellipticals give the same τ\tau because they share ρ\rho; Clayton and Gumbel with θ=2\theta = 2 also share it (0.50.5), with opposite tail structures. It remains to apply arbitrary marginals and see what changes.

[ ]Pearson changes with marginals; Spearman does notBrowser
rho = 0.8
U = sample_gaussian(np.array([[1, rho], [rho, 1]]), 200_000, rng)
Z = ndtri(U)                                                # marginales normales: F^{-1} = ndtri
casos = {
    "normal y normal":             (Z[:, 0], Z[:, 1], rho),
    "lognormal(1) y lognormal(1)": (np.exp(Z[:, 0]), np.exp(Z[:, 1]), (np.exp(rho) - 1) / (np.e - 1)),
    "normal y lognormal(1)":       (Z[:, 0], np.exp(Z[:, 1]), None),
    "exponencial y exponencial":   (-np.log1p(-U[:, 0]), -np.log1p(-U[:, 1]), None),
    "lognormal(2) y lognormal(2)": (np.exp(2 * Z[:, 0]), np.exp(2 * Z[:, 1]), (np.exp(4 * rho) - 1) / (np.exp(4) - 1)),
}
print(f"Spearman teórico (6/pi) arcsin(rho/2) = {6 / np.pi * np.arcsin(rho / 2):.4f}")
for nombre, (xx, yy, teo) in casos.items():
    r = np.corrcoef(xx, yy)[0, 1]
    print(f"{nombre:28s} Pearson {r:.4f}" + (f" (teoría {teo:.4f})" if teo else "              ") + f"   Spearman {spearman(xx, yy):.4f}")

Spearman is the same across all five rows, 0.7850.785 (the theoretical value is 0.7860.786), because all five use the same UU and the marginals are increasing. Pearson ranges from 0.800.80 with normals to 0.460.46 with two lognormals of σ=2\sigma = 2, where the estimate is also unreliable (theory gives 0.440.44): with marginals this skewed the sample variance of a lognormal product is enormous.

Now the tails. Simulate 5⋅1055 \cdot 10^5 pairs from three copulas with the same Kendall τ\tau, 1/31/3: the Gaussian and tt with the same parameter ρ=0.5\rho = 0.5, and Clayton calibrated to that τ\tau, and count the fraction of times that when AA falls in its worst qq so does BB; 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 qq (0.320.32, 0.130.13, 0.0540.054) and tt flattens near λ=0.253\lambda = 0.253; Clayton stays around 2−1/θ=0.52^{-1/\theta} = 0.5 (θ=1\theta = 1). At q=0.001q = 0.001 there are only about 130130 coincidences of tt, 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 tt, 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 tt.

TaskSciPy
Multivariate normal / ttstats.multivariate_normal, stats.multivariate_t
Kendall’s τ\tau, ρS\rho_Sstats.kendalltau, stats.spearmanr
Marginals: cdf, quantiledist.cdf, dist.ppf
Pseudo-observationsstats.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 (tt with 3 degrees of freedom, n=400n = 400 and 300300 repetitions), both estimators are approximately unbiased, but the one based on τ\tau has standard deviation about two and a half times smaller (0.040.04 versus 0.100.10): one extreme observation dominates Pearson’s product of deviations, while in τ\tau only the sign of its pairs matters, each weighted 1/(n2)1/\binom{n}{2}. The final block is the standard copula-fitting workflow: first ranks (pseudo-observations, U^=rango/(n+1)\hat U = \text{rango}/(n + 1), which eliminate the marginals), then the copula.

Common mistakes

Exercises

NumericPosterior of a component
In mixture 0.7 N(0,1)+0.3 N(3,1)0.7\,\Normal(0, 1) + 0.3\,\Normal(3, 1), calculate the posterior probability of the second component given x=2x = 2.
NumericVariance of a mixture
Let X∼12 N(0,1)+12 N(4,1)X \sim \tfrac12\,\Normal(0, 1) + \tfrac12\,\Normal(4, 1). Calculate Var⁡(X)\Var(X).
NumericTail of a Clayton copula
A Clayton copula has Kendall's τ\tau equal to 0.50.5. What is its lower-tail dependence coefficient λL\lambda_L?
NumericPearson after exponentiation
Z1Z_1 and Z2Z_2 are standard normals with correlation 0.80.8. Calculate the Pearson correlation between eZ1e^{Z_1} and eZ2e^{Z_2}.
QuizMore joint crashes
Three models for returns of two assets all have normal marginals and the same Kendall τ\tau, 1/31/3 (that of a bivariate normal with correlation 0.50.5); their Pearson correlations are between 0.480.48 and 0.510.51. Which produces more extreme joint crashes (both in their worst 0.1 %0.1\,\%)?
QuizWhat is the law of $X$ given $Y = X$?
Let X,YX, Y be independent standard normals. One person claims that, given event {Y=X}\{Y = X\}, the law of XX is N(0,1/2)\Normal(0, 1/2); another says its density is ∣x∣e−x2\abs{x}e^{-x^2}. 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,YX, Y have continuous distribution functions FF, GG, and let α,β:R→R\alpha, \beta : \R \to \R be strictly increasing and measurable. Then ρS(α(X),β(Y))=ρS(X,Y)\rho_S(\alpha(X), \beta(Y)) = \rho_S(X, Y), where ρS(X,Y)=Corr⁡(F(X),G(Y))\rho_S(X, Y) = \Corr(F(X), G(Y)).
0
Call FαF_\alpha and GβG_\beta the distribution functions of α(X)\alpha(X) and β(Y)\beta(Y). Since α\alpha is injective, α(X)\alpha(X) has no atoms and FαF_\alpha is continuous, so ρS(α(X),β(Y))=Corr⁡(Fα(α(X)),Gβ(β(Y)))\rho_S(\alpha(X), \beta(Y)) = \Corr(F_\alpha(\alpha(X)), G_\beta(\beta(Y))).

Step 1 of 3. What is Fα(α(x))F_\alpha(\alpha(x)) for x∈Rx \in \R?

ProofStudent's t as a gamma mixture
Prove: If W∼Gamma(ν/2,ν/2)W \sim \mathrm{Gamma}(\nu/2, \nu/2) (shape and rate) and, given W=wW = w, X∼N(0,1/w)X \sim \Normal(0, 1/w), then XX has the density of a Student tt with ν\nu degrees of freedom: fν(x)=Γ(ν+12)νπ Γ(ν2)(1+x2ν)−ν+12f_\nu(x) = \dfrac{\Gamma(\frac{\nu+1}{2})}{\sqrt{\nu\pi}\,\Gamma(\frac\nu2)}\Big(1 + \dfrac{x^2}{\nu}\Big)^{-\frac{\nu+1}{2}}.
0
Recall that N(0,1/w)\Normal(0, 1/w) has density w/(2π) e−wx2/2\sqrt{w/(2\pi)}\,e^{-wx^2/2} and gamma has density (ν/2)ν/2Γ(ν/2) wν/2−1e−νw/2\dfrac{(\nu/2)^{\nu/2}}{\Gamma(\nu/2)}\,w^{\nu/2 - 1}e^{-\nu w/2}.

Step 1 of 4. How do you obtain the marginal density of XX?

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×dd \times d) and marginals given by quantile functions ppfs[j] (one per column: ppfs[j](u) receives an array in (0,1)(0,1)). Use np.random.default_rng(seed) and Cholesky factorization; you may use scipy.special.ndtr as Φ\Phi. 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)f(y \given x) = f(x, y)/f_X(x) for fX(x)>0f_X(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\int p(x \given z)p(z)\dd z and its variance is never less than the average conditional variance: Var⁡(X)≥E[Var⁡(X∣Z)]\Var(X) \ge \E[\Var(X \given Z)]. Student’s tt 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))H(x, y) = C(F(x), G(y)), with CC unique if marginals are continuous, and every pair (marginals, copula) produces one. c(u,v)c(u, v) is the correction factor relative to independence, and Archimedean copulas are hierarchical models with a shared latent variable.
  • Tails. λL=lim⁡C(q,q)/q\lambda_L = \lim C(q, q)/q. Gaussian has λ=0\lambda = 0 for ∣ρ∣<1\abs{\rho} < 1; tt has λ>0\lambda > 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\rho_S and τ\tau depend only on the copula and are invariant under increasing transformations; for the Gaussian, ρS=6πarcsin⁡ρ2\rho_S = \frac6\pi\arcsin\frac\rho2 and τ=2πarcsin⁡ρ\tau = \frac2\pi\arcsin\rho. Pearson is not invariant and its attainable range depends on the marginals.
  • Beware null events. Conditioning on {Y=X}\{Y = X\} gives different laws depending on the variable used to enclose it (band or wedge). The conditional law is defined relative to a σ\sigma-algebra, developed in the next lesson.