Examples

Install with pip install skaters. The Python streaming recipes below use the imports and observations from the first example.

  1. A first forecast
  2. Several steps ahead
  3. Series that are always positive
  4. Units and scale
  5. Is it calibrated?
  6. Spotting anomalies
  7. Mean-reverting spreads
  8. Your own transform
  9. In the browser

A first forecast

A skater is a function f(y, state) -> (dists, state). Start with state = None and pass back whatever it returns. dists[0] is the predictive distribution for the next observation.

import math
from skaters import laplace

observations = [20.0 + math.sin(t / 5) for t in range(120)]
y_next = 20.0 + math.sin(len(observations) / 5)

f = laplace()
state = None
for y in observations:
    dists, state = f(y, state)

d = dists[0]
d.mean                  # point forecast for the next value
d.std                   # its uncertainty
d.quantile(0.05), d.quantile(0.95)   # a 90% interval
d.logpdf(y_next)        # log score, once y_next arrives

Score a forecast only against values that arrive after it was issued. Keep the previous dists around and evaluate it when the next y comes in.

Several steps ahead

Ask for k horizons and you get k distributions back, one for each step.

f = laplace(k=12)
state = None
for y in observations:
    dists, state = f(y, state)

dists[0]      # one step ahead
dists[11]     # twelve steps ahead
[d.quantile(0.9) for d in dists]   # the upper edge of the fan

Series that are always positive

If you know a series is strictly positive, you can encode that in the forecast. flesaker runs laplace on the log of the series and maps the forecast back through the exponential, giving a positive, possibly skewed predictive. It is named after Bjorn Flesaker, whose positive-interest framework with Hughston builds the guarantee that rates stay positive into the model. It is experimental: an example composition that may change or move into examples/; the pieces underneath (laplace, log_transform, conjugate) are the stable surface.

from skaters import flesaker

f = flesaker(k=5)
state = None
for y in observations:
    dists, state = f(y, state)

dists[4].quantile(0.01)    # always > 0

flesaker(lower=-3.0)         # any floor
flesaker(upper=1.0)          # a ceiling, with support on (-infinity, 1)

On a synthetic rate that dips toward zero, plain laplace put up to 33% of its probability below zero; flesaker put none there (the series is generated on the log scale, so the comparison favours flesaker by construction). Every observation must lie strictly inside the bound, so a series with exact zeros needs the floor set a little below zero. See the flesaker page and its live demo. The full comparison is examples/positive_series.py.

Units and scale

Rescaling a series can improve laplace. Its transforms carry constants in absolute units (a variance intercept, a ridge, division floors), tuned for series whose values and steps sit roughly between 10-3 and 103. The synthetic growth series below has a held-out value of 29.00. The medians are both reported in the original units.

input unitslaplace medianflesaker median
multiplied by 10203.63 × 10729.01
original29.0129.01
growth = [16.0 * math.exp(0.003 * t + 0.015 * math.sin(t / 7))
          for t in range(200)]

for scale in (1e20, 1.0):
    medians = []
    for make_skater in (laplace, flesaker):
        f, state = make_skater(), None
        for y in growth[:-1]:
            dists, state = f(scale * y, state)
        medians.append(dists[0].quantile(0.5) / scale)
    print(scale, medians, growth[-1])

Pick units the way you would write them down, and keep values and steps inside about 10-3 to 106. For a series that spans many orders of magnitude, flesaker works in the log coordinate, where changing units adds a constant to the observations. More on the scope page.

Is it calibrated?

laplace keeps score for you. When an observation arrives, state["pit"][0] holds where it fell in the forecast made one step earlier, as a probability between 0 and 1. If the forecasts are calibrated these are uniform, so a 90% interval should contain about 90% of outcomes.

f = laplace()
state, pits = None, []
for y in observations:
    dists, state = f(y, state)
    if state["pit"][0] is not None:
        pits.append(state["pit"][0])

inside = sum(0.05 <= u <= 0.95 for u in pits) / len(pits)
print(f"{inside:.1%} of outcomes inside the 90% interval")

state["pit"][h-1] does the same for the h-step forecast.

Spotting anomalies

state["z"][0] is the same surprise on the standard normal scale. Values beyond 4 are rare under a calibrated forecast, so they make a simple alarm.

f = laplace()
state = None
for t, y in enumerate(observations):
    dists, state = f(y, state)
    z = state["z"][0]
    if z is not None and abs(z) > 4:
        print(f"t={t}: surprise z={z:.1f}")

For several horizons at once, skaters.mahalanobis combines the surprises into one score.

Mean-reverting spreads

If you know a series reverts to its mean (a pairs-trading spread, an interest-rate differential), say so with a transform. The building blocks compose: a transform changes the coordinates, a skater forecasts in them, and conjugate maps the forecast back.

from skaters import conjugate, leaf, ou_transform

f = conjugate(leaf(k=10), ou_transform(kappa=0.1), k=10)

laplace(k>1) already includes this in its pool, so reach for it only when you want the specialist alone.

Your own transform

A transform is a pair: forward maps one observation, and inverse_k maps the list of forecasts back. Here is one that lets a skater work in thousands.

from skaters import Dist, conjugate, ema

def in_thousands():
    def forward(y, state):
        return y / 1000.0, state or {}

    def inverse_k(dists, state):
        return [Dist([(w, 1000.0 * m, 1000.0 * s) for w, m, s in d.components])
                for d in dists]

    return forward, inverse_k

f = conjugate(ema(alpha=0.1, k=1), in_thousands(), k=1)

Dist is a Gaussian mixture of (weight, mean, std) components. laplace returns a richer distribution with fitted tails, so a transform meant to wrap laplace should map quantiles, as log_transform does. The methodology guide lists every built-in transform.

In the browser

The same library runs as plain JavaScript with no install. Rust, R and Julia ports are on the languages page.

<script type="module">
  import { laplace } from "https://skaters.microprediction.org/js/skaters/index.mjs";
  const observations = Array.from({ length: 120 }, (_, t) => 20 + Math.sin(t / 5));
  const f = laplace(1);
  let state = null;
  for (const y of observations) {
    const [dists, st] = f(y, state); state = st;
    console.log(dists[0].mean, dists[0].quantile(0.95));
  }
</script>

The playground runs it live on series you draw. More scripts are in the repository's examples/ folder.