{
  "markdown": "<!-- mcp-name: io.github.astrogilda/tsbootstrap -->\n\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n[![All Contributors](https://img.shields.io/github/all-contributors/astrogilda/tsbootstrap?color=ee8449&style=flat-square)](#contributors)\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n\n\n<div align=\"center\">\n    <div style=\"float: left; margin-right: 20px;\">\n        <img src=\"https://github.com/astrogilda/tsbootstrap/blob/main/tsbootstrap_logo.png\" width=\"120\" />\n    </div>\n    <h3>Generate bootstrapped samples from time-series data. The full documentation is available <a href=\"https://tsbootstrap.readthedocs.io/en/latest/\">here</a>.</h3>\n    <div style=\"clear: both;\"></div>\n    <br>\n    <p align=\"center\">\n        <img src=\"https://img.shields.io/badge/Markdown-000000.svg?style=flat&logo=Markdown&logoColor=white\" alt=\"Markdown\" />\n        <img src=\"https://img.shields.io/badge/Python-3776AB.svg?style=flat&logo=Python&logoColor=white\" alt=\"Python\" />\n        <img src=\"https://img.shields.io/badge/Pytest-0A9EDC.svg?style=flat&logo=Pytest&logoColor=white\" alt=\"pytest\" />\n        <img src=\"https://img.shields.io/badge/GitHub%20Actions-2088FF.svg?style=flat&logo=GitHub-Actions&logoColor=white\" alt=\"actions\" />\n    </p>\n    <a href=\"https://arxiv.org/abs/2607.06690\"><img src=\"https://img.shields.io/static/v1?label=arXiv&message=2607.06690&color=B31B1B&logo=arXiv\" alt=\"preprint\">\n    </a>\n    <a href=\"https://pypi.org/project/tsbootstrap/\">\n        <img src=\"https://img.shields.io/pypi/v/tsbootstrap?color=5D6D7E&logo=pypi\" alt=\"pypi-version\" />\n    </a>\n    <a href=\"https://pypi.org/project/tsbootstrap/\">\n        <img src=\"https://img.shields.io/pypi/pyversions/tsbootstrap?color=5D6D7E&logo=python\" alt=\"pypi-python-version\" />\n    </a>\n    <a href=\"https://pepy.tech/project/tsbootstrap\">\n        <img src=\"https://static.pepy.tech/badge/tsbootstrap\" alt=\"Downloads\"/>\n    </a>\n    <img src=\"https://img.shields.io/github/license/eli64s/readme-ai?color=5D6D7E\" alt=\"github-license\" />\n    <img src=\"https://github.com/astrogilda/tsbootstrap/workflows/CI/badge.svg\" alt=\"Build Status\"/>\n    <a href=\"https://codecov.io/gh/astrogilda/tsbootstrap\"><img src=\"https://codecov.io/gh/astrogilda/tsbootstrap/branch/main/graph/badge.svg\" alt=\"codecov\"/></a>\n    <a href=\"https://doi.org/10.5281/zenodo.8226495\"><img src=\"https://zenodo.org/badge/DOI/10.5281/zenodo.8226495.svg\" alt=\"DOI\"/></a>\n    <a href=\"https://mybinder.org/v2/gh/astrogilda/tsbootstrap/HEAD?labpath=docs/source/tutorials/quickstart.ipynb\"><img src=\"https://mybinder.org/badge_logo.svg\" alt=\"Launch tutorials on Binder\"/></a>\n    <img src=\"https://img.shields.io/github/last-commit/astrogilda/tsbootstrap\" alt=\"Last Commit\"/>\n    <img src=\"https://img.shields.io/github/issues/astrogilda/tsbootstrap\" alt=\"Issues\"/>\n    <img src=\"https://img.shields.io/github/issues-pr/astrogilda/tsbootstrap\" alt=\"Pull Requests\"/>\n    <img src=\"https://img.shields.io/github/v/tag/astrogilda/tsbootstrap\" alt=\"Tag\"/>\n    <a href=\"https://deepwiki.com/astrogilda/tsbootstrap\"><img src=\"https://deepwiki.com/badge.svg\" alt=\"Ask DeepWiki\"/></a>\n    <a href=\"https://context7.com/astrogilda/tsbootstrap\"><img src=\"https://img.shields.io/badge/Context7-indexed-3b82f6\" alt=\"Context7\"/></a>\n</div>\n\n\n\n## 📒 Table of Contents\n\n1. [🚀 Getting Started](#-getting-started)\n2. [⚡ Performance](#-performance)\n3. [📚 Articles](#-articles)\n4. [🧩 Modules](#-modules)\n5. [🗺 Roadmap](#-roadmap)\n6. [🤝 Contributing](#-contributing)\n7. [📄 License](#-license)\n8. [📍 Time Series Bootstrapping Methods intro](#time-series-bootstrapping)\n9. [👏 Contributors](#-contributors)\n\n\n\n---\n\n## 🚀 Getting Started\n\n### 🎮 Using tsbootstrap\n\n`tsbootstrap` exposes one typed entry point, `bootstrap`, configured with a method\nspecification. The same call works for every method.\n\n```python\nimport numpy as np\nfrom tsbootstrap import bootstrap, MovingBlock\n\nx = np.random.default_rng(0).standard_normal(200)\n\nresult = bootstrap(x, method=MovingBlock(block_length=\"auto\"), n_bootstraps=999, random_state=0)\n\nsamples = result.values()      # (n_bootstraps, n) resampled series\noob = result.get_oob_mask()    # (n_bootstraps, n) out-of-bag mask\n```\n\nChoose a method spec for the structure you need (block lengths default to the\nautomatic Politis-White selection):\n\n```python\nfrom tsbootstrap import StationaryBlock, ResidualBootstrap, SieveAR, AR, ARIMA, diagnose\n\nbootstrap(x, method=StationaryBlock(avg_block_length=\"auto\"))\n\n# recursive model-based bootstraps (need the model extra: uv add \"tsbootstrap[models]\")\nbootstrap(x, method=ResidualBootstrap(model=AR(order=2)))\nbootstrap(x, method=ResidualBootstrap(model=ARIMA(order=(1, 1, 1))))\nbootstrap(x, method=SieveAR())\n\n# not sure which fits? ask:\nprint(diagnose(x).recommended_methods)\n```\n\nInputs can be NumPy arrays, lists, or pandas / Polars DataFrames and Series. The\nresult is a `BootstrapResult` carrying the samples, provenance metadata, and\nout-of-bag / in-bag primitives. For the sktime ecosystem, the same methods are\nalso available as estimator classes (`MovingBlockBootstrap`, `ARResidualBootstrap`,\n`SieveBootstrap`, and the rest) under `tsbootstrap.adapters`.\n\n### Uncertainty quantification\n\nThe `uq` layer turns resampled series into prediction intervals. `forecast_intervals`\ngives forward forecast bands for an AR model; `EnbPIEnsemble` produces out-of-bag\nprediction intervals for an sklearn-style regressor, with calibrators for stationary,\nvolatility-clustered, and drifting data (static, sliding window, and the adaptive ACI,\nAgACI, and NexCP schemes); and `bootstrap_reduce` streams a per-replicate statistic so\ncalibration scales to large replicate counts without holding every path in memory.\n\n```python\nfrom tsbootstrap import AR, forecast_intervals\n\nlower, upper, median = forecast_intervals(x, model=AR(order=2), horizon=12, alpha=0.1)\n```\n\nFor a confidence interval on a statistic of one series, `conf_int` runs the bootstrap\nand reads the interval in one call:\n\n```python\nfrom tsbootstrap import IID, conf_int\n\nlower, upper, point = conf_int(x, \"mean\", method=IID(), kind=\"bca\", alpha=0.1)\n```\n\nThe conformal pieces (`EnbPIEnsemble` and the calibrators) need the `uq` extra\n(scikit-learn). The interactive\n[tutorial gallery](https://tsbootstrap.readthedocs.io/en/latest/tutorials/index.html)\nworks through every method on real and synthetic data, including a \"which bootstrap\nshould I use?\" decision guide.\n\n### MCP server\n\n`tsbootstrap` ships a read-only [Model Context Protocol](https://modelcontextprotocol.io)\nserver so an MCP client (an LLM agent, an IDE) can diagnose a short series and compute a\nbootstrap confidence interval without writing any Python. Run it with no install step:\n\n```sh\nuvx --from \"tsbootstrap[mcp]\" tsbootstrap-mcp\n```\n\nIt speaks the stdio transport and exposes exactly two read-only tools:\n\n- `diagnose_series`: serial-dependence and stationarity diagnostics, a recommended\n  Politis-White block length, and the bootstrap methods the server supports for the series.\n- `bootstrap_confidence_interval`: a percentile confidence interval for the mean, median,\n  std, or variance, using an i.i.d. or block bootstrap.\n\nBoth tools accept at most 500 observations and run at most 500 replicates. For larger\nseries, model-based methods, or the uncertainty layer, use the library directly in a\nlocal script.\n\n### 📦 Installation\n\nRequires Python 3.10 or higher.\n\n```sh\n# with uv (recommended):\nuv add tsbootstrap                   # core: i.i.d. and block methods\nuv add \"tsbootstrap[models]\"         # adds AR / ARIMA / VAR / sieve (statsmodels)\n\n# with pip:\npip install tsbootstrap\npip install \"tsbootstrap[models]\"\n```\n\nThe model-based methods import statsmodels lazily and raise a clear install hint if\nthe `models` extra is missing.\n\n## ⚡ Performance\n\n![tsbootstrap: speedup over arch and peak-memory reduction](benchmarks/launch_speed_memory.png)\n\n*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). The figure and the table below are generated from the committed benchmark data in [benchmarks/results/](benchmarks/results/); regenerate with `python benchmarks/plot_launch.py`.*\n\ntsbootstrap ships an optional compiled backend (`backend=\"compiled\"`, via the\n`[accel]` extra) that is faster than the [`arch`](https://github.com/bashtage/arch)\nlibrary on every overlapping resampling method. The table below is the speedup of\nthe streaming reduce path over `arch.apply` on an 8-core CPU (higher is better),\nread from [`benchmarks/results/vs_arch_ccx33_2026-07-11_settled.json`](benchmarks/results/vs_arch_ccx33_2026-07-11_settled.json)\n(the settled-min statistic; methodology in [benchmarks/README.md](benchmarks/README.md)).\n\n| Method | n=200, B=999 | n=200, B=10000 | n=2000, B=999 | n=2000, B=10000 |\n|-----------------|--------------|----------------|---------------|-----------------|\n| IID | 15x | 19x | 4.7x | 8.6x |\n| MovingBlock | 38x | 61x | 9.8x | 26x |\n| CircularBlock | 41x | 66x | 13x | 33x |\n| StationaryBlock | 19x | 24x | 6.8x | 12x |\n\nRead these as sustained gains of roughly 4.7x to 33x on the larger n=2000\nworkloads; the very large small-n multiples come from `arch`'s per-replicate\nPython callback in `bs.apply`, whose overhead dominates its runtime when each\nresample is cheap, so they measure that overhead as much as the compiled kernel.\n\nThe compiled reduce fuses index build, gather, and reduction into one pass, so\npeak memory stays flat in the number of replicates: at n=2000 the streaming\nreduce holds about 20 MB at B=50000 where materializing every replicate takes\nabout 1.94 GB (roughly 96x lighter), from\n[`benchmarks/results/membench_2026-07-04.json`](benchmarks/results/membench_2026-07-04.json).\nThe multivariate and ragged-panel reduce\npaths have no equivalent in `arch`. The panel reduce\n(`bootstrap_reduce_panel`) returns the full per-series bootstrap distribution\nof the statistic (`n_bootstraps x num_series`), so quantile and tail workflows\non an estimator are served directly with no replicate tensor. Use the\nmaterializing path only when the workflow consumes the resampled paths\nthemselves. Full methodology,\nsingle-threaded numbers, and the reproduction script are in\n[benchmarks/README.md](benchmarks/README.md).\n\n```sh\n# install the compiled backend\nuv add \"tsbootstrap[accel]\"\n# or\npip install \"tsbootstrap[accel]\"\n```\n\n## 📚 Articles\n\nDeep dives on the statistics and engineering behind the library, with worked\nexamples and animations:\n\n- [Your bootstrap is lying to you](https://thepragmaticquant.com/your-bootstrap-is-lying-to-you/):\n  why the ordinary i.i.d. bootstrap collapses on autocorrelated data (a nominal 90%\n  interval that covers 49.6% of the time) and how block resampling repairs it.\n- [When your errors aren't equal](https://thepragmaticquant.com/when-your-errors-arent-equal/):\n  the wild bootstrap for heteroskedastic errors, and what a block-wild variant preserves.\n- [Count the bytes, not the FLOPs](https://thepragmaticquant.com/why-we-stopped-materializing-arrays/):\n  the memory-wall engineering behind the compiled backend, with hardware-counter receipts.\n\n## 🧩 Modules\n\nPackage layout:\n\n| Area | Module(s) | Role |\n| --- | --- | --- |\n| 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()` |\n| 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 |\n| Block methods | `block/` | vectorized index kernels, true Politis-Romano stationary, energy-normalized tapering, PWSD block length, OOB primitives |\n| Model methods | `model/`, `engines/` | model fitting, stability guards, and recursive AR/ARMA/VAR simulation |\n| Uncertainty quantification | `uq/` | classical confidence intervals (percentile, basic, studentized, BCa) via `conf_int`, EnbPI prediction intervals, the static / sliding-window / ACI / AgACI / NexCP calibrators, and AR forecast intervals |\n| Ecosystem | `adapters/` | skbase / sktime estimator classes over the functional core |\n\n\n## 🗺 Roadmap\n\nThe full, living roadmap is [issue #181](https://github.com/astrogilda/tsbootstrap/issues/181). Highlights:\n\nNear term:\n- Out-of-sample forecast intervals for ARIMA and VAR (currently AR-only).\n- Python 3.14, once statsmodels publishes a 3.14 wheel ([#202](https://github.com/astrogilda/tsbootstrap/issues/202)).\n\nCandidate methods (good first issues):\n- Generalized block ([#104](https://github.com/astrogilda/tsbootstrap/issues/104)), local block ([#105](https://github.com/astrogilda/tsbootstrap/issues/105)), and frequency-domain ([#107](https://github.com/astrogilda/tsbootstrap/issues/107)) bootstraps.\n- A GARCH / volatility residual bootstrap, and the smooth-kernel dependent-wild bootstrap.\n\nDistributed execution (`Dask` / `Spark` / `Ray`), an async layer, and a string-keyed\nfactory were considered and deliberately left out. The library is a CPU-bound,\nsingle-process toolkit.\n\n## 🤝 Contributing\n\nSee our [good first issues ](https://github.com/astrogilda/tsbootstrap/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22)\nfor getting started.\n\n### Developer setup\n\n1. Fork the tsbootstrap repository\n\n2. Clone the fork to local:\n```sh\ngit clone https://github.com/astrogilda/tsbootstrap\n```\n\n3. In the local repository root, sync the locked development environment with uv:\n```sh\nuv sync --extra dev\n```\n\n4. uv creates an isolated virtual environment from `uv.lock` and editable-installs the\npackage, so changes to the package are reflected in your environment automatically. Run\ntools through the environment with `uv run` (for example `uv run pytest`).\n\n5. Install the pre-commit hooks:\n```sh\nuv run pre-commit install\n```\n\nThe hooks run ruff, formatting, and the other code-quality checks on each commit.\n\n### Verifying the Installation\n\nVerify the installation:\n```\npython -c \"import tsbootstrap; print(tsbootstrap.__version__)\"\n```\n\nThis prints the installed version.\n\n### Contribution workflow\n\n1. Create a new branch with a descriptive name (e.g., `new-feature-branch` or `bugfix-issue-123`).\n```sh\ngit checkout -b new-feature-branch\n```\n2. Make changes to the project's codebase.\n3. Commit your changes to your local branch with a clear commit message that explains the changes you've made.\n```sh\ngit commit -m 'Implemented new feature.'\n```\n4. Push your changes to your forked repository on GitHub using the following command\n```sh\ngit push origin new-feature-branch\n```\n5. 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.\n\n### 🧪 Running Tests\n\nTo run all tests, in your developer environment, run:\n\n```sh\nuv run pytest tests/\n```\n\nThat runs in a single process. Add the pytest-xdist flags CI uses to run the\nsuite in parallel, which is several times faster on a multi-core machine:\n\n```sh\nuv run pytest tests/ -n auto --dist loadscope --max-worker-restart 3\n```\n\nThe sktime adapter classes can be validated with sktime's estimator checks:\n\n```python\nfrom sktime.utils import check_estimator\nfrom tsbootstrap.adapters import MovingBlockBootstrap\n\ncheck_estimator(MovingBlockBootstrap)\n```\n\n### Contribution guide\n\nSee [CONTRIBUTING.md](https://github.com/astrogilda/tsbootstrap/blob/main/CONTRIBUTING.md) for details.\n---\n\n## 📄 License\n\nThis project is licensed under the `ℹ️  MIT` License. See the [LICENSE](https://docs.github.com/en/communities/setting-up-your-project-for-healthy-contributions/adding-a-license-to-a-repository) file for additional info.\n\n---\n## 👏 Contributors\n\nContributors:\n\n<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->\n<!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n\n<!-- markdownlint-restore -->\n<!-- prettier-ignore-end -->\n\n<!-- ALL-CONTRIBUTORS-LIST:END -->\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!\n\n\n---\n\n\n## 📍 Time Series Bootstrapping\n`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.\n\n### Overview\nTraditional 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.\n\n### Bootstrapping methodology\n`tsbootstrap` resamples either the observations directly (i.i.d. and block methods) or\nthe innovations of a fitted model (residual and sieve methods), respecting the\nchronological order and dependence structure of the data.\n\n### Block bootstrap\nBlock methods resample blocks of consecutive observations to preserve short-range\ndependence. The block length defaults to the automatic Politis-White (2004) selection.\n\n- **Moving block** (`MovingBlock`): overlapping fixed-length blocks (Kunsch 1989).\n- **Circular block** (`CircularBlock`): blocks wrap around the series end (Politis-Romano 1992).\n- **Stationary block** (`StationaryBlock`): geometric block lengths with independent uniform\n  restart points (Politis-Romano 1994).\n- **Non-overlapping block** (`NonOverlappingBlock`): disjoint blocks (Carlstein 1986).\n- **Tapered block** (`TaperedBlock(window=...)`): blocks weighted by an energy-normalized\n  window (Bartlett, Blackman, Hamming, Hann, or Tukey; Paparoditis-Politis 2001).\n\n### Residual bootstrap\nFor dependent data with a good model fit, `ResidualBootstrap(model=...)` regenerates the\nseries **recursively** from the fitted dynamics and resampled, centered innovations (not\n`fitted + residuals`). Supported models: `AR`, `ARIMA`, and `VAR` (multivariate). A\nnon-stationary fit is refused (or skipped, per `stability_policy`) rather than producing\nexplosive paths.\n\n### Sieve bootstrap\n`SieveAR` selects an autoregressive order on the original series, then runs the AR recursion;\nsuited to data with autoregressive structure.\n\n### Innovation resamplers\nThe `innovation` argument on `ResidualBootstrap` and `SieveAR` controls how the centered\nresiduals are resampled. It defaults to `IID` (uniform resampling); two wild resamplers relax\nthe exchangeability that assumes.\n\n- **Wild** (`Wild(distribution=...)`): multiplies each residual in place by a mean-zero,\n  unit-variance draw (`e*_t = v_t * e_hat_t`), keeping its time position and magnitude, so it\n  stays valid under conditional heteroskedasticity (Wu 1986; Liu 1988; Rademacher default per\n  Davidson-Flachaire 2008).\n- **Block-wild** (`BlockWild(block_length=...)`): holds one multiplier constant across each\n  block of residuals, so serial dependence left by a misspecified mean survives the resampling\n  (piecewise-constant dependent wild bootstrap, Shao 2010).\n\nBoth require the host model's `burn_in=0` and `initial=\"fixed\"` defaults so the multipliers\nalign one-to-one with the residuals.\n\n### Deferred to a later release\nMarkov resampling, the distribution bootstrap, GARCH/volatility models, and\nfrequency-domain / seasonal block methods are planned for a future version. The\nstatistic-preserving method has been removed.\n",
  "bytes": 19579,
  "sha": "f5be0fe1cd1b8be9214ebe22f53af2af48936df3b91b2b3eb1ec15fdfd748703",
  "repo_slug": "astrogilda/tsbootstrap",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_astrogilda_tsbootstrap_4b41cb82/readme"
}