16  The Bootstrap

In this chapter we turn to a fundamentally different use of simulation: not for evaluating the objective function, but for inference. The bootstrap uses resampling to approximate the sampling distribution of an estimator, providing standard errors and confidence intervals without requiring analytical derivations.

16.1 Motivation

In many settings we face one or more of the following challenges:

  1. The variance formula is difficult to derive (e.g. for multi-step estimators).
  2. The derivatives of the criterion function are hard or costly to compute.
  3. The estimation criterion is non-smooth in finite samples.
  4. The sample size is too small for the CLT to provide a good approximation.

The bootstrap addresses all of these by directly approximating the finite-sample distribution.

16.2 Framework

Let \(T_{N} = T_{N}(X_{1},\ldots,X_{N})\) be a statistic — for instance, \(T_{N}=\hat{\theta}\) or \(T_{N}=\sqrt{N}(\hat{\theta}-\theta_{0})\). The finite-sample distribution \(G_{N}(\cdot,F_{0})\) is typically unknown. The bootstrap idea is to replace \(F_{0}\) with an estimate \(\hat{F}_{N}\) and use \(G_{N}(\cdot,\hat{F}_{N})\) to approximate \(G_{N}(\cdot,F_{0})\).

There are two main approaches to constructing \(\hat{F}_{N}\):

Definition 16.1 (Nonparametric Bootstrap) Replace \(F_{0}\) with the empirical distribution function: \[\hat{F}_{N}(x) = \frac{1}{N}\sum_{n=1}^{N}\mathbf{1}\{X_{n}\leq x\}\] Bootstrap samples are obtained by sampling \(N\) observations with replacement from the original data.

Definition 16.2 (Parametric Bootstrap) Replace \(F_{0}\) with \(F(\cdot,\hat{\theta}_{N})\), the model-implied distribution evaluated at the estimated parameters. Bootstrap samples are obtained by simulating from the estimated model.

The nonparametric bootstrap is more general and requires fewer assumptions, while the parametric bootstrap can be more efficient when the model is correctly specified. For structural models, the parametric bootstrap is natural since we already have the machinery to simulate from the model.

16.3 Procedure

Given an estimator \(\hat{\theta}_{N}\):

  1. Draw a bootstrap sample of size \(N\): \(\mathbf{X}^{b}=\{X_{1}^{b},\ldots,X_{N}^{b}\}\)
    • Nonparametric: sample with replacement from \(\{X_{1},\ldots,X_{N}\}\)
    • Parametric: simulate from \(F(\cdot,\hat{\theta}_{N})\)
  2. Compute the bootstrap estimate: \(\hat{\theta}^{b}_{N}=T_{N}(\mathbf{X}^{b})\)
  3. Repeat steps 1-2 for \(b=1,\ldots,B\) to obtain the bootstrap distribution \(\{\hat{\theta}^{1}_{N},\ldots,\hat{\theta}^{B}_{N}\}\)

From this distribution we can compute:

  • Bootstrap standard errors: \(\text{se}^{*}(\hat{\theta}) = \text{sd}(\hat{\theta}^{1},\ldots,\hat{\theta}^{B})\)
  • Percentile confidence intervals: \([q_{\alpha/2},\ q_{1-\alpha/2}]\) where \(q_{\alpha}\) is the \(\alpha\)-quantile of the bootstrap distribution
  • Bootstrap-\(t\) confidence intervals: based on the distribution of the pivotal statistic \(t^{b}=(\hat{\theta}^{b}-\hat{\theta})/\text{se}(\hat{\theta}^{b})\)

16.4 When Does the Bootstrap Work?

Why should resampling from \(\hat{F}_{N}\) tell us anything about sampling from \(F_{0}\)? Let’s start with the simplest case, the sample mean. If \(\theta_{0}=\mathbb{E}[X]\) and \(\hat{\theta}=\bar{X}\), then conditional on the data, \(\sqrt{N}(\bar{X}^{b}-\bar{X})\) is itself a normalized sum of iid draws from \(\hat{F}_{N}\), and a central limit theorem applies to it just as it applies to \(\sqrt{N}(\bar{X}-\theta_{0})\). Since the variance of \(\hat{F}_{N}\) converges to the variance of \(F_{0}\), the two distributions converge to the same normal limit.

Most of our estimators are not sample means, but they behave like smooth functions of sample means. Write \(\theta_{0}=\phi(F_{0})\) and \(\hat{\theta}=\phi(\hat{F}_{N})\). If \(\phi\) is differentiable at \(F_{0}\), then (as in the delta method and our asymptotic normality results for extremum estimators) \(\sqrt{N}(\hat{\theta}-\theta_{0})\) is asymptotically equivalent to a linear function of a sample average, and therefore asymptotically normal. The same linearization applies to \(\sqrt{N}(\hat{\theta}^{b}-\hat{\theta})\), because \(\hat{F}_{N}\) is close to \(F_{0}\) and the derivative of \(\phi\) is continuous there. This gives the standard result: when \(\phi\) is suitably differentiable at \(F_{0}\), so that the estimator is asymptotically normal, the bootstrap is consistent: the distribution of \(\sqrt{N}(\hat{\theta}^{b}-\hat{\theta})\) conditional on the data converges to the asymptotic distribution of \(\sqrt{N}(\hat{\theta}-\theta_{0})\).

This argument relies on two conditions. First, the estimator must be approximately linear in the data, which follows from differentiability. Second, the approximation must hold not only at \(F_{0}\) but at the nearby distribution \(\hat{F}_{N}\) from which we resample. When either fails, the bootstrap can fail, as the example in the next section shows.

The bootstrap can actually do better than the asymptotic normal approximation when the statistic is asymptotically pivotal — that is, when its asymptotic distribution does not depend on unknown parameters. The \(t\)-statistic \(\sqrt{N}(\hat{\theta}-\theta_{0})/\text{se}(\hat{\theta})\) is a canonical example. In this case, the bootstrap provides a higher-order refinement over the normal approximation. See Horowitz (2001) for a detailed discussion.

Replicating the Dependence Structure

The bootstrap requires that the resampling scheme correctly replicates the dependence structure in the data. For iid data, sampling with replacement is sufficient. For panel data, one should resample entire individuals (not individual observations) to preserve the within-person correlation structure. For time series data, block bootstrap methods are needed.

Example 16.1 Let’s apply the bootstrap to construct confidence intervals for the income process parameters estimated by minimum distance in Example 12.2. Rather than relying on the analytical standard errors from Example 13.2, we resample individuals from the PSID panel and re-estimate the parameters on each bootstrap sample.

Since the PSID is panel data, we resample entire individuals (all observations for a given person) to preserve the within-person correlation.

using CSV, DataFrames, DataFramesMeta, Statistics, Optim, Plots, Random
include("../scripts/plot_theme.jl")

# Load and prepare data
data_psid = @chain begin
    CSV.read("../data/abb_aea_data.csv",DataFrame,missingstring = "NA")
    @select :person :y :tot_assets1 :asset :age :year
    @subset :age.>=25 :age.<=64
end

# Model moments and estimation functions (from @exm-md_income)
function model_moments(θ, T)
    ρ, σ2_α, σ2_η = θ
    m = [σ2_α + (1-ρ^(2(t-1)))/(1-ρ^2) * σ2_η for t in 1:T]
    return m
end

function md_estimate(data)
    m_hat = @chain data begin
        groupby(:age)
        @combine :var_logy = var(log.(:y))
        @orderby :age
        _.var_logy
    end
    T = length(m_hat)

    function md_objective(x)
        ρ = tanh(x[1])
        σ2_α = exp(x[2])
        σ2_η = exp(x[3])
        θ = (ρ, σ2_α, σ2_η)
        m_model = model_moments(θ, T)
        diff = m_hat .- m_model
        return diff' * diff
    end

    x0 = [0.5, log(0.1), log(0.05)]
    res = optimize(md_objective, x0, Newton(), autodiff=:forward)
    x = res.minimizer
    return [tanh(x[1]), exp(x[2]), exp(x[3])]
end

# Point estimate
θ_hat = md_estimate(data_psid)
println("Point estimates: ρ=$(round(θ_hat[1],digits=3)), σ²_α=$(round(θ_hat[2],digits=3)), σ²_η=$(round(θ_hat[3],digits=3))")
Point estimates: ρ=0.918, σ²_α=0.279, σ²_η=0.085

Now the bootstrap. We resample persons with replacement and re-estimate on each bootstrap sample.

Random.seed!(42)
persons = unique(data_psid.person)
N_persons = length(persons)
B = 200

θ_boot = mapreduce(vcat, 1:B) do b
    # Resample persons with replacement
    boot_persons = persons[rand(1:N_persons, N_persons)]
    # Build bootstrap dataset (preserving panel structure)
    boot_data = mapreduce(vcat, boot_persons) do p
        @subset(data_psid, :person .== p)
    end
    try
        return md_estimate(boot_data)'
    catch
        return [NaN NaN NaN]
    end
end

# Remove any failed bootstrap replications
θ_boot = θ_boot[.!any(isnan.(θ_boot), dims=2)[:], :]

# Bootstrap standard errors
se_boot = std.(eachcol(θ_boot))
println("\nBootstrap standard errors (B=$B):")
println("  se(ρ)    = $(round(se_boot[1], digits=4))")
println("  se(σ²_α) = $(round(se_boot[2], digits=4))")
println("  se(σ²_η) = $(round(se_boot[3], digits=4))")

# 95% percentile confidence intervals
ci_lower = [quantile(θ_boot[:,j], 0.025) for j in 1:3]
ci_upper = [quantile(θ_boot[:,j], 0.975) for j in 1:3]
println("\n95% Confidence Intervals:")
println("  ρ:    [$(round(ci_lower[1],digits=3)), $(round(ci_upper[1],digits=3))]")
println("  σ²_α: [$(round(ci_lower[2],digits=3)), $(round(ci_upper[2],digits=3))]")
println("  σ²_η: [$(round(ci_lower[3],digits=3)), $(round(ci_upper[3],digits=3))]")

Bootstrap standard errors (B=200):
  se(ρ)    = 0.079
  se(σ²_α) = 0.115
  se(σ²_η) = 0.0758

95% Confidence Intervals:
  ρ:    [0.742, 1.0]
  σ²_α: [0.144, 0.515]
  σ²_η: [0.012, 0.249]

Let’s visualize the bootstrap distributions.

labels = ["\$\\rho\$", "\$\\sigma^2_\\alpha\$", "\$\\sigma^2_\\eta\$"]
pl = [begin
    histogram(θ_boot[:,j], normalize=:pdf, label=false, alpha=0.5)
    plot!([θ_hat[j], θ_hat[j]], [0, ylims()[2]*0.9], color=MCM.orange,
          linewidth=2, label="Point Estimate")
    plot!(title=labels[j])
end for j in 1:3]
plot(pl..., layout=(1,3), size=(900,300))

Notice that bootstrapping panel data by resampling individuals is straightforward to implement and automatically accounts for within-person dependence, arbitrary heteroskedasticity, and the full complexity of the minimum distance estimator. Compare these to the analytical standard errors from Example 13.2.

16.5 When the Bootstrap Fails

Consider two independent samples of size \(N\), \(\{X_{1n}\}\) and \(\{X_{2n}\}\), with means \(\mu_{1}\) and \(\mu_{2}\) and unit variances. Suppose the object of interest is the larger of the two means: \[ \theta_{0} = \max\{\mu_{1},\mu_{2}\},\qquad \hat{\theta} = \max\{\bar{X}_{1},\bar{X}_{2}\}. \] This example isn’t as artificial as it looks. Statistics like this arise whenever a parameter is defined by an optimization over a finite set (the value of the best of several options), whenever a parameter may lie on the boundary of the parameter space (such as a variance component that may be zero, or a mixture weight in a model with too many types), and in models defined by moment inequalities (Andrews 2000).

Let’s see why the two conditions fail here. We have \(\theta_{0}=\phi(\mu_{1},\mu_{2})\) with \(\phi(a,b)=\max\{a,b\}\). When \(\mu_{1}\neq\mu_{2}\), \(\phi\) is differentiable at \((\mu_{1},\mu_{2})\): if \(\mu_{1}>\mu_{2}\), then with probability approaching one \(\hat{\theta}=\bar{X}_{1}\), so \(\sqrt{N}(\hat{\theta}-\theta_{0})\rightarrow_{d}\mathcal{N}(0,1)\) and the bootstrap is consistent. But when \(\mu_{1}=\mu_{2}=\mu\), \(\phi\) has a kink exactly at the true parameter, and it is not differentiable there. Writing \(Z_{jN}=\sqrt{N}(\bar{X}_{j}-\mu)\): \[ \sqrt{N}(\hat{\theta}-\theta_{0}) = \max\{Z_{1N},Z_{2N}\}\rightarrow_{d}\max\{Z_{1},Z_{2}\},\qquad Z_{1},Z_{2}\overset{iid}{\sim}\mathcal{N}(0,1). \] This limit isn’t normal, and it has a positive mean (\(1/\sqrt{\pi}\approx 0.56\)), so \(\hat{\theta}\) is biased upward by about \(0.56/\sqrt{N}\).

Now consider the bootstrap. Let \(Z^{b}_{jN}=\sqrt{N}(\bar{X}^{b}_{j}-\bar{X}_{j})\), which behaves like a standard normal conditional on the data. Then: \[ \sqrt{N}(\hat{\theta}^{b}-\hat{\theta}) = \max\left\{Z^{b}_{1N} + \sqrt{N}(\bar{X}_{1}-\hat{\theta}),\ Z^{b}_{2N} + \sqrt{N}(\bar{X}_{2}-\hat{\theta})\right\}. \] One of the two shift terms is zero, and the other is \(-\sqrt{N}|\bar{X}_{1}-\bar{X}_{2}|\). In the true sampling distribution the two means are equal, so there is no shift. When we resample, the “true” means are the sample means, which differ by an amount of order \(1/\sqrt{N}\). After scaling by \(\sqrt{N}\) this difference does not vanish: \(\sqrt{N}|\bar{X}_{1}-\bar{X}_{2}|\) converges to the random variable \(|Z_{1}-Z_{2}|\). So the bootstrap distribution depends on the realized data even in the limit, and it doesn’t converge to the distribution of \(\max\{Z_{1},Z_{2}\}\).

Going back to the two conditions, the estimator is not approximately linear in the data at \(\mu_{1}=\mu_{2}\) (differentiability fails), and the distribution we resample from, \(\hat{F}_{N}\), always has \(\bar{X}_{1}\neq\bar{X}_{2}\) and therefore sits on the smooth part of \(\phi\) rather than at the kink. So a small difference between \(\hat{F}_{N}\) and \(F_{0}\) produces a large difference in the distribution of the statistic.

Example 16.2 Let’s verify this with a simulation. We draw two samples of size \(N=100\) and compute the bootstrap distribution of \(\sqrt{N}(\hat{\theta}^{b}-\hat{\theta})\) for three different datasets, comparing each to the true sampling distribution of \(\sqrt{N}(\hat{\theta}-\theta_{0})\) when \(\mu_{1}=\mu_{2}=0\).

using Random, Statistics

draw_data(μ, N; rng) = (; x1 = μ[1] .+ randn(rng, N), x2 = μ[2] .+ randn(rng, N))
max_mean(d) = max(mean(d.x1), mean(d.x2))

# bootstrap draws of the estimator, resampling each sample with replacement
function bootstrap_draws(d, B; rng)
    N = length(d.x1)
    map(1:B) do _
        i1 = rand(rng, 1:N, N)
        i2 = rand(rng, 1:N, N)
        max(mean(view(d.x1, i1)), mean(view(d.x2, i2)))
    end
end

N = 100
rng = Xoshiro(2024)
μ = [0.0, 0.0]

# true sampling distribution of √N(θ̂ - θ₀)
true_draws = [sqrt(N) * max_mean(draw_data(μ, N; rng)) for _ in 1:20_000]

pl = stephist(true_draws, normalize=:pdf, bins=60, linewidth=3, color=MCM.charcoal,
              label="True sampling distribution", xlabel="\$\\sqrt{N}(\\hat{\\theta}-\\theta)\$", ylabel="Density",
              title="Bootstrap distributions from three datasets")
for (k, col) in enumerate([MCM.teal, MCM.orange, MCM.mustard])
    d = draw_data(μ, N; rng)
    gap = round(sqrt(N) * abs(mean(d.x1) - mean(d.x2)), digits = 2)
    boot = sqrt(N) .* (bootstrap_draws(d, 5_000; rng) .- max_mean(d))
    stephist!(pl, boot, normalize=:pdf, bins=60, color=col, label="Dataset $k: \$\\sqrt{N}|\\bar{X}_1-\\bar{X}_2| = $gap\$")
end
pl

The bootstrap distributions differ from dataset to dataset, depending on how far apart the two sample means happen to be. When the realized gap is large, the bootstrap distribution looks like a standard normal centered at zero. In this case the bootstrap treats one mean as clearly larger than the other and misses the upward bias of \(\hat{\theta}\) entirely. When the gap is small, it looks more like the true distribution.

To see what this means for inference, let’s calculate the coverage of a nominal 95% percentile confidence interval, \([q^{b}_{0.025},q^{b}_{0.975}]\), as a function of the true gap between the means.

function coverage(μ, N; M = 1000, B = 499, α = 0.05, rng)
    θ₀ = maximum(μ)
    hits = 0
    for m in 1:M
        d = draw_data(μ, N; rng)
        tb = bootstrap_draws(d, B; rng)
        hits += quantile(tb, α/2) <= θ₀ <= quantile(tb, 1 - α/2)
    end
    return hits / M
end

gaps = 0:0.025:0.5
cov_pct = [coverage([0.0, g], N; rng) for g in gaps]
plot(sqrt(N) .* gaps, cov_pct, marker = :circle, label = "Percentile bootstrap",
     xlabel = "\$\\sqrt{N}(\\mu_2-\\mu_1)\$", ylabel = "Coverage", ylims = (0.8, 1.0),
     title = "Coverage of nominal 95% intervals")
hline!([0.95], color = MCM.charcoal, linestyle = :dash, label = "Nominal")

When the means are equal, the interval covers the truth only about 87% of the time. Coverage approaches its nominal level once the gap between the means is larger than about \(1/\sqrt{N}\). Notice that for any fixed gap \(\mu_{2}-\mu_{1}>0\) the bootstrap is consistent, since eventually \(N\) is large enough that \(\sqrt{N}(\mu_{2}-\mu_{1})\) is large. But in a given sample, what matters is whether the gap is large relative to the sampling noise. Near the kink, neither the normal approximation nor the bootstrap is reliable.

There are a few remedies for this kind of failure. The \(m\)-out-of-\(n\) bootstrap resamples \(m<N\) observations, with \(m\rightarrow\infty\) and \(m/N\rightarrow 0\), so that the shift term \(\sqrt{m}|\bar{X}_{1}-\bar{X}_{2}|\) vanishes (Bickel, Götze, and Zwet 1997). Fang and Santos (2019) develop a general theory of inference for parameters that are directionally (but not fully) differentiable functions of the data, which includes this example. You will try the first remedy in Exercise 16.3.

16.6 Simulation Noise and Bootstrap Standard Errors

Although it is critical to fix the seed for randomization when implementing these methods, you have to think carefully about how you then set the seed if you are using bootstrap methods for inference. If the number of simulations \(R\) is comparable to the number of observations, our theory tells us that simulation error will be a non-negligible component of the variance of the estimator. To accommodate this, you should ensure that you change the initial seed in each bootstrap trial. Even if you think simulation error is negligible compared to sampling error (i.e. \(R>>N\)), it is still good practice and costs nothing to incorporate it.

16.7 Exercises

Exercise

Exercise 16.1 Continuing from Exercise 15.1:

  1. Implement a bootstrap to compute standard errors for \((\hat{\beta},\hat{\sigma})\). Use the same bootstrap samples (resampled individuals from the PSID) that you used to construct confidence intervals for the income process parameters in Example 16.1. For each bootstrap replication \(b\), re-estimate the income process parameters \((\hat{\rho}^{b},\hat{\sigma}^{2b}_{\alpha},\hat{\sigma}^{2b}_{\eta})\) on the bootstrap sample, then re-estimate the savings model preference parameters \((\hat{\beta}^{b},\hat{\sigma}^{b})\) using those first-stage estimates. Use \(B=100\) replications.
  2. Construct 95% confidence intervals for each parameter.
  3. Explain why it is important to use the same bootstrap draws for both the income process and the savings model estimation, rather than bootstrapping each independently. What would go wrong if you used separate bootstrap samples?
  4. Which parameter is most precisely estimated? Which is least? Does this match your intuition from the identification discussion?
Exercise

Exercise 16.2 Return to the minimum distance estimation of the income process from Example 12.2. Instead of using the identity weighting matrix, implement estimation with:

  1. The diagonal weighting matrix, where each moment is weighted by the inverse of the variance of the corresponding sample moment. Use the bootstrap (resampling individuals as in Example 16.1) to estimate the variance of each sample moment.
  2. The optimal weighting matrix, which uses the full variance-covariance matrix of the sample moments. Again, estimate this variance-covariance matrix using the bootstrap.

Compare the estimates and standard errors across all three weighting schemes (identity, diagonal, optimal). How much does the choice of weighting matrix matter in practice?

Exercise

Exercise 16.3 Return to the maximum of two means from Example 16.2.

  1. Implement the \(m\)-out-of-\(n\) bootstrap: draw bootstrap samples of size \(m<N\) from each sample, and use the distribution of \(\sqrt{m}(\hat{\theta}^{b}_{m}-\hat{\theta})\) to approximate the distribution of \(\sqrt{N}(\hat{\theta}-\theta_{0})\). Use it to construct 95% confidence intervals.
  2. Calculate the coverage of your intervals as a function of the gap \(\mu_{2}-\mu_{1}\) for \(N=100\) and \(m\in\{10,25,50\}\). Compare with the coverage of the standard percentile bootstrap.
  3. Explain the trade-off involved in choosing \(m\).
  4. The income process in Example 16.1 includes a variance \(\sigma^{2}_{\alpha}\) that is constrained to be non-negative. Explain why the standard bootstrap might be unreliable if the true value of \(\sigma^{2}_{\alpha}\) were close to zero.