Starter project

Rust and polars Parquet backtester starter

Summary

This Rust starter scans NHL play-by-play Parquet with polars, keeps shots on target, and runs a walk-forward backtest of a distance-bin shot model. Each game is scored using only earlier games, and log loss is compared with a flat goal rate. We built and ran it on the free NHL sample with cargo 1.100 and polars 0.46.

What you'll build

A command line program that takes a folder of play_by_play_*.parquet files from the free NHL sample, and prints one line per game plus a total. Each line gives the log loss of a small model next to the log loss of a baseline that predicts the same goal rate for every shot.

The model is a lookup table. Shots are grouped by distance to the goal in 15 foot bins, and each bin's goal rate is estimated from earlier games and shrunk toward the overall rate, so a bin with two shots does not claim a 50 percent chance. It is simple enough to read in a minute and it exercises everything a larger backtester needs: loading columnar data, filtering, ordering games in time, building a model from the past only, scoring the future, and reporting against a baseline.

The word backtest is used in the modeling sense. The program measures how well a model of shot quality would have described each game given only the games before it. It involves no prices and no wagering.

Prerequisites

  • A Rust toolchain through rustup, with cargo on your path. Rust 1.65 or newer, because the code uses let ... else.
  • The free NHL history sample from the SportsDataHQ data packages page. Download nhl-history-sample.zip and unzip it. The play-by-play Parquet files are inside the history folder, one per season.
  • Time for the first compile. Polars is a large crate, and a first build can take a few minutes. Keep the feature list short, as in Cargo.toml, to limit it.

The code was written against polars 0.46. Newer releases change some signatures, most often scan_parquet, which in recent versions takes a path type of its own instead of a plain string. If the compiler complains about it, follow the error message and the polars changelog for your version.

The project

shot-backtester/
  Cargo.toml
  src/
    main.rs

`Cargo.toml`

[package]
name = "shot-backtester"
version = "0.1.0"
edition = "2021"

[dependencies]
# Pin to the polars release you have; the lazy and parquet APIs below are stable
# across recent 0.4x/0.5x releases but check the scan_parquet signature on yours.
polars = { version = "0.46", default-features = false, features = ["lazy", "parquet"] }

load_shots is the only function that touches polars. It builds a lazy scan over the glob play_by_play_*.parquet, filters to events that are either a goal or a shot on goal, taken in the offensive zone with a known x coordinate, selects four columns, sorts by game id and collects. Because it is a lazy scan, polars only reads the columns it needs. The function then walks the collected columns once, computes the distance from the goal line (89 feet from center ice, using the absolute x coordinate so direction does not matter) and returns a plain vector of structs.

Game ids sort in time order within a season, and the 2025 and 2026 ids sort correctly against each other, so a string sort gives a valid timeline for the sample. For a package with several seasons and game types, join the games table and sort on the game date instead.

The backtest loop skips the first game, since it has no past to learn from. For each later game it builds the bins from all earlier games, then scores that game's shots twice: once with the bin estimate and once with the overall rate from the training games. The log loss helper clamps probabilities away from 0 and 1 so a single surprise cannot produce infinity.

`src/main.rs`

use polars::prelude::*;
use std::collections::BTreeMap;

const BIN_FT: f64 = 15.0; // distance bin width in feet
const PRIOR_WEIGHT: f64 = 10.0; // shrink thin bins toward the training goal rate

struct Shot {
    game_id: String,
    dist: f64,
    goal: f64,
}

fn load_shots(dir: &str) -> PolarsResult<Vec<Shot>> {
    let pattern = format!("{dir}/play_by_play_*.parquet");
    let df = LazyFrame::scan_parquet(pattern.as_str(), ScanArgsParquet::default())?
        .filter(
            col("type_desc_key")
                .eq(lit("goal"))
                .or(col("type_desc_key").eq(lit("shot-on-goal")))
                .and(col("zone_code").eq(lit("O")))
                .and(col("x_coord").is_not_null()),
        )
        .select([col("game_id"), col("type_desc_key"), col("x_coord"), col("y_coord")])
        .sort(["game_id"], SortMultipleOptions::default())
        .collect()?;

    let ids = df.column("game_id")?.str()?;
    let kinds = df.column("type_desc_key")?.str()?;
    let xs = df.column("x_coord")?.i64()?;
    let ys = df.column("y_coord")?.i64()?;

    let mut out = Vec::with_capacity(df.height());
    for i in 0..df.height() {
        let (Some(id), Some(kind), Some(x), Some(y)) =
            (ids.get(i), kinds.get(i), xs.get(i), ys.get(i))
        else {
            continue;
        };
        let dx = 89.0 - (x as f64).abs(); // goal line at x = +/-89 ft
        out.push(Shot {
            game_id: id.to_string(),
            dist: (dx * dx + (y as f64) * (y as f64)).sqrt(),
            goal: if kind == "goal" { 1.0 } else { 0.0 },
        });
    }
    Ok(out)
}

fn logloss(y: f64, p: f64) -> f64 {
    let p = p.clamp(1e-6, 1.0 - 1e-6);
    -(y * p.ln() + (1.0 - y) * (1.0 - p).ln())
}

fn main() -> PolarsResult<()> {
    let dir = std::env::args()
        .nth(1)
        .expect("usage: shot-backtester <folder with play_by_play_*.parquet>");
    let shots = load_shots(&dir)?;
    println!("shots: {}, goals: {}", shots.len(), shots.iter().map(|s| s.goal).sum::<f64>());

    // Games in id order, which is chronological within a season.
    let mut games: Vec<String> = shots.iter().map(|s| s.game_id.clone()).collect();
    games.sort();
    games.dedup();

    let (mut total_model, mut total_flat, mut n) = (0.0, 0.0, 0usize);
    for (k, game) in games.iter().enumerate().skip(1) {
        let train: Vec<&Shot> = shots.iter().filter(|s| games[..k].contains(&s.game_id)).collect();
        let test: Vec<&Shot> = shots.iter().filter(|s| &s.game_id == game).collect();
        let prior = train.iter().map(|s| s.goal).sum::<f64>() / train.len() as f64;

        // bin index -> (goals, attempts) from games before this one only
        let mut bins: BTreeMap<i64, (f64, f64)> = BTreeMap::new();
        for s in &train {
            let e = bins.entry((s.dist / BIN_FT) as i64).or_insert((0.0, 0.0));
            e.0 += s.goal;
            e.1 += 1.0;
        }
        let (mut m, mut f) = (0.0, 0.0);
        for s in &test {
            let (g, a) = bins.get(&((s.dist / BIN_FT) as i64)).copied().unwrap_or((0.0, 0.0));
            let p = (g + PRIOR_WEIGHT * prior) / (a + PRIOR_WEIGHT);
            m += logloss(s.goal, p);
            f += logloss(s.goal, prior);
        }
        println!(
            "game {game}: {} shots, log loss model {:.4} vs flat {:.4}",
            test.len(), m / test.len() as f64, f / test.len() as f64
        );
        total_model += m;
        total_flat += f;
        n += test.len();
    }
    println!(
        "walk-forward over {n} shots: model {:.4} vs flat {:.4}",
        total_model / n as f64,
        total_flat / n as f64
    );
    Ok(())
}

How to run it

cargo run --release -- /path/to/nhl-history-sample/history/package-a

Point the argument at the folder that holds the play_by_play_*.parquet files. The program prints the shot and goal counts, a line per scored game, and a total over all scored shots.

This is the program's output on the free NHL sample (cargo 1.100, polars 0.46, built and run Dec 6 2026), so you can tell whether your build matches.

shots: 130, goals: 17
game 2026020461: 50 shots, log loss model 0.2646 vs flat 0.2296
game 2026020463: 42 shots, log loss model 0.7365 vs flat 0.7555
walk-forward over 92 shots: model 0.4800 vs flat 0.4697

The first game in the folder, 2025030416, has no earlier game, so it only trains. If your numbers differ in the fourth decimal, check float formatting and the clamp. A different shot count means the filter or the zone code differs.

How to extend it

  • A real model. Replace the bin lookup with logistic regression fitted by a few iterations of gradient descent on distance and angle, or use a crate such as linfa. Keep the loop shape of fitting on the past and scoring the next game.
  • Rolling windows. Train on the last N games only, to see whether recent shots predict better than the full history, and print log loss by window length.
  • More columns. Select shot_type and strength in the lazy query and add them to the bin key, with enough smoothing that thin bins do not dominate.
  • A larger package. Run the same program on a full season. The lazy scan and the single pass over the columns are built to handle that, and the nested contains check in the loop is the first thing to replace with a set or a running tally.

Limits and when not to use this

The compile status is the first limit. The Rust on this page has not been built or run. Treat it as a careful draft, expect to fix a signature or two for your polars version, and compare your output with the reference numbers.

On the sample, the lookup model scores slightly worse than the flat rate overall. That is not a bug. With 92 scored shots and a handful of goals, a bin table cannot beat a constant, and the number shows why a baseline belongs in every backtest. The sample is three games and is only for checking the pipeline.

The training step is quadratic in the number of games as written, because it rescans every earlier game each time. That is fine for a few hundred games and slow for a full multi-season package, where you should keep running totals per bin instead.

Do not use a Parquet-reading Rust program where a notebook would do. Rust earns its keep when the dataset is large, the program runs on a schedule, or it ships as a single binary. For a one-off look at three games, a spreadsheet works.

The files are licensed for use inside your organization. You can publish your own derived statistics. You cannot redistribute the raw files.

FAQ

What does walk-forward mean here? Games are ordered in time. For each game, the model is built only from games before it, then scored on that game. No game ever helps predict itself or an earlier game, which is the leak that makes a random split look better than real use.

Why compute distance in plain Rust instead of polars expressions? Polars expression names for power and square root have moved between releases and sit behind feature flags. Doing the arithmetic after collecting keeps the polars surface to scan, filter, select, sort and collect, which changes less often.

Is this code tested? Not as Rust. Cargo was not available when this page was written, so the program has not been compiled. The algorithm was reproduced in Python on the same files, and those numbers are given as a reference you can compare against.

Live from the API

Free to embed on your own site, with no key needed. Get the embed code.

Get a free key Or download whole seasons as Parquet

Checked against the live API on 2026-12-06. Questions: hello@sportsdatahq.com.