From 5743cd743220b415ea9ea5efd6c0ba51618afa61 Mon Sep 17 00:00:00 2001 From: Esther-MacMini Date: Fri, 4 Dec 2026 12:42:57 -0500 Subject: [PATCH] Compare two recorded bookmakers at an exact decision cutoff --- .github/workflows/R-CMD-check.yaml | 2 + README.md | 1 + tutorials/point-in-time/README.md | 4 ++ tutorials/point-in-time/compare-books.R | 52 ++++++++++++++++++++ tutorials/point-in-time/compare-books.md | 30 +++++++++++ tutorials/point-in-time/test_compare_books.R | 39 +++++++++++++++ tutorials/quote-joins/README.md | 2 + 7 files changed, 130 insertions(+) create mode 100644 tutorials/point-in-time/compare-books.R create mode 100644 tutorials/point-in-time/compare-books.md create mode 100644 tutorials/point-in-time/test_compare_books.R diff --git a/.github/workflows/R-CMD-check.yaml b/.github/workflows/R-CMD-check.yaml index 7e13907..ab08117 100644 --- a/.github/workflows/R-CMD-check.yaml +++ b/.github/workflows/R-CMD-check.yaml @@ -50,6 +50,8 @@ jobs: Rscript replay.R Rscript test_replay.R Rscript test_replay_log.R + Rscript test_compare_books.R + Rscript compare-books.R example-log.csv 2026-10-01T14:00:06.049Z 6000 fictional-final game "Harbor Owls" north south Rscript replay-log.R example-log.csv 2026-10-01T14:00:06.050Z - name: Check fixture report and offline command diff --git a/README.md b/README.md index 8ddbd97..2ea2204 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ and the request cost before using your key. [Rebuild what was known at a decision time](tutorials/point-in-time/README.md) compares the price a backtest would assign with the quote the analyst had received. 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. [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 diff --git a/tutorials/point-in-time/README.md b/tutorials/point-in-time/README.md index 9c71092..eff007a 100644 --- a/tutorials/point-in-time/README.md +++ b/tutorials/point-in-time/README.md @@ -41,6 +41,10 @@ In this fictional final, North’s last known Owls price is **1.90**. Move the c [See the file format and output states](log-guide.md). For your own log, use the nine columns in [example-log.csv](example-log.csv). Keep event ID, bookmaker, market, period and selection separate. Use `h2h`, decimal prices, and UTC source and receipt timestamps ending in `Z` with up to three fractional digits. Leave the price blank on a withdrawal. The output includes only selections observed by the cutoff. A withdrawn or conflicting selection has an empty price. Receipt times must come from your collector. A file containing only final prices cannot establish arrival history. +## Compare two books at the same deadline + +[Run the two-book replay](compare-books.md) on the same fictional final. At 14:00:06.049 South leads with 1.95. One millisecond later North leads with 2.10. Tighten the source-age limit or move past the withdrawal to see when a comparison becomes unavailable. + ## Watch two plausible shortcuts fail Save the script, start R in that directory, and run these lines. Filtering on source time alone makes the delayed update visible too early. diff --git a/tutorials/point-in-time/compare-books.R b/tutorials/point-in-time/compare-books.R new file mode 100644 index 0000000..e424164 --- /dev/null +++ b/tutorials/point-in-time/compare-books.R @@ -0,0 +1,52 @@ +# Compare the last received moneyline observations for two named books. +# Source replay.R and replay-log.R first when calling compare_books() in R. +compare_books <- function(path, cutoff, max_age_ms, event_id, period, selection, book_a, book_b) { + identity <- list(event_id, period, selection, book_a, book_b) + valid_id <- function(x) is.character(x) && length(x) == 1L && !is.na(x) && nzchar(trimws(x)) + if (!all(vapply(identity, valid_id, logical(1))) || book_a == book_b) + stop("Enter one event, period and selection, and two different bookmakers.") + if (!is.numeric(max_age_ms) || length(max_age_ms) != 1L || !is.finite(max_age_ms) || + max_age_ms < 0 || max_age_ms != floor(max_age_ms)) + stop("The maximum source age must be a nonnegative whole number of milliseconds.") + + snapshot <- replay_file(path, cutoff) + matched <- snapshot[snapshot$event_id == event_id & snapshot$market == "h2h" & + snapshot$period == period & snapshot$selection == selection, , drop = FALSE] + books <- c(book_a, book_b) + index <- match(books, matched$book) + state <- matched$state[index] + state[is.na(index)] <- "unseen" + updated <- matched$updated_utc[index] + age <- rep(NA_real_, 2L) + known <- !is.na(index) + if (any(known)) { + # Subtract integer milliseconds so decimal clock boundaries stay inclusive. + decision_ms <- round(as.numeric(parse_utc(cutoff)) * 1000) + age[known] <- decision_ms - round(as.numeric(parse_utc(updated[known])) * 1000) + } + state[state == "quoted" & age > max_age_ms] <- "stale" + price <- matched$decimal_price[index] + price[state != "quoted"] <- NA_real_ + comparison <- rep("unavailable", 2L) + if (all(state == "quoted")) { + comparison <- if (price[1L] == price[2L]) rep("tied", 2L) else ifelse(price == max(price), "higher", "lower") + } + data.frame(event_id = event_id, market = "h2h", period = period, selection = selection, + book = books, cutoff_utc = cutoff, max_age_ms = max_age_ms, state = state, + source_updated_utc = updated, source_age_ms = age, + eligible_decimal_price = price, comparison = comparison, stringsAsFactors = FALSE) +} + +if (sys.nframe() == 0L) { + args <- commandArgs(trailingOnly = TRUE) + if (length(args) != 8L) + stop("Usage: Rscript compare-books.R FILE.csv CUTOFF_UTC MAX_AGE_MS EVENT PERIOD SELECTION BOOK_A BOOK_B", + call. = FALSE) + script <- sub("^--file=", "", grep("^--file=", commandArgs(FALSE), value = TRUE)) + here <- dirname(normalizePath(script)) + source(file.path(here, "replay.R")) + source(file.path(here, "replay-log.R")) + output <- compare_books(args[1], args[2], suppressWarnings(as.numeric(args[3])), + args[4], args[5], args[6], args[7], args[8]) + write.csv(output, stdout(), row.names = FALSE, na = "") +} diff --git a/tutorials/point-in-time/compare-books.md b/tutorials/point-in-time/compare-books.md new file mode 100644 index 0000000..c3d7b3c --- /dev/null +++ b/tutorials/point-in-time/compare-books.md @@ -0,0 +1,30 @@ +# Which book had the higher recorded price when the decision was made? + +North and South both quoted the Harbor Owls to win a fictional basketball final. At 14:00:06.049 UTC, South’s 1.95 was higher than North’s 1.90. A millisecond later the analyst received North’s 2.10. Both prices met the analyst’s six-second source-age limit at those cutoffs. + +[Download the two-book replay kit](https://github.com/JacobiusMakes/parlayapiR/releases/download/two-book-replay-v1/two-book-replay.zip). Extract the ZIP, open a terminal in the extracted directory and run the following command with base R. It reads the included CSV locally. + +```sh +Rscript compare-books.R example-log.csv 2026-10-01T14:00:06.049Z 6000 fictional-final game "Harbor Owls" north south +``` + +Change the cutoff to `2026-10-01T14:00:06.050Z` and run it again. The result contains one CSV row per requested book. Each row names the event, market, period and selection. It also gives the source timestamp chosen from messages received by the cutoff, its age, and the comparison result. + +| Decision time (UTC) | Maximum source age | North | South | Higher recorded price | +| --- | ---: | --- | --- | --- | +| 14:00:06.049 | 6,000 ms | 1.90 | 1.95 | South | +| 14:00:06.050 | 6,000 ms | 2.10 | 1.95 | North | +| 14:00:06.050 | 3,049 ms | Stale at 3,050 ms | 1.95 | Unavailable | +| 14:00:09.000 | 6,000 ms | Withdrawn | 1.95 | Unavailable | + +[Download the eight output rows as CSV](https://github.com/JacobiusMakes/parlayapiR/releases/download/two-book-replay-v1/worked-cutoffs.csv) to inspect both books at all four settings in a spreadsheet. + +The cutoff admits messages the collector received at or before that instant. Source age is the cutoff time minus the selected message’s source update time. A source age exactly at the limit qualifies. If the log has a withdrawal, conflicting messages, an over-age quote or no observation for either book, both comparison fields say `unavailable`. Equal eligible prices produce `tied`. + +## Use your own two-book log + +Supply the [nine-column moneyline CSV](log-guide.md#supply-your-observations) with timestamps from comparable UTC clocks. Replace the event, period, team and two book identifiers with the exact values in your log. A repeat meeting or another period has a separate identity. Choose an age limit for your use case. This exercise describes quotes visible in the recorded observations. Confirm settlement rules and actual availability separately before treating prices as interchangeable. + +Run `Rscript test_compare_books.R` from the extracted directory to check the cutoff and source-age boundaries, duplicate-timestamp conflict, withdrawal, tie and separate scopes. + +The maintainer’s [NBA preview](https://parlay-api.com/try?utm_source=github&utm_medium=r_tutorial&utm_campaign=decision_log_replay&utm_content=two_book_cutoff) lets you inspect a small current sample without a key. To replay a real decision you also need a history of when your collector received each observation. diff --git a/tutorials/point-in-time/test_compare_books.R b/tutorials/point-in-time/test_compare_books.R new file mode 100644 index 0000000..62564b2 --- /dev/null +++ b/tutorials/point-in-time/test_compare_books.R @@ -0,0 +1,39 @@ +source("replay.R") +source("replay-log.R") +source("compare-books.R") +at <- function(time, age = 6000, path = "example-log.csv", event = "fictional-final", + period = "game", team = "Harbor Owls", a = "north", b = "south") { + compare_books(path, paste0("2026-10-01T14:00:", time, "Z"), age, event, period, team, a, b) +} +before <- at("06.049") +after <- at("06.050") +stopifnot(identical(before$comparison, c("lower", "higher")), all(before$eligible_decimal_price == c(1.90, 1.95)), + identical(after$comparison, c("higher", "lower")), all(after$eligible_decimal_price == c(2.10, 1.95)), + all(after$source_age_ms == c(3050, 2049)), all(at("07")$eligible_decimal_price == c(2.10, 1.95))) +boundary <- at("06.050", 3050) +too_old <- at("06.050", 3049) +stopifnot(all(boundary$state == "quoted"), identical(too_old$state, c("stale", "quoted")), + identical(is.na(too_old$eligible_decimal_price), c(TRUE, FALSE)), all(too_old$comparison == "unavailable")) +withdrawn <- at("09") +stopifnot(identical(withdrawn$state, c("withdrawn","quoted")), all(withdrawn$comparison == "unavailable"), + identical(at("04")$state, c("quoted","unseen")), all(at("00")$state == "unseen"), + all(at("06.050", event = "other")$state == "unseen"), all(at("06.050", period = "half")$state == "unseen"), + identical(at("06.050", team = "Valley Foxes")$state, c("quoted", "unseen")), + identical(at("06.050", a = "south", b = "north")$comparison, rev(after$comparison))) +local({ + rows <- read.csv("example-log.csv", colClasses = "character", na.strings = character()) + path <- tempfile(fileext = ".csv") + on.exit(unlink(path)) + disagree <- rows[3, ]; disagree$decimal_price <- "2.05" + write.csv(rbind(rows, disagree), path, row.names = FALSE) + x <- at("06.050", path = path) + stopifnot(identical(x$state, c("conflict", "quoted")), all(x$comparison == "unavailable")) + rows$decimal_price[3] <- "1.95" + write.csv(rows[nrow(rows):1, ], path, row.names = FALSE) + stopifnot(all(at("06.050", path = path)$comparison == "tied")) +}) +for (age in list(-1, 0.5, NA_real_, Inf, "1000", numeric())) { + stopifnot(inherits(try(at("06.050", age), silent = TRUE), "try-error")) +} +stopifnot(inherits(try(at("06.050", b = "north"), silent = TRUE), "try-error")) +cat("Two-book cutoff, scope, freshness, withdrawal, conflict, tie and invalid-input checks passed.\n") diff --git a/tutorials/quote-joins/README.md b/tutorials/quote-joins/README.md index 0d0beed..307580f 100644 --- a/tutorials/quote-joins/README.md +++ b/tutorials/quote-joins/README.md @@ -50,6 +50,8 @@ good[c("line", "decimal_price_left", "decimal_price_right")] The two matching handicaps now produce two rows. The synthetic -3.5 selection pairs 1.91 with 1.95; the -4.5 selection pairs 2.08 with 2.12. Changing a display name does not break the match because display names are not keys. +Matching the selection is the first step. For a moneyline example using source and receipt times, [compare two bookmakers at one decision time](../point-in-time/compare-books.md). A delayed price changes which book offered the higher recorded quote a millisecond later. + ## Make ambiguity an error `validate_spread_quotes()` rejects missing identifiers, missing or nonfinite spread lines, invalid decimal prices, and repeated complete keys. Even two duplicate rows with identical prices fail: silently choosing one would conceal an upstream snapshot problem.