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
- 05Nonparametric bootstrapParametric bootstrapBootstrap percentile and basic intervalsJackknifePivotal quantityHypothesis testPermutation testWelch's t-testSimulation study (ADEMP)
- 04Characteristic functionCumulant generating function
- 26Weak (second-order) stationarityAutocovariance functionAutocorrelation function
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 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, .
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 ( 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 . 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- and BCa, which we will construct shortly.
What the race shows, and the rest of the lesson explains:
- 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 : the Edgeworth expansion. The order- term is skewness, which first-order intervals do not capture well.
- How to fix it. Resample a pivotal quantity (bootstrap-) or correct quantile levels (BCa). Both cancel the order- term: they are second-order.
- How to test a hypothesis by bootstrap, imposing the null during resampling.
- When bootstrap fails entirely, as for a sample maximum, and the remedy of resampling fewer than observations.
- What to do with time series, where resampling observation by observation destroys dependence: block bootstrap.
How wrong is an interval?
Let be a parameter and its estimator from observations. An upper confidence limit at nominal level is a statistic with ; its coverage error is . A two-sided equal-tailed interval, , is the intersection of lower and upper limits each at level , and its coverage error is the sum of the two tail errors.
To assess a bootstrap interval’s quality, we need the distribution of 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 or in which direction. The Edgeworth expansion supplies that.
The Edgeworth expansion, sketched
Let have mean , variance , skewness and excess kurtosis . Standardize and consider
The cumulant generating function of a sum of independent variables is the sum of those of its terms, and scaling by multiplies the order- cumulant by . Since those of are , those of are , , , , and so on. In terms of the characteristic function,
It remains to invert. The normal density is , and differentiating under the integral gives . That is, multiplication by on the Fourier side is equivalent to applying to , producing with the probabilists’ Hermite polynomial (, ). Thus the density of is approximately and, integrating with ,
The correction term is even in and has the sign of : with right-skewed data (), the distribution function of falls below for and above it for ; that is, the mean has less mass than the normal predicts in the left tail and more in the right. Its order is , not : 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 has jumps of size that no smooth polynomial describes. Notice the sign of : studentization reverses skewness. When a large observation is missing, and fall together and goes far left. For exponential data () and , is about 0.15, not 0.05: a “95%” upper limit of the form fails three times more than promised (and with the Student quantile for 9 degrees of freedom, 1.833, it still fails 13% of the time).
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 ), so it too has an Edgeworth expansion, with moments of instead of those of :
Since , the difference between the bootstrap distribution of and the true distribution of is : bootstrap automatically reproduces the skewness term. This happens because the leading term of the expansion of , , depends on nothing unknown: is asymptotically pivotal.
Compare this with percentile or basic intervals, which resample the unstandardized root . Its distribution is , and the bootstrap distribution is the same with instead of . Already the leading term differs by , because . Scale estimation error is of the same order as the skewness correction and obscures it.
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 the pattern is clean: doubling divides normal error by and Edgeworth error by 2. With the Edgeworth term corrects most error, although at the next order- term still matters: an asymptotic expansion describes how error decreases, not a guarantee of small error for a particular (and in the last column, from , 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 , the quantile of is , with . This lets us compare each interval with the “ideal” interval, which uses exact quantiles of .
The transition from endpoint error to coverage error is simple: if the limit falls short by , coverage loses . Since fluctuates on scale , that probability is of order .
Proof
Sketch, ignoring terms and the difference between and , which is of relative order . By Cornish–Fisher, , and the ideal is the table’s value. For percentile, has the expansion of with in the bootstrap world, whose quantile is , so . Basic is with , changing the correction’s sign. Bootstrap- uses quantile , which agrees with ideal apart from . Subtracting each correction from ideal (with ) gives the third column, and the previous argument converts it to coverage error: an endpoint deficit of subtracts from coverage.
∎For exponential data () and a 95% upper limit (), the table predicts normal, percentile and basic lose , and coverage with , while bootstrap- loses nothing at that order. A simulation with 8000 samples per row and (run outside the browser; the coverage study below is similar, smaller and uses two-sided intervals) gives:
| normal | percentile | basic | bootstrap- | normal / percentile / basic prediction | |
|---|---|---|---|---|---|
| 10 | 0.831 | 0.839 | 0.817 | 0.918 | 0.880 / 0.899 / 0.862 |
| 20 | 0.873 | 0.882 | 0.862 | 0.930 | 0.901 / 0.914 / 0.888 |
| 40 | 0.898 | 0.906 | 0.890 | 0.938 | 0.915 / 0.924 / 0.906 |
| 80 | 0.922 | 0.926 | 0.913 | 0.948 | 0.925 / 0.932 / 0.919 |
The first three have the predicted order (percentile, normal, basic), and the prediction fits increasingly well; at the order- terms ignored by the table are still large. Bootstrap- is always much closer to 95%.
Bootstrap-t: resample a pivot
The theorem’s lesson is direct: instead of resampling , 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 from a statement about the root), using root instead of . It naturally generalizes Student’s interval: if data are normal, is exactly ; otherwise bootstrap estimates the distribution of instead of assuming it. Notice the quantiles cross: the upper quantile of gives the lower endpoint. If 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, ; for variance, with central moments ; for correlation, the nonparametric delta method. This is what the race uses.
- A nested bootstrap: within each resample, resamples of the resample ( to suffices for standard error). Cost becomes statistic evaluations.
- The jackknife of each resample: 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- intervals for and 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 is unstable: a resample with a coincidentally tiny standard error yields a huge , and extreme quantiles of generate very long intervals. This often occurs with correlation near . The classical remedy is to apply bootstrap- on a variance-stabilizing scale (Fisher’s , , for correlation; log for variance or a ratio) and transform the interval back.
BCa: correct levels, not the distribution
Bootstrap- 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 , levels are and and percentile is recovered. measures median bias of the bootstrap distribution: if more than half the replicates lie below , . measures how standard error changes with the parameter, estimated using skewness of jackknife influences. For the mean, and the formula reduces to
sample skewness divided by : the same as the Edgeworth term.
Where the formulas come from
Proof
Assume (for , repeat with ; with the model is a translation and calculation is direct). Write the model as , with . Adding to both sides and multiplying by , , and taking logs, with ,
whose distribution does not depend on : it is a pivot, increasing in . The lower level- limit for is , with , because . Undoing the logarithm, the limit for is
In the bootstrap world, , so
which is the BCa level: is the quantile at that level of . As is increasing, quantiles commute with it, and the quantile at the same level of is , the exact limit for . Finally, , which justifies estimator .
∎The model is more flexible than it looks: absorbs order- bias on the normalizing scale, and allows the standard deviation of 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- to : BCa is second-order without needing a standard error per resample. It also inherits percentile invariance: does not change when transforming the parameter, and the BCa interval for is the image of that for (with theoretical ; the jackknife estimate is not exactly invariant, but differences are of lower order).
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 is twice as large). Two practical consequences:
- BCa needs more replicates than percentile. If , the upper endpoint is the 99.5% quantile of replicates, relying on five values with . Efron and Tibshirani recommend for intervals; for BCa more is advisable.
- BCa performs no miracles with very small . 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 .
Implementation from scratch
The following two functions implement bootstrap- and BCa intervals in vectorized form: the statistic receives an array whose last dimension contains observations, so all resamples are evaluated at once. Jackknife is also vectorized with an matrix of leave-one-out samples.
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- 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- 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- compensates with a highly variable per-resample standard error, both its virtue and its weakness. And mean acceleration agrees with 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 . Estimands: and . Methods: normal, percentile, basic, bootstrap- (formula-based SE) and BCa, with . Performance measures: coverage, failures in each tail and mean width, with Monte Carlo error.
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- 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 order- 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- 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 .
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 (), so we can do what the first cell did without leaving the sample:
- For each outer resample , , generate inner resamples of and calculate , the position of within the inner bootstrap distribution.
- If percentile were exact, would be uniform on : percentile fails below exactly when . The tails of therefore measure actual coverage on each side.
- Take quantiles and of the as corrected levels and , and return 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 , so calibrated percentile is second-order. Its cost, evaluations, was prohibitive in 1990 and is often affordable today for cheap statistics.
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 , 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 at level if lies outside the level- 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 , of a statistic at least as extreme as observed.
The in numerator and denominator counts the observed data as another resample and ensures and test size at most if 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-. For the first, there are two ways to construct :
- Shift the data. For , resample from . For equality of two group means, center each at the combined mean: , , and resample each group separately.
- Reweight the data. Keep but change resampling probabilities from to weights satisfying the null, , and as close as possible to uniform (for example by maximizing , as in empirical likelihood, or with exponential tilting ). This respects the data support, unlike shifting positive data.
A third way, equivalent to duality, leaves data untouched and centers the statistic: compare with the distribution of for a location statistic. What does not work is resampling the data as they are and comparing with : 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.)
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 , Student’s rejects a true hypothesis nearly three times the nominal rate (the skewness of 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 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 near , which determines the distribution of , is exactly what cannot mimic. Compare the mean, which depends equally on all observations.
Parametric bootstrap has no such problem. If the uniform model is credible, resampling from gives , exactly the distribution of : here is a pivot and parametric bootstrap is exact. Inconsistency affects the nonparametric method.
Other failures
- Mean with infinite variance. If is in the domain of attraction of a stable law with index (tails of order , 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 and truth is , restricted estimator 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. when , when (the value of the better of two tied models), or error of a validation-selected classifier. The map 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 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 -out-of- bootstrap (Bickel, Götze and van Zwet, 1997) takes resamples of size with replacement and uses to approximate the law of . If and , it is consistent in all the examples above. For the maximum, the reason is that the probability of repeating the observed maximum becomes ; with few draws the resample barely sees the discretization of near the extreme, which now looks continuous at scale . Subsampling (Politis, Romano and Wolf, 1999) does the same without replacement, with subsets of size : each subsample is a genuine sample of size from , so it works under even more general conditions, practically whenever a limiting law exists.
Both have costs. The rate ( for the maximum, for the mean) must be known to rescale from to . One must choose , and the result depends on that choice; Bickel and Sakov (2008) propose taking the at which bootstrap distributions for consecutive values of stop changing. And when ordinary bootstrap does work, -out-of- loses second-order accuracy: hence the original paper’s title, “gains, losses and remedies.”
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 . -out-of- with rises to 92%, and parametric, exact here apart from Monte Carlo error, gives 94%. -out-of- is not free: with fixed , the resample is small and its quantile noisy, and in other problems the choice of changes the result more than here.
Dependent data: block bootstrap
Everything above assumes independent data. For a weakly stationary time series with autocovariance function , variance of the mean is
where is long-run variance. For an AR(1), , with autocorrelations , the sum gives : with the true standard error is times what independent data would yield. The i.i.d. bootstrap resamples individual observations, destroys time order, and estimates : it ignores all terms with .
The solution is to resample pieces of the series long enough to retain short-range dependence.
The i.i.d. bootstrap is the case . Original dependence is preserved intact within each block; it is lost only at joins, a fraction of positions. For the mean with moving blocks and , bootstrap variance even has closed form: the resampled mean averages randomly selected block means, so
with the mean of the block starting at and the mean of all of them. The following figure uses it to compute bootstrap standard error without Monte Carlo.
Choosing the length
controls a bias–variance tradeoff:
- Short blocks: each join breaks dependence, and small means many joins. The variance estimator has downward bias of order (for the mean, of order ).
- Long blocks: there are only distinct “effective” blocks, and bootstrap variance is estimated from few observations: its own variance grows like . A second downward bias of order 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 ).
Balancing squared bias of order against variance of order , optimal for estimating variance grows as (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.
With negative autocorrelation the i.i.d. bootstrap overestimates error, because terms with odd 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 , 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, for returns (annualized by multiplying by 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.
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 , the three schemes give 0.61 to 0.63, almost all the way, agreeing apart from single-series noise; at 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-. The implementation above and SciPy’s should agree apart from Monte Carlo error, since they use the same formulas for and :
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")
| Tool | What it offers | When |
|---|---|---|
scipy.stats.bootstrap | percentile, basic, BCa; multiple samples; paired mode | independent data, vectorizable statistics |
arch.bootstrap | i.i.d., moving blocks, circular, stationary; percentile, basic, studentized, BC and BCa intervals; optimal_block_length | time series, finance |
| own implementation | bootstrap- with nested SE, double bootstrap, tests imposing the null, -out-of- | everything not already provided |
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. What is ?
Step 1 of 4. What is the quantile of ?
p_bootstrap_medias(x, y, B, rng) to return the two-sided p-value of a bootstrap test of using Welch's statistic, imposing the null: center each group at the combined mean and resample each group separately. Use . 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)Summary
- Edgeworth. for a standardized mean, and 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 and one-sided coverage error ; bootstrap-, BCa and percentile calibrated by double bootstrap, and . For two-sided intervals all have , but first-order failures are unbalanced.
- Bootstrap-. Resamples ; requires a standard error per resample (formula, nested or jackknife), depends on scale, and is erratic when is unstable.
- BCa. Reads quantiles of the same bootstrap distribution at levels , with from the fraction of replicates below and from jackknife ( for the mean). Exact in Efron’s transformation model, invariant and second-order.
- Tests. Resample from satisfying the null (by shifting or reweighting), with a studentized statistic and . Unlike permutation tests, these test parameter nulls (equal means with unequal variances) approximately.
- Failures. Maximum (atom ), infinite variance, boundary parameters and nonsmooth statistics. Remedies: -out-of- with , subsampling, or a parametric model.
- Dependence. Moving, circular or stationary blocks preserve autocorrelation within each block; balances short-block bias and long-block variance. Without blocks, error of the Sharpe ratio or any temporal mean is underestimated.