block_bootstrap_ci(series, *, statistic: Callable = mean, block_size: int | None = None, n_boot: int = 2000, alpha: float = 0.05, seed: int = 42) -> Series
Moving-block bootstrap confidence interval for a statistic of a dependent series.
Resamples contiguous blocks (not individual points) so the within-block
autocorrelation is preserved, the way to bootstrap a time series. The default
block size is n**(1/3) (the standard rate). Seeded, hence reproducible.
Returns:
| Type |
Description |
Series
|
{estimate, ci_lo, ci_hi} at the central 1 - alpha level.
|
References
Lahiri (2003). Resampling Methods for Dependent Data. Springer.
See Also
effective_sample_size : Autocorrelation-adjusted sample size.
flag_rate_ci : Cluster bootstrap on audit flag rates.
Examples:
>>> import pandas as pd
>>> s = pd.Series([1.0, 2.0, 3.0, 4.0, 5.0] * 20)
>>> round(float(block_bootstrap_ci(s, seed=1)["estimate"]), 1)
3.0
Source code in src/gbfs_toolkit/analytics/resampling.py
| def block_bootstrap_ci(
series,
*,
statistic: Callable = np.mean,
block_size: int | None = None,
n_boot: int = 2000,
alpha: float = 0.05,
seed: int = 42,
) -> pd.Series:
"""Moving-block bootstrap confidence interval for a statistic of a dependent series.
Resamples contiguous blocks (not individual points) so the within-block
autocorrelation is preserved, the way to bootstrap a time series. The default
block size is ``n**(1/3)`` (the standard rate). Seeded, hence reproducible.
Returns
-------
pandas.Series
``{estimate, ci_lo, ci_hi}`` at the central ``1 - alpha`` level.
References
----------
Lahiri (2003). *Resampling Methods for Dependent Data*. Springer.
See Also
--------
[`effective_sample_size`][gbfs_toolkit.effective_sample_size] : Autocorrelation-adjusted sample size.
[`flag_rate_ci`][gbfs_toolkit.flag_rate_ci] : Cluster bootstrap on audit flag rates.
Examples
--------
>>> import pandas as pd
>>> s = pd.Series([1.0, 2.0, 3.0, 4.0, 5.0] * 20)
>>> round(float(block_bootstrap_ci(s, seed=1)["estimate"]), 1)
3.0
"""
x = np.asarray(series, dtype="float64")
x = x[np.isfinite(x)]
n = x.size
if n == 0:
return pd.Series({"estimate": float("nan"), "ci_lo": float("nan"), "ci_hi": float("nan")})
if block_size is None:
block_size = max(1, int(round(n ** (1 / 3))))
block_size = min(block_size, n)
n_blocks = int(np.ceil(n / block_size))
starts_max = n - block_size + 1
rng = np.random.default_rng(seed)
boots = np.empty(n_boot)
for b in range(n_boot):
starts = rng.integers(0, starts_max, size=n_blocks)
sample = np.concatenate([x[s : s + block_size] for s in starts])[:n]
boots[b] = statistic(sample)
lo, hi = np.percentile(boots, [100 * alpha / 2, 100 * (1 - alpha / 2)])
return pd.Series({"estimate": float(statistic(x)), "ci_lo": float(lo), "ci_hi": float(hi)})
|