### Install tsbootstrap with examples Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/tutorials/residual_and_sieve.ipynb Installs the tsbootstrap library with necessary extras for examples, including statsmodels and sktime. This is a prerequisite for running the demonstrations. ```python try: import tsbootstrap # noqa: F401 except ImportError: %pip install -q "tsbootstrap[examples]" # The ARIMA and sieve paths use statsmodels, which ships in the [examples] extra # (it pulls in tsbootstrap[models]). The bundled datasets come from sktime and # statsmodels, both also in [examples]. ``` -------------------------------- ### Install tsbootstrap Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/tutorials/quickstart.ipynb Install the tsbootstrap library, including example dependencies, if it's not already present. This is useful for environments like Colab or Binder. ```python try: import tsbootstrap # noqa: F401 except ImportError: %pip install -q "tsbootstrap[examples]" ``` -------------------------------- ### Install tsbootstrap with uv or pip Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/quickstart.md Install the core library or with the 'models' extra for advanced methods. Requires Python 3.10+. ```sh # 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]" ``` -------------------------------- ### Install tsbootstrap with sktime support Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/adapters_guide.md Install the tsbootstrap package with sktime extras using uv or pip. ```sh uv add "tsbootstrap[sktime]" # or: pip install "tsbootstrap[sktime]" ``` -------------------------------- ### Install Optional Dependencies with uv Source: https://github.com/astrogilda/tsbootstrap/blob/main/DEVELOPER_NOTES.md Installs core dependencies, development environment, or all optional extras using the uv package manager. ```bash uv sync # core only uv sync --extra dev # development environment uv sync --all-extras # everything ``` -------------------------------- ### Install Profiling Dependencies Source: https://github.com/astrogilda/tsbootstrap/blob/main/profiling/README.md Installs the necessary profiling tools including scalene, line_profiler, memory_profiler, py-spy, and snakeviz. ```bash pip install -e ".[profile]" ``` -------------------------------- ### Example Workflow: Diagnose and Bootstrap Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/diagnostics_guide.md Demonstrates diagnosing a random walk time series and acting on the recommendations by performing a bootstrap. Requires `numpy` and `tsbootstrap` components. ```python import numpy as np from tsbootstrap import bootstrap, diagnose, MovingBlock, StationaryBlock rng = np.random.default_rng(1) x = np.cumsum(rng.standard_normal(300)) # random walk d = diagnose(x) print(d.nonstationary) # True print(d.recommended_methods) # ('ResidualBootstrap(model=ARIMA(...))', 'SieveAR') # Act on the recommendation from tsbootstrap import ResidualBootstrap, ARIMA result = bootstrap(x, method=ResidualBootstrap(model=ARIMA(order=(0, 1, 0)))) ``` -------------------------------- ### Initialize ResidualBootstrap with different models Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/methods_guide.md Demonstrates initializing the ResidualBootstrap method with univariate AR, integrated ARIMA, and multivariate VAR models. Ensure the 'models' extra is installed. ```python from tsbootstrap import ResidualBootstrap, AR, ARIMA, VAR # Univariate AR method = ResidualBootstrap(model=AR(order=2)) # Integrated ARIMA method = ResidualBootstrap(model=ARIMA(order=(1, 1, 1))) # Multivariate VAR method = ResidualBootstrap(model=VAR(order=1)) ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/astrogilda/tsbootstrap/blob/main/CONTRIBUTING.md Installs pre-commit hooks to automatically run Ruff for linting and formatting, along with other code quality checks on each commit. ```sh uv run pre-commit install ``` -------------------------------- ### Install tsbootstrap with models extra Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/methods_guide.md Install the 'tsbootstrap' library with the 'models' extra to use model-based methods. This is required for ResidualBootstrap and SieveAR. ```sh uv add "tsbootstrap[models]" # or: pip install "tsbootstrap[models]" ``` -------------------------------- ### Verify tsbootstrap Installation Source: https://github.com/astrogilda/tsbootstrap/blob/main/CONTRIBUTING.md Verifies the tsbootstrap installation by printing the installed version. This command is executed using `uv run`. ```python uv run python -c "import tsbootstrap; print(tsbootstrap.__version__)" ``` -------------------------------- ### Verify tsbootstrap Installation Source: https://github.com/astrogilda/tsbootstrap/blob/main/README.md Verify the installation of the tsbootstrap package by printing its version. This command should be run in the isolated virtual environment. ```python python -c "import tsbootstrap; print(tsbootstrap.__version__)" ``` -------------------------------- ### tsbootstrap Method Selection and Diagnosis Source: https://github.com/astrogilda/tsbootstrap/blob/main/README.md Shows how to use different bootstrapping methods like StationaryBlock, ResidualBootstrap, and SieveAR. For model-based methods (ResidualBootstrap, SieveAR), the 'models' extra needs to be installed. The diagnose function can recommend suitable methods. ```python 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) ``` -------------------------------- ### Basic Bootstrap Replication with Moving Block Method Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/index.md This snippet demonstrates how to generate bootstrap replicates of a time series using the MovingBlock method. It shows how to access the generated samples and the out-of-bag mask. Ensure numpy and tsbootstrap are installed. ```python 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() # shape (999, 200) oob = result.get_oob_mask() # shape (999, 200) boolean out-of-bag mask ``` -------------------------------- ### Diagnose Time Series and Get Recommendations Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/diagnostics_guide.md Inspect a time series to get recommended bootstrap methods and explanatory notes. Requires `numpy` and `tsbootstrap`. ```python from tsbootstrap import diagnose import numpy as np x = np.random.default_rng(0).standard_normal(200) d = diagnose(x) print(d.recommended_methods) # e.g. ('IID', 'MovingBlock') for note in d.notes: print(note) ``` -------------------------------- ### Import Libraries and Define Constants Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/tutorials/adaptive_drift_aci_nexcp.ipynb Imports necessary libraries and defines the target coverage level. This setup is common for conformal inference tasks. ```python import matplotlib.pyplot as plt import numpy as np from tsbootstrap.uq.adaptive import aci_halfwidths, nexcp_quantile ALPHA = 0.1 NOMINAL = 1.0 - ALPHA # target coverage 0.90 print("target coverage 1 - alpha =", NOMINAL) ``` -------------------------------- ### Handling Failed Bootstrap Runs Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/results_guide.md Provides an example of how to check if a bootstrap run failed due to non-stationary model fitting when `stability_policy='skip'` is used, and how to access the failure reason. ```python from tsbootstrap import ResidualBootstrap, AR from tsbootstrap.methods import AR method = ResidualBootstrap(model=AR(order=1, stability_policy="skip")) result = bootstrap(very_nonstationary_x, method=method) if result.metadata.failed: print("Model fit failed:", result.metadata.failure_reason) else: arr = result.values() ``` -------------------------------- ### Sync Development Environment with uv Source: https://github.com/astrogilda/tsbootstrap/blob/main/CONTRIBUTING.md Synchronizes the locked development environment using uv. This command builds the virtual environment with an editable install, making code changes effective immediately. Tools can be invoked using `uv run`. ```sh uv sync --extra dev ``` -------------------------------- ### Diagnose Time Series with tsbootstrap Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/tutorials/cheat_sheet.ipynb Use the `diagnose` function to inspect time series properties and get recommended method specifications. Treat the output as a heuristic starting point. ```python from tsbootstrap import diagnose diagnose(x).recommended_methods ``` -------------------------------- ### bootstrap() Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/index.md Initializes and runs the bootstrap process. This is the main entry point for using the tsbootstrap library. ```APIDOC ## bootstrap() ### Description Initializes and runs the bootstrap process. This is the main entry point for using the tsbootstrap library. ### Method (Function Call) ### Parameters (Specific parameters would be detailed in api_bootstrap.md) ### Request Example (Example usage would be detailed in api_bootstrap.md) ### Response (Response details would be detailed in api_bootstrap.md) ``` -------------------------------- ### Diagnose Bootstrap Method Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/tutorials/quickstart.ipynb Use the `diagnose` function to inspect the time series and get recommended bootstrap method specifications. This provides a starting point for choosing the appropriate method. ```python from tsbootstrap import diagnose diagnose(x).recommended_methods ``` -------------------------------- ### Use MovingBlockBootstrap adapter Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/adapters_guide.md Demonstrates how to instantiate and use the MovingBlockBootstrap adapter to generate bootstrap samples from time series data. It shows how to iterate over samples and optionally return observation indices. ```python from tsbootstrap.adapters import MovingBlockBootstrap import numpy as np x = np.random.default_rng(0).standard_normal(200) est = MovingBlockBootstrap(block_length=10, n_bootstraps=100, random_state=0) for sample in est.bootstrap(x): ... # sample is an ndarray of shape (n,) # With observation indices for values, indices in est.bootstrap(x, return_indices=True): print(values.shape, indices) ``` -------------------------------- ### Using sktime adapters for bootstrapping Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/quickstart.md Shows how to use the MovingBlockBootstrap adapter from tsbootstrap.adapters with sktime. ```python from tsbootstrap.adapters import MovingBlockBootstrap est = MovingBlockBootstrap(block_length=10, n_bootstraps=100, random_state=0) for sample in est.bootstrap(x): ... # each sample is an ndarray of shape (n,) ``` -------------------------------- ### Choosing a tsbootstrap method Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/quickstart.md Illustrates various bootstrapping methods available in tsbootstrap, including IID, block-based, and model-based methods. ```python from tsbootstrap import ( bootstrap, IID, MovingBlock, CircularBlock, StationaryBlock, NonOverlappingBlock, TaperedBlock, ResidualBootstrap, SieveAR, AR, ARIMA, VAR, ) # Baseline, no serial dependence assumed bootstrap(x, method=IID()) # Block methods (block_length defaults to "auto" = Politis-White selection) bootstrap(x, method=MovingBlock()) bootstrap(x, method=CircularBlock()) bootstrap(x, method=StationaryBlock()) # avg_block_length parameter bootstrap(x, method=NonOverlappingBlock()) bootstrap(x, method=TaperedBlock(window="bartlett")) # Model-based (requires the models 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()) ``` -------------------------------- ### Initialize and Apply Bootstrap Adapters Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/tutorials/sktime_adapters.ipynb Initializes different bootstrap adapters and generates bootstrap replicates for a time series. Use this to compare how various bootstrapping methods handle time series data. ```python from tsbootstrap.adapters import ARResidualBootstrap, IIDBootstrap estimators = { "MovingBlockBootstrap(block_length=12)": MovingBlockBootstrap( block_length=12, n_bootstraps=50, random_state=0 ), "IIDBootstrap()": IIDBootstrap(n_bootstraps=50, random_state=0), "ARResidualBootstrap(order=2)": ARResidualBootstrap(order=2, n_bootstraps=50, random_state=0), } # Colorblind-safe palette (Wong 2011); each adapter also gets a distinct # linestyle so the families stay distinguishable in grayscale or for readers # with colour-vision deficiency. styles = { "MovingBlockBootstrap(block_length=12)": ("#0072B2", "-"), # blue, solid "IIDBootstrap()": ("#E69F00", "--"), # orange, dashed "ARResidualBootstrap(order=2)": ("#009E73", ":"), # green, dotted } months = np.arange(1, len(y_values) + 1) fig, ax = plt.subplots(figsize=(9, 5), layout="constrained") # Faint replicate clouds, eight per adapter, coloured + styled per family. for label, est in estimators.items(): color, ls = styles[label] for i, rep in enumerate(est.bootstrap(y_values)): if i >= 8: break ax.plot(months, rep, color=color, linestyle=ls, alpha=0.35, lw=0.9, zorder=1) # Original series emphasized on top, in front of every replicate. ax.plot(months, y_values, color="black", lw=2.6, zorder=3, label="Original airline series") # One bold proxy line per adapter for a readable legend (the faint replicates # would otherwise make the legend swatches nearly invisible). from matplotlib.lines import Line2D legend_handles = [Line2D([0], [0], color="black", lw=2.6, label="Original airline series")] legend_handles += [ Line2D([0], [0], color=styles[label][0], linestyle=styles[label][1], lw=2.0, label=label) for label in estimators ] ax.set_title("Eight bootstrap replicates per adapter family, overlaid on the airline series") ax.set_xlabel("Time (months from start of series)") ax.set_ylabel("Air passengers (thousands)") ax.set_xlim(months[0], months[-1]) ax.legend(handles=legend_handles, loc="upper left", framealpha=0.9, fontsize=9) ax.grid(True, alpha=0.25, linewidth=0.5) plt.show() ``` -------------------------------- ### Initialize and Use MovingBlockBootstrap Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/tutorials/sktime_adapters.ipynb Initializes the MovingBlockBootstrap adapter with specified parameters and generates bootstrap replicates from the provided data. The adapter is initialized in a scikit-learn compatible style. ```python from tsbootstrap.adapters import MovingBlockBootstrap mbb = MovingBlockBootstrap(block_length=12, n_bootstraps=200, random_state=0) print("get_params:", mbb.get_params()) print("get_n_bootstraps:", mbb.get_n_bootstraps()) gen = mbb.bootstrap(y_values) # a generator, nothing computed yet import types print("is a generator:", isinstance(gen, types.GeneratorType)) replicates = list(gen) # draining the generator does the work print("collected:", len(replicates), "replicates, each shape", replicates[0].shape) ``` -------------------------------- ### Diagnosing recommended methods Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/quickstart.md Uses the diagnose function to get recommended methods and notes for time series data. ```python from tsbootstrap import diagnose d = diagnose(x) print(d.recommended_methods) print(d.notes) ``` -------------------------------- ### IID Resampling Example Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/tutorials/observation_resampling.ipynb Demonstrates IID resampling, which is suitable when observations are independent. This method destroys autocorrelation by shuffling rows. ```python _ = show_replicates( x, IID(), "IID: independent resampling (autocorrelation destroyed)", color="tab:red", ) ``` -------------------------------- ### Accessing Bootstrap Samples Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/results_guide.md Demonstrates how to iterate, index, and access stacked arrays of bootstrap samples. Ensure 'tsbootstrap' and 'numpy' are imported. ```python from tsbootstrap import bootstrap, MovingBlock import numpy as np x = np.random.default_rng(0).standard_normal(200) result = bootstrap(x, method=MovingBlock(), n_bootstraps=200, random_state=0) # Iterate for sample in result: print(sample.values.shape) # (200,) # Index first = result[0] # Stacked array: shape (n_bootstraps, n) arr = result.values() # Stacked indices: shape (n_bootstraps, n) , None for recursive methods idx = result.indices() ``` -------------------------------- ### Perform Static Type Checking Source: https://github.com/astrogilda/tsbootstrap/blob/main/DEVELOPER_NOTES.md Enforces strict type checking using mypy and pyright. Ensure 'dev' extra is installed. ```bash uv run mypy src/tsbootstrap # strict-minus typing gate (config: [tool.mypy]) uv run pyright # strict type checking (config: [tool.pyright]) ``` -------------------------------- ### Lint and Format Code with Ruff Source: https://github.com/astrogilda/tsbootstrap/blob/main/DEVELOPER_NOTES.md Checks code for linting issues and enforces formatting standards using Ruff. Ensure 'dev' extra is installed. ```bash uv run ruff check src/ tests/ # lint (config: [tool.ruff]) uv run ruff format src/ tests/ # formatting (line length 100) ``` -------------------------------- ### Generate Random Walk time series Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/tutorials/AA_datasets_and_dgps.ipynb Generates a Random Walk process, which is a textbook example of a non-stationary process where variance grows without bound. ```python x_rw = np.cumsum(rng.standard_normal(400)) fig, ax = plt.subplots(figsize=(8, 3)) ax.plot(x_rw, color="tab:brown", lw=0.9) ax.set_title("Random walk: unit root (non-stationary)") ax.set_xlabel("time") ax.set_ylabel("value") plt.show() ``` -------------------------------- ### Load Data and Initialize Parameters Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/tutorials/observation_resampling.ipynb Loads synthetic AR(1) and real lynx trapping data, and sets up parameters for bootstrapping. This code prepares the data for time series resampling. ```python import matplotlib.pyplot as plt import numpy as np from sktime.datasets import load_lynx from tsbootstrap import ( IID, CircularBlock, MovingBlock, NonOverlappingBlock, StationaryBlock, TaperedBlock, bootstrap, ) from tsbootstrap.block.pwsd import optimal_block_length rng = np.random.default_rng(0) n, phi = 240, 0.6 x = np.zeros(n) e = rng.standard_normal(n) for t in range(1, n): x[t] = phi * x[t - 1] + e[t] lynx = load_lynx().to_numpy(dtype=float) # 114 yearly lynx trapping counts B = 300 # replicates per call; small for CI print(f"AR(1): n = {x.shape[0]}, lynx: n = {lynx.shape[0]}") ``` -------------------------------- ### Run Pytest with CI Hypothesis Profile Source: https://github.com/astrogilda/tsbootstrap/blob/main/tests/README.md This command executes Pytest using the `ci` Hypothesis profile, which runs a larger set of examples for more comprehensive testing. ```bash HYPOTHESIS_PROFILE=ci uv run pytest tests/property/ ``` -------------------------------- ### Using the new bootstrap() API in tsbootstrap 0.2.0 Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/development/migration_to_0.2.0.md Demonstrates the usage of the new functional `bootstrap()` API with a MovingBlock method. Shows how to retrieve results and out-of-bag masks. ```python from tsbootstrap import bootstrap, MovingBlock result = bootstrap(x, method=MovingBlock(block_length="auto"), n_bootstraps=999, random_state=0) samples = result.values() # (n_bootstraps, n[, d]) oob = result.get_oob_mask() # (n_bootstraps, n) for observation-resampling methods ``` -------------------------------- ### Reproducing a Bootstrap Run with Recorded Entropy Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/tutorials/provenance_and_scaling.ipynb Demonstrates how to replay a bootstrap run exactly by using the `seed_entropy` recorded from a previous run. This is useful for ensuring reproducibility of exploratory analyses. ```python # The recorded entropy replays a 'random' run exactly. auto = bootstrap(x, method=MovingBlock(block_length=10), n_bootstraps=50, random_state=None) recorded = auto.metadata.seed_entropy print(f"random_state_kind: {auto.metadata.random_state_kind!r}") print(f"recorded seed_entropy: {recorded}") replay = bootstrap( x, method=MovingBlock(block_length=10), n_bootstraps=50, random_state=np.random.SeedSequence(recorded), ) print( f"replay from recorded entropy reproduces the run: {np.array_equal(auto.values(), replay.values())}" ) ``` -------------------------------- ### Basic tsbootstrap Usage with MovingBlock Source: https://github.com/astrogilda/tsbootstrap/blob/main/README.md Demonstrates the basic usage of the bootstrap function with the MovingBlock method. Requires numpy and tsbootstrap. The result object provides access to resampled series and out-of-bag masks. ```python 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 ``` -------------------------------- ### Simulate Volatility Scores Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/tutorials/adaptive_drift_aci_nexcp.ipynb Generates a series of nonconformity scores with a gradually increasing scale to simulate drifting volatility. This setup is used to test adaptive calibration methods. ```python rng = np.random.default_rng(3) M = 500 RAMP_START = 200 # Scale is flat, then ramps from 1 to 4: a slowly drifting / clustering volatility. scale = np.concatenate( [ np.full(RAMP_START, 1.0), np.linspace(1.0, 4.0, M - RAMP_START), ] ) vol_scores = np.abs(rng.standard_normal(M) * scale) # nonconformity scores fig, ax = plt.subplots(figsize=(9, 3), constrained_layout=True) ax.plot(vol_scores, color="#555555", lw=0.7) ax.axvline(RAMP_START, color="black", ls="--", lw=1.4, label="volatility ramp begins") ax.set_xlabel("time index") ax.set_ylabel("nonconformity score |residual|") ax.set_title("Scores are calm for 200 steps, then their scale ramps from 1 to 4") ax.legend(fontsize=9, framealpha=0.9) plt.show() ``` -------------------------------- ### Basic tsbootstrap usage Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/quickstart.md Demonstrates basic usage of the bootstrap function with MovingBlock method and accessing results. ```python 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() # ndarray shape (999, 200) oob = result.get_oob_mask() # ndarray shape (999, 200) ``` -------------------------------- ### Get Out-of-Bag Mask Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/tutorials/quickstart.ipynb Retrieve the out-of-bag mask from the bootstrap result. This mask indicates which original data points were excluded from each bootstrap replicate, useful for methods like EnbPI. ```python mask = result.get_oob_mask() mask.shape, round(float(mask.mean()), 3) # ~0.37 of points are OOB per replicate ``` -------------------------------- ### Perform Mutation Testing Source: https://github.com/astrogilda/tsbootstrap/blob/main/DEVELOPER_NOTES.md Executes mutation tests using mutmut, disabling Numba JIT compilation and setting a specific Hypothesis profile for reproducibility. Ensure 'dev' extra is installed. ```bash NUMBA_DISABLE_JIT=1 HYPOTHESIS_PROFILE=mutmut uv run mutmut run ``` -------------------------------- ### Load and Prepare Macroeconomic Data Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/tutorials/multivariate_var.ipynb Loads macroeconomic data and calculates the quarterly log growth rates for real GDP, real consumption, and CPI. This step is crucial for preparing stationary time series data suitable for VAR modeling. ```python import pandas as pd import statsmodels.api as sm macro = sm.datasets.macrodata.load_pandas().data levels = macro[["realgdp", "realcons", "cpi"]].to_numpy() labels = ["realgdp", "realcons", "cpi"] # Quarterly log growth (in percent): a stationary multivariate series. growth = np.diff(np.log(levels), axis=0) * 100.0 print("growth shape:", growth.shape, " (n, d)") orig_corr = np.corrcoef(growth.T) print("original cross-correlation matrix:") pd.DataFrame(orig_corr, index=labels, columns=labels).round(3) ``` -------------------------------- ### Generate Synthetic Bivariate VAR(1) Data Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/tutorials/multivariate_var.ipynb Generates a synthetic time series dataset following a bivariate VAR(1) process. This example demonstrates creating data with both contemporaneous correlation and lead-lag dynamics. ```python import matplotlib.pyplot as plt import numpy as np rng = np.random.default_rng(0) n = 200 # Coefficient matrix: x0 picks up the lagged value of x1 (x1 leads x0). A = np.array([[0.5, 0.3], [0.0, 0.5]]) # Innovation covariance: positive contemporaneous correlation between the series. cov = np.array([[1.0, 0.5], [0.5, 1.0]]) chol = np.linalg.cholesky(cov) X = np.zeros((n, 2)) for t in range(1, n): X[t] = A @ X[t - 1] + chol @ rng.standard_normal(2) print("X shape:", X.shape, " (n time steps, d series)") fig, ax = plt.subplots(figsize=(9, 3.5), constrained_layout=True) ax.plot(X[:, 0], color="tab:blue", lw=1.4, label="series 0 (lags series 1)") ax.plot(X[:, 1], color="tab:orange", lw=1.4, label="series 1 (leads series 0)") ax.set_title("Synthetic bivariate VAR(1) with contemporaneous and lead-lag structure") ax.set_xlabel("time step") ax.set_ylabel("value") ax.grid(True, alpha=0.3) ax.legend(loc="upper right", framealpha=0.9) plt.show() ``` -------------------------------- ### Generate Coverage Report Source: https://github.com/astrogilda/tsbootstrap/blob/main/DEVELOPER_NOTES.md Runs the test suite and generates an HTML coverage report for the 'src/tsbootstrap' directory. ```bash uv run pytest tests/ --cov=src/tsbootstrap --cov-report=html ``` -------------------------------- ### Run Single Test File or Test Source: https://github.com/astrogilda/tsbootstrap/blob/main/tests/README.md Execute a single test file or a specific test case within a file. ```bash uv run pytest tests/unit/test_uq.py ``` ```bash uv run pytest tests/unit/test_uq.py::test_enbpi_coverage ``` -------------------------------- ### Run Test Suite with Coverage Reporting (HTML) Source: https://github.com/astrogilda/tsbootstrap/blob/main/tests/README.md Execute the test suite and generate an HTML report for code coverage, which will be written to the 'htmlcov/' directory. ```bash uv run pytest tests/ --cov=src --cov-report=html ``` -------------------------------- ### Run All Profilers Source: https://github.com/astrogilda/tsbootstrap/blob/main/profiling/README.md Executes all deterministic profiling tools in one command to gather comprehensive performance data. ```bash python -m profiling.run_all ``` -------------------------------- ### ARIMA Residual Bootstrap Source: https://github.com/astrogilda/tsbootstrap/blob/main/docs/source/tutorials/residual_and_sieve.ipynb Applies ResidualBootstrap with an ARIMA(1,1,1) model to the Nile river flow dataset. Requires the 'statsmodels' library and its '[models]' or '[examples]' extra. The output shows the shape of the bootstrap samples and whether the run failed. ```python import statsmodels.api as sm nile = sm.datasets.nile.load_pandas().data["volume"].to_numpy(dtype=float) print("nile length:", nile.shape[0]) res_arima = bootstrap( nile, method=ResidualBootstrap(model=ARIMA(order=(1, 1, 1))), n_bootstraps=200, random_state=2, ) samples_arima = res_arima.values() print("ARIMA replicate shape:", samples_arima.shape) print("run failed:", res_arima.metadata.failed) print("indices():", res_arima.indices()) # still None: ARIMA is recursive too ``` -------------------------------- ### Create a New Branch Source: https://github.com/astrogilda/tsbootstrap/wiki/Contributor's-Guide Use this command to create and switch to a new branch for your changes. Ensure the branch name is descriptive. ```sh git checkout -b new-feature-branch ```