Algorithm Search⌘K

Algorithmadvanced

Block bootstrap

Also called moving block bootstrap, stationary bootstrap.

Resamples blocks of consecutive observations of a time series to keep their dependence. The stationary bootstrap of Politis and Romano uses blocks of random length.

Time
Θ(b n) worst
Space
Θ(b + n) extra
Where
b = the number of bootstrap replicates; n = the length of the series
Properties
randomizednot exactofflinerandomizediterative
Origin
Hans Künsch, Regina Liu, Kesar Singh, Dimitris Politis, Joseph Romano, 1989

The block bootstrap resamples a time series by joining blocks of consecutive observations, drawn with replacement, instead of single observations. Inside each block the original dependence is kept, so the resampled series has nearly the right short-range correlation, and the bootstrap estimates of variance and of sampling distributions stay valid for weakly dependent stationary series. The moving block bootstrap uses all n−l+1n - l + 1 overlapping blocks of a fixed length ll. The stationary bootstrap, a variant, uses blocks of random geometric length that wrap around the end of the series, which makes the resampled series stationary.

In plain words

The ordinary bootstrap shuffles single data points. For a time series this destroys the pattern that each value is close to the one before it, so the bootstrap thinks the average is much more precise than it is. The block bootstrap cuts the series into short runs of neighbouring values, such as runs of five, picks runs at random with replacement and joins them into a new series of the same length. Inside each run the pattern is kept. Only at the joins is it broken. Longer runs keep more of the pattern, but there are fewer different runs to pick from, so the answer is noisier. The block length is a balance between these two errors.

The problem

Input. A series x1,…,xnx_1, \ldots, x_n from a stationary process with dependence that dies out with the lag, a statistic ss, a block length 1≤l≤n1 \le l \le n and a number of replicates bb.

Output. Replicates θ1∗,…,θb∗\theta^*_1, \ldots, \theta^*_b of ss, whose spread estimates the sampling variability of θ^=s(x)\hat\theta = s(x), for example its standard error.

Blocks. Let Bi=(xi,…,xi+l−1)B_i = (x_i, \ldots, x_{i+l-1}) for i=1,…,Ni = 1, \ldots, N with N=n−l+1N = n - l + 1, and k=⌈n/l⌉k = \lceil n/l \rceil. A moving block resample is BI1,…,BIkB_{I_1}, \ldots, B_{I_k} joined and cut to its first nn values, with I1,…,IkI_1, \ldots, I_k independent and uniform on {1,…,N}\{1, \ldots, N\}. With l=1l = 1 this is the ordinary bootstrap.

The algorithm

  1. MOVING-BLOCK-BOOTSTRAP(x_1, ..., x_n, s, l, b)
  2. 1k ← ⌈n/l⌉, N ← n - l + 1
  3. 2for j ← 1 to b do
  4. 3x* ← the empty sequence
  5. 4for q ← 1 to k do
  6. 5I ← a uniform random index in {1, ..., N}
  7. 6append x_I, x_{I+1}, ..., x_{I+l-1} to x*
  8. 7cut x* to its first n values
  9. 8θ*_j ← s(x*)
  10. 9return θ*_1, ..., θ*_b

The standard error estimate is the standard deviation of the replicates. The implementation also has the circular and the stationary versions of lines L4 to L7 described under Variants, and closed forms for the exact bootstrap variance of the mean, which the tests compare with full enumeration.

Example

A series of n=120n = 120 values from the AR(1) model Xt=0.5 Xt−1+εtX_t = 0.5\, X_{t-1} + \varepsilon_t with standard normal εt\varepsilon_t, started in its stationary law (seed 2024), has mean xˉ=0.248\bar x = 0.248. For this model the true standard error of xˉ\bar x is 0.1820.182; see autoregressive model. The bootstrap estimates of the standard error are:

method standard error of xˉ\bar x
iid bootstrap (l=1l = 1), exact 0.104
moving blocks, l=5l = 5, exact 0.145
moving blocks, l=5l = 5, b=2000b = 2000 (seed 1) 0.150
circular blocks, l=5l = 5, b=2000b = 2000 (seed 1) 0.147
stationary, p=1/5p = 1/5, exact 0.156
stationary, p=1/5p = 1/5, b=2000b = 2000 (seed 1) 0.160

The iid bootstrap is far too small. For an AR(1) process with coefficient ϕ\phi the variance of the mean is about 1+ϕ1−ϕ\frac{1 + \phi}{1 - \phi} times what independence would give, so the iid bootstrap variance is too small by the factor 1−ϕ1+ϕ=13\frac{1 - \phi}{1 + \phi} = \frac13.

Choice of block length (measured). For 2000 such series, the ratio of the exact moving block bootstrap variance of xˉ\bar x to the true variance had this mean and root mean squared error (seed 12):

ll 1 2 4 5 8 12 20 30 40
mean ratio 0.33 0.49 0.66 0.71 0.77 0.79 0.76 0.67 0.56
RMSE 0.67 0.52 0.38 0.36 0.35 0.39 0.49 0.59 0.65

Short blocks break too much dependence (bias), and long blocks leave too few distinct blocks (variance and, for very long blocks, a downward bias from centring at the mean of few blocks). The best values are near l=5l = 5 to 88, close to n1/3=4.9n^{1/3} = 4.9. The stationary bootstrap with p=1/lp = 1/l gave a slightly larger RMSE at each of these lengths.

Correctness

The proof is in proofs/correctness.md. What is proved:

  • When ll divides nn, the resample mean of the moving block bootstrap is the average of kk independent uniform draws from the NN block means Bˉ1,…,BˉN\bar B_1, \ldots, \bar B_N. So its exact bootstrap mean is Bˉ=1N∑iBˉi\bar B = \frac1N\sum_i \bar B_i and its exact bootstrap variance is 1k⋅1N∑i(Bˉi−Bˉ)2\frac{1}{k} \cdot \frac{1}{N}\sum_i (\bar B_i - \bar B)^2. The tests compare this with all NkN^k block choices.
  • Bˉ≠xˉ\bar B \ne \bar x in general: the moving blocks give less weight to the first and last l−1l - 1 observations. The circular and the stationary bootstraps are exactly centred, E∗xˉ∗=xˉE^*\bar x^* = \bar x.
  • The stationary bootstrap resample is a stationary sequence given the data, and Var∗(xˉ∗)=c^(0)n+2n∑i=1n−1(1−in)(1−p)ic^(i)\mathrm{Var}^*(\bar x^*) = \frac{\hat c(0)}{n} + \frac{2}{n}\sum_{i=1}^{n-1}\bigl(1 - \frac in\bigr)(1 - p)^i \hat c(i), with circular sample autocovariances c^(i)\hat c(i). The tests check this against all nnn^n index paths.

What is not proved here: consistency. Künsch (1989) proved that, under mixing and moment conditions, the block bootstrap variance of a smooth function of means is consistent when l→∞l \to \infty and l/n→0l/n \to 0. The tables above are measurements.

Proof: Exact bootstrap moments of the block bootstrap meanfull

We use the pseudocode and the notation of the page. The series x1,…,xnx_1, \ldots, x_n is fixed, P∗P^* and E∗E^* refer to the resampling only, N=n−l+1N = n - l + 1, k=⌈n/l⌉k = \lceil n/l \rceil, and Bˉi=1l∑t=ii+l−1xt\bar B_i = \frac1l\sum_{t=i}^{i+l-1} x_t is the mean of the block that starts at ii. Lines L1 to L7 build the resample from kk blocks whose start indices are independent and uniform on {1,…,N}\{1, \ldots, N\}, and line L8 evaluates ss on it. So the algorithm samples from the moving block bootstrap law, and it remains to compute that law for the mean.

This file proves exact identities given the data. It does not prove that the block bootstrap is consistent; that needs conditions on the process (Künsch 1989), and the page measures it.

Claim 1 (moving blocks, l divides n). If n=kln = k l, then xˉ∗=1k∑q=1kBˉIq\bar x^* = \frac1k\sum_{q=1}^k \bar B_{I_q}, and

E∗xˉ∗=Bˉ:=1N∑i=1NBˉi,Var∗(xˉ∗)=1k⋅1N∑i=1N(Bˉi−Bˉ)2.E^*\bar x^* = \bar B := \frac1N\sum_{i=1}^N \bar B_i, \qquad \mathrm{Var}^*(\bar x^*) = \frac1k \cdot \frac1N\sum_{i=1}^N (\bar B_i - \bar B)^2.

Proof. When ll divides nn, line L7 removes nothing, and the resample consists of exactly kk whole blocks of ll values each. Its mean is the average of the kk block means. The BˉIq\bar B_{I_q} are independent and each is uniform on the multiset {Bˉ1,…,BˉN}\{\bar B_1, \ldots, \bar B_N\}, so each has mean Bˉ\bar B and variance 1N∑i(Bˉi−Bˉ)2\frac1N\sum_i(\bar B_i - \bar B)^2. The mean of kk independent copies has the same mean and 1/k1/k of the variance. □\square

With l=1l = 1, N=nN = n, k=nk = n and Bˉi=xi\bar B_i = x_i, so the claim gives E∗xˉ∗=xˉE^*\bar x^* = \bar x and Var∗(xˉ∗)=1n2∑i(xi−xˉ)2\mathrm{Var}^*(\bar x^*) = \frac{1}{n^2}\sum_i(x_i - \bar x)^2, the iid bootstrap. Line L5 with l=1l = 1 draws exactly the indices of the iid bootstrap, and the tests check that both give the same resample from the same seed.

Claim 2 (end effects). Bˉ=∑t=1nwtxt\bar B = \sum_{t=1}^n w_t x_t with wt=mtNlw_t = \frac{m_t}{N l}, where mtm_t is the number of blocks that contain position tt: mt=min⁡(t,l,N,n−t+1)m_t = \min(t, l, N, n - t + 1). So Bˉ=xˉ\bar B = \bar x for all data only if l=1l = 1.

Proof. Each block mean gives weight 1/l1/l to each of its ll positions, and Bˉ\bar B averages NN block means, so position tt gets weight mt/(Nl)m_t/(N l). Position tt lies in the block that starts at ii exactly when max⁡(1,t−l+1)≤i≤min⁡(t,N)\max(1, t - l + 1) \le i \le \min(t, N), which gives the count mtm_t. For 1<l<n1 < l < n, m1=1<l=mlm_1 = 1 < l = m_l when l≤Nl \le N, or m1=1<N=mlm_1 = 1 < N = m_l otherwise, so the weights are not all equal and some data give Bˉ≠xˉ\bar B \ne \bar x. □\square

The tests use x=(10,0,0,0,0,0)x = (10, 0, 0, 0, 0, 0) with l=2l = 2, where Bˉ=1\bar B = 1 and xˉ=5/3\bar x = 5/3.

Claim 3 (circular blocks are centred). In the circular block bootstrap, each start is uniform on {1,…,n}\{1, \ldots, n\} and the block wraps around, so every resampled value xt∗x^*_t is uniform on the multiset {x1,…,xn}\{x_1, \ldots, x_n\}. Hence E∗xˉ∗=xˉE^*\bar x^* = \bar x.

Proof. Position jj inside a block that starts at a uniform II holds x((I+j−2) mod n)+1x_{((I + j - 2) \bmod n) + 1}, and a uniform index shifted modulo nn is uniform. Linearity of expectation gives the result, also when line L7 cuts the last block. □\square

Claim 4 (the stationary bootstrap). Let J1,…,JnJ_1, \ldots, J_n be the indices of the stationary bootstrap: J1J_1 is uniform, and Jt+1J_{t+1} is uniform with probability pp and Jt+1 mod nJ_t + 1 \bmod n otherwise. Then (Jt)(J_t) is a stationary Markov chain with uniform marginal law, E∗xˉ∗=xˉE^*\bar x^* = \bar x, and

Var∗(xˉ∗)=c^(0)n+2n∑i=1n−1(1−in)(1−p)i c^(i),c^(i)=1n∑j=1n(xj−xˉ)(xj+i−xˉ),\mathrm{Var}^*(\bar x^*) = \frac{\hat c(0)}{n} + \frac{2}{n}\sum_{i=1}^{n-1}\Bigl(1 - \frac in\Bigr)(1 - p)^i\, \hat c(i), \qquad \hat c(i) = \frac1n\sum_{j=1}^n (x_j - \bar x)(x_{j+i} - \bar x),

with the index j+ij + i taken modulo nn.

Proof. The transition probability is P(a,c)=p/n+(1−p) [c=a+1 mod n]P(a, c) = p/n + (1 - p)\,[c = a + 1 \bmod n]. Each column of PP sums to p+(1−p)=1p + (1 - p) = 1, so the uniform law is stationary, and the chain starts in it. So every JtJ_t is uniform, E∗xt∗=xˉE^* x^*_t = \bar x, and Var∗xt∗=c^(0)\mathrm{Var}^* x^*_t = \hat c(0).

For s<ts < t with t−s=it - s = i, condition on whether a new block starts at one of the steps s+1,…,ts + 1, \ldots, t. With probability (1−p)i(1 - p)^i no new block starts, and then Jt=Js+i mod nJ_t = J_s + i \bmod n with JsJ_s uniform, so the covariance is c^(i)\hat c(i). Otherwise, after the last new start the index is uniform and independent of JsJ_s, so xt∗x^*_t is independent of xs∗x^*_s, and the covariance is 0. Since E∗xt∗=xˉE^* x^*_t = \bar x in both cases, the two cases combine to Cov∗(xs∗,xt∗)=(1−p)ic^(i)\mathrm{Cov}^*(x^*_s, x^*_t) = (1 - p)^i \hat c(i). Then

Var∗(xˉ∗)=1n2(n c^(0)+2∑i=1n−1(n−i)(1−p)ic^(i)),\mathrm{Var}^*(\bar x^*) = \frac{1}{n^2}\Bigl(n\,\hat c(0) + 2\sum_{i=1}^{n-1}(n - i)(1 - p)^i \hat c(i)\Bigr),

because n−in - i pairs (s,t)(s, t) have t−s=it - s = i. This is the stated formula. □\square

The independence step needs care: given that a new block starts at step r≤tr \le t, the index JrJ_r is a fresh uniform draw, independent of everything before, and the later steps up to tt depend only on JrJ_r and fresh random numbers. So JtJ_t is uniform and independent of JsJ_s.

The tests compute the exact law of xˉ∗\bar x^* by listing all nnn^n index paths with their probabilities as fractions, for n≤5n \le 5, and compare its mean and variance with xˉ\bar x and with the formula.

Why the iid bootstrap fails, as a computation. With l=1l = 1, Var∗(xˉ∗)=c^(0)/n\mathrm{Var}^*(\bar x^*) = \hat c(0)/n. For a stationary process with autocovariances γ(i)\gamma(i), Var(Xˉ)=γ(0)n+2n∑i=1n−1(1−in)γ(i)\mathrm{Var}(\bar X) = \frac{\gamma(0)}{n} + \frac{2}{n}\sum_{i=1}^{n-1}(1 - \frac in)\gamma(i). The iid bootstrap keeps only the first term. For AR(1), γ(i)=ϕiγ(0)\gamma(i) = \phi^i\gamma(0), and nVar(Xˉ)→γ(0)1+ϕ1−ϕn\mathrm{Var}(\bar X) \to \gamma(0)\frac{1 + \phi}{1 - \phi}, so the ratio tends to 1−ϕ1+ϕ\frac{1 - \phi}{1 + \phi}, which is 13\frac13 for ϕ=0.5\phi = 0.5. The stationary bootstrap keeps the other terms with the weights (1−p)i(1 - p)^i, which tend to 1 for each fixed ii as p→0p \to 0. Making this into a consistency proof needs p→0p \to 0, np→∞n p \to \infty and summable autocovariances; we do not give it here.

Cost. Lines L4 to L7 copy kl<n+lk l < n + l values, so one resample costs Θ(n)\Theta(n), and with a linear-time statistic the bb replicates cost Θ(bn)\Theta(b n) time. The resample and the replicates need Θ(n+b)\Theta(n + b) space.

Complexity

Each replicate copies nn values in kk blocks and evaluates ss, which costs Θ(n)\Theta(n) for the mean, so the time is Θ(bn)\Theta(b n). The extra space is Θ(n)\Theta(n) for one resample and Θ(b)\Theta(b) for the replicates. For the mean, the exact bootstrap variances need no resampling: the moving block closed form costs Θ(n)\Theta(n) with prefix sums for the block means, and the stationary bootstrap formula costs Θ(n2)\Theta(n^2) for the nn circular autocovariances.

Properties

  • Keeps dependence inside blocks. The resample has the original joint law of up to ll consecutive values within each block and independence between blocks.
  • Block length trade-off. For the variance of the mean, the bias of the block bootstrap estimate is of order 1/l1/l and its variance of order l/nl/n, so the mean squared error is smallest for ll of order n1/3n^{1/3}. For one-sided and two-sided distribution functions the optimal orders are n1/4n^{1/4} and n1/5n^{1/5} (Hall, Horowitz and Jing 1995). The constants depend on the autocorrelation and must be estimated.
  • End effects. The moving block bootstrap is not centred at xˉ\bar x, which matters for bootstrap-t intervals and tests; centre at Bˉ\bar B instead.
  • The stationary bootstrap is less sensitive to ll than fixed blocks, but for the same mean block length its mean squared error is somewhat larger.
  • Long-range dependence and nonstationarity are outside the basic theory: for long-memory processes the block bootstrap of the mean can fail, and trends must be removed first.

Variants and improvements

  • Stationary bootstrap (Politis and Romano 1994). Start at a uniform random position. At each step, with probability pp jump to a new uniform position, otherwise move to the next value, wrapping from xnx_n to x1x_1. The blocks have geometric lengths with mean 1/p1/p. Given the data, the index sequence is a Markov chain started in its uniform stationary law, so the resampled series is stationary, which gives the method its name, and it is exactly centred.
  • Circular block bootstrap (Politis and Romano 1992). Wrap the series into a circle so that all nn positions start a block of length ll. Every value has the same weight, and the resample mean is exactly centred at xˉ\bar x.
  • Non-overlapping blocks (Carlstein 1986). Use only the n/ln/l disjoint blocks. It is simpler, but its variance estimate is less efficient than that of overlapping blocks.
  • Blocks of blocks. For a statistic that depends on the joint law of mm consecutive values, such as a lag-mm autocorrelation, first form the vectors (xt,…,xt+m−1)(x_t, \ldots, x_{t+m-1}), then resample blocks of these vectors (Künsch 1989).
  • Sieve bootstrap. Fit an autoregressive model of growing order, resample its residuals and generate new series from the fitted model. It is a parametric bootstrap with a model that grows with nn, and it works well for linear processes.
  • Block subsampling. Compute the statistic on each of the NN blocks of length mm without resampling; see subsampling. It needs fewer conditions than the block bootstrap.
  • Block length selection. Plug-in rules estimate the constants of the n1/3n^{1/3} rule from the autocorrelations of the data.

When to use it

Use it for standard errors and confidence intervals of statistics of a stationary, weakly dependent series: means, autocorrelations, quantiles, regression coefficients with dependent errors, and the output of a Markov chain Monte Carlo run, where the effective sample size and MCMC autocorrelation pages give model-based alternatives. Use the iid bootstrap only after checking that the autocorrelation is negligible. If a good parametric time series model is available, the sieve or model-based bootstrap is often more accurate.

Pitfalls

  • Ignoring the dependence. With positive autocorrelation the iid bootstrap is overconfident; in the example its standard error is 0.1040.104 against a true 0.1820.182.
  • Block length chosen by eye. Results can change a lot with ll. Report the rule used, and check a few lengths around it.
  • Too few blocks. With ll close to nn, there are few distinct blocks, and the bootstrap distribution is very discrete and centred badly.
  • Centring in the moving block bootstrap. Bootstrap-t statistics should use Bˉ\bar B, not xˉ\bar x, as the centre, or the circular version.
  • Trends and seasonality. Blocks of a nonstationary series mix different regimes. Remove the trend and the seasonal pattern first, or resample residuals of a model.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

block_bootstrap.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/block-bootstrap/. The authors are listed in prov/Q86QP6.jsonl.

import math
import random
from typing import Callable, Sequence

Statistic = Callable[[Sequence[float]], float]


def moving_block_resample(x: Sequence[float], l: int, rng: random.Random) -> list:
    """One moving block bootstrap resample of Kunsch (1989): k = ceil(n/l) blocks of l
    consecutive values, with start points drawn uniformly from the N = n - l + 1 possible ones,
    joined and cut to length n."""
    n = len(x)
    if not 1 <= l <= n:
        raise ValueError("need 1 <= l <= n")
    k = -(-n // l)  # @line L1
    big_n = n - l + 1
    out = []  # @line L3
    for _ in range(k):  # @line L4
        start = rng.randrange(big_n)  # @line L5
        out.extend(x[start : start + l])  # @line L6
    return out[:n]  # @line L7


def circular_block_resample(x: Sequence[float], l: int, rng: random.Random) -> list:
    """Politis and Romano (1992): blocks may wrap around the end, so all n start points are used."""
    n = len(x)
    if not 1 <= l <= n:
        raise ValueError("need 1 <= l <= n")
    out = []
    for _ in range(-(-n // l)):
        start = rng.randrange(n)
        out.extend(x[(start + t) % n] for t in range(l))
    return out[:n]


def stationary_resample(x: Sequence[float], p: float, rng: random.Random) -> list:
    """Politis and Romano (1994): blocks of geometric length with mean 1/p, which wrap around.
    Each step starts a new block with probability p, else it continues the current one."""
    n = len(x)
    if not 0 < p <= 1:
        raise ValueError("need 0 < p <= 1")
    i = rng.randrange(n)
    out = [x[i]]
    while len(out) < n:
        i = rng.randrange(n) if rng.random() < p else (i + 1) % n
        out.append(x[i])
    return out


def block_bootstrap(
    x: Sequence[float],
    statistic: Statistic,
    b: int,
    rng: random.Random,
    l: int | None = None,
    method: str = "moving",
    p: float | None = None,
) -> list:
    """b block bootstrap replicates of the statistic. method is 'moving', 'circular' or 'stationary'."""
    reps = []
    for _ in range(b):  # @line L2
        if method == "moving":
            xs = moving_block_resample(x, l, rng)
        elif method == "circular":
            xs = circular_block_resample(x, l, rng)
        elif method == "stationary":
            xs = stationary_resample(x, p if p is not None else 1.0 / l, rng)
        else:
            raise ValueError("unknown method")
        reps.append(statistic(xs))  # @line L8
    return reps  # @line L9


def standard_deviation(values: Sequence[float]) -> float:
    m = math.fsum(values) / len(values)
    return math.sqrt(math.fsum((v - m) ** 2 for v in values) / (len(values) - 1))


def mbb_mean_moments(x: Sequence, l: int) -> tuple:
    """The exact bootstrap mean and variance of the resample mean under the moving block
    bootstrap, when l divides n: the resample mean is the average of k = n/l block means drawn
    independently and uniformly from the N = n - l + 1 block means."""
    n = len(x)
    if n % l:
        raise ValueError("this closed form needs l to divide n")
    k, big_n = n // l, n - l + 1
    blocks = [sum(x[j : j + l]) / l for j in range(big_n)]
    centre = sum(blocks) / big_n
    return centre, sum((v - centre) ** 2 for v in blocks) / (big_n * k)


def circular_autocovariance(x: Sequence, lag: int):
    n = len(x)
    m = sum(x) / n
    return sum((x[j] - m) * (x[(j + lag) % n] - m) for j in range(n)) / n


def stationary_mean_variance(x: Sequence, p) -> object:
    """The exact bootstrap variance of the resample mean under the stationary bootstrap
    (Politis and Romano 1994): c(0)/n + (2/n) sum_{i=1}^{n-1} (1 - i/n) (1 - p)^i c(i),
    with the circular autocovariances c(i)."""
    n = len(x)
    total = circular_autocovariance(x, 0) / n
    for i in range(1, n):
        total += 2 * (n - i) * (1 - p) ** i * circular_autocovariance(x, i) / (n * n)
    return total
test_block_bootstrap.py 152 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/block-bootstrap/. The authors are listed in prov/Q86QP6.jsonl.

import itertools
import math
import random
from fractions import Fraction

import pytest

from block_bootstrap import (
    block_bootstrap,
    circular_block_resample,
    mbb_mean_moments,
    moving_block_resample,
    standard_deviation,
    stationary_mean_variance,
    stationary_resample,
)


def fr_mean(xs):
    return sum(xs, Fraction(0)) / len(xs)


def law_moments(outcomes):
    """Mean and variance of a finite law given as (value, probability) pairs."""
    m = sum(p * v for v, p in outcomes)
    return m, sum(p * (v - m) ** 2 for v, p in outcomes)


def random_series(rng, n):
    return [Fraction(rng.randint(-20, 20), rng.randint(1, 4)) for _ in range(n)]


def test_moving_block_variance_matches_all_block_choices():
    rng = random.Random(1)
    for n, l in ((6, 1), (6, 2), (6, 3), (8, 2), (8, 4), (9, 3)):
        x = random_series(rng, n)
        k, big_n = n // l, n - l + 1
        w = Fraction(1, big_n**k)
        outcomes = []
        for starts in itertools.product(range(big_n), repeat=k):
            xs = [x[s + t] for s in starts for t in range(l)]
            outcomes.append((fr_mean(xs), w))
        assert law_moments(outcomes) == mbb_mean_moments(x, l)


def test_block_length_one_is_the_iid_bootstrap():
    x = [3.0, 1.0, 4.0, 1.0, 5.0, 9.0, 2.0, 6.0]
    a = moving_block_resample(x, 1, random.Random(7))
    g = random.Random(7)
    assert a == [x[g.randrange(8)] for _ in range(8)]
    xf = [Fraction(v) for v in x]
    m = fr_mean(xf)
    assert mbb_mean_moments(xf, 1) == (m, sum((v - m) ** 2 for v in xf) / 64)


def test_moving_blocks_underweight_the_ends():
    x = [Fraction(v) for v in (10, 0, 0, 0, 0, 0)]
    centre, _ = mbb_mean_moments(x, 2)
    assert centre == Fraction(1, 1) and fr_mean(x) == Fraction(5, 3)


def test_circular_block_bootstrap_is_centred_exactly():
    rng = random.Random(2)
    n, l = 6, 2
    x = random_series(rng, n)
    k = n // l
    outcomes = []
    for starts in itertools.product(range(n), repeat=k):
        xs = [x[(s + t) % n] for s in starts for t in range(l)]
        outcomes.append((fr_mean(xs), Fraction(1, n**k)))
    assert law_moments(outcomes)[0] == fr_mean(x)


def stationary_law(x, p):
    """The exact law of the stationary bootstrap mean, by listing all n^n index paths."""
    n = len(x)
    outcomes = []
    for path in itertools.product(range(n), repeat=n):
        prob = Fraction(1, n)
        for a, b in zip(path, path[1:]):
            prob *= p / n + (1 - p) * (b == (a + 1) % n)
        if prob:
            outcomes.append((fr_mean([x[i] for i in path]), prob))
    return outcomes


def test_stationary_bootstrap_mean_and_variance_exact():
    rng = random.Random(3)
    for n, p in ((3, Fraction(1, 2)), (4, Fraction(1, 3)), (5, Fraction(1, 4)), (5, Fraction(1))):
        x = random_series(rng, n)
        law = stationary_law(x, p)
        assert sum(q for _, q in law) == 1
        mean, var = law_moments(law)
        assert mean == fr_mean(x)
        assert var == stationary_mean_variance(x, p)


def test_resample_shapes():
    rng = random.Random(4)
    x = list(range(20))
    for _ in range(50):
        xs = moving_block_resample(x, 6, rng)
        assert len(xs) == 20
        for j in range(0, 18, 6):
            assert xs[j : j + 6] == list(range(xs[j], xs[j] + 6))
        assert len(circular_block_resample(x, 6, rng)) == 20
        assert len(stationary_resample(x, 0.2, rng)) == 20
    with pytest.raises(ValueError):
        moving_block_resample(x, 0, rng)
    with pytest.raises(ValueError):
        stationary_resample(x, 0.0, rng)


def test_monte_carlo_matches_the_exact_variance():
    rng = random.Random(5)
    x = [rng.gauss(0.0, 1.0) for _ in range(24)]
    reps = block_bootstrap(x, lambda v: math.fsum(v) / len(v), 4000, random.Random(6), l=4)
    _, exact = mbb_mean_moments(x, 4)
    assert abs(standard_deviation(reps) ** 2 / exact - 1) < 0.1


def ar1(rng, n, phi):
    x = [rng.gauss(0.0, 1.0) / math.sqrt(1 - phi * phi)]
    for _ in range(n - 1):
        x.append(phi * x[-1] + rng.gauss(0.0, 1.0))
    return x


def ar1_mean_variance(n, phi):
    g = [phi**h / (1 - phi * phi) for h in range(n)]
    return (g[0] + 2 * sum((1 - h / n) * g[h] for h in range(1, n))) / n


def test_dependence_measured_on_ar1():
    """Measured, not proved: for AR(1) with phi = 0.5 the iid bootstrap variance of the mean is
    about (1 - phi)/(1 + phi) = 1/3 of the truth; blocks of length near n^(1/3) recover most of it."""
    rng = random.Random(8)
    n, phi, r = 125, 0.5, 300
    truth = ar1_mean_variance(n, phi)
    iid, mbb, sb = [], [], []
    for _ in range(r):
        x = ar1(rng, n, phi)
        m = math.fsum(x) / n
        iid.append(math.fsum((v - m) ** 2 for v in x) / n / n / truth)
        mbb.append(mbb_mean_moments(x[:120], 5)[1] / ar1_mean_variance(120, phi))
        sb.append(stationary_mean_variance(x, 0.2) / truth)
    assert abs(math.fsum(iid) / r - 1 / 3) < 0.06
    assert math.fsum(mbb) / r > 0.65
    assert math.fsum(sb) / r > 0.65

History

Edward Carlstein (1986) used non-overlapping blocks to estimate the variance of a statistic of a time series. Hans Künsch (1989) introduced the moving block bootstrap with overlapping blocks, together with a blockwise jackknife, and proved its consistency; Regina Liu and Kesar Singh developed the same method independently, published in 1992. Dimitris Politis and Joseph Romano proposed the circular block bootstrap in 1992 and the stationary bootstrap in 1994, to remove the end effects and to make the resampled series stationary. Peter Hall, Joel Horowitz and Bing-Yi Jing (1995) derived the optimal orders of the block length, and S. N. Lahiri's 2003 book collected the theory.

References

  1. Hans R. Künsch, The jackknife and the bootstrap for general stationary observations, The Annals of Statistics 17(3), 1989, pp. 1217 to 1241 (the moving block bootstrap and the blockwise jackknife, consistency for smooth functions of the mean)
  2. Dimitris N. Politis and Joseph P. Romano, The stationary bootstrap, Journal of the American Statistical Association 89(428), 1994, pp. 1303 to 1313 (blocks of geometric length that wrap around, the stationarity of the resampled series and the variance of the resample mean)
  3. D. N. Politis and J. P. Romano, A circular block-resampling procedure for stationary data, 1992, pp. 263 to 270 (the circular block bootstrap)
  4. Peter Hall, Joel L. Horowitz and Bing-Yi Jing, On blocking rules for the bootstrap with dependent data, Biometrika 82(3), 1995, pp. 561 to 574 (optimal block lengths of order n^(1/3) for variance and bias, n^(1/4) and n^(1/5) for distribution functions)
  5. S. N. Lahiri, Resampling Methods for Dependent Data, Springer, 2003, the chapters on block bootstrap methods and their comparison (general locator)
  6. A. C. Davison and D. V. Hinkley, Bootstrap Methods and their Application, Cambridge University Press, 1997, Chapter 8 (complex dependence, block resampling and the choice of block length)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example