Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .Rbuildignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@
^_pkgdown\.yml$
^pkgdown$
^docs$
^vignettes/scoring-basketball-forecasts\.Rmd$
3 changes: 3 additions & 0 deletions .github/workflows/R-CMD-check.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ jobs:
http-user-agent: ${{ matrix.config.http-user-agent }}
use-public-rspm: true

- name: Check the downloadable basketball forecast scorer
run: Rscript tutorials/forecast-scores/test_scorer.R

- name: Check offline quote-join tutorial
run: |
Rscript tutorials/quote-joins/odds_join.R
Expand Down
5 changes: 5 additions & 0 deletions .github/workflows/reference.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ jobs:
reference <- paste(readLines("docs/reference/index.html"), collapse = "\n")
stopifnot(all(vapply(exports, function(name) grepl(name, reference, fixed = TRUE), logical(1))))
stopifnot(file.exists("docs/sitemap.xml"), file.exists("docs/reference/pa_odds.html"))
article <- xml2::read_html("docs/articles/scoring-basketball-forecasts.html")
cells <- xml2::xml_text(xml2::xml_find_all(article, "//table//td"))
stopifnot(all(c("0.2267", "0.2767", "0.2500") %in% cells))
downloads <- c("basketball.csv", "score-games.R")
stopifnot(all(file.exists(file.path("docs/forecast-audit", downloads))))
- name: Render and check the decision-clock report
working-directory: tutorials/point-in-time
run: Rscript build-clock-report.R ../../docs/clock-report
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ compares the price a backtest would assign with the quote the analyst had receiv
Try eight cutoffs in your browser, inspect the [illustrated timeline](https://jacobiusmakes.github.io/parlayapi-notebooks/point-in-time-replay/#compare-eight-decision-times), or run the fictional replay offline.
For two bookmakers, [compare the recorded prices at one cutoff](https://github.com/JacobiusMakes/parlayapiR/blob/main/tutorials/point-in-time/compare-books.md) and see when a withdrawal or a source-age limit rules out the comparison.

[Score two pregame basketball models](https://jacobiusmakes.github.io/parlayapiR/articles/scoring-basketball-forecasts.html) that both picked eight of twelve winners. Download the fictional games and run the same Brier-score comparison on your own saved forecasts in base R.

[Choose the right fixture for a two-sided report](tutorials/fixture-report/README.md)
uses two games between the same teams. Download the base-R exercise to see
which away price the editor could publish at each deadline.
Expand Down
13 changes: 13 additions & 0 deletions pkgdown/assets/forecast-audit/basketball.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
game_id,home,away,forecast_utc,tipoff_utc,p_a,p_b,home_won
F01,Owls,Comets,2026-01-01T18:00:00Z,2026-01-01T19:00:00Z,0.6,0.9,1
F02,Breakers,Pilots,2026-01-02T18:00:00Z,2026-01-02T19:00:00Z,0.6,0.9,0
F03,Foxes,Owls,2026-01-03T18:00:00Z,2026-01-03T19:00:00Z,0.6,0.9,1
F04,Comets,Pilots,2026-01-04T18:00:00Z,2026-01-04T19:00:00Z,0.6,0.9,1
F05,Breakers,Foxes,2026-01-05T18:00:00Z,2026-01-05T19:00:00Z,0.6,0.9,0
F06,Pilots,Owls,2026-01-06T18:00:00Z,2026-01-06T19:00:00Z,0.6,0.9,1
F07,Comets,Foxes,2026-01-07T18:00:00Z,2026-01-07T19:00:00Z,0.4,0.1,0
F08,Owls,Breakers,2026-01-08T18:00:00Z,2026-01-08T19:00:00Z,0.4,0.1,1
F09,Pilots,Foxes,2026-01-09T18:00:00Z,2026-01-09T19:00:00Z,0.4,0.1,0
F10,Breakers,Comets,2026-01-10T18:00:00Z,2026-01-10T19:00:00Z,0.4,0.1,0
F11,Foxes,Pilots,2026-01-11T18:00:00Z,2026-01-11T19:00:00Z,0.4,0.1,1
F12,Owls,Comets,2026-01-12T18:00:00Z,2026-01-12T19:00:00Z,0.4,0.1,0
43 changes: 43 additions & 0 deletions pkgdown/assets/forecast-audit/score-games.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Score two pregame forecasts for the home team on the same settled games.
# Run with base R: Rscript score-games.R basketball.csv

utc_seconds <- function(x, field) {
parsed <- as.POSIXct(strptime(x, "%Y-%m-%dT%H:%M:%SZ", tz = "UTC"))
rendered <- format(parsed, "%Y-%m-%dT%H:%M:%SZ", tz = "UTC")
if (anyNA(parsed) || !all(rendered == x)) {
stop(field, " must contain UTC timestamps such as 2026-01-01T18:00:00Z.")
}
parsed
}

score_games <- function(path) {
games <- read.csv(path, colClasses = "character", check.names = FALSE,
strip.white = TRUE, na.strings = "", row.names = NULL)
required <- c("game_id", "forecast_utc", "tipoff_utc", "p_a", "p_b", "home_won")
if (!nrow(games) || anyDuplicated(names(games)) || !all(required %in% names(games))) {
stop("Supply at least one game and unique headers including ", paste(required, collapse = ", "), ".")
}
ids <- trimws(games$game_id)
if (anyNA(ids) || any(ids == "") || anyDuplicated(ids)) stop("Each game needs a unique ID.")
recorded <- utc_seconds(games$forecast_utc, "forecast_utc")
tipoff <- utc_seconds(games$tipoff_utc, "tipoff_utc")
if (any(recorded >= tipoff)) stop("Both forecasts must be recorded before tipoff.")
if (!all(games$home_won %in% c("0", "1"))) stop("Complete each settled result with 0 or 1.")
result <- as.integer(games$home_won)
evaluate <- function(label, probability) {
p <- suppressWarnings(as.numeric(probability))
if (any(!is.finite(p) | p < 0 | p > 1)) stop(label, " probabilities must be between 0 and 1.")
picked <- p != 0.5
correct <- sum(picked & ((p > 0.5) == result))
data.frame(model = label, games = length(p), picks = sum(picked),
correct = correct, brier = mean((p - result)^2))
}
rbind(evaluate("Model A", games$p_a), evaluate("Model B", games$p_b),
evaluate("Always 50%", rep(0.5, nrow(games))))
}

if (sys.nframe() == 0L) {
args <- commandArgs(trailingOnly = TRUE)
if (length(args) != 1L) stop("Usage: Rscript score-games.R basketball.csv")
print(score_games(args[1L]), row.names = FALSE, digits = 5)
}
28 changes: 28 additions & 0 deletions tutorials/forecast-scores/test_scorer.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
asset_dir <- "pkgdown/assets/forecast-audit"
source(file.path(asset_dir, "score-games.R"))
path <- file.path(asset_dir, "basketball.csv")
sample <- read.csv(path, colClasses = "character")
scores <- score_games(path)
stopifnot(all(scores$games == 12), all(scores$picks == c(12, 12, 0)),
all(scores$correct == c(8, 8, 0)),
isTRUE(all.equal(scores$brier, c(17/75, 83/300, 1/4))))

check_change <- function(column, value, error = NULL) {
changed <- sample
changed[[column]][1] <- value
f <- tempfile(fileext = ".csv")
on.exit(unlink(f))
write.csv(changed, f, row.names = FALSE)
if (is.null(error)) return(score_games(f))
message <- tryCatch({score_games(f); ""}, error = conditionMessage)
stopifnot(grepl(error, message, fixed = TRUE))
}
check_change("game_id", sample$game_id[2], "unique ID")
check_change("home_won", "", "settled result")
check_change("forecast_utc", sample$tipoff_utc[1], "before tipoff")
check_change("forecast_utc", "2026-01-01", "UTC timestamps")
check_change("forecast_utc", "2026-02-30T12:00:00Z", "UTC timestamps")
check_change("p_b", "Inf", "probabilities")
check_change("p_a", "-0.01", "probabilities")
tie <- check_change("p_a", "0.5")
stopifnot(tie$picks[1] == 11L, tie$correct[1] == 7L, tie$games[1] == 12L)
2 changes: 2 additions & 0 deletions tutorials/point-in-time/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ The withdrawal took one second to reach the analyst. So did the next quote. Even

Each selection here belongs to the same fictional event, bookmaker, period and moneyline market. In a real log, identify that entire stream before comparing records. Both clocks in this example share a UTC time base. The receipt timestamp records when the observation became available to this analyst.

[Score two pregame basketball models](https://jacobiusmakes.github.io/parlayapiR/articles/scoring-basketball-forecasts.html) that both picked eight of twelve winners. Download the fictional games and run the same Brier-score comparison on your own saved forecasts in base R.

For a worked example with two games between the same teams, try [choosing the right fixture for a two-sided report](../fixture-report/README.md). An editor has several away prices in hand and must decide which one belongs in the report.

To follow new exercises and changes to the tools behind them, [import the sports data reading list](https://jacobiusmakes.github.io/parlayapi-notebooks/sports-data-reading-desk/) or subscribe to [Field Notes alone](https://jacobiusmakes.github.io/parlayapi-notebooks/field-notes.atom.xml).
Expand Down
60 changes: 60 additions & 0 deletions vignettes/scoring-basketball-forecasts.Rmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
---
title: "Two basketball models picked the same eight winners. Which forecast was better?"
description: "Score two pregame forecasts on 12 fictional basketball games. Download the CSV and base R scorer to compare your own probabilities against a 50% baseline."
---

```{r setup, include=FALSE}
here <- normalizePath(Sys.getenv("GITHUB_WORKSPACE", unset = "."))
repeat {
assets <- file.path(here, "pkgdown", "assets", "forecast-audit")
if (file.exists(file.path(assets, "score-games.R"))) break
parent <- dirname(here)
if (parent == here) stop("Cannot find the forecast audit files.")
here <- parent
}
knitr::opts_knit$set(root.dir = assets)
```

Before the Owls hosted the Comets, Model A gave the Owls a **60%** chance to win. Model B said **90%**. The Owls won. Both models got a tick in the win column. The next night they backed the Breakers at those same probabilities. The Breakers lost.

Over twelve fictional basketball games, both models picked the same eight winners and missed the same four. Which forecast would you trust more on this slate?

## Score the misses

Grade the home team's probability against the result, using 1 for a home win and 0 for a loss. Square the difference. On the Owls' win, Model B scores 0.01, better than Model A's 0.16. On the Breakers' loss, B scores 0.81 and A scores 0.36. A confident miss costs B much more than a confident hit saves it.

The mean across games is the **binary Brier score**. Zero is perfect. A forecast of 50% for every game scores 0.25 whatever the results. [Definition and formula, Japan Meteorological Agency (Appendix A.3)](https://www.jma.go.jp/jma/jma-eng/jma-center/nwp/outline2023-nwp/pdf/outline2023_Appendix_A.pdf#page=7).

```{r scores}
source("score-games.R")
scores <- score_games("basketball.csv")
knitr::kable(scores, digits = 4,
col.names = c("Forecast", "Games", "Picks", "Correct picks", "Brier score"))
```

Model A scores **0.2267**, below the 50% baseline. Model B scores **0.2767**, above it. A 50% forecast makes no directional pick and still gets scored on every game. Eight wins alone concealed the difference.

## Check where the confidence came from

```{r groups}
games <- read.csv("basketball.csv")
groups <- aggregate(cbind(home_wins = home_won, games = rep(1, nrow(games))) ~ p_a + p_b,
data = games, FUN = sum)
groups$home_win_rate <- groups$home_wins / groups$games
knitr::kable(groups, digits = 3,
col.names = c("Model A", "Model B", "Home wins", "Games", "Home win rate"))
```

B called the home team a 90% favorite six times. Four won. It called the home team a 10% long shot six times. Two won. These groups explain B's result on this exercise. To assess calibration on your own forecasts, use a larger held-out slate and keep the game count beside each rate.

## Score your own slate in base R

Save the [twelve-game CSV](https://jacobiusmakes.github.io/parlayapiR/forecast-audit/basketball.csv) and the [R scorer](https://jacobiusmakes.github.io/parlayapiR/forecast-audit/score-games.R) in one folder, then run this command there.

```sh
Rscript score-games.R basketball.csv
```

Replace the sample with one row per settled game. Both probabilities refer to a home win under the same settlement rule. Use a common pregame snapshot for both models, represent probabilities on a 0–1 scale, and set `home_won` to 1 or 0. The scorer stops on duplicate game IDs, incomplete results or snapshots recorded at or after tipoff. Use the time the forecasts were actually saved. A timestamp entered afterward cannot establish what either model knew.

To see how much a model estimate matters to a price calculation, open the [Kelly calculator](https://parlay-api.com/tools/kelly-calculator) and hold the offered price at +100 while changing the assumed win probability. To start recording a forward test, [inspect the public NBA preview](https://parlay-api.com/try?utm_source=r_package&utm_medium=article&utm_campaign=r_forecast_score) and save the event ID and quote observation time before the game. The preview supplies prices; you supply the forecast and obtain the settled result separately.
Loading