# Backtesting

> Measure accuracy and calibration on your own history, compare with baselines and with the forecast you use today.

A backtest answers "how good would these forecasts have been?" before you rely on them. It cuts each series at several points
near its end, forecasts from each cut using only the data before it, and scores the forecasts against what happened.

## Run a backtest

This replays four 28-day forecasts over the last 112 days of the Melbourne temperatures:

```python
import pandas as pd
from yhatlabs import Client

url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/"
temps = pd.read_csv(url + "daily-min-temperatures.csv")

yh = Client()
ev = yh.evaluate(temps, h=28, windows=4, time_col="Date", target_col="Temp")
print(ev.summary[["mase", "wql", "coverage@0.8", "skill_mase", "skill_wql"]].round(3))
```

Output:

```
             mase    wql  coverage@0.8  skill_mase  skill_wql
model                                                            
chakra-ts       0.971  0.141         0.786       0.309      0.486
seasonal_naive  1.535  0.275         0.955       0.000      0.000
```

```bash
curl -sO https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-min-temperatures.csv
yhatlabs evaluate daily-min-temperatures.csv --h 28 --windows 4 --time-col Date --target-col Temp 2>&1
```

Output:

```
yhatlabs: warning: Filled 2 missing timestamps with gaps (sent as missing values).
              mase     sql     wql     mae    rmse  coverage@0.8  skill_mase  skill_sql  skill_wql  skill_mae  skill_rmse
model                                                                                                                        
chakra-ts       0.9711  0.7899  0.1415  2.0716  2.7788        0.7857      0.3086     0.4858     0.4858     0.3086      0.2341
seasonal_naive  1.5349  1.5499  0.2750  3.2759  3.8653        0.9554      0.0000     0.0000     0.0000     0.0000      0.0000
```

Each row is a model. `seasonal_naive` is a simple baseline, computed locally: it repeats the last week on daily data and the
last year on weekly data (the last value when the history is shorter than two seasons):

| Column | Meaning |
|---|---|
| `mase` | average error, scaled by how hard the series is (below 1 beats a naive guess) |
| `wql` | quantile loss: how good the whole range is, not just the median |
| `coverage@0.8` | the share of actuals inside the 80% interval (ideally 0.8) |
| `skill_<metric>` | improvement over the baseline: 0.33 means a third less error; above 0 beats it |

Here ChakraTS has nearly a third less error than the baseline, and half the quantile loss.

| Argument | Meaning |
|---|---|
| `windows=4` | how many cutoffs |
| `step` | steps between cutoffs; default `h`, so the windows don't overlap |
| `baselines` | `("seasonal_naive",)` by default; `"naive"` (repeat the last value) too |
| `known=`, `calendar=` | covariates, read from the table itself |

## Compare with your current forecast

The question that usually matters is "is it better than what we use today?". `compare=` scores your own forecasts on the same
windows. Here the "current" forecast is simply last year's value on the same day:

```python
import pandas as pd
from yhatlabs import Client

url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/"
temps = pd.read_csv(url + "daily-min-temperatures.csv")
temps["Date"] = pd.to_datetime(temps["Date"])

# your current forecast for the last 112 days; here, simply "same as a year ago"
current = temps.tail(112)[["Date"]].copy()
current["forecast"] = temps["Temp"].shift(365).tail(112).to_numpy()

yh = Client()
ev = yh.evaluate(temps, h=28, windows=4, time_col="Date", target_col="Temp", compare={"current": current})
print(ev.summary[["mase", "mae", "skill_mase"]].round(3))
```

Output:

```
             mase    mae  skill_mase
model                                   
chakra-ts       0.971  2.072       0.309
seasonal_naive  1.535  3.276       0.000
current         1.441  3.075      -0.020
```

`compare` takes a table per forecast: the time column (plus the id column for several series), and either quantile columns
(`median`, `q10`, ...) or a single `forecast` column. Only the windows it covers are scored.

## Check the uncertainty

An 80% interval is only useful if it really holds about 80% of the actuals. `ev.calibration` measures that:

```python
import pandas as pd
from yhatlabs import Client

url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/"
temps = pd.read_csv(url + "daily-min-temperatures.csv")

yh = Client()
ev = yh.evaluate(temps, h=28, windows=4, time_col="Date", target_col="Temp")
cal = ev.calibration
print(cal[cal["kind"] == "interval"].round(3).to_string(index=False))
```

Output:

```
     model     kind  nominal  observed    gap   n
 chakra-ts interval      0.8     0.786 -0.014 112
 chakra-ts interval      0.6     0.634  0.034 112
 chakra-ts interval      0.4     0.438  0.037 112
 chakra-ts interval      0.2     0.286  0.086 112
seasonal_naive interval      0.8     0.955  0.155 112
seasonal_naive interval      0.6     0.902  0.302 112
seasonal_naive interval      0.4     0.688  0.288 112
seasonal_naive interval      0.2     0.438  0.238 112
```

- `kind="interval"`: the share of actuals inside each central interval. `nominal` is what it should be, `observed` what it was.
- `gap` is observed minus nominal. Negative means the intervals were too narrow; positive, too wide.
- Here ChakraTS's 80% interval held 79% of the actuals, close to what it says. The baseline's held 96% because it is much wider.
- `kind="below"` rows (not shown) give the share of actuals below each quantile; `ev.plot_calibration()` draws them (needs `[plot]`).

`ev.scores` has one row per model, series and window; `ev.forecasts` has every window's forecast next to the actual values.

## Plot the backtest

`ev.plot()` draws the actuals across the scored windows, each window's forecast with its intervals, and a dotted line at each
cutoff (needs `[plot]`):

```python
import pandas as pd
from yhatlabs import Client

url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/"
temps = pd.read_csv(url + "daily-min-temperatures.csv")
temps["Date"] = pd.to_datetime(temps["Date"])

yh = Client()
ev = yh.evaluate(temps, h=28, windows=3, time_col="Date", target_col="Temp")
ev.plot().savefig("backtest.png", dpi=110)
print("saved backtest.png")
```

Output:

```
saved backtest.png
```

![Three 28-day backtest windows: actual temperatures against each window's median and interval bands](https://yhatlabs.com/models/docs/img/ts_plot_backtest-backtest.png)
