Starter project

R and Arrow Parquet shot model starter

Summary

This starter reads the free NHL play-by-play Parquet sample with the R arrow package, turns shot coordinates into distance and angle, and fits a logistic regression for the chance a shot on target becomes a goal. It then checks the model with leave-one-game-out log loss against a flat goal rate.

What you'll build

A single script, shot_model.R, that does five things in order:

  1. Downloads the free NHL history sample zip from SportsDataHQ and extracts it into a temporary folder.
  2. Reads the play-by-play Parquet files with read_parquet, selecting only six columns.
  3. Keeps shots that reached the net in the offensive zone and computes two features from the rink coordinates: distance to the goal and the angle off the goal line.
  4. Fits glm(goal ~ dist + angle, family = binomial()) and prints the coefficient table.
  5. Scores the model with leave-one-game-out log loss and compares it with a baseline that predicts the same goal rate for every shot.

This is the smallest honest version of an expected goals model. It has no shooter skill, no rebound or rush flags and no goalie. That is deliberate. Keep a first model short enough that you can see every number it uses, and always include the evaluation step.

Prerequisites

  • R 4.2 or newer and the arrow package. On macOS, Linux and Windows, install.packages("arrow") normally installs a prebuilt binary. Some source-built R installs need NOT_CRAN=true first so the build downloads the Arrow C++ libraries.
  • Internet access for the sample download, which is a small zip. You can instead download it once from the data packages page and point zip_url at a local file:// path.
  • Nothing else. The script uses base R for the model, so there is no tidyverse install.

The project

nhl-shot-model/
  shot_model.R

The sample zip extracts to a folder tree with README.md, a manifest, checksums and a history/ folder. Inside are tables for games, play-by-play, shifts, skater and goalie game lines, rosters and starting goalies. Play-by-play comes as one file per season, named play_by_play_<season>.parquet. The script finds those files with a pattern, so it does not depend on the exact folder names.

Columns used here, from the play-by-play table:

  • game_id, the key that joins every file in the package.
  • type_desc_key, the event type: shot-on-goal, goal, missed-shot, blocked-shot, hit and others.
  • zone_code, where the event happened relative to the team that owns it: O, D or N.
  • x_coord and y_coord, integer rink coordinates in feet with the center ice dot at the origin.
  • shot_type, loaded for later experiments though the model here does not use it.

The geometry is the only part that needs care. The goal line is 89 feet from center ice, and teams change ends each period, so the sign of x_coord flips. Taking the absolute value of x_coord removes the direction, and keeping only offensive-zone events means every shot is aimed at the nearer goal. Blocked and missed shots are dropped because only shots that reached the goalie are scored here.

`shot_model.R`

# Fit a shot-quality model (goal chance from distance and angle) on the free NHL sample.
suppressPackageStartupMessages(library(arrow))

zip_url <- "https://sportsdatahq.com/samples/data-packages/nhl-history-sample.zip"
dir <- file.path(tempdir(), "nhl-sample")
zf  <- tempfile(fileext = ".zip")
download.file(zip_url, zf, quiet = TRUE, mode = "wb")
unzip(zf, exdir = dir)

files <- list.files(dir, pattern = "^play_by_play_.*\\.parquet$",
                    recursive = TRUE, full.names = TRUE)
cols  <- c("game_id", "type_desc_key", "zone_code", "x_coord", "y_coord", "shot_type")
pbp   <- do.call(rbind, lapply(files, read_parquet, col_select = all_of(cols)))
cat("play-by-play rows:", nrow(pbp), "from", length(files), "files\n")

# Shots that reached the net, taken in the offensive zone.
shots <- pbp[pbp$type_desc_key %in% c("shot-on-goal", "goal") &
             pbp$zone_code == "O" & !is.na(pbp$x_coord), ]
dx <- 89 - abs(shots$x_coord)              # goal line sits at x = +/-89 ft
shots$dist  <- sqrt(dx^2 + shots$y_coord^2)
shots$angle <- atan2(abs(shots$y_coord), dx) * 180 / pi
shots$goal  <- as.integer(shots$type_desc_key == "goal")
cat("shots:", nrow(shots), " goals:", sum(shots$goal), "\n")

fit <- glm(goal ~ dist + angle, data = shots, family = binomial())
print(round(summary(fit)$coefficients, 4))

# Leave-one-game-out check against a flat league-rate baseline.
logloss <- function(y, p) -mean(y * log(p) + (1 - y) * log(1 - p))
p_model <- p_base <- numeric(nrow(shots))
for (g in unique(shots$game_id)) {
  test <- shots$game_id == g
  m <- glm(goal ~ dist + angle, data = shots[!test, ], family = binomial())
  p_model[test] <- predict(m, shots[test, ], type = "response")
  p_base[test]  <- mean(shots$goal[!test])
}
cat(sprintf("leave-one-game-out log loss: model %.4f vs flat rate %.4f\n",
            logloss(shots$goal, p_model), logloss(shots$goal, p_base)))

A run on December 6, 2026 printed this:

play-by-play rows: 952 from 2 files
shots: 130  goals: 17
            Estimate Std. Error z value Pr(>|z|)
(Intercept)  -0.7435     0.6504 -1.1431   0.2530
dist         -0.0309     0.0166 -1.8647   0.0622
angle        -0.0077     0.0121 -0.6344   0.5258
leave-one-game-out log loss: model 0.4394 vs flat rate 0.4417

The sign on dist is the one you would expect: the farther the shot, the lower the chance of a goal. Its p-value of 0.06 on 130 shots shows how thin the evidence is. The model beats the flat baseline by 0.0023 log loss, which is within noise at this size.

How to run it

Save the script as shot_model.R and run Rscript shot_model.R. If arrow is installed in a project library, set R_LIBS_USER to that folder first. The download takes a moment and the model fit is instant.

To use a full package instead of the sample, change zip_url to the file you downloaded, or unzip it yourself and set dir to the extracted folder. Everything after the files <- line stays the same. The paid packages carry every game in the listed seasons, so the same code will fit thousands of shots per game-week.

How to extend it

  • Add features. Pull shot_type into the formula as a factor, add strength (5v5, power play) from the full play-by-play columns, and add a flag for the previous event being a faceoff or a takeaway by sorting each game on sort_order.
  • Use Arrow for scale. Replace lapply(files, read_parquet) with open_dataset(dir) and filter before collecting. Arrow pushes the filter into the file scan, so a multi-season package never has to fit in memory whole.
  • Join context. Join game_id to the games table for home and away teams and to skater game lines for shooter ice time, then compare team-level model goals with actual goals by game.
  • Calibration. Bin predictions into deciles, compare the mean prediction with the goal rate in each bin, and plot it. A model with good log loss can still be miscalibrated at the extremes.

Limits and when not to use this

The sample is three games. Treat every number on this page as a demonstration of the pipeline. Do not read player or team conclusions into it.

The features are crude. Distance and angle ignore screens, passes before the shot, rebounds, goalie position and shooter quality, which is why public shot models usually add several of those. Coordinates are recorded as integers, so very short distances are lumpy.

Leave-one-game-out is a fair test on a handful of games but it is not a season-level backtest. For real work, split by date, so the model never sees games after the one it predicts.

Arrow installation is the most common stumbling block. If install.packages("arrow") falls back to a long source build, install a binary build for your platform or use a prebuilt environment, rather than waiting on a compile.

This starter measures how likely a shot was to score. It is a description of past play, not a prediction service and not advice about wagering. If you only need tidy tables and have no model in mind, plain read_parquet plus a data frame is enough and you can skip the glm.

FAQ

Why use arrow instead of reading the CSV files in the sample? Parquet keeps column types, reads only the columns you ask for through col_select, and is compact. The free sample ships both formats, but the paid packages ship the largest tables as Parquet only, so code written against Parquet carries over unchanged.

Is a model fitted on three games meaningful? No. The sample holds three real games, about 130 on-target shots and 17 goals, which is enough to prove the pipeline and not enough to trust a coefficient. Point the same script at a full season package and the code needs no change beyond the folder path.

Can I use the sample files in a product? You may use the files inside your organization, including commercially, for analysis, models, backtests and publishing your own derived statistics. You may not resell or redistribute the raw files. Read the licence on the data packages page before shipping anything built on the full packages.

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.