Dataset

Polars sports backtesting with Parquet

Short answer: the SportsDataHQ packages are CSV and Parquet files that Polars scans lazily, and the odds files carry minutes_before_start on every row, which is what a backtest needs to avoid look-ahead. This page shows a lazy scan across the Parquet packages and a walk-forward skeleton that scores a model against the market's closing line. We ran every snippet on the free samples.

Why Polars, and why lazy

A sports backtest is a pipeline: scan the games, join the market's numbers, build features that only use the past, fit, predict, score. In a pandas-style workflow each step materializes a frame. In Polars you can describe the whole pipeline as a lazy query, and the engine decides what to read.

That matters here for two reasons. The files are wide. An NFL play table has 155 columns, and the NHL play-by-play has 46. A question about closing totals needs three of the 14 odds columns, and a lazy scan reads three. And the files are many. A package stores each large table as one file per season, so a ten-season question is a glob over ten files. scan_parquet takes the glob and treats them as one table.

Parquet also carries types. A date is a date, an id is a string and a price is an integer, with no parsing step and no guessing from the first thousand rows. CSV needs try_parse_dates and care with ids, as we show in a moment.

This is market history, not advice. The closing line is a benchmark for your model's error, not a recommendation.

What you scan

Every odds package holds a games table and a table of odds by book and capture. History tiers add plays and player lines. Complete tiers add graded player props and the full line history. The packages page lists them, and the DuckDB roundup has a table of all 20 with the page that covers each.

The paid files for the large tables are Parquet. In the free samples only the NHL ships Parquet, and it ships both formats side by side, so we use it for the Parquet examples. Everything else in the samples is CSV, which Polars scans lazily as well with scan_csv.

Package familyParquet in the paid filesIn the free sample
NHL History, History + Odds, CompleteEvery table, with CSV beside itParquet and CSV
NFL, NBA, college basketballLarge tables, one file per seasonCSV
NBA and NFL line history, NBA playsParquet onlyCSV
MLB Odds, College football OddsOne file per season for large tablesCSV

The NHL sample is laid out as history/package-a/ for History and history/package-b/ for History + Odds, with a manifest, a data dictionary and checksums in history/. In package-b the odds tables are odds_open_close, odds_snapshots and odds_coverage_by_season_book. There is no consensus file for the NHL, so you compute your own closing line from the books, as below. The NHL odds file calls the book column sportsbook, where the other leagues call it bookmaker.

Step 1: a lazy scan and a closing line

This scans the games and the odds, takes the median closing total across books for each game, and joins it to the games with a left join, so a game with no closing row stays in. Nothing is read until collect.

import polars as pl

P = "nhl-history-odds/history/package-b"
odds = pl.scan_parquet(f"{P}/odds_open_close_*.parquet")   # one file per season, as one table
games = pl.scan_parquet(f"{P}/games.parquet")

close = (
    odds.filter(pl.col("snapshot_type") == "closing")
    .group_by("game_id")
    .agg(
        pl.col("total").median().alias("close_total"),
        pl.col("sportsbook").n_unique().alias("books"),
    )
)

table = (
    games.join(close, on="game_id", how="left")
    .with_columns((pl.col("home_score") + pl.col("away_score")).alias("goals"))
    .sort("scheduled_start")
)
print(table.select("game_id", "scheduled_start", "goals", "close_total", "books").collect())

On the sample it returns three games. Game 2025030416 on June 15, 2026 had 3 goals against a closing total of 6.0, 2026020461 had 3 against 6.0, and 2026020463 had 11 against 6.5. Each has 8 books. Print table.explain() to see the plan, and for the odds scan alone it reads PROJECT 3/14 COLUMNS with the snapshot_type == "closing" filter pushed into the scan, which is what lazy buys you.

Use .collect(engine="streaming") for a scan too big for memory. We ran it on the CSV example below.

Step 2: scan CSV the same way

The college football and MLB odds samples are CSV. Polars scans them lazily too. This picks each book's last snapshot as the close, joins it to the opening row and averages across books.

odds = pl.scan_csv("ncaaf-odds/game_odds.csv", try_parse_dates=True)

last = (
    odds.filter(pl.col("snapshot_type") == "snapshot").sort("captured_at")
    .group_by("game_id", "bookmaker")
    .agg(pl.col("spread_home").last().alias("close_spread"), pl.col("total").last().alias("close_total"))
)
opening = odds.filter(pl.col("snapshot_type") == "opening").select(
    "game_id", "bookmaker", pl.col("spread_home").alias("open_spread"), pl.col("total").alias("open_total"))

out = (
    last.join(opening, on=["game_id", "bookmaker"]).group_by("game_id")
    .agg(pl.len().alias("books"), pl.col("open_spread").mean().round(1), pl.col("close_spread").mean().round(1),
         pl.col("open_total").mean().round(1), pl.col("close_total").mean().round(1))
    .sort("game_id").collect(engine="streaming")
)
print(out)

The first game, 401869533, comes out at 8 books, an opening mean spread of -2.5 and a last-snapshot mean of -1.2. The sample has no closing rows, so the last snapshot is the close.

To put several leagues in one frame, scan each file and pl.concat them. Cast game_id first, since it is text for the NFL and numeric for college football and Polars refuses a concat with mismatched types. We hit that error on the first try and fixed it by passing schema_overrides={"game_id": pl.Utf8} to each scan_csv.

files = {"nfl": "nfl-history-odds", "nba": "nba-history-odds", "ncaam": "ncaam-history-odds",
         "mlb": "mlb-odds", "ncaaf": "ncaaf-odds"}
all_odds = pl.concat([
    pl.scan_csv(f"{d}/game_odds.csv", schema_overrides={"game_id": pl.Utf8})
      .select("game_id", "bookmaker", "snapshot_type", "minutes_before_start")
      .with_columns(pl.lit(k).alias("league"))
    for k, d in files.items()
])
print(all_odds.group_by("league").agg(pl.col("game_id").n_unique().alias("games"), pl.len().alias("rows")).sort("league").collect())

Step 3: a walk-forward skeleton

Walk-forward testing trains on the past and predicts the next game, then moves the window forward. It is the honest way to test a sports model, because a random split lets a model see games that came after the one it is predicting.

Two pieces do the work. First, an expanding feature built with shift(1), so a game's feature never includes its own result. Second, a loop that fits on df[:i] and predicts row i, with an assert that the training window ends before the test game starts.

feat = table.with_columns(
    (pl.col("goals").cum_sum().shift(1) / pl.int_range(pl.len())).alias("prior_mean_goals")
)

def walk_forward(df: pl.DataFrame, min_train: int = 1) -> pl.DataFrame:
    out = []
    for i in range(min_train, df.height):
        train, test = df[:i], df[i : i + 1]
        assert train["scheduled_start"].max() <= test["scheduled_start"].min()   # no look-ahead
        pred = train["goals"].mean()                                              # replace with your model
        out.append(
            test.select("game_id", "goals", "close_total").with_columns(
                pl.lit(pred).alias("model_total"),
                (pl.lit(pred) - pl.col("goals")).abs().alias("model_abs_err"),
                (pl.col("close_total") - pl.col("goals")).abs().alias("market_abs_err"),
            )
        )
    return pl.concat(out)

res = walk_forward(feat.collect())
print(res)
print(res.select(pl.col("model_abs_err").mean(), pl.col("market_abs_err").mean()))

On the three-game sample this makes two folds. The model, a running mean of goals, predicts 3.0 for both. The errors are 0.0 and 8.0 for the model and 3.0 and 4.5 for the market, a mean of 4.0 against 3.75. That is two games, and it means nothing about either method. It shows the skeleton runs end to end. The second fold is a game with 11 goals, which no total predicts.

Replace the pred line with your fit, and the df[:i] slice with a weekly or monthly block for a real sample. Keep the assert. It is a cheap guard against the most common backtest bug.

What the columns mean in practice

  • `minutes_before_start` is the clock for look-ahead control. Filter to rows at least 60 minutes before the start and you have a price your model could have seen before a decision, whatever the true close was.
  • `snapshot_type` is opening, closing or snapshot. The NHL sample has opening and closing rows, and the college football sample has no closing rows. Check the counts before you filter.
  • `captured_at` can be blank. Opening rows often have no capture time. Unknown values are blank, never 0, so Polars reads them as null, and mean skips them.
  • The close is a median across books here. The NHL has no consensus file, so the median is our choice. A mean, or one fixed book, gives different numbers. Pick one and keep it.
  • Totals move in half steps. A 6.0 total can push, and a 6.5 cannot. Score error in goals, and handle pushes explicitly if you grade over and under.
  • Season files carry a season string. The NHL files read 20252026. A glob over them is one table, and filename or the season column tells you where a row came from.

Reading the rows

Sort by the start time, not the date, because games finish after midnight UTC. Join on game_id with a left join from the games table, so a game with no odds stays visible as a null and not as a missing row. Count games, not rows, because each game has many book and capture rows. Hold out whole seasons for a last check, and never tune on them.

Book counts change by season. A model trained on years with 16 books and tested on years with 6 is tested on a different market. Add books as a column and look at it before you pool.

When not to use this

  • You want a ready backtest result. This is a skeleton, and the sample has three games.
  • You want live data. Odds are pregame only, and the files refresh monthly for plans from Pro up.
  • You want profit curves. Nothing here computes stakes or returns, and we do not provide advice.
  • You want to resell the files. The licence allows internal and commercial use and publishing your own derived statistics, not redistribution of the raw files.
  • You have data that fits in a spreadsheet. Then Polars is more than you need.
  • You want soccer Parquet. Soccer is available on request and served by API for now.

Who uses this

Modelers who test a team rating, a total or a win-probability model against the market's number, and need to be sure the test did not peek. Others build feature stores from play-by-play and join the market on top. Polars suits them because the pipeline is one lazy query that you can read top to bottom.

Free samples first

The NHL History + Odds sample, sportsdatahq.com/samples/data-packages/nhl-history-odds-sample.zip, holds both Parquet and CSV. Run Step 1 on it before you buy. The data packages page has prices, the licence and the refund rule.

Get a free key Or download whole seasons as Parquet

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