Metadata-Version: 2.4
Name: btforest
Version: 0.25.1
Summary: Branching Trajectory Forests: probabilistic multi-horizon forecasting that re-serves whole historical futures on a linear spine
Author: Alex Paton
License-Expression: MIT
Project-URL: Homepage, https://github.com/AlexPaton/btforest
Project-URL: Repository, https://github.com/AlexPaton/btforest
Project-URL: Issues, https://github.com/AlexPaton/btforest/issues
Project-URL: Changelog, https://github.com/AlexPaton/btforest/blob/main/CHANGELOG.md
Keywords: forecasting,probabilistic forecasting,time series,random forest,analogue ensemble,scenario generation,machine learning,branching trajectory forest
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.23
Requires-Dist: pandas>=1.5
Requires-Dist: scikit-learn>=1.3
Provides-Extra: test
Requires-Dist: pytest>=7; extra == "test"
Provides-Extra: research
Requires-Dist: lightgbm; extra == "research"
Requires-Dist: statsmodels; extra == "research"
Requires-Dist: statsforecast; extra == "research"
Requires-Dist: joblib; extra == "research"
Requires-Dist: matplotlib; extra == "research"
Requires-Dist: scipy; extra == "research"
Dynamic: license-file

# btforest (v0.25)

[![tests](https://github.com/AlexPaton/btforest/actions/workflows/tests.yml/badge.svg)](https://github.com/AlexPaton/btforest/actions/workflows/tests.yml)
[![PyPI](https://img.shields.io/pypi/v/btforest.svg)](https://pypi.org/project/btforest/)
[![Python](https://img.shields.io/pypi/pyversions/btforest.svg)](https://pypi.org/project/btforest/)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

**Branching Trajectory Forests**: probabilistic multi-horizon forecasting where the leaves hold whole future paths.

A linear main trajectory (the spine) predicts the expected path; two forests find past days that looked like today
and branch the forecast into the whole futures that followed them. The result is a fan of real, coherent paths
rather than separate per-step guesses.

    pip install btforest
    import btforest as btf

    y[t+1..t+H] - anchor(t) = L(x_t) + M(x_t) + S(x_t)

- **L**: a ridge backbone predicting the whole path from today's state (the spine)
- **M**: the smooth part of what L misses, held in a path forest
- **S**: the rough band around it, held in a second path forest
- **The draw**: each sampled path takes ONE historical origin, weighted `w_M x (w_S + eps)^0.5` by leaf
  co-occurrence, and re-serves that origin's whole residual future on today's spine

So every path in the bundle is a real future that happened once. Nothing is generated step by step, which is why
path questions (the range over the next month, the worst drawdown, three hot days in a row) come out right, and why
it cannot invent a shape it has never seen.

![architecture](docs/architecture.png)

## Where it stands

Against seven other architectures on six daily series (COMPARISON.md):

- **Where `screen()` says it fits** (electricity demand, river flow, temperature, wind) it has the best or
  second-best energy score of eight models, ahead of SARIMA, a DeepAR-style GRU and zero-shot Chronos on all four.
- **No other model is in the top group on both accuracy and path shape.** LightGBM quantiles come within 1-4% on
  accuracy and are 24-52% worse on path functionals; DeepAR matches the paths and is 5-16% behind on accuracy.
- **Where `screen()` says do not use it** (VIX, the Bitcoin level) it is seventh and last of eight. Run the screen.
- **Questions about the path are where it pulls ahead.** Asked "will the range stay below X", "will it peak above
  Y", "how deep will the drawdown be", it is best or second-best of ten models on three of the four fitting series,
  with calibration error at most 0.05. LightGBM quantiles match it on single days and fall to -23% skill on wind
  path events, because a shuffle borrowed afterwards cannot give each origin its own path shape
  (research/extensions/RESULTS.md).

What the research found, including everything that did not work, is in FINDINGS.md (the summary) and
RESEARCH_NOTES.md (the full record, release by release).

On standard benchmarks (research/benchmarks): within 4% of NLinear and DLinear on ETTh2 univariate (MSE 0.134
against 0.129), between the published deep models on UCI electricity under the TFT protocol (P50 0.062, P90 0.031),
and well behind the linear models on ETTh1, whose test months are a regime shift (Regime shifts, below).

## Install

    pip install btforest   # once published; until then: pip install -e .
    pytest tests -q               # 76 tests, about 50 s

## Quick start

```python
import numpy as np
import btforest as btf
from btforest import Forecaster, demo_series, screen, walk_forward, summarise

y = demo_series("demand")                         # or any pandas Series with a DatetimeIndex
screen(y, H=28)                                   # is this series a fit at all? prints a recommendation

train = np.asarray(y.index.year <= 2023)
m = Forecaster(H=28, freq="daily").fit(y, train_mask=train)
m.forecast_frame(y)          # q05..q95 by forecast date, in your units
B = m.predict(y, k=400)      # (1, 400, 28): 400 whole paths, in your units
m.analogues(y, n=10)         # which past dates the forecast is built from
m.effective_n(y)             # below about 30, the bundle is a handful of rows
P, W = m.fold(y, m=32)       # 32 weighted paths chosen deterministically, for storing or plotting

# walk forward against climatology, persistence and the ridge backbone, one fold per year
print(summarise(walk_forward(y, lambda: Forecaster(H=28), test_periods=[2022, 2023])))
```

Once fitted, `predict`, `fold`, `forecast_frame` and the rest reuse the training mask from `fit`, so a forecast is
always expressed against the climatology the model was trained on. Pass `train_mask=` again only to change it.

Path probabilities come straight off the bundle:

```python
thr = 34000
p = np.mean([(np.convolve(path > thr, np.ones(3), "valid") == 3).any() for path in B[0]])   # 3 days running above thr
```

`examples/` has five scripts that run as they are, on synthetic data, in under 20 s each: `quickstart.py`,
`daily_walkforward.py` (the low-level API piece by piece), `monthly_template.py`, `any_axis.py` and
`volatility.py`. Each also takes your own CSV.

## Which configuration

![decision flow](docs/decision_flow.png)

| Situation | Use | Why |
|---|---|---|
| Daily or sub-daily series with persistent anomalies | `Forecaster(H, freq=...)` | the case it was built for |
| `screen()` says near random walk, level matters | persistence, the ridge backbone, or `PersistenceGate` | the library loses to all of them there |
| Level unpredictable, scale predictable (prices, yields) | `VolatilityScaledForecaster` | forest on volatility paths, shape from history |
| A good incumbent model already exists | `fit(..., incumbent=forecast)` or `ResidualCorrector` | the library corrects its residual paths |
| Short monthly series (a few hundred points) | `freq="monthly"`, then usually `ResidualCorrector` | CPI classes: residual corrector won 29 of 52, the plain library 14 |
| The axis is not time (maturity, quantile, cross-section) | `BranchingForest(split_window=0, target_rank=d95)` | run `axis_screen(Y)` first |
| Known future effects (calendar, tax change) | `offset=` on fit and predict | as an offset it beats the same information as a feature |

`freq` is `"daily"`, `"weekly"`, `"monthly"`, `"hourly"`, `"halfhourly"` or `"minute"` and sets feature
windows, forest size and the split width. Other common keywords: `log=True` for strictly positive skewed series,
`trend=False` where there is no drift, `exog=DataFrame` for drivers, `local_linear=1.0` to interpolate inside
leaves (keep it only if it wins at h=1 on your dev period), `target="aggregate"` to forecast the H-step mean,
`calibrate="dispersion" | "pit" | False`, and any `BranchingForest` keyword to override.

## Scoring it properly

| Function | Use for |
|---|---|
| `score_bundle(B, truth)` | per-horizon CRPS, coverage, PIT of an equally weighted bundle |
| `energy_score(B, truth)` | the whole path at once: the only score here that sees dependence along the horizon |
| `score_weighted_bundle(P, W, truth)` | a folded bundle, whose paths are not equally likely |
| `walk_forward` + `summarise` | expanding-window evaluation against climatology, persistence and ridge |

**Use the energy score** whenever the paths matter. Per-slice CRPS cannot tell a bundle of real paths from one with
the same marginals and scrambled dependence: in `examples/any_axis.py` scrambling costs 10% on the energy score and
0.0% on CRPS. The calibration bug fixed in 0.21 lived in exactly that blind spot (FINDINGS.md, section 6).

## Diagnostics before you trust a forecast

| Check | How | What it means |
|---|---|---|
| Does it beat the benchmarks? | `summarise(walk_forward(...))` | if climatology or persistence wins, use them |
| Is the bundle real? | `m.effective_n(y)` | below about 30, a feature is acting as a clock and emptying the leaves |
| Which histories? | `m.analogues(y)` | the audit trail; implausible dates mean the features match the wrong thing |
| Is it calibrated? | `score_bundle(B, truth)["cov90"]` | near 0.90; collapse means empty leaves, inflation a misfit trend |
| Is a feature a clock? | `time_localised_features(X)` | variance concentrated in recent history empties leaves for recent queries |
| Unfamiliar state? | `Novelty().fit(X_train).score(X)` | high novelty and wide bundles both predict error (Spearman 0.3-0.56) |

## Regime shifts: when today is somewhere history has not been

The library matches today against past states and replays what followed. If today's level or volatility lies
outside the training range there are no true analogues, and every forecast from `Forecaster.predict`
then carries a `RegimeShiftWarning` with advice:

    notice: 1 of 1 forecast origin(s) start with volatility 2.52x the training median, but it has not persisted
    (under half of the last 28 steps). Usually a storm, spike or one-off: keep the plain library. ...

    REGIME SHIFT, persistent: ... volatility 0.49x the training median, and the condition has held for at least
    half of the last 168 steps. Switch recommended: a level-free state (level_free) with paths rescaled by
    today's volatility (ScaledLibrary, scale=local_volatility), volatility kept out of the state.

`m.shift_check(y, rows=...)` returns the per-origin table (level and volatility percentiles, flags, persistence)
with the advice in `.attrs["advice"]`; `screen()` reports the same for its dev window and the latest origin.
Silence it with `Forecaster(..., warn_shift=False)`.

The advice is advice, not an automatic switch, and the distinction between a flag and a persistent flag is
measured (research/shift, ten series):

| | ETTh1 | Bitcoin level | demand, Thames, wind, bike |
|---|---|---|---|
| shift-aware library always on | -28% | -21% | +1 to +6% worse |
| switched on every flag | -19% | -12% | +0.5 to +0.8% worse |
| switched only on persistent flags | -10% | -11% | 0.0 to +0.5% |

```python
from btforest import ScaledLibrary, level_free, local_volatility
sig = local_volatility(a, 168)                         # one week of hourly changes
Xlf, cols = level_free(X, a, train_rows)               # level-type columns relative to the current value
lib = ScaledLibrary(n_estimators=60).fit(Xlf[tr], Y[tr], Ys[tr], scale=sig[tr])
B = lib.predict(Xlf[te], sig[te], k=200)               # paths replayed at today's volatility
```

Rule: a quantity that can leave its historical range must rescale the paths, never describe the state. With
volatility as a state column the ETTh1 result swung from +8% to +133% with the window length.

## API at a glance

**High level** (`pipeline.py`, `volatility.py`): `Forecaster` with `fit`, `predict`, `fold`,
`forecast_frame`, `point_path`, `analogues`, `effective_n`, `targets`, `save`/`load`, and `branch=` for
paths that switch past future at every step (`"auto"` tests it on a holdout and reports on `.branch_report_`);
`VolatilityScaledForecaster` with `fit`, `predict`, `forecast_frame`, `volatility_frame`, `targets`.

**Low level** (`core.py`): `BranchingForest(H, split_window, sub_exponent, use_backbone, linear_cols,
n_estimators, min_samples_leaf, max_features, ridge_alpha, split_rank, target_rank)` with `fit(X, Y, Y_smooth,
offset)`, `predict`, `predict_fast`, `predict_branched`, `fold_bundle`, `predict_quantiles`, `predict_mean`,
`backbone_bundle`, `point_path`, `top_analogues`, `effective_n`, `weights`. Also `PathForest`, `make_paths`,
`split_paths`, `ResidualCorrector`, `PanelLibrary`.

**Design** (`features.py`): `build_features`, `causal_haar`, `seasonal_climatology`, `anchor_level`, `cadence`,
`future_index`. **Screens**: `screen`, `axis_screen`, `variance_ratio`. **Benchmarks**: `climatology_bundle`,
`persistence_bundle`, `ridge_bundle`. **Scoring**: `crps_ensemble`, `wcrps_ensemble`, `energy_score`,
`score_bundle`, `score_weighted_bundle`, `recalibrate`, `event_probability`, `pinball_crps`. **Regime**:
`Novelty`, `PersistenceGate`, `RollingRecalibrator`, `transition_matrix`, `regime_sequence_weights`.
**Regime shift** (`shift.py`): `ShiftCheck`, `ScaledLibrary`, `level_free`, `local_volatility`, `RegimeShiftWarning`.
**Data**: `demo_series` (synthetic; no published result was measured on it).

## Layout

    btforest/   the package (core, pipeline, features, scoring, evaluate, screen, volatility, regime, demo)
    examples/             five runnable scripts
    tests/                test_basic.py (behaviour), test_regressions.py (one test per bug fixed in 0.21)
    docs/                 architecture.png, decision_flow.png, fig_compare.png; docs/src draws the diagrams
    research/             experiment scripts and results; research/compare/ is the v0.20 comparison
    FINDINGS.md           what the research established, in one place
    COMPARISON.md         against seven other architectures, and how far their forecasts diverge
    RESEARCH_NOTES.md     the full record, release by release, including what failed
    CHANGELOG.md

## Known limits

- A path can only be re-served, never invented: a regime break (the 2020 lockdown, the 2022 heatwave) sits outside
  the bundle. The regime-shift check flags it and, for shifts in level or volatility, says what to do; a shape
  never seen before cannot be forecast by re-serving.
- The accuracy ceiling is the state description, not the model: learned analogue metrics, rotations of the state
  and generic driver blocks all failed under controls (FINDINGS.md, section 5). Problem-specific features are what
  has worked.
- Weight computation is O(n_query x n_train) per forest; fine to about 50k training rows. At sub-daily resolution use
  `fit(..., thin=, max_train_rows=)`.
- Fitting two 100-tree forests on 8k rows takes about 20 s on one core; `n_jobs=-1` parallelises the fit only.
- A folded bundle is weighted. Anything that assumes equally likely paths (`np.quantile`, `score_bundle`,
  `event_probability`) must be given the weights.
- The low-level API knows nothing about the calendar. Hand it day-of-week columns, as `daily_walkforward.py` does.

## Citing and licence

Up to 0.23 the package was called `trajectory_library` (main class `TrajectoryForecaster`). Both old names still
work in 0.24 and 0.25 with a deprecation warning and will be removed in 0.26.


MIT licence, copyright Alex Paton. The accompanying paper, "Branching Trajectory Forests: re-serving whole historical
futures on a linear spine, evaluated against published models", is in preparation; until it is posted, cite this repository and
version. The closest prior method is the distributional random forest (Cevid et al., JMLR 2022), which also
forecasts with forest-weighted training responses.
