Skip to main content

A Python package to generate bootstrapped time series

Project description

All Contributors

Generate bootstrapped samples from time-series data. The full documentation is available here.


Markdown Python pytest actions

preprint pypi-version pypi-python-version Downloads github-license Build Status codecov DOI Launch tutorials on Binder Last Commit Issues Pull Requests Tag Ask DeepWiki Context7

📒 Table of Contents

  1. 🚀 Getting Started
  2. ⚡ Performance
  3. 🧩 Modules
  4. 🗺 Roadmap
  5. 🤝 Contributing
  6. 📄 License
  7. 📍 Time Series Bootstrapping Methods intro
  8. 👏 Contributors

🚀 Getting Started

🎮 Using tsbootstrap

tsbootstrap exposes one typed entry point, bootstrap, configured with a method specification. The same call works for every method.

import numpy as np
from tsbootstrap import bootstrap, MovingBlock

x = np.random.default_rng(0).standard_normal(200)

result = bootstrap(x, method=MovingBlock(block_length="auto"), n_bootstraps=999, random_state=0)

samples = result.values()      # (n_bootstraps, n) resampled series
oob = result.get_oob_mask()    # (n_bootstraps, n) out-of-bag mask

Choose a method spec for the structure you need (block lengths default to the automatic Politis-White selection):

from tsbootstrap import StationaryBlock, ResidualBootstrap, SieveAR, AR, ARIMA, diagnose

bootstrap(x, method=StationaryBlock(avg_block_length="auto"))

# recursive model-based bootstraps (need the model extra: uv add "tsbootstrap[models]")
bootstrap(x, method=ResidualBootstrap(model=AR(order=2)))
bootstrap(x, method=ResidualBootstrap(model=ARIMA(order=(1, 1, 1))))
bootstrap(x, method=SieveAR())

# not sure which fits? ask:
print(diagnose(x).recommended_methods)

Inputs can be NumPy arrays, lists, or pandas / Polars DataFrames and Series. The result is a BootstrapResult carrying the samples, provenance metadata, and out-of-bag / in-bag primitives. For the sktime ecosystem, the same methods are also available as estimator classes (MovingBlockBootstrap, ARResidualBootstrap, SieveBootstrap, and the rest) under tsbootstrap.adapters.

Uncertainty quantification

The uq layer turns resampled series into prediction intervals. forecast_intervals gives forward forecast bands for an AR model; EnbPIEnsemble produces out-of-bag prediction intervals for an sklearn-style regressor, with calibrators for stationary, volatility-clustered, and drifting data (static, sliding window, and the adaptive ACI and NexCP schemes); and bootstrap_reduce streams a per-replicate statistic so calibration scales to large replicate counts without holding every path in memory.

from tsbootstrap import AR, forecast_intervals

lower, upper, median = forecast_intervals(x, model=AR(order=2), horizon=12, alpha=0.1)

The conformal pieces (EnbPIEnsemble and the calibrators) need the uq extra (scikit-learn). The interactive tutorial gallery works through every method on real and synthetic data, including a "which bootstrap should I use?" decision guide.

MCP server

tsbootstrap ships a read-only Model Context Protocol server so an MCP client (an LLM agent, an IDE) can diagnose a short series and compute a bootstrap confidence interval without writing any Python. Run it with no install step:

uvx --from "tsbootstrap[mcp]" tsbootstrap-mcp

It speaks the stdio transport and exposes exactly two read-only tools:

  • diagnose_series: serial-dependence and stationarity diagnostics, a recommended Politis-White block length, and the bootstrap methods the server supports for the series.
  • bootstrap_confidence_interval: a percentile confidence interval for the mean, median, std, or variance, using an i.i.d. or block bootstrap.

Both tools accept at most 500 observations and run at most 500 replicates. For larger series, model-based methods, or the uncertainty layer, use the library directly in a local script.

📦 Installation

Requires Python 3.10 or higher.

# with uv (recommended):
uv add tsbootstrap                   # core: i.i.d. and block methods
uv add "tsbootstrap[models]"         # adds AR / ARIMA / VAR / sieve (statsmodels)

# with pip:
pip install tsbootstrap
pip install "tsbootstrap[models]"

The model-based methods import statsmodels lazily and raise a clear install hint if the models extra is missing.

⚡ Performance

tsbootstrap 0.3.0: speedup over arch and peak-memory reduction

Left: speedup of the compiled reduce path over the arch library on the four overlapping methods. Right: peak memory before and after on the two headline reduce workloads (baseline = materialize every path, then reduce). Regenerate with python benchmarks/plot_launch.py.

tsbootstrap ships an optional compiled backend (backend="compiled", via the [accel] extra) that is faster than the arch library on every overlapping resampling method. The table below is the speedup of the streaming reduce path over arch.apply on an 8-core CPU (higher is better).

Method n=200, B=999 n=200, B=10000 n=2000, B=999 n=2000, B=10000
IID 1.3x 1.3x 1.8x 1.8x
MovingBlock 1.6x 1.6x 1.9x 1.8x
CircularBlock 1.7x 1.7x 2.4x 2.4x
StationaryBlock 1.6x 1.6x 2.5x 2.7x

The compiled reduce fuses index build, gather, and reduction into one pass, so peak memory stays flat in the number of replicates: a multivariate VAR residual bootstrap that would materialize a 480 MB tensor needs about 1.4 MB, and a 1000-series panel uses about 8 MB instead of 1.6 GB. The multivariate and ragged-panel reduce paths have no equivalent in arch. Full methodology, single-threaded numbers, and the reproduction script are in benchmarks/README.md.

# install the compiled backend
uv add "tsbootstrap[accel]"
# or
pip install "tsbootstrap[accel]"

🧩 Modules

Package layout:

Area Module(s) Role
Public API api.py, methods.py, results.py, errors.py, diagnostics.py the bootstrap() entry point, typed method specs, structured results, error taxonomy, and diagnose()
Infrastructure rng.py, validation.py, dispatch.py, metadata.py deterministic RNG contract, input coercion (incl. the narwhals DataFrame boundary), spec to executor dispatch, method metadata
Block methods block/ vectorized index kernels, true Politis-Romano stationary, energy-normalized tapering, PWSD block length, OOB primitives
Model methods model/, engines/ model fitting, stability guards, and recursive AR/ARMA/VAR simulation
Uncertainty quantification uq/ EnbPI prediction intervals, the static / sliding-window / ACI / NexCP calibrators, and AR forecast intervals
Ecosystem adapters/ skbase / sktime estimator classes over the functional core

🗺 Roadmap

The full, living roadmap is issue #181. Highlights:

Near term (v0.2.x):

  • Out-of-sample forecast intervals for ARIMA and VAR (v0.2.0 ships AR-only).
  • The tutorial gallery and getting-started notebook (#46).
  • Python 3.14, once statsmodels publishes a 3.14 wheel (#202).

Candidate methods (good first issues):

  • Generalized block (#104), local block (#105), and frequency-domain (#107) bootstraps.
  • Wild and dependent-wild bootstraps, and a GARCH / volatility residual bootstrap.

Distributed execution (Dask / Spark / Ray), an async layer, and a string-keyed factory were considered and deliberately left out. The library is a CPU-bound, single-process toolkit.

🤝 Contributing

See our good first issues for getting started.

Developer setup

  1. Fork the tsbootstrap repository

  2. Clone the fork to local:

git clone https://github.com/astrogilda/tsbootstrap
  1. In the local repository root, sync the locked development environment with uv:
uv sync --extra dev
  1. uv creates an isolated virtual environment from uv.lock and editable-installs the package, so changes to the package are reflected in your environment automatically. Run tools through the environment with uv run (for example uv run pytest).

  2. Install the pre-commit hooks:

uv run pre-commit install

The hooks run ruff, formatting, and the other code-quality checks on each commit.

Verifying the Installation

Verify the installation:

python -c "import tsbootstrap; print(tsbootstrap.__version__)"

This prints the installed version.

Contribution workflow

  1. Create a new branch with a descriptive name (e.g., new-feature-branch or bugfix-issue-123).
git checkout -b new-feature-branch
  1. Make changes to the project's codebase.
  2. Commit your changes to your local branch with a clear commit message that explains the changes you've made.
git commit -m 'Implemented new feature.'
  1. Push your changes to your forked repository on GitHub using the following command
git push origin new-feature-branch
  1. Create a new pull request to the original project repository. In the pull request, describe the changes you've made and why they're necessary.

🧪 Running Tests

To run all tests, in your developer environment, run:

uv run pytest tests/

The sktime adapter classes can be validated with sktime's estimator checks:

from sktime.utils import check_estimator
from tsbootstrap.adapters import MovingBlockBootstrap

check_estimator(MovingBlockBootstrap)

Contribution guide

See CONTRIBUTING.md for details.

📄 License

This project is licensed under the ℹ️ MIT License. See the LICENSE file for additional info.


👏 Contributors

Contributors:

This project follows the all-contributors specification. Contributions of any kind welcome!


📍 Time Series Bootstrapping

tsbootstrap implements bootstrapping methods for time series data. It generates resampled copies of univariate and multivariate series that preserve their chronological order and dependence structure.

Overview

Traditional bootstrap methods resample observations independently, which breaks the dependence in a time series: each observation usually depends on the ones before it. Time series bootstraps resample while preserving chronological order and correlation, so the resulting uncertainty estimates stay valid under that dependence.

Bootstrapping methodology

tsbootstrap resamples either the observations directly (i.i.d. and block methods) or the innovations of a fitted model (residual and sieve methods), respecting the chronological order and dependence structure of the data.

Block bootstrap

Block methods resample blocks of consecutive observations to preserve short-range dependence. The block length defaults to the automatic Politis-White (2004) selection.

  • Moving block (MovingBlock): overlapping fixed-length blocks (Kunsch 1989).
  • Circular block (CircularBlock): blocks wrap around the series end (Politis-Romano 1992).
  • Stationary block (StationaryBlock): geometric block lengths with independent uniform restart points (Politis-Romano 1994).
  • Non-overlapping block (NonOverlappingBlock): disjoint blocks (Carlstein 1986).
  • Tapered block (TaperedBlock(window=...)): blocks weighted by an energy-normalized window (Bartlett, Blackman, Hamming, Hann, or Tukey; Paparoditis-Politis 2001).

Residual bootstrap

For dependent data with a good model fit, ResidualBootstrap(model=...) regenerates the series recursively from the fitted dynamics and resampled, centered innovations (not fitted + residuals). Supported models: AR, ARIMA, and VAR (multivariate). A non-stationary fit is refused (or skipped, per stability_policy) rather than producing explosive paths.

Sieve bootstrap

SieveAR selects an autoregressive order on the original series, then runs the AR recursion; suited to data with autoregressive structure.

Deferred to a later release

Markov resampling, the distribution bootstrap, GARCH/volatility models, and frequency-domain / seasonal block methods are planned for a future version. The statistic-preserving method has been removed.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tsbootstrap-0.3.1.tar.gz (102.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tsbootstrap-0.3.1-py3-none-any.whl (106.1 kB view details)

Uploaded Python 3

File details

Details for the file tsbootstrap-0.3.1.tar.gz.

File metadata

  • Download URL: tsbootstrap-0.3.1.tar.gz
  • Upload date:
  • Size: 102.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.13

File hashes

Hashes for tsbootstrap-0.3.1.tar.gz
Algorithm Hash digest
SHA256 ac9331e9fb8ff1cb8f2709724c320202dbf97a2127bef34826255a70e33ad024
MD5 8fc8346617316a88010d0f583c9ef6d7
BLAKE2b-256 2ed040384a507864839387864a74489177301fcec9051cebd683c00daf5d1f26

See more details on using hashes here.

Provenance

The following attestation bundles were made for tsbootstrap-0.3.1.tar.gz:

Publisher: release.yml on astrogilda/tsbootstrap

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file tsbootstrap-0.3.1-py3-none-any.whl.

File metadata

  • Download URL: tsbootstrap-0.3.1-py3-none-any.whl
  • Upload date:
  • Size: 106.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.13

File hashes

Hashes for tsbootstrap-0.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 d8c57f596a48b241b00fde6f01f362d010a27a6643d948439077431b94467378
MD5 3f7f81c3eb20065928fe818d660945fc
BLAKE2b-256 2c18303bb7ffcdfdb63aec3a7aac95a39ec8bdd4c13c89fb28f8f5455fb35817

See more details on using hashes here.

Provenance

The following attestation bundles were made for tsbootstrap-0.3.1-py3-none-any.whl:

Publisher: release.yml on astrogilda/tsbootstrap

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page