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
- Model
- Real RAM
- Properties
- randomizednot exactofflinerandomizediterative
- Evidence
- Proof sketchCode in 1 languages
- 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 overlapping blocks of a fixed length . 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 from a stationary process with dependence that dies out with the lag, a statistic , a block length and a number of replicates .
Output. Replicates of , whose spread estimates the sampling variability of , for example its standard error.
Blocks. Let for with , and . A moving block resample is joined and cut to its first values, with independent and uniform on . With this is the ordinary bootstrap.
The algorithm
MOVING-BLOCK-BOOTSTRAP(x_1, ..., x_n, s, l, b)- 1
k ← ⌈n/l⌉, N ← n - l + 1 - 2
for j ← 1 to b do - 3
x* ← the empty sequence - 4
for q ← 1 to k do - 5
I ← a uniform random index in {1, ..., N} - 6
append x_I, x_{I+1}, ..., x_{I+l-1} to x* - 7
cut x* to its first n values - 8
θ*_j ← s(x*) - 9
return θ*_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 values from the AR(1) model with standard normal , started in its stationary law (seed 2024), has mean . For this model the true standard error of is ; see autoregressive model. The bootstrap estimates of the standard error are:
| method | standard error of |
|---|---|
| iid bootstrap (), exact | 0.104 |
| moving blocks, , exact | 0.145 |
| moving blocks, , (seed 1) | 0.150 |
| circular blocks, , (seed 1) | 0.147 |
| stationary, , exact | 0.156 |
| stationary, , (seed 1) | 0.160 |
The iid bootstrap is far too small. For an AR(1) process with coefficient the variance of the mean is about times what independence would give, so the iid bootstrap variance is too small by the factor .
Choice of block length (measured). For 2000 such series, the ratio of the exact moving block bootstrap variance of to the true variance had this mean and root mean squared error (seed 12):
| 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 to , close to . The stationary bootstrap with gave a slightly larger RMSE at each of these lengths.
Correctness
The proof is in proofs/correctness.md. What is proved:
- When divides , the resample mean of the moving block bootstrap is the average of independent uniform draws from the block means . So its exact bootstrap mean is and its exact bootstrap variance is . The tests compare this with all block choices.
- in general: the moving blocks give less weight to the first and last observations. The circular and the stationary bootstraps are exactly centred, .
- The stationary bootstrap resample is a stationary sequence given the data, and , with circular sample autocovariances . The tests check this against all 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 and . 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 is fixed, and refer to the resampling only, , , and is the mean of the block that starts at . Lines L1 to L7 build the resample from blocks whose start indices are independent and uniform on , and line L8 evaluates 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 , then , and
Proof. When divides , line L7 removes nothing, and the resample consists of exactly whole blocks of values each. Its mean is the average of the block means. The are independent and each is uniform on the multiset , so each has mean and variance . The mean of independent copies has the same mean and of the variance.
With , , and , so the claim gives and , the iid bootstrap. Line L5 with 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). with , where is the number of blocks that contain position : . So for all data only if .
Proof. Each block mean gives weight to each of its positions, and averages block means, so position gets weight . Position lies in the block that starts at exactly when , which gives the count . For , when , or otherwise, so the weights are not all equal and some data give .
The tests use with , where and .
Claim 3 (circular blocks are centred). In the circular block bootstrap, each start is uniform on and the block wraps around, so every resampled value is uniform on the multiset . Hence .
Proof. Position inside a block that starts at a uniform holds , and a uniform index shifted modulo is uniform. Linearity of expectation gives the result, also when line L7 cuts the last block.
Claim 4 (the stationary bootstrap). Let be the indices of the stationary bootstrap: is uniform, and is uniform with probability and otherwise. Then is a stationary Markov chain with uniform marginal law, , and
with the index taken modulo .
Proof. The transition probability is . Each column of sums to , so the uniform law is stationary, and the chain starts in it. So every is uniform, , and .
For with , condition on whether a new block starts at one of the steps . With probability no new block starts, and then with uniform, so the covariance is . Otherwise, after the last new start the index is uniform and independent of , so is independent of , and the covariance is 0. Since in both cases, the two cases combine to . Then
because pairs have . This is the stated formula.
The independence step needs care: given that a new block starts at step , the index is a fresh uniform draw, independent of everything before, and the later steps up to depend only on and fresh random numbers. So is uniform and independent of .
The tests compute the exact law of by listing all index paths with their probabilities as fractions, for , and compare its mean and variance with and with the formula.
Why the iid bootstrap fails, as a computation. With , . For a stationary process with autocovariances , . The iid bootstrap keeps only the first term. For AR(1), , and , so the ratio tends to , which is for . The stationary bootstrap keeps the other terms with the weights , which tend to 1 for each fixed as . Making this into a consistency proof needs , and summable autocovariances; we do not give it here.
Cost. Lines L4 to L7 copy values, so one resample costs , and with a linear-time statistic the replicates cost time. The resample and the replicates need space.
Complexity
Each replicate copies values in blocks and evaluates , which costs for the mean, so the time is . The extra space is for one resample and for the replicates. For the mean, the exact bootstrap variances need no resampling: the moving block closed form costs with prefix sums for the block means, and the stationary bootstrap formula costs for the circular autocovariances.
Properties
- Keeps dependence inside blocks. The resample has the original joint law of up to 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 and its variance of order , so the mean squared error is smallest for of order . For one-sided and two-sided distribution functions the optimal orders are and (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 , which matters for bootstrap-t intervals and tests; centre at instead.
- The stationary bootstrap is less sensitive to 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 jump to a new uniform position, otherwise move to the next value, wrapping from to . The blocks have geometric lengths with mean . 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 positions start a block of length . Every value has the same weight, and the resample mean is exactly centred at .
- Non-overlapping blocks (Carlstein 1986). Use only the 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 consecutive values, such as a lag- autocorrelation, first form the vectors , 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 , and it works well for linear processes.
- Block subsampling. Compute the statistic on each of the blocks of length without resampling; see subsampling. It needs fewer conditions than the block bootstrap.
- Block length selection. Plug-in rules estimate the constants of the 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 against a true .
- Block length chosen by eye. Results can change a lot with . Report the rule used, and check a few lengths around it.
- Too few blocks. With close to , 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 , not , 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.
# 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
- 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)
- 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)
- D. N. Politis and J. P. Romano, A circular block-resampling procedure for stationary data, 1992, pp. 263 to 270 (the circular block bootstrap)
- 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)
- S. N. Lahiri, Resampling Methods for Dependent Data, Springer, 2003, the chapters on block bootstrap methods and their comparison (general locator)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag Q86QP6 Edit this page History Report an error Markdown