Skip to content
Log inGet startedHugging FaceGitHub

Time-series forecasting

Forecasting

forecast predicts the next values of every series in a table, with a range of likely outcomes around each one.

This forecasts the next 28 days of Melbourne’s daily minimum temperature from ten years of history:

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") # 10 years of daily data: Date, Temp
yh = Client()
fc = yh.forecast(temps, h=28, time_col="Date", target_col="Temp")
print(fc.df.head(3).round(1))
print(fc.quantile_levels, fc.usage)
Output
unique_id Date q10 median q90
series_0 1991-01-01 11.6 13.7 16.5
series_0 1991-01-02 11.7 14.3 17.5
series_0 1991-01-03 11.9 14.5 17.9
[0.1, 0.5, 0.9] {'series': 1, 'requests': 1}

Parameters: Client.forecast

Each row is one future day: median is the most likely value, and q10 to q90 is an 80% interval (the actual should fall inside it 8 days out of 10). usage shows what the call used: credits for keys of an organization, series for keys without one (as here).

Argument Meaning
temps the table: one row per date
h=28 how many steps to forecast, at the series’ own frequency (here, days)
time_col="Date" the timestamp column, needed because it is not called ds
target_col="Temp" the column to forecast, needed because it is not called y

Every forecast is a set of quantiles: the 0.1 quantile is a value the actual falls below 10% of the time. Ask for the ones your decision needs:

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()
fc = yh.forecast(temps, h=28, time_col="Date", target_col="Temp", quantiles=[0.1, 0.25, 0.5, 0.75, 0.9])
print(fc.df.head(2).round(1))
print("interpolated:", fc.derived)
Output
unique_id Date q10 q25 median q75 q90
series_0 1991-01-01 11.5 12.6 13.6 14.6 15.8
series_0 1991-01-02 11.8 13.0 14.2 15.6 17.1
interpolated: ['q25', 'q75']

Parameters: Client.forecast

You pass You get
nothing q10, median, q90: an 80% interval
level=[50, 80, 95] central intervals by width in percent, under 100
quantiles=[0.1, 0.25, ...] any levels strictly between 0 and 1
quantiles="all" every level the model produces: 0.1, 0.2, …, 0.9

The model produces the levels 0.1, 0.2, …, 0.9 directly. Levels in between (like 0.25 above) are interpolated, and fc.derived lists them, so an interpolated value is never presented as a model output. Levels outside 0.1 to 0.9 are computed by the API (next section).

level=[50, 80] asks for central intervals by their width in percent, and fc.intervals() returns them as lower_ and upper_ columns next to the median. mean=True adds the mean as well:

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()
fc = yh.forecast(temps, h=28, time_col="Date", target_col="Temp", level=[50, 80], mean=True)
print(fc.intervals([50, 80]).head(3).round(1).to_string(index=False))
print("mean next to the median:", fc.df[["median", "mean"]].iloc[0].round(2).tolist())
print("derived (not direct model outputs):", fc.derived)
Output
unique_id Date median lower_50 upper_50 lower_80 upper_80
series_0 1991-01-01 13.6 12.6 14.6 11.5 15.8
series_0 1991-01-02 14.2 13.0 15.6 11.8 17.1
series_0 1991-01-03 14.4 13.2 16.0 12.0 17.5
mean next to the median: [13.61, 13.61]
derived (not direct model outputs): ['q25', 'q75', 'mean']

Parameters: Client.forecast, ForecastResult.intervals

  • lower_80 / upper_80 come from q10 / q90; lower_50 / upper_50 from q25 / q75.
  • fc.intervals(w) needs the quantiles of width w in the forecast; ask for them with level=[w].
  • q25, q75 and mean are listed in fc.derived: they are computed from the model’s quantiles, not produced by it.

For decisions about rare outcomes (a reserve margin, a safety stock), ask for wider intervals: level=[95, 99], or quantiles like 0.01 and 0.99:

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()
fc = yh.forecast(temps, h=14, time_col="Date", target_col="Temp", level=[80, 95, 99])
print(fc.intervals(95).head(3).round(1).to_string(index=False))
print(fc.intervals(99).head(3).round(1).to_string(index=False))
print("interpolated:", fc.derived)
Output
unique_id Date median lower_95 upper_95
series_0 1991-01-01 13.6 9.9 17.4
series_0 1991-01-02 14.1 10.1 19.2
series_0 1991-01-03 14.3 10.1 19.7
unique_id Date median lower_99 upper_99
series_0 1991-01-01 13.6 8.3 19.0
series_0 1991-01-02 14.1 8.3 21.3
series_0 1991-01-03 14.3 8.3 21.9
interpolated: []

Parameters: Client.forecast, ForecastResult.intervals

  • The API computes these levels from the model’s quantiles, with tails fitted to the outer levels, and calibrates them on the series’ own past: earlier windows of the history are forecast, and every level is adjusted so it held as often as it says there. With little history the adjustment is shrunk toward none.
  • They are not interpolated, so fc.derived stays empty.
  • A 99% interval is only as reliable as the history behind it: a year of daily data has a few dozen days beyond the 1% tails. Check it with evaluate before relying on it.

The median is the point forecast: half the outcomes fall below it, and it is what the benchmarks score. The mean is what you want when forecasts are added up, over days or over products: medians of skewed quantities do not sum to the median of the total, and the sum of means is the mean of the sum. mean=True computes it from the model’s quantiles (integrating the quantile curve, with exponential tails beyond the outermost levels). On a symmetric forecast the two match, as above.

fc.prob(above=x) or fc.prob(below=x) turns the forecast into the probability of crossing a limit at each step: a capacity, a stock level, a temperature threshold. This asks, night by night, how likely the minimum stays above 15 degrees:

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()
fc = yh.forecast(temps, h=14, time_col="Date", target_col="Temp", quantiles="all")
warm = fc.prob(above=15) # chance the night stays above 15 degrees, per day
print(warm.head(5).round(2).to_string(index=False))
print("expected nights above 15 degrees in the next 14:", round(warm["prob"].sum(), 1))
Output
unique_id Date prob
series_0 1991-01-01 0.18
series_0 1991-01-02 0.33
series_0 1991-01-03 0.38
series_0 1991-01-04 0.41
series_0 1991-01-05 0.42
expected nights above 15 degrees in the next 14: 5.8

Parameters: Client.forecast, ForecastResult.prob

  • The limit is one number, or one per row.
  • Summing the probabilities gives the expected number of steps over the limit: about 6 of the next 14 nights here.
  • quantiles="all" gives the finest answer, since every level the model produces is used. Beyond its outermost levels the tail is extrapolated, so probabilities under 10% or over 90% are estimates.

Quantiles describe each step on its own. Questions about the whole horizon (the total over a fortnight, the peak, how many days cross a limit, whether three days in a row do) need sample paths: possible futures, each a full trajectory. samples=1000 returns 1000 of them:

import numpy as np
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()
fc = yh.forecast(temps, h=14, time_col="Date", target_col="Temp", samples=1000, seed=0)
paths = fc.sample_paths() # one row per sample, one column per day
print(paths.shape)
warm = (paths > 15).sum(axis=1) # warm nights in each simulated fortnight
print("warm nights, 90% range:", np.quantile(warm, [0.05, 0.95]).tolist(), " mean:", round(warm.mean(), 1))
print("chance of 3 warm nights in a row:", round(np.mean([(np.convolve(p > 15, np.ones(3), "valid") == 3).any() for p in paths]), 2))
Output
(1000, 14)
warm nights, 90% range: [0.0, 12.0] mean: 5.8
chance of 3 warm nights in a row: 0.66

Parameters: Client.forecast, ForecastResult.sample_paths

  • fc.sample_paths() is an array with one row per path and one column per step (pass a series id for the others); fc.samples holds them all as a long table: id, time, sample, value.
  • Each step’s values follow the forecast’s quantiles; neighbouring steps move together, with a correlation estimated from the series’ own past forecasts (0.8 when the history is too short to tell), so a warm night makes the next one likelier to be warm too.
  • seed= makes the paths reproducible. Up to 1000 paths per series, and 2 million values per request in all.
  • The probability of any event comes from counting paths: here, three warm nights in a row in two fortnights out of three, which no single-step quantile can tell you.

history=True also returns what the model would have forecast from earlier points in the history, on the same settings. Put them next to what happened to see how forecasts behave on this series, without running a full backtest:

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()
fc = yh.forecast(temps, h=14, time_col="Date", target_col="Temp", history=True)
past = fc.history # what the model forecast from earlier cutoffs, next to what happened
print(past.columns.tolist())
print(past.head(3).round(1).to_string(index=False))
Output
['unique_id', 'cutoff', 'Date', 'q10', 'q20', 'q30', 'q40', 'median', 'q60', 'q70', 'q80', 'q90']
unique_id cutoff Date q10 q20 q30 q40 median q60 q70 q80 q90
series_0 1990-11-19 1990-11-20 9.2 9.9 10.5 10.9 11.2 11.7 12.3 12.9 13.9
series_0 1990-11-19 1990-11-21 9.8 10.7 11.2 11.8 12.1 12.7 13.4 13.9 15.1
series_0 1990-11-19 1990-11-22 10.1 10.9 11.4 12.1 12.4 13.0 13.7 14.4 15.7

Parameters: Client.forecast

fc.history has one block per earlier cutoff: the forecasts made with data up to cutoff, for the steps after it. For a scored backtest with baselines, use evaluate.

fc.to_wide() puts every series in its own column, one row per timestamp, the shape a spreadsheet or a dashboard expects. This forecasts the population of three countries five years ahead, from yearly figures:

import pandas as pd
from yhatlabs import Client
pop = pd.read_csv("https://raw.githubusercontent.com/datasets/population/main/data/population.csv")
pop = pop[pop["Country Code"].isin(["IND", "CHN", "USA"])] # one row per country and year
yh = Client()
fc = yh.forecast(pop, h=5, id_col="Country Code", time_col="Year", target_col="Value", freq="YS")
print((fc.to_wide() / 1e6).round(1)) # millions; one column per country
Output
Year CHN IND USA
2026 1403.5 1476.5 343.6
2027 1400.3 1489.0 345.5
2028 1396.9 1501.2 347.7
2029 1393.4 1512.8 349.8
2030 1390.0 1525.0 352.1

Parameters: Client.forecast, ForecastResult.to_wide

to_wide(value="q90") (or "mean", …) spreads another column. Here Year holds plain integers: they are read as steps of the series and the forecast continues them, with freq="YS" telling the model the data is yearly.

fc.plot(history=df) draws the median and every interval in the forecast as nested bands, after the end of the history (needs pip install "yhatlabs[plot]"):

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()
fc = yh.forecast(temps, h=60, time_col="Date", target_col="Temp", level=[50, 80])
fig = fc.plot(history=temps.tail(180))
fig.savefig("forecast.png", dpi=110)
print("saved forecast.png")
Output
saved forecast.png

Parameters: Client.forecast, ForecastResult.plot

60-day forecast of Melbourne minimum temperature with 50% and 80% bands after six months of history

target_col=["load", "price"] forecasts both columns of each series together. The results gain a target column.

preset="pro" (yhatlabs 0.2.2 and later) asks for a slower forecast that is slightly sharper on benchmarks; "fast" is the default. Start on fast: pro is worth it when a small gain in accuracy matters more than seconds. For a larger gain on your own data, see Tuning on your data.

A forecast goes up to 2,048 steps ahead. Forecast at the resolution you make decisions at: resample very fine data first (5-second readings to 1-minute averages, then h=180 for three hours). Raw high-frequency data forecasts worse and gives over-confident intervals, and a horizon in the thousands of steps is usually a sign the data is finer than the decision.

fc.df keeps your own id and time column names (unique_id / ds stay unique_id / ds, store / timestamp stay store / timestamp), followed by the quantile columns.

Inputs too large for one request are split and sent in parallel (max_concurrency= on the client, default 4). If some requests fail, on_error="warn" still returns the series that succeeded and lists the rest in fc.errors; the default, "raise", raises the first error. Spark, Dask, Ray and polars tables are accepted as well as pandas.

store=False on a call and it isn’t shown in your Logs (Data handling).

fc.df the forecast table
fc.to_long() one row per series, time and quantile (and the mean, when asked for)
fc.to_wide(value="median") one column per series
fc.intervals(80) lower_80 / upper_80 next to the median
fc.samples, fc.sample_paths(id) sample paths, with samples=N
fc.history forecasts from earlier cutoffs, with history=True
fc.prob(above=x), fc.prob(below=x) the chance of crossing a limit at each step
fc.plot(history=df) the median and nested interval bands after the history (needs pip install "yhatlabs[plot]")
fc.quantile_levels, fc.derived the levels returned, and which were interpolated
fc.provenance model, settings, request ids and a fingerprint of the input
fc.timing, fc.usage seconds taken, and what the call used (credits, or series for keys without an organization; added up over split requests)
fc.to_polars() the table as polars