Module contents
Lesson 17 of 27Advanced 110 min

Advanced bootstrap: second-order intervals, failures and dependent data

Improve bootstrap intervals, test hypotheses by resampling, and diagnose failure and dependence.

After this lesson you can

  • Use Edgeworth expansions to compare first- and second-order accuracy.
  • Construct bootstrap-t and BCa intervals and compare coverage.
  • Impose the null in bootstrap hypothesis tests and recognize inconsistent bootstrap problems.
  • Apply block bootstrap to dependent time series.

Before you start

Motivation: a 95% interval that is not 95%

In the previous lesson you built the nonparametric bootstrap and its simplest intervals: normal, basic, and percentile. They work without a single formula, which is their appeal. But you also saw that with skewed statistics and small samples, none achieves its promised coverage. This lesson begins where that one ended: how wrong are they, why, and how can they be fixed?

A typical case is the mean of data with a long right tail: incomes, response times, claim amounts, or cost per model query. With n=20n = 20 lognormal observations, the next cell repeats the entire procedure eight hundred times (sample, six hundred resamples, 95% percentile interval) and counts how often the interval contains the true mean, μ=e1/2\mu = e^{1/2}.

[ ]Testing the percentile intervalBrowser
import numpy as np

rng = np.random.default_rng(17)
n, B, R = 20, 600, 800
mu = np.exp(0.5)                       # media de una lognormal(0, 1)
debajo = encima = 0                    # mu por debajo del intervalo | por encima
for _ in range(R):
    x = rng.lognormal(0.0, 1.0, n)
    medias = x[rng.integers(0, n, (B, n))].mean(axis=1)
    lo, hi = np.quantile(medias, [0.025, 0.975])
    debajo += mu < lo
    encima += mu > hi
cob = 1 - (debajo + encima) / R
print(f"cobertura del percentil al 95 %: {cob:.3f}   (error de Monte Carlo: {np.sqrt(cob * (1 - cob) / R):.3f})")
print(f"mu por debajo del intervalo: {debajo / R:.3f}   mu por encima: {encima / R:.3f}   (nominal: 0.025 y 0.025)")

The “95%” interval covers about 87%, and failure is not evenly distributed: almost all of it occurs on the same side (μ\mu lies above the interval 12% of the time and below it 1%). Samples containing none of the large tail values have a low mean and small dispersion, so their interval is too short and below μ\mu. As we will see, the concentration of the 5% failure in one tail is the signature of a first-order interval.

The following figure maps the lesson. It compares five 95% bootstrap intervals in three skewed problems: the previous lesson’s three and two new ones, bootstrap-tt and BCa, which we will construct shortly.

InteractiveCoverage race
Actual coverage (%) of the 95% intervals
normalpercentilebasicbootstrap-tBCa
Misses by tail (%): θ below | θ above the interval
  • nominal: 95% and 2.5% per tail
  • ±2 Monte Carlo errors
  • θ < lower endpoint
  • θ > upper endpoint
Statistic and population
20
True parameter θ\theta | simulated samples1.649 | 0 of 1000
Mean width: normal | percentile | basic…
Mean width: bootstrap-t | BCa…
Simulating: 0 of 1000 samples, each with 400 resamples and five intervals.
Each race repeats the entire procedure a thousand times (sample, 400 resamples, five 95% intervals), accumulating actual coverage live (left) and failures on each side (right; nominal is 2.5% per tail, shown by dashed lines). The gray band is ±2 Monte Carlo errors around 95%. Start with the lognormal mean and n=20n = 20: on which side do the first three fail? Increase nn to 80: does the gap close? Switch to normal variance and correlation: the order changes, but bootstrap-tt and BCa beat percentile (except for ties within Monte Carlo error), with more balanced tails. Press 'Repeat race' to see how figures vary across races.

What the race shows, and the rest of the lesson explains:

  1. Why simple intervals fail. Characteristic functions and cumulants allow a statistic’s distribution to be written as the normal distribution plus corrections in powers of n−1/2n^{-1/2}: the Edgeworth expansion. The order-n−1/2n^{-1/2} term is skewness, which first-order intervals do not capture well.
  2. How to fix it. Resample a pivotal quantity (bootstrap-tt) or correct quantile levels (BCa). Both cancel the order-n−1/2n^{-1/2} term: they are second-order.
  3. How to test a hypothesis by bootstrap, imposing the null during resampling.
  4. When bootstrap fails entirely, as for a sample maximum, and the remedy of resampling fewer than nn observations.
  5. What to do with time series, where resampling observation by observation destroys dependence: block bootstrap.

How wrong is an interval?

Let θ\theta be a parameter and θ^\hat\theta its estimator from nn observations. An upper confidence limit at nominal level 1−α1 - \alpha is a statistic θ^sup\hat\theta_{\text{sup}} with P(θ≤θ^sup)≈1−α\Pr(\theta \le \hat\theta_{\text{sup}}) \approx 1 - \alpha; its coverage error is P(θ≤θ^sup)−(1−α)\Pr(\theta \le \hat\theta_{\text{sup}}) - (1 - \alpha). A two-sided equal-tailed interval, [θ^inf,θ^sup][\hat\theta_{\text{inf}}, \hat\theta_{\text{sup}}], is the intersection of lower and upper limits each at level 1−α/21 - \alpha/2, and its coverage error is the sum of the two tail errors.

To assess a bootstrap interval’s quality, we need the distribution of θ^\hat\theta more precisely than the central limit theorem provides. The theorem says a standardized mean is approximately normal; it does not say how wrong that approximation is for finite nn or in which direction. The Edgeworth expansion supplies that.

The Edgeworth expansion, sketched

Let X1,…,Xn∼iidFX_1, \dots, X_n \iid F have mean μ\mu, variance σ2\sigma^2, skewness γ=E[(X−μ)3]/σ3\gamma = \E[(X - \mu)^3]/\sigma^3 and excess kurtosis κ\kappa. Standardize Yi=(Xi−μ)/σY_i = (X_i - \mu)/\sigma and consider

S=n(Xˉ−μ)σ=1n∑i=1nYi.S = \frac{\sqrt n(\bar X - \mu)}{\sigma} = \frac{1}{\sqrt n}\sum_{i=1}^n Y_i.

The cumulant generating function of a sum of independent variables is the sum of those of its terms, and scaling by 1/n1/\sqrt n multiplies the order-rr cumulant by n−r/2n^{-r/2}. Since those of YY are 0,1,γ,κ,…0, 1, \gamma, \kappa, \dots, those of SS are 00, 11, γ/n\gamma/\sqrt n, κ/n\kappa/n, and so on. In terms of the characteristic function,

log⁡E[eitS]=−t22+γ6n(it)3+κ24n(it)4+⋯⟹E[eitS]=e−t2/2(1+γ6n(it)3+O(n−1)).\log \E\big[e^{itS}\big] = -\frac{t^2}{2} + \frac{\gamma}{6\sqrt n}(it)^3 + \frac{\kappa}{24 n}(it)^4 + \cdots \quad\Longrightarrow\quad \E\big[e^{itS}\big] = e^{-t^2/2}\Big(1 + \frac{\gamma}{6\sqrt n}(it)^3 + \bigO(n^{-1})\Big).

It remains to invert. The normal density is ϕ(x)=12π∫e−itxe−t2/2 ⁣dt\phi(x) = \frac{1}{2\pi}\int e^{-itx}e^{-t^2/2}\dd t, and differentiating under the integral gives (−ddx)kϕ(x)=12π∫e−itx(it)ke−t2/2 ⁣dt(-\tfrac{\mathrm{d}}{\mathrm{d}x})^k\phi(x) = \frac{1}{2\pi}\int e^{-itx}(it)^k e^{-t^2/2}\dd t. That is, multiplication by (it)k(it)^k on the Fourier side is equivalent to applying (−ddx)k(-\tfrac{\mathrm{d}}{\mathrm{d}x})^k to ϕ\phi, producing Hek(x)ϕ(x)He_k(x)\phi(x) with HekHe_k the probabilists’ Hermite polynomial (He2=x2−1He_2 = x^2 - 1, He3=x3−3xHe_3 = x^3 - 3x). Thus the density of SS is approximately ϕ(x)(1+γ6nHe3(x))\phi(x)\big(1 + \frac{\gamma}{6\sqrt n}He_3(x)\big) and, integrating with ∫−∞xHe3ϕ=−He2(x)ϕ(x)\int_{-\infty}^x He_3\phi = -He_2(x)\phi(x),

P(S≤x)=Φ(x)−γ6n(x2−1) ϕ(x)+O(n−1).\Pr(S \le x) = \Phi(x) - \frac{\gamma}{6\sqrt n}(x^2 - 1)\,\phi(x) + \bigO(n^{-1}).

The correction term is even in xx and has the sign of γ\gamma: with right-skewed data (γ>0\gamma > 0), the distribution function of SS falls below Φ\Phi for ∣x∣>1\abs{x} > 1 and above it for ∣x∣<1\abs{x} < 1; that is, the mean has less mass than the normal predicts in the left tail and more in the right. Its order is n−1/2n^{-1/2}, not n−1n^{-1}: skewness is the first defect of the normal approximation and the slowest to disappear.

Cramér’s condition excludes lattice distributions (Bernoulli, for example), where the distribution function of Xˉ\bar X has jumps of size n−1/2n^{-1/2} that no smooth polynomial describes. Notice the sign of q1q_1: studentization reverses skewness. When a large observation is missing, Xˉ\bar X and ss fall together and TT goes far left. For exponential data (γ=2\gamma = 2) and n=10n = 10, P(T≤−1.645)\Pr(T \le -1.645) is about 0.15, not 0.05: a “95%” upper limit of the form Xˉ+1.645 s/n\bar X + 1.645\,s/\sqrt n fails three times more than promised (and with the Student tt quantile for 9 degrees of freedom, 1.833, it still fails 13% of the time).

InteractiveThe Edgeworth lens
Deviation from normal, Fn(x)−Φ(x)F_n(x) - \Phi(x), for S=n(Xˉ−μ)/σS = \sqrt{n}(\bar X - \mu)/\sigma, exact
Maximum error versus n (log-log)
slope −1/2slope −1
  • true (exact) minus normal
  • Edgeworth term
  • bootstrap minus normal
  • normal (deviation 0)
Quantity
10
Maximum error: normal | Edgeworth0.0421 | 0.0080
n⋅\sqrt{n}\cdotnormal error | n⋅n\cdotEdgeworth error0.133 | 0.080
Sample skewness γ^\hat\gamma (true: 2)1.54
When nn is quadrupled, the normal approximation error halves and the Edgeworth error falls fourfold: n⋅\sqrt{n}\cdoterror ≈ 0.133 and n⋅n\cdoterror ≈ 0.080 barely change with nn. The bootstrap curve uses only one sample and does not know γ\gamma.
Exponential data. In the text color, deviation of the true distribution from normal, Fn(x)−Φ(x)F_n(x) - \Phi(x), for SS (exact, because nXˉn\bar X is gamma) or TT (Monte Carlo with 40,000 samples). Dashed orange is the first Edgeworth term. Blue is the same deviation estimated by bootstrap from a single sample, without knowing γ\gamma. On the right, maximum normal and Edgeworth approximation errors versus nn on a log-log scale, with lines of slope −1/2-1/2 and −1-1. Increase nn and check the slopes. Switch to TT: the shape reverses and is larger (for TT, at large nn Edgeworth error falls below Monte Carlo noise and its line flattens). Request several samples: does the blue curve follow the true one?

The blue curve is the key to this entire lesson. Bootstrap knows nothing about cumulants, but the bootstrap distribution is itself a sampling distribution (that of resampling from F^n\hat F_n), so it too has an Edgeworth expansion, with moments of F^n\hat F_n instead of those of FF:

P∗(T∗≤x)=Φ(x)+n−1/2q^1(x)ϕ(x)+Op(n−1),q^1(x)=γ^6(2x2+1).\Pr^\ast(T^\ast \le x) = \Phi(x) + n^{-1/2}\hat q_1(x)\phi(x) + \bigO_p(n^{-1}), \qquad \hat q_1(x) = \frac{\hat\gamma}{6}(2x^2 + 1).

Since γ^−γ=Op(n−1/2)\hat\gamma - \gamma = \bigO_p(n^{-1/2}), the difference between the bootstrap distribution of T∗T^\ast and the true distribution of TT is n−1/2(q^1−q1)ϕ=Op(n−1)n^{-1/2}(\hat q_1 - q_1)\phi = \bigO_p(n^{-1}): bootstrap automatically reproduces the skewness term. This happens because the leading term of the expansion of TT, Φ(x)\Phi(x), depends on nothing unknown: TT is asymptotically pivotal.

Compare this with percentile or basic intervals, which resample the unstandardized root U=n(θ^−θ)U = \sqrt n(\hat\theta - \theta). Its distribution is Φ(x/σ)+n−1/2p1(x/σ)ϕ(x/σ)+⋯\Phi(x/\sigma) + n^{-1/2}p_1(x/\sigma)\phi(x/\sigma) + \cdots, and the bootstrap distribution is the same with σ^\hat\sigma instead of σ\sigma. Already the leading term differs by Φ(x/σ^)−Φ(x/σ)=Op(n−1/2)\Phi(x/\hat\sigma) - \Phi(x/\sigma) = \bigO_p(n^{-1/2}), because σ^−σ=Op(n−1/2)\hat\sigma - \sigma = \bigO_p(n^{-1/2}). Scale estimation error is of the same order as the skewness correction and obscures it.

[ ]Edgeworth versus reality: exact S and simulated TBrowser
import numpy as np
from scipy.stats import norm, gamma

rng = np.random.default_rng(3)
g = 2.0                                          # asimetría de la exponencial
x = np.linspace(-2.5, 2.5, 51)
print("   n |  normal, S | Edgeworth, S |  normal, T | Edgeworth, T   (error máximo en la función de distribución)")
for n in [5, 10, 20, 40]:
    FS = gamma.cdf(n + x * np.sqrt(n), a=n)      # exacta: n·media ~ Gamma(n, 1)
    X = rng.exponential(1.0, (60_000, n))
    T = np.sqrt(n) * (X.mean(1) - 1) / X.std(1, ddof=1)
    FT = np.searchsorted(np.sort(T), x, side="right") / len(T)
    edgS = norm.cdf(x) - g / (6 * np.sqrt(n)) * (x**2 - 1) * norm.pdf(x)
    edgT = norm.cdf(x) + g / (6 * np.sqrt(n)) * (2 * x**2 + 1) * norm.pdf(x)
    print(f"{n:4d} | {np.abs(FS - norm.cdf(x)).max():10.4f} | {np.abs(FS - edgS).max():12.4f} | "
          f"{np.abs(FT - norm.cdf(x)).max():10.4f} | {np.abs(FT - edgT).max():12.4f}")
X = rng.exponential(1.0, (60_000, 10))
T = np.sqrt(10) * (X.mean(1) - 1) / X.std(1, ddof=1)
print(f"\nP(T <= -1.645) con n = 10: {np.mean(T <= -1.645):.3f}  (la normal dice 0.050; Edgeworth, "
      f"{norm.cdf(-1.645) + g / (6 * np.sqrt(10)) * (2 * 1.645**2 + 1) * norm.pdf(1.645):.3f})")

With SS the pattern is clean: doubling nn divides normal error by 2\sqrt 2 and Edgeworth error by 2. With TT the Edgeworth term corrects most error, although at n=5n = 5 the next order-n−1n^{-1} term still matters: an asymptotic expansion describes how error decreases, not a guarantee of small error for a particular nn (and in the last column, from n=20n = 20, it mixes with Monte Carlo error of about 0.002).

First- and second-order accuracy

Inverting an Edgeworth expansion gives a quantile expansion, the Cornish–Fisher expansion: if P(T≤x)=Φ(x)+n−1/2q1(x)ϕ(x)+⋯\Pr(T \le x) = \Phi(x) + n^{-1/2}q_1(x)\phi(x) + \cdots, the pp quantile of TT is tp=zp−n−1/2q1(zp)+O(n−1)t_p = z_p - n^{-1/2}q_1(z_p) + \bigO(n^{-1}), with zp=Φ−1(p)z_p = \Phi^{-1}(p). This lets us compare each interval with the “ideal” interval, which uses exact quantiles of TT.

The transition from endpoint error to coverage error is simple: if the limit falls short by c/nc/n, coverage loses P(θ∈(θ^sup−c/n,θ^sup])\Pr\big(\theta \in (\hat\theta_{\text{sup}} - c/n, \hat\theta_{\text{sup}}]\big). Since θ^sup\hat\theta_{\text{sup}} fluctuates on scale σ/n\sigma/\sqrt n, that probability is of order ϕ(zα) (c/n)/(σ/n)=O(n−1/2)\phi(z_\alpha)\,(c/n)/(\sigma/\sqrt n) = \bigO(n^{-1/2}).

Proof

Sketch, ignoring Op(n−3/2)\bigO_p(n^{-3/2}) terms and the difference between σ^\hat\sigma and ss, which is of relative order n−1n^{-1}. By Cornish–Fisher, tα=−z−n−1/2γ6(2z2+1)t_\alpha = -z - n^{-1/2}\frac{\gamma}{6}(2z^2 + 1), and the ideal Xˉ−n−1/2σ^tα\bar X - n^{-1/2}\hat\sigma t_\alpha is the table’s value. For percentile, Xˉ∗−Xˉ\bar X^\ast - \bar X has the expansion of SS with γ^\hat\gamma in the bootstrap world, whose quantile is sp=zp+n−1/2γ^6(zp2−1)s_p = z_p + n^{-1/2}\frac{\hat\gamma}{6}(z_p^2 - 1), so q1−α∗=Xˉ+n−1/2σ^(z+n−1/2γ^6(z2−1))q^\ast_{1-\alpha} = \bar X + n^{-1/2}\hat\sigma\big(z + n^{-1/2}\frac{\hat\gamma}{6}(z^2 - 1)\big). Basic is 2Xˉ−qα∗2\bar X - q^\ast_\alpha with zα=−zz_\alpha = -z, changing the correction’s sign. Bootstrap-tt uses quantile tα∗=−z−n−1/2γ^6(2z2+1)+Op(n−1)t^\ast_\alpha = -z - n^{-1/2}\frac{\hat\gamma}{6}(2z^2 + 1) + \bigO_p(n^{-1}), which agrees with ideal apart from γ^−γ=Op(n−1/2)\hat\gamma - \gamma = \bigO_p(n^{-1/2}). Subtracting each correction from ideal (with γ^=γ+Op(n−1/2)\hat\gamma = \gamma + \bigO_p(n^{-1/2})) gives the third column, and the previous argument converts it to coverage error: an endpoint deficit of c σ^/nc\,\hat\sigma/n subtracts c ϕ(z)/nc\,\phi(z)/\sqrt n from coverage.

∎

For exponential data (γ=2\gamma = 2) and a 95% upper limit (z=1.645z = 1.645), the table predicts normal, percentile and basic lose 0.0490.049, 0.0360.036 and 0.0620.062 coverage with n=20n = 20, while bootstrap-tt loses nothing at that order. A simulation with 8000 samples per row and B=800B = 800 (run outside the browser; the coverage study below is similar, smaller and uses two-sided intervals) gives:

nnnormalpercentilebasicbootstrap-ttnormal / percentile / basic prediction
100.8310.8390.8170.9180.880 / 0.899 / 0.862
200.8730.8820.8620.9300.901 / 0.914 / 0.888
400.8980.9060.8900.9380.915 / 0.924 / 0.906
800.9220.9260.9130.9480.925 / 0.932 / 0.919

The first three have the predicted order (percentile, normal, basic), and the prediction fits increasingly well; at n=10n = 10 the order-n−1n^{-1} terms ignored by the table are still large. Bootstrap-tt is always much closer to 95%.

Bootstrap-t: resample a pivot

The theorem’s lesson is direct: instead of resampling θ^\hat\theta, resample its studentized version, which is (asymptotically) a pivotal quantity.

This is the same reasoning as for the previous lesson’s basic interval (solve for θ\theta from a statement about the root), using root T=(θ^−θ)/SE^T = (\hat\theta - \theta)/\widehat{\mathrm{SE}} instead of θ^−θ\hat\theta - \theta. It naturally generalizes Student’s tt interval: if data are normal, TT is exactly tn−1t_{n-1}; otherwise bootstrap estimates the distribution of TT instead of assuming it. Notice the quantiles cross: the upper quantile of T∗T^\ast gives the lower endpoint. If T∗T^\ast is left-skewed, as for the mean of right-tailed data, the interval extends to the right.

The price lies in the denominator: a standard error is needed in each resample, and its quality determines that of the interval. There are three options:

  • A formula, if available. For the mean, s/ns/\sqrt n; for variance, (m4−m22)/n\sqrt{(m_4 - m_2^2)/n} with central moments mkm_k; for correlation, the nonparametric delta method. This is what the race uses.
  • A nested bootstrap: within each resample, B2B_2 resamples of the resample (B2≈25B_2 \approx 25 to 5050 suffices for standard error). Cost becomes B⋅B2B \cdot B_2 statistic evaluations.
  • The jackknife of each resample: nn evaluations per resample, good for smooth statistics and bad for median and other quantiles.

It has two known weaknesses. First, it does not respect transformations: bootstrap-tt intervals for σ2\sigma^2 and log⁡σ2\log\sigma^2 are not images of one another (you will prove this in an exercise), and the former can have negative endpoints. Second, it is erratic when SE^\widehat{\mathrm{SE}} is unstable: a resample with a coincidentally tiny standard error yields a huge T∗T^\ast, and extreme quantiles of T∗T^\ast generate very long intervals. This often occurs with correlation near ∣ρ∣=1\abs{\rho} = 1. The classical remedy is to apply bootstrap-tt on a variance-stabilizing scale (Fisher’s zz, artanh⁡r\operatorname{artanh} r, for correlation; log for variance or a ratio) and transform the interval back.

BCa: correct levels, not the distribution

Bootstrap-tt needs a standard error per resample and depends on scale. In 1987 Bradley Efron proposed an interval retaining percentile invariance while achieving second order: the bias-corrected and accelerated interval. The idea is to read the same bootstrap distribution at different quantile levels.

With z^0=a^=0\hat z_0 = \hat a = 0, levels are α/2\alpha/2 and 1−α/21 - \alpha/2 and percentile is recovered. z^0\hat z_0 measures median bias of the bootstrap distribution: if more than half the replicates lie below θ^\hat\theta, z^0>0\hat z_0 > 0. a^\hat a measures how standard error changes with the parameter, estimated using skewness of jackknife influences. For the mean, θ^(⋅)−θ^(−i)=(xi−xˉ)/(n−1)\hat\theta_{(\cdot)} - \hat\theta_{(-i)} = (x_i - \bar x)/(n - 1) and the formula reduces to

a^=γ^6n,γ^=1n∑i(xi−xˉ)3(1n∑i(xi−xˉ)2)3/2,\hat a = \frac{\hat\gamma}{6\sqrt n}, \qquad \hat\gamma = \frac{\frac1n\sum_i(x_i - \bar x)^3}{\big(\frac1n\sum_i(x_i - \bar x)^2\big)^{3/2}},

sample skewness divided by 6n6\sqrt n: the same γ/(6n)\gamma/(6\sqrt n) as the Edgeworth term.

Where the formulas come from

Proof

Assume a>0a > 0 (for a<0a < 0, repeat with ζ=−log⁡(1+aφ)\zeta = -\log(1 + a\varphi); with a=0a = 0 the model is a translation and calculation is direct). Write the model as φ^=φ+(1+aφ)(Z−z0)\hat\varphi = \varphi + (1 + a\varphi)(Z - z_0), with Z∼N(0,1)Z \sim \Normal(0, 1). Adding 1/a1/a to both sides and multiplying by aa, 1+aφ^=(1+aφ)(1+a(Z−z0))1 + a\hat\varphi = (1 + a\varphi)\big(1 + a(Z - z_0)\big), and taking logs, with ζ=log⁡(1+aφ)\zeta = \log(1 + a\varphi),

ζ^−ζ=log⁡(1+a(Z−z0))=:W,\hat\zeta - \zeta = \log\big(1 + a(Z - z_0)\big) =: W,

whose distribution does not depend on φ\varphi: it is a pivot, increasing in ZZ. The lower level-1−α1 - \alpha limit for ζ\zeta is ζ^−w1−α\hat\zeta - w_{1-\alpha}, with w1−α=log⁡(1+a(z1−α−z0))=log⁡(1−a(z0+zα))w_{1-\alpha} = \log\big(1 + a(z_{1-\alpha} - z_0)\big) = \log\big(1 - a(z_0 + z_\alpha)\big), because P(ζ≥ζ^−w1−α)=P(W≤w1−α)=1−α\Pr(\zeta \ge \hat\zeta - w_{1-\alpha}) = \Pr(W \le w_{1-\alpha}) = 1 - \alpha. Undoing the logarithm, the limit for φ\varphi is

φ[α]=φ^+(1+aφ^)z0+zα1−a(z0+zα).\varphi_{[\alpha]} = \hat\varphi + (1 + a\hat\varphi)\frac{z_0 + z_\alpha}{1 - a(z_0 + z_\alpha)}.

In the bootstrap world, φ^∗=φ^+(1+aφ^)(Z∗−z0)\hat\varphi^\ast = \hat\varphi + (1 + a\hat\varphi)(Z^\ast - z_0), so

P∗(φ^∗≤φ[α])=P(Z∗−z0≤z0+zα1−a(z0+zα))=Φ(z0+z0+zα1−a(z0+zα)),\Pr^\ast(\hat\varphi^\ast \le \varphi_{[\alpha]}) = \Pr\Big(Z^\ast - z_0 \le \frac{z_0 + z_\alpha}{1 - a(z_0 + z_\alpha)}\Big) = \Phi\Big(z_0 + \frac{z_0 + z_\alpha}{1 - a(z_0 + z_\alpha)}\Big),

which is the BCa level: φ[α]\varphi_{[\alpha]} is the quantile at that level of φ^∗\hat\varphi^\ast. As hh is increasing, quantiles commute with it, and the quantile at the same level of θ^∗\hat\theta^\ast is h−1(φ[α])h^{-1}(\varphi_{[\alpha]}), the exact limit for θ\theta. Finally, P∗(θ^∗<θ^)=P∗(φ^∗<φ^)=P(Z∗<z0)=Φ(z0)\Pr^\ast(\hat\theta^\ast < \hat\theta) = \Pr^\ast(\hat\varphi^\ast < \hat\varphi) = \Pr(Z^\ast < z_0) = \Phi(z_0), which justifies estimator z^0\hat z_0.

∎

The model is more flexible than it looks: z0z_0 absorbs order-n−1/2n^{-1/2} bias on the normalizing scale, and aa allows the standard deviation of φ^\hat\varphi to depend linearly on the parameter, exactly what skewness produces. DiCiccio and Efron (1996) show that in the smooth-function model BCa endpoints agree with bootstrap-tt to Op(n−3/2)\bigO_p(n^{-3/2}): BCa is second-order without needing a standard error per resample. It also inherits percentile invariance: z^0\hat z_0 does not change when transforming the parameter, and the BCa interval for h(θ)h(\theta) is the image of that for θ\theta (with theoretical a^\hat a; the jackknife estimate is not exactly invariant, but differences are of lower order).

InteractiveWhat BCa corrects
Bootstrap distribution of the mean (4000 replicates): the same for both intervals
θ̂
Levels on the zz scale: nominal versus BCa
  • percentile (2.5%, 97.5%)
  • BCa
  • mass outside the BCa interval
  • θ̂
Statistic (lognormal sample, n=20n = 20)
0.046
0.0439
Estimate θ^\hat\theta | replicates below θ^\hat\theta1.235 | 51.8 %
BCa levels α1\alpha_1 | α2\alpha_24.28 % | 98.77 %
Percentile interval[0.851, 1.680]
BCa interval[0.893, 1.762]
BCa reads the 4.28 % and 98.77 % quantiles instead of 2.5% and 97.5%. Estimated from the sample: z^0\hat z_0 = 0.046 and a^\hat a = 0.0439. The bootstrap distribution has not changed: only where it is cut.
A lognormal sample with n=20n = 20 and the bootstrap distribution of its mean or variance. Dashed lines show the percentile interval (2.5% and 97.5% levels); solid lines show BCa, read on the same distribution at different levels; orange mass lies outside the BCa interval. Right: mapping of levels on the zz scale: the diagonal is percentile and the curve BCa. Start with estimated values. Set a=0a = 0 and move z0z_0: the line shifts and both levels move together. Set z0=0z_0 = 0 and move aa: the curve bends and the interval extends toward the long tail. Take aa to its maximum: what happens to the upper level?

For the initial sample’s mean, BCa reads the 4.3% and 98.8% quantiles instead of 2.5% and 97.5%; for its variance, 8.5% and 99.8%. In both cases it shifts the whole interval toward the long tail, the correction needed by the lognormal mean in the race, and shifts it further for variance, whose distribution is more skewed (its a^\hat a is twice as large). Two practical consequences:

  • BCa needs more replicates than percentile. If α2=0.995\alpha_2 = 0.995, the upper endpoint is the 99.5% quantile of replicates, relying on five values with B=1000B = 1000. Efron and Tibshirani recommend B≥1000B \ge 1000 for intervals; for BCa more is advisable.
  • BCa performs no miracles with very small nn. If the bootstrap distribution lacks information about the tail (a sample of 10 lognormals may contain no large value), no change of levels recovers it. The race shows this at n=10n = 10.

Implementation from scratch

The following two functions implement bootstrap-tt and BCa intervals in vectorized form: the statistic receives an array whose last dimension contains observations, so all BB resamples are evaluated at once. Jackknife is also vectorized with an n×(n−1)n \times (n-1) matrix of leave-one-out samples.

[ ]Bootstrap-t and BCa from scratchBrowser
import numpy as np
from scipy.stats import norm

def sin_una(x):
    """Matriz n x (n-1): la fila i es la muestra sin la observación i."""
    n = len(x)
    return np.broadcast_to(x, (n, n))[~np.eye(n, dtype=bool)].reshape(n, n - 1)

def aceleracion_jackknife(x, est):
    jack = est(sin_una(x))
    u = jack.mean() - jack
    return np.sum(u**3) / (6 * np.sum(u**2) ** 1.5)

def intervalo_bca(x, est, B=4000, alpha=0.05, rng=None):
    rng = np.random.default_rng() if rng is None else rng
    n, t = len(x), est(x)
    rep = est(x[rng.integers(0, n, (B, n))])
    z0 = norm.ppf((np.sum(rep < t) + 0.5 * np.sum(rep == t)) / B)
    a = aceleracion_jackknife(x, est)
    z = norm.ppf([alpha / 2, 1 - alpha / 2])
    niveles = norm.cdf(z0 + (z0 + z) / (1 - a * (z0 + z)))
    return np.quantile(rep, niveles), z0, a, niveles

def intervalo_boot_t(x, est, ee, B=4000, alpha=0.05, rng=None):
    rng = np.random.default_rng() if rng is None else rng
    n, t, s = len(x), est(x), ee(x)
    X = x[rng.integers(0, n, (B, n))]
    T = (est(X) - t) / ee(X)
    tl, th = np.quantile(T, [alpha / 2, 1 - alpha / 2])
    return np.array([t - th * s, t - tl * s])

def ee_anidado(X, est, B2=50, rng=None):
    """Error estándar bootstrap de cada fila de X (bootstrap dentro del bootstrap)."""
    rng = np.random.default_rng(0) if rng is None else rng
    X = np.atleast_2d(X)
    m, n = X.shape
    idx = rng.integers(0, n, (m, B2, n))
    return est(np.take_along_axis(X[:, None, :], idx, axis=2)).std(axis=-1, ddof=1).squeeze()

media = lambda a: a.mean(axis=-1)
ee_media = lambda a: a.std(axis=-1, ddof=1) / np.sqrt(a.shape[-1])
varianza = lambda a: a.var(axis=-1, ddof=1)
def ee_varianza(a):
    d = a - a.mean(axis=-1, keepdims=True)
    m2, m4 = (d**2).mean(axis=-1), (d**4).mean(axis=-1)
    return np.sqrt(np.maximum(m4 - m2**2, 1e-300) / a.shape[-1])

rng = np.random.default_rng(8)
x = rng.lognormal(0.0, 1.0, 20)
n = len(x)
for nombre, est, ee, verdad in [("media", media, ee_media, np.exp(0.5)), ("varianza", varianza, ee_varianza, (np.e - 1) * np.e)]:
    rep = est(x[rng.integers(0, n, (4000, n))])
    perc = np.quantile(rep, [0.025, 0.975])
    bca, z0, a, niv = intervalo_bca(x, est, rng=rng)
    bt = intervalo_boot_t(x, est, ee, rng=rng)
    print(f"{nombre}: estimación {est(x):.3f}, verdad {verdad:.3f}")
    print(f"   percentil    [{perc[0]:7.3f}, {perc[1]:7.3f}]")
    print(f"   bootstrap-t  [{bt[0]:7.3f}, {bt[1]:7.3f}]")
    print(f"   BCa          [{bca[0]:7.3f}, {bca[1]:7.3f}]   z0 = {z0:.3f}, a = {a:.4f}, niveles = {np.round(niv, 4)}")

d = x - x.mean()
gam = np.mean(d**3) / np.mean(d**2) ** 1.5
print(f"\na de la media por jackknife: {aceleracion_jackknife(x, media):.5f}   asimetría/(6 raíz de n): {gam / (6 * np.sqrt(n)):.5f}")
bt_anidado = intervalo_boot_t(x, media, lambda a: ee_anidado(a, media, B2=50), B=1000, rng=rng)
print(f"bootstrap-t de la media con EE anidado (1000 x 50 remuestras): [{bt_anidado[0]:.3f}, {bt_anidado[1]:.3f}]")

Three things to read in the output. Bootstrap-tt and BCa shift the interval right relative to percentile, as theory predicts, and BCa does so by reading quantiles 3.8% and 98.5% (mean) or 6.4% and 99.4% (variance). For variance, bootstrap-tt greatly stretches the upper endpoint to 6.2: it alone contains the true variance, 4.67, which this sample underestimates by half because it has not seen the tail. The sample lacks the information; bootstrap-tt compensates with a highly variable per-resample standard error, both its virtue and its weakness. And mean acceleration agrees with γ^/(6n)\hat\gamma/(6\sqrt n) to every digit.

A systematic coverage study

A new interval should be measured, not simply believed. The ADEMP framework for simulation studies organizes the comparison. Aim: compare coverage of five 95% intervals. Data-generating mechanisms: mean of a lognormal(0, 1) and variance of a normal, with n=20n = 20. Estimands: μ=e1/2\mu = e^{1/2} and σ2=1\sigma^2 = 1. Methods: normal, percentile, basic, bootstrap-tt (formula-based SE) and BCa, with B=500B = 500. Performance measures: coverage, failures in each tail and mean width, with Monte Carlo error.

[ ]ADEMP study: coverage of five intervalsBrowser
import numpy as np
from scipy.stats import norm

rng = np.random.default_rng(2024)
R, B, n, alpha = 400, 500, 20, 0.05
z = norm.ppf(1 - alpha / 2)
metodos = ["normal", "percentil", "básico", "bootstrap-t", "BCa"]
escenarios = {
    "media, lognormal(0, 1)": (lambda: rng.lognormal(0, 1, n), media, ee_media, np.exp(0.5)),
    "varianza, normal(0, 1)": (lambda: rng.normal(0, 1, n), varianza, ee_varianza, 1.0),
}
for nombre, (gen, est, ee, verdad) in escenarios.items():
    abajo, arriba, ancho = np.zeros(5), np.zeros(5), np.zeros(5)
    for _ in range(R):
        x = gen()
        t, s = est(x), ee(x)
        X = x[rng.integers(0, n, (B, n))]
        rep = est(X)
        T = (rep - t) / ee(X)
        ql, qh = np.quantile(rep, [alpha / 2, 1 - alpha / 2])
        tl, th = np.quantile(T, [alpha / 2, 1 - alpha / 2])
        z0 = norm.ppf(np.clip(np.mean(rep < t), 0.5 / B, 1 - 0.5 / B))
        a = aceleracion_jackknife(x, est)
        zz = z0 + norm.ppf([alpha / 2, 1 - alpha / 2])
        bl, bh = np.quantile(rep, norm.cdf(z0 + zz / (1 - a * zz)))
        ivs = [(t - z * rep.std(ddof=1), t + z * rep.std(ddof=1)), (ql, qh), (2 * t - qh, 2 * t - ql), (t - th * s, t - tl * s), (bl, bh)]
        for j, (lo, hi) in enumerate(ivs):
            abajo[j] += verdad < lo
            arriba[j] += verdad > hi
            ancho[j] += hi - lo
    print(f"{nombre}   (R = {R}; error de Monte Carlo de una cobertura de 0.9: {np.sqrt(0.09 / R):.3f})")
    for j, m in enumerate(metodos):
        print(f"   {m:12s} cobertura {1 - (abajo[j] + arriba[j]) / R:.3f}   fallos: {abajo[j] / R:.3f} | {arriba[j] / R:.3f}   anchura media {ancho[j] / R:.3f}")

The results confirm the theory in essence, with nuances worth reading. The three first-order intervals stay between 81.5% and 83% for the lognormal and at 88% for variance, nearly always failing on the same side (11% to 18% above). Bootstrap-tt is best in both scenarios: exactly 0.95 for normal variance, with balanced failures, and 0.89 for the lognormal, still far from 95% because at n=20n = 20 order-n−1n^{-1} terms for such a skewed distribution still matter. BCa balances tails much better than percentile (4% and 12% versus 1% and 16%), but total coverage improves little for the lognormal (0.84 versus 0.83, within Monte Carlo error) and by 1.5 points for variance. The price: average bootstrap-tt width is nearly double. Getting closer to correct coverage with wider intervals is not cheating: it is the actual cost of uncertainty for a heavy-tailed mean with n=20n = 20.

Double bootstrap: calibrating coverage

A third, costlier and more general route to second order uses bootstrap to measure and correct coverage of the bootstrap procedure itself. In the bootstrap world the parameter is known (θ^\hat\theta), so we can do what the first cell did without leaving the sample:

  1. For each outer resample x∗b\vb{x}^{\ast b}, b=1,…,B1b = 1, \dots, B_1, generate B2B_2 inner resamples of x∗b\vb{x}^{\ast b} and calculate ub=P∗∗(θ^∗∗≤θ^∣x∗b)u_b = \Pr^{\ast\ast}(\hat\theta^{\ast\ast} \le \hat\theta \given \vb{x}^{\ast b}), the position of θ^\hat\theta within the inner bootstrap distribution.
  2. If percentile were exact, ubu_b would be uniform on (0,1)(0, 1): percentile fails below exactly when ub<α/2u_b < \alpha/2. The tails of ubu_b therefore measure actual coverage on each side.
  3. Take quantiles α/2\alpha/2 and 1−α/21 - \alpha/2 of the ubu_b as corrected levels λ^1\hat\lambda_1 and λ^2\hat\lambda_2, and return [qλ^1∗,qλ^2∗]\big[q^\ast_{\hat\lambda_1}, q^\ast_{\hat\lambda_2}\big] from the outer bootstrap distribution.

This is Beran’s prepivoting (1987): transforming the statistic by its own bootstrap distribution function moves it closer to a uniform variable, which is a pivot. Hall and Martin (1988) proved that each bootstrap iteration reduces one-sided interval coverage error by a factor of n−1/2n^{-1/2}, so calibrated percentile is second-order. Its cost, B1⋅B2B_1 \cdot B_2 evaluations, was prohibitive in 1990 and is often affordable today for cheap statistics.

[ ]Double bootstrap: calibrated levels for percentileBrowser
import numpy as np

rng = np.random.default_rng(8)
x = rng.lognormal(0.0, 1.0, 20)        # la misma muestra que en la celda de BCa
n, B1, B2 = len(x), 1000, 400
t = x.mean()
X1 = x[rng.integers(0, n, (B1, n))]                         # remuestras exteriores
rep = X1.mean(axis=1)
u = np.empty(B1)
for b in range(B1):
    inter = X1[b][rng.integers(0, n, (B2, n))].mean(axis=1)  # remuestras de la remuestra
    u[b] = np.mean(inter <= t)
l1, l2 = np.quantile(u, [0.025, 0.975])
print(f"fracción de u_b < 0.025: {np.mean(u < 0.025):.3f}   fracción de u_b > 0.975: {np.mean(u > 0.975):.3f}   (deberían ser 0.025)")
print(f"niveles calibrados: {l1:.4f} y {l2:.4f}   (en lugar de 0.025 y 0.975)")
print("percentil              ", np.round(np.quantile(rep, [0.025, 0.975]), 3))
print("percentil calibrado    ", np.round(np.quantile(rep, [l1, l2]), 3))
print("BCa (celda anterior)   ", np.round(intervalo_bca(x, media, rng=rng)[0], 3))

Calibration detects the tail problem on its own: in the bootstrap world, percentile would fail above almost twice as often as nominal, so the corrected upper level rises from 0.975 to 0.99 and the interval extends right, in the same direction as BCa. The correction takes a different form: double bootstrap raises the upper level somewhat more than BCa (0.990 versus 0.985) but leaves the lower almost unchanged (even lowering it slightly, to 0.022), extending the interval right rather than shifting it whole. Neither goes as far as necessary in the race: both measure skewness in the world of F^n\hat F_n, which has a shorter tail than reality, so they correct only part of the problem. Its advantage is generality: it needs no model, standard-error formula, or smoothness beyond what bootstrap itself requires.

Bootstrap hypothesis tests

A bootstrap interval yields a test by duality: reject H0:θ=θ0H_0: \theta = \theta_0 at level α\alpha if θ0\theta_0 lies outside the level-1−α1 - \alpha interval. But often a direct p-value is wanted, or the hypothesis is not a parameter value but a statement about several populations. The organizing principle is that of any hypothesis test: the p-value is the probability, calculated under H0H_0, of a statistic at least as extreme as observed.

The +1+1 in numerator and denominator counts the observed data as another resample and ensures p^>0\hat p > 0 and test size at most α\alpha if TT had exactly the bootstrap distribution. Hall and Wilson (1991) summarized practice in two rules: resample under the null and use a pivotal, studentized statistic. The second gives the test the same second-order accuracy as bootstrap-tt. For the first, there are two ways to construct F^0\hat F_0:

  • Shift the data. For H0:μ=μ0H_0: \mu = \mu_0, resample from x~i=xi−xˉ+μ0\tilde x_i = x_i - \bar x + \mu_0. For equality of two group means, center each at the combined mean: x~i=xi−xˉ+zˉ\tilde x_i = x_i - \bar x + \bar z, y~j=yj−yˉ+zˉ\tilde y_j = y_j - \bar y + \bar z, and resample each group separately.
  • Reweight the data. Keep xix_i but change resampling probabilities from 1/n1/n to weights pip_i satisfying the null, ∑ipixi=μ0\sum_i p_i x_i = \mu_0, and as close as possible to uniform (for example by maximizing ∑ilog⁡pi\sum_i\log p_i, as in empirical likelihood, or with exponential tilting pi∝eλxip_i \propto e^{\lambda x_i}). This respects the data support, unlike shifting positive data.

A third way, equivalent to duality, leaves data untouched and centers the statistic: compare T(x)T(\vb{x}) with the distribution of T(x∗)−T(x)T(\vb{x}^\ast) - T(\vb{x}) for a location statistic. What does not work is resampling the data as they are and comparing T(x∗)T(\vb{x}^\ast) with T(x)T(\vb{x}): that distribution is centered on the observed value, not the null, the p-value is around 0.5 regardless of truth, and the test never rejects.

How does this differ from a permutation test? Permutation is exact but tests a stronger null: observations are exchangeable between groups, meaning the two distributions are equal. If you only want to test that means are equal while permitting different variances and shapes (the Behrens–Fisher problem), a permutation test with mean difference no longer controls size. Bootstrap with the Welch statistic and each group centered separately tests exactly that null, at the cost of being only approximate. (The permutation alternative is the studentized permutation test, asymptotically valid for that same null.)

[ ]Imposing the null, or not: actual size of three testsBrowser
import numpy as np
from scipy.stats import ttest_1samp

rng = np.random.default_rng(11)
R, B, n = 500, 499, 20
mu0 = np.exp(0.5)                                   # H0 cierta: es la media de la lognormal(0, 1)
tstat = lambda a, m: (a.mean(-1) - m) / (a.std(-1, ddof=1) / np.sqrt(a.shape[-1]))
rech = {"t de Student": 0, "bootstrap, nula impuesta": 0, "bootstrap, sin imponer la nula": 0}
for _ in range(R):
    x = rng.lognormal(0, 1, n)
    t_obs = abs(tstat(x, mu0))
    idx = rng.integers(0, n, (B, n))
    x0 = x - x.mean() + mu0                         # los datos desplazados cumplen H0
    p_bien = (1 + np.sum(np.abs(tstat(x0[idx], mu0)) >= t_obs)) / (B + 1)
    p_mal = (1 + np.sum(np.abs(tstat(x[idx], mu0)) >= t_obs)) / (B + 1)
    rech["t de Student"] += ttest_1samp(x, mu0).pvalue <= 0.05
    rech["bootstrap, nula impuesta"] += p_bien <= 0.05
    rech["bootstrap, sin imponer la nula"] += p_mal <= 0.05
for k, v in rech.items():
    print(f"{k:32s} tamaño real {v / R:.3f}   (nominal 0.05; error de Monte Carlo {np.sqrt(0.05 * 0.95 / R):.3f})")

With such skewed data and n=20n = 20, Student’s tt rejects a true hypothesis nearly three times the nominal rate (the skewness of TT seen with Edgeworth). The bootstrap test with the null imposed improves considerably, although it still misses 5%: it is second-order, not exact, and a lognormal with n=20n = 20 is a hard case. Without imposing the null, the “test” never rejects: its size is zero, and its power would be too.

When bootstrap fails

Everything above rests on a property we have so far taken for granted.

Bootstrap is always consistent in the smooth-function model; failures appear outside it. The canonical example is the maximum.

The proof is short and you will do it in the exercises. The cause is that the maximum depends on one observation, and the empirical distribution has nothing to its right: the tail of FF near θ\theta, which determines the distribution of MM, is exactly what F^n\hat F_n cannot mimic. Compare the mean, which depends equally on all observations.

InteractiveBootstrap for the maximum
Above, the sample in [0,1][0, 1]. Below, distribution functions of n(θ−max⁡)n(\theta - \max) and its bootstrap versions
θ = 1
Mass of the atom at T∗=0T^\ast = 0 versus nn
1 − 1/e
  • true
  • Exp(1) limit
  • n-out-of-n bootstrap
  • m-out-of-n bootstrap
200
m = 20
P∗(max⁡∗=max⁡)P^\ast(\max^\ast = \max) con m=nm = n63.30 %
Same for mm out of nn: 1−(1−1/n)m1 - (1 - 1/n)^m9.54 %
Kolmogorov distance to the true law: nn out of nn | mm out of nn0.633 | 0.095
With n=200n = 200, the bootstrap places mass 63.3 % at T∗=0T^\ast = 0 (the resampled maximum equals the observed maximum), while the true law is continuous: the Kolmogorov distance between them is 0.633 and does not shrink as nn grows. With m=20m = 20 the atom has mass 9.5 % and the distance is 0.095.
A sample from Unif⁡(0,1)\Unif(0, 1) (top, maximum in red) and three distribution functions: true distribution of n(θ−max⁡)n(\theta - \max) in the text color, bootstrap distribution of n(max⁡−max⁡∗)n(\max - \max^\ast) in red, and mm-out-of-nn bootstrap in green. Bootstrap distributions are exact, without Monte Carlo. The red jump at t=0t = 0 is the probability that a resample repeats the maximum. Right: jump mass versus nn, tending to 1−1/e1 - 1/e with ordinary bootstrap and zero with mm-out-of-nn. Increase nn to 1000: does the red jump disappear? Decrease mm: when does the green staircase approach the true curve, and what happens when mm is tiny? Enable parametric bootstrap and request several samples.

Parametric bootstrap has no such problem. If the uniform model is credible, resampling from Unif⁡(0,M)\Unif(0, M) gives P(n(M−M∗)/M≤t)=1−(1−t/n)n\Pr(n(M - M^\ast)/M \le t) = 1 - (1 - t/n)^n, exactly the distribution of n(θ−M)/θn(\theta - M)/\theta: here M/θM/\theta is a pivot and parametric bootstrap is exact. Inconsistency affects the nonparametric method.

Other failures

  • Mean with infinite variance. If FF is in the domain of attraction of a stable law with index 1<α<21 < \alpha < 2 (tails P(∣X∣>x)\Pr(\abs X > x) of order x−αx^{-\alpha}, finite mean and infinite variance), the bootstrap distribution of the mean converges, conditional on data, to a random distribution: it depends on which few giant observations appear in the sample (Athreya, 1987). The bootstrap interval changes from sample to sample far more than the true one.
  • Parameters on the boundary. If θ≥0\theta \ge 0 and truth is θ=0\theta = 0, restricted estimator θ^=max⁡(Xˉ,0)\hat\theta = \max(\bar X, 0) has a limiting law mixing an atom at zero and a half-normal, which bootstrap does not reproduce (Andrews, 2000). The same happens to any estimator with an active constraint: zero random-effect variances, sign-constrained coefficients.
  • Statistics nonsmooth at the truth. ∣Xˉ∣\abs{\bar X} when μ=0\mu = 0, max⁡(μ1,μ2)\max(\mu_1, \mu_2) when μ1=μ2\mu_1 = \mu_2 (the value of the better of two tied models), or error of a validation-selected classifier. The map F↦θ(F)F \mapsto \theta(F) is not differentiable where it matters and the analogy between the two worlds breaks.

The median, by contrast, bootstraps well (although its jackknife fails), as do smooth moment statistics. A useful rule: if θ^\hat\theta depends smoothly on the empirical distribution and has a normal limiting law, bootstrap is consistent; if it depends on a few extreme observations, an active constraint, or a nondifferentiable point, be suspicious.

The remedy: resample fewer observations

The mm-out-of-nn bootstrap (Bickel, Götze and van Zwet, 1997) takes resamples of size m<nm < n with replacement and uses τm(θ^m∗−θ^n)\tau_m(\hat\theta^\ast_m - \hat\theta_n) to approximate the law of τn(θ^n−θ)\tau_n(\hat\theta_n - \theta). If m→∞m \to \infty and m/n→0m/n \to 0, it is consistent in all the examples above. For the maximum, the reason is that the probability of repeating the observed maximum becomes 1−(1−1/n)m≈m/n→01 - (1 - 1/n)^m \approx m/n \to 0; with few draws the resample barely sees the discretization of F^n\hat F_n near the extreme, which now looks continuous at scale 1/m1/m. Subsampling (Politis, Romano and Wolf, 1999) does the same without replacement, with subsets of size bb: each subsample is a genuine sample of size bb from FF, so it works under even more general conditions, practically whenever a limiting law exists.

Both have costs. The rate τn\tau_n (nn for the maximum, n\sqrt n for the mean) must be known to rescale from mm to nn. One must choose mm, and the result depends on that choice; Bickel and Sakov (2008) propose taking the mm at which bootstrap distributions for consecutive values of mm stop changing. And when ordinary bootstrap does work, mm-out-of-nn loses second-order accuracy: hence the original paper’s title, “gains, losses and remedies.”

[ ]The maximum: n out of n, m out of n, and parametricBrowser
import numpy as np

rng = np.random.default_rng(5)
for n in [10, 100, 1000, 10000]:
    print(f"n = {n:5d}:  P*(máx* = máx) = {1 - (1 - 1 / n) ** n:.4f}")
print(f"límite: 1 - 1/e = {1 - np.exp(-1):.4f}")

# Límite superior del 95 % para theta: [máx, máx + c/n], con c el cuantil 0.95 de la ley estimada de n(theta - máx).
# El máximo de m extracciones con reemplazo de una muestra ordenada es su elemento ceil(n U^(1/m)), U uniforme.
def cuantil_c(xs, m, B, rng):
    n = len(xs)
    k = np.ceil(n * rng.random(B) ** (1 / m)).astype(int) - 1
    return np.quantile(m * (xs[-1] - xs[k]), 0.95)

R, B, n, theta = 2000, 1000, 200, 1.0
cubre = {"n de n": 0, "m de n (m = 20)": 0, "paramétrico": 0}
for _ in range(R):
    xs = np.sort(rng.uniform(0, theta, n))
    M = xs[-1]
    cubre["n de n"] += theta <= M + cuantil_c(xs, n, B, rng) / n
    cubre["m de n (m = 20)"] += theta <= M + cuantil_c(xs, 20, B, rng) / n
    c_par = np.quantile(n * (M - M * rng.random(B) ** (1 / n)), 0.95)   # máx de U(0, M) = M U^(1/n)
    cubre["paramétrico"] += theta <= M + c_par / n
for k, v in cubre.items():
    print(f"cobertura del límite superior del 95 %, {k:16s}: {v / R:.3f}")

Ordinary bootstrap promises 95% and covers 80%: its 0.95 quantile relies on jumps between the last observed data points, which say nothing about distance to θ\theta. mm-out-of-nn with m=20m = 20 rises to 92%, and parametric, exact here apart from BB Monte Carlo error, gives 94%. mm-out-of-nn is not free: with fixed mm, the resample is small and its quantile noisy, and in other problems the choice of mm changes the result more than here.

Dependent data: block bootstrap

Everything above assumes independent data. For a weakly stationary time series with autocovariance function γ(h)\gamma(h), variance of the mean is

Var⁡(Xˉ)=1n∑h=−(n−1)n−1(1−∣h∣n)γ(h)  ≈  1n∑h=−∞∞γ(h)=σ∞2n,\Var(\bar X) = \frac1n\sum_{h = -(n-1)}^{n-1}\Big(1 - \frac{\abs h}{n}\Big)\gamma(h) \;\approx\; \frac{1}{n}\sum_{h=-\infty}^{\infty}\gamma(h) = \frac{\sigma^2_\infty}{n},

where σ∞2\sigma^2_\infty is long-run variance. For an AR(1), Xt=φXt−1+εtX_t = \varphi X_{t-1} + \eps_t, with autocorrelations ρ(h)=φ∣h∣\rho(h) = \varphi^{\abs h}, the sum gives σ∞2=γ(0)1+φ1−φ\sigma^2_\infty = \gamma(0)\frac{1 + \varphi}{1 - \varphi}: with φ=0.5\varphi = 0.5 the true standard error is 3≈1.73\sqrt 3 \approx 1.73 times what independent data would yield. The i.i.d. bootstrap resamples individual observations, destroys time order, and estimates γ(0)/n\gamma(0)/n: it ignores all terms with h≠0h \ne 0.

The solution is to resample pieces of the series long enough to retain short-range dependence.

The i.i.d. bootstrap is the case ℓ=1\ell = 1. Original dependence is preserved intact within each block; it is lost only at joins, a fraction 1/ℓ1/\ell of positions. For the mean with moving blocks and n=kℓn = k\ell, bootstrap variance even has closed form: the resampled mean averages kk randomly selected block means, so

Var⁡∗(Xˉ∗)=1k⋅1n−ℓ+1∑j=1n−ℓ+1(xˉj,ℓ−xˉˉ)2,\Var^\ast(\bar X^\ast) = \frac{1}{k}\cdot\frac{1}{n - \ell + 1}\sum_{j=1}^{n-\ell+1}\big(\bar x_{j,\ell} - \bar{\bar x}\big)^2,

with xˉj,ℓ\bar x_{j,\ell} the mean of the block starting at jj and xˉˉ\bar{\bar x} the mean of all of them. The following figure uses it to compute bootstrap standard error without Monte Carlo.

Choosing the length

ℓ\ell controls a bias–variance tradeoff:

  • Short blocks: each join breaks dependence, and small ℓ\ell means many joins. The variance estimator has downward bias of order 1/ℓ1/\ell (for the mean, of order −1ℓn∑h∣h∣γ(h)-\frac{1}{\ell n}\sum_h\abs h\gamma(h)).
  • Long blocks: there are only n/ℓn/\ell distinct “effective” blocks, and bootstrap variance is estimated from few observations: its own variance grows like ℓ/n\ell/n. A second downward bias of order ℓ/n\ell/n also appears because block-mean dispersion is measured around their own mean, which with few effective blocks already absorbs some variation (in the figure the mean curve falls again for large ℓ\ell).

Balancing squared bias of order ℓ−2\ell^{-2} against variance of order ℓ/n\ell/n, optimal ℓ\ell for estimating variance grows as n1/3n^{1/3} (Hall, Horowitz and Jing, 1995). The constant depends on autocorrelation, and Politis and White (2004) gave an automatic spectral estimator, later corrected by Patton, Politis and White (2009). Stationary bootstrap is less sensitive to the exact choice than moving blocks, although somewhat less efficient.

InteractiveBlock length
Observed series in blocks of ℓ=10\ell = 10 (above) and one moving-block resample (below)
Bootstrap standard error of the mean versus ℓ\ell
  • True SE
  • this series
  • mean of 200 series
  • 10th to 90th percentiles of 200 series
0.60
10
240
True standard error of the mean0.1607
Bootstrap SE for this series: ℓ=1\ell = 1 | selected ℓ\ell0.0758 | 0.1490
Relative root mean squared error at ℓ\ell (200 series)18.4 %
With φ=0.60\varphi = 0.60, the i.i.d. bootstrap (ℓ=1\ell = 1) gives an average standard error of 49 % of the true value. With ℓ=10\ell = 10, the average bias is −13 % and variation across series (10th to 90th percentiles) ranges from 72 % to 106 % of the true value. The smallest mean squared error is reached at ℓ≈10\ell \approx 10.
An AR(1) series split into blocks of length ℓ\ell and, below, a moving-block resample: each colored segment is a block copied from a random place in the series, with alternating colors. Right: bootstrap standard error of the mean versus ℓ\ell (using the formula above, without Monte Carlo) for this series and 200 independent series (dashed mean and 10–90% band), against true standard error in the text color. With φ=0.6\varphi = 0.6, look at ℓ=1\ell = 1: what fraction of true error does i.i.d. bootstrap estimate? Increase ℓ\ell: bias closes, but the band widens. Try φ=0.9\varphi = 0.9 and negative φ\varphi: which way does optimal ℓ\ell move? What happens with φ=0\varphi = 0?

With negative autocorrelation the i.i.d. bootstrap overestimates error, because γ(h)\gamma(h) terms with odd hh are negative and offset one another; ignoring dependence does not always err in the same direction. A technical detail: with moving blocks, the resampled series mean does not have expectation xˉ\bar x, since endpoint observations appear in fewer blocks. For the mean this does not matter (variance does not change), but to center a studentized statistic or construct an interval, circular or stationary bootstrap avoids this edge effect.

A strategy’s Sharpe ratio

The Sharpe ratio, SR=μ/σ\mathrm{SR} = \mu/\sigma for returns (annualized by multiplying by 252\sqrt{252} for daily data), is central to evaluating strategies, and its standard error is often underestimated. The next cell implements the three block bootstraps from scratch and applies them to a synthetic four-year series of daily returns with two realistic features: clustered volatility, generated by a GARCH(1, 1), and first-order autocorrelation 0.2, typical of strategies in illiquid assets whose prices are smoothed. Because the series is synthetic, true standard error is obtained by simulating 2000 series.

[ ]Block bootstrap from scratch: Sharpe ratio errorBrowser
import numpy as np

def indices_moviles(n, l, rng):
    k = -(-n // l)                                          # techo de n / l
    ini = rng.integers(0, n - l + 1, k)
    return (ini[:, None] + np.arange(l)).ravel()[:n]

def indices_circulares(n, l, rng):
    k = -(-n // l)
    ini = rng.integers(0, n, k)
    return ((ini[:, None] + np.arange(l)) % n).ravel()[:n]

def indices_estacionarios(n, l, rng):
    nuevo = rng.random(n) < 1 / l                           # empieza bloque con probabilidad p = 1/l
    nuevo[0] = True
    bloque = np.cumsum(nuevo) - 1
    primero = np.flatnonzero(nuevo)
    ini = rng.integers(0, n, len(primero))
    return (ini[bloque] + np.arange(n) - primero[bloque]) % n

def simular_retornos(n, m, rng, mu=0.0004, phi=0.2, w=2e-6, a=0.08, b=0.9):
    """m series de n retornos diarios: AR(1) con innovaciones GARCH(1, 1)."""
    s2 = np.full(m, w / (1 - a - b))
    eta = np.zeros(m)
    e = np.zeros(m)
    r = np.empty((m, n))
    for t in range(n):
        s2 = w + a * eta**2 + b * s2
        eta = np.sqrt(s2) * rng.standard_normal(m)
        e = phi * e + eta
        r[:, t] = mu + e
    return r

sharpe = lambda r: np.sqrt(252) * r.mean(-1) / r.std(-1, ddof=1)

rng = np.random.default_rng(42)
n = 1000
verdad = sharpe(simular_retornos(n, 2000, rng)).std(ddof=1)
r = simular_retornos(n, 1, rng)[0]
print(f"Sharpe anualizado de la serie observada: {sharpe(r):.3f}")
print(f"error estándar verdadero (2000 series simuladas): {verdad:.3f}\n")

B = 1000
iid = sharpe(r[rng.integers(0, n, (B, n))]).std(ddof=1)
print(f"i.i.d. (l = 1)        : {iid:.3f}   ({iid / verdad:.0%} del verdadero)")
for l in [5, 10, 20, 40]:
    fila = []
    for nombre, f in [("móviles", indices_moviles), ("circulares", indices_circulares), ("estacionario", indices_estacionarios)]:
        idx = np.array([f(n, l, rng) for _ in range(B)])
        fila.append(f"{nombre} {sharpe(r[idx]).std(ddof=1):.3f}")
    print(f"l = {l:2d}: " + "   ".join(fila))

The i.i.d. bootstrap gives standard error 77% of the truth (0.50 versus 0.65). With blocks of order n1/3=10n^{1/3} = 10, the three schemes give 0.61 to 0.63, almost all the way, agreeing apart from single-series noise; at ℓ=40\ell = 40 that noise is already visible (stationary overshoots to 0.73), the other side of the tradeoff. A Sharpe interval constructed with i.i.d. error would be too narrow, making a mediocre strategy look significantly good. This is the main use case for blocks in quantitative finance.

With libraries

SciPy implements BCa in scipy.stats.bootstrap (its default method) alongside percentile and basic; it does not include bootstrap-tt. The implementation above and SciPy’s should agree apart from Monte Carlo error, since they use the same formulas for z^0\hat z_0 and a^\hat a:

[ ]Own BCa versus scipy.stats.bootstrapBrowser
import numpy as np
from scipy.stats import bootstrap

rng = np.random.default_rng(8)
x = rng.lognormal(0.0, 1.0, 20)
for nombre, est in [("media", media), ("varianza", varianza)]:
    propio = intervalo_bca(x, est, B=20000, rng=rng)[0]
    res = bootstrap((x,), lambda a, axis=-1: est(np.moveaxis(a, axis, -1)), method="BCa", n_resamples=20000,
                    vectorized=True, random_state=rng)
    ci = res.confidence_interval
    print(f"{nombre:9s} propio [{propio[0]:.3f}, {propio[1]:.3f}]   scipy [{ci.low:.3f}, {ci.high:.3f}]")

For time series, Kevin Sheppard’s arch package provides all three block bootstraps and automatic Politis–White selection. It is unavailable in the browser, so this block does not run here:

from arch.bootstrap import StationaryBootstrap, optimal_block_length

l_opt = optimal_block_length(r)                 # columnas 'stationary' y 'circular'
bs = StationaryBootstrap(l_opt.loc[0, "stationary"], r, seed=0)
ic = bs.conf_int(lambda y: np.sqrt(252) * y.mean() / y.std(ddof=1), reps=2000, method="bca")
ToolWhat it offersWhen
scipy.stats.bootstrappercentile, basic, BCa; multiple samples; paired modeindependent data, vectorizable statistics
arch.bootstrapi.i.d., moving blocks, circular, stationary; percentile, basic, studentized, BC and BCa intervals; optimal_block_lengthtime series, finance
own implementationbootstrap-tt with nested SE, double bootstrap, tests imposing the null, mm-out-of-nneverything not already provided

Common mistakes

Exercises

NumericThe maximum's atom
For nonparametric bootstrap, P∗(max⁡∗=max⁡)=1−(1−1/n)n\Pr^\ast(\max^\ast = \max) = 1 - (1 - 1/n)^n. Calculate its limit as n→∞n \to \infty.
NumericThe atom with m out of n
For n=1000n = 1000 uniform observations and resamples of size m=50m = 50, what is the probability that the resample maximum equals the observed maximum?
NumericAcceleration of a mean
A sample of n=25n = 25 observations has sample skewness γ^=2\hat\gamma = 2 (moments divided by nn). What is the BCa interval acceleration a^\hat a for the mean, estimated by jackknife?
NumericA BCa level
With z^0=0.1\hat z_0 = 0.1 and a^=0.05\hat a = 0.05, which quantile level α1\alpha_1 does the 95% BCa interval use for its lower endpoint? Give a proportion (for example, 0.025).
NumericHow wrong is i.i.d. bootstrap?
For a stationary AR(1) with φ=0.5\varphi = 0.5, by what factor must the standard error of the mean from i.i.d. bootstrap be multiplied to obtain the true one as n→∞n \to \infty?
QuizWhy bootstrap-t gains an order
In the smooth-function model, why does bootstrap-tt have one-sided coverage error O(n−1)\bigO(n^{-1}) and percentile only O(n−1/2)\bigO(n^{-1/2})?
QuizThe right method
Which problem and method combinations are suitable? Select all that apply.

More than one answer may be correct.

ProofBootstrap for the maximum is inconsistent
Prove: If X1,…,Xn∼iidUnif⁡(0,θ)X_1, \dots, X_n \iid \Unif(0, \theta) and M=max⁡iXiM = \max_i X_i, the nonparametric bootstrap distribution of n(M−M∗)n(M - M^\ast) does not converge to the limiting law of n(θ−M)n(\theta - M).
0
Let M∗M^\ast be the maximum of a bootstrap resample. With probability 1 there are no ties, so MM is one observation.

Step 1 of 4. What is P∗(M∗<M)\Pr^\ast(M^\ast < M)?

ProofPercentile respects transformations; bootstrap-t does not
Prove: Let hh be continuous and strictly increasing and φ=h(θ)\varphi = h(\theta). The percentile interval of φ\varphi is the image under hh of that for θ\theta; bootstrap-tt generally is not.
0
Let θ^∗\hat\theta^\ast be bootstrap replicates, qp∗q^\ast_p their quantiles, and φ^∗=h(θ^∗)\hat\varphi^\ast = h(\hat\theta^\ast).

Step 1 of 4. What is the pp quantile of φ^∗\hat\varphi^\ast?

CodeA bootstrap test of equal means
Implement p_bootstrap_medias(x, y, B, rng) to return the two-sided p-value of a bootstrap test of H0:E[X]=E[Y]H_0: \E[X] = \E[Y] using Welch's statistic, imposing the null: center each group at the combined mean and resample each group separately. Use p^=(1+#{∣t∗∣≥∣tobs∣})/(B+1)\hat p = (1 + \#\{\abs{t^\ast} \ge \abs{t_{\text{obs}}}\})/(B + 1). The starter code resamples the data as they are (the common mistake). Tests measure actual size under unequal variances and compare it with SciPy's Welch test.
import numpy as np

def welch(a, b):
  """Estadístico de Welch; a y b pueden tener una dimensión inicial de remuestras."""
  va = a.var(axis=-1, ddof=1) / a.shape[-1]
  vb = b.var(axis=-1, ddof=1) / b.shape[-1]
  return (a.mean(axis=-1) - b.mean(axis=-1)) / np.sqrt(va + vb)

def p_bootstrap_medias(x, y, B=999, rng=None):
  rng = np.random.default_rng() if rng is None else rng
  x, y = np.asarray(x, dtype=float), np.asarray(y, dtype=float)
  t_obs = welch(x, y)
  # tu código: impón la nula antes de remuestrear (ahora se remuestrean los datos tal cual)
  xs = x[rng.integers(0, len(x), (B, len(x)))]
  ys = y[rng.integers(0, len(y), (B, len(y)))]
  t_ast = welch(xs, ys)
  return (1 + np.sum(np.abs(t_ast) >= abs(t_obs))) / (B + 1)
Shift+Enter to run

Summary

Key idea
Simple bootstrap intervals fail because they do not capture skewness, the order-n−1/2n^{-1/2} Edgeworth term; resampling a pivot (bootstrap-tt) or correcting quantile levels (BCa) captures it and reduces one-sided coverage error from O(n−1/2)\bigO(n^{-1/2}) to O(n−1)\bigO(n^{-1}). Before refining the interval, ensure bootstrap works: independent data (otherwise blocks) and a smooth statistic (otherwise mm-out-of-nn).
  • Edgeworth. P(S≤x)=Φ(x)−γ6n(x2−1)ϕ(x)+O(n−1)\Pr(S \le x) = \Phi(x) - \frac{\gamma}{6\sqrt n}(x^2 - 1)\phi(x) + \bigO(n^{-1}) for a standardized mean, and +γ6n(2x2+1)ϕ(x)+\frac{\gamma}{6\sqrt n}(2x^2 + 1)\phi(x) for the studentized mean. Bootstrap of a pivotal quantity reproduces that term; bootstrap of an unstandardized root does not.
  • First and second order. Normal, percentile and basic have endpoints with error Op(n−1)\bigO_p(n^{-1}) and one-sided coverage error O(n−1/2)\bigO(n^{-1/2}); bootstrap-tt, BCa and percentile calibrated by double bootstrap, Op(n−3/2)\bigO_p(n^{-3/2}) and O(n−1)\bigO(n^{-1}). For two-sided intervals all have O(n−1)\bigO(n^{-1}), but first-order failures are unbalanced.
  • Bootstrap-tt. Resamples T∗=(θ^∗−θ^)/SE^∗T^\ast = (\hat\theta^\ast - \hat\theta)/\widehat{\mathrm{SE}}^\ast; requires a standard error per resample (formula, nested or jackknife), depends on scale, and is erratic when SE^\widehat{\mathrm{SE}} is unstable.
  • BCa. Reads quantiles of the same bootstrap distribution at levels Φ(z^0+(z^0+zα)/(1−a^(z^0+zα)))\Phi\big(\hat z_0 + (\hat z_0 + z_\alpha)/(1 - \hat a(\hat z_0 + z_\alpha))\big), with z^0\hat z_0 from the fraction of replicates below θ^\hat\theta and a^\hat a from jackknife (γ^/(6n)\hat\gamma/(6\sqrt n) for the mean). Exact in Efron’s transformation model, invariant and second-order.
  • Tests. Resample from F^0\hat F_0 satisfying the null (by shifting or reweighting), with a studentized statistic and p^=(1+#)/(B+1)\hat p = (1 + \#)/(B + 1). Unlike permutation tests, these test parameter nulls (equal means with unequal variances) approximately.
  • Failures. Maximum (atom 1−(1−1/n)n→0.6321 - (1 - 1/n)^n \to 0.632), infinite variance, boundary parameters and nonsmooth statistics. Remedies: mm-out-of-nn with m/n→0m/n \to 0, subsampling, or a parametric model.
  • Dependence. Moving, circular or stationary blocks preserve autocorrelation within each block; ℓ∝n1/3\ell \propto n^{1/3} balances short-block bias and long-block variance. Without blocks, error of the Sharpe ratio or any temporal mean is underestimated.