From fb83998f01d9ce4d615b98969ddcee7678511171 Mon Sep 17 00:00:00 2001 From: Esther-MacMini Date: Sat, 5 Dec 2026 15:02:43 -0500 Subject: [PATCH] Show when two moneylines qualified across a decision window --- .github/workflows/R-CMD-check.yaml | 1 + .github/workflows/reference.yml | 3 ++ tutorials/point-in-time/COMPARE-WINDOW.md | 21 ++++++++ tutorials/point-in-time/README.md | 2 + tutorials/point-in-time/build-window.R | 27 +++++++++++ tutorials/point-in-time/compare-books.R | 6 ++- tutorials/point-in-time/compare-window.R | 48 +++++++++++++++++++ tutorials/point-in-time/render-window.R | 36 ++++++++++++++ tutorials/point-in-time/test_compare_window.R | 45 +++++++++++++++++ tutorials/point-in-time/window-template.html | 43 +++++++++++++++++ 10 files changed, 231 insertions(+), 1 deletion(-) create mode 100644 tutorials/point-in-time/COMPARE-WINDOW.md create mode 100644 tutorials/point-in-time/build-window.R create mode 100644 tutorials/point-in-time/compare-window.R create mode 100644 tutorials/point-in-time/render-window.R create mode 100644 tutorials/point-in-time/test_compare_window.R create mode 100644 tutorials/point-in-time/window-template.html diff --git a/.github/workflows/R-CMD-check.yaml b/.github/workflows/R-CMD-check.yaml index eac77bc..3f99e3d 100644 --- a/.github/workflows/R-CMD-check.yaml +++ b/.github/workflows/R-CMD-check.yaml @@ -62,6 +62,7 @@ jobs: Rscript test_replay.R Rscript test_replay_log.R Rscript test_compare_books.R + Rscript test_compare_window.R Rscript test_change_report.R Rscript change-report.R example-log.csv 2026-10-01T14:00:06.049Z 2026-10-01T14:00:06.050Z > "$RUNNER_TEMP/change-report.html" grep -Fq "1 of 3 selections changed" "$RUNNER_TEMP/change-report.html" diff --git a/.github/workflows/reference.yml b/.github/workflows/reference.yml index e08a86f..757cf11 100644 --- a/.github/workflows/reference.yml +++ b/.github/workflows/reference.yml @@ -44,6 +44,9 @@ jobs: - name: Build the two-deadline report and its offline project working-directory: tutorials/point-in-time run: Rscript build-change-report.R ../../docs/decision-changes + - name: Publish the two-book decision window and its base R project + working-directory: tutorials/point-in-time + run: Rscript build-window.R ../../docs/two-book-window - name: Build and install the documented source package id: source-package run: | diff --git a/tutorials/point-in-time/COMPARE-WINDOW.md b/tutorials/point-in-time/COMPARE-WINDOW.md new file mode 100644 index 0000000..0e45ca4 --- /dev/null +++ b/tutorials/point-in-time/COMPARE-WINDOW.md @@ -0,0 +1,21 @@ +# When could both prices be compared? + +In a fictional basketball final, compare North and South on the Harbor Owls to win. The CSV contains six observations. Five belong to this team and one belongs to its opponent. + +Extract the ZIP, open a terminal in the extracted directory and run this command with base R. + +```sh +Rscript compare-window.R example-log.csv 2026-10-01T14:00:00Z 2026-10-01T14:00:11Z 1000 4000 fictional-final game "Harbor Owls" north south > decisions.csv +``` + +Open the CSV after the command succeeds. Twelve rows represent decisions one second apart. With a four-second maximum source age, both books qualify at 14:00:05 and 14:00:07 UTC. South offers 1.95 against North's 1.90 at the first deadline. At the second, North's delayed 2.10 has arrived. The age limit is inclusive. Change 4000 to 2000 or 5000 to see how the eligible sample changes. + +## Bring a local observation log + +Use the nine named columns in [example-log.csv](example-log.csv). Keep the event, bookmaker, market, period and selection identifiers consistent. This tool compares decimal prices on the same moneyline selection. A quoted price must exceed 1. Record a withdrawal explicitly with an empty price. A selection missing from a partial response does not establish a withdrawal. + +Use UTC timestamps ending in Z, with up to three fractional digits. Supply both the source update and the time your collector received each observation. The first cutoff is included. The final cutoff is included only if it falls on the grid. Each report supports up to 2,000 decisions. + +Each row shows both books' states and the age of each known source update at that decision. A book can be unseen, stale, withdrawn, in conflict, or quoted. Both books must be quoted and within the age limit for a comparison. Equal eligible prices count as tied. The counts describe the chosen instants in your log. They do not measure continuous availability, fills or a provider's update latency. + +Run `Rscript test_compare_window.R` in the project directory to check the included examples. The script reads local files. It needs no API account or additional R packages. diff --git a/tutorials/point-in-time/README.md b/tutorials/point-in-time/README.md index fbc60e1..982a58e 100644 --- a/tutorials/point-in-time/README.md +++ b/tutorials/point-in-time/README.md @@ -21,6 +21,8 @@ Three cutoffs show how a research result changes when the backtest treats a sour | 14:00:08 | 2.10 | Withdrawn | | 14:00:10 | Withdrawn | 1.97 | +Across [twelve one-second decisions](https://jacobiusmakes.github.io/parlayapiR/two-book-window/), how often could you compare two books on the Owls? Open the worked table and choose a maximum quote age of two, four or five seconds. The downloadable base R project repeats the check on your own log. + The withdrawal took one second to reach the analyst. So did the next quote. Even a message that removes a price can change which decision a backtest would have allowed. 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. diff --git a/tutorials/point-in-time/build-window.R b/tutorials/point-in-time/build-window.R new file mode 100644 index 0000000..dd3f696 --- /dev/null +++ b/tutorials/point-in-time/build-window.R @@ -0,0 +1,27 @@ +# Run from tutorials/point-in-time during the existing reference-site build. +for (file in c("replay.R", "replay-log.R", "compare-books.R", "compare-window.R", + "render-window.R", "register-report.R")) source(file) +args <- commandArgs(trailingOnly = TRUE) +stopifnot(length(args) == 1L) +dir.create(args[1], recursive = TRUE, showWarnings = FALSE) +dest <- normalizePath(args[1], mustWork = TRUE) +writeLines(enc2utf8(render_example("window-template.html")), file.path(dest, "index.html"), useBytes = TRUE) +write.csv(window_example(4000), file.path(dest, "worked.csv"), row.names = FALSE, na = "") +build_project <- function(archive) { + root <- getwd() + stage <- tempfile("window-project-") + dir.create(stage) + on.exit({setwd(root); unlink(stage, recursive = TRUE)}, add = TRUE) + files <- c("compare-window.R", "compare-books.R", "replay.R", "replay-log.R", + "example-log.csv", "test_compare_window.R") + stopifnot(all(file.copy(files, stage)), + file.copy("COMPARE-WINDOW.md", file.path(stage, "README.md")), + file.copy("../../LICENSE.md", file.path(stage, "LICENSE.md"))) + setwd(stage) + files <- c(files, "README.md", "LICENSE.md") + if (file.exists(archive)) unlink(archive) + stopifnot(utils::zip(archive, files, flags = "-qX") == 0L) + stopifnot(setequal(utils::unzip(archive, list = TRUE)$Name, files)) +} +build_project(file.path(dest, "project.zip")) +register_report(file.path(dirname(dest), "sitemap.xml"), "https://jacobiusmakes.github.io/parlayapiR/two-book-window/") diff --git a/tutorials/point-in-time/compare-books.R b/tutorials/point-in-time/compare-books.R index e424164..4440c9a 100644 --- a/tutorials/point-in-time/compare-books.R +++ b/tutorials/point-in-time/compare-books.R @@ -1,6 +1,11 @@ # 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) { + compare_snapshot(replay_file(path, cutoff), cutoff, max_age_ms, event_id, period, selection, book_a, book_b) +} + +# A sequence of decisions can reuse a validated local log and replay it at each cutoff. +compare_snapshot <- function(snapshot, 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) @@ -9,7 +14,6 @@ compare_books <- function(path, cutoff, max_age_ms, event_id, period, selection, 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) diff --git a/tutorials/point-in-time/compare-window.R b/tutorials/point-in-time/compare-window.R new file mode 100644 index 0000000..8a5b2f2 --- /dev/null +++ b/tutorials/point-in-time/compare-window.R @@ -0,0 +1,48 @@ +# Evaluate one moneyline selection at equally spaced decision times, including endpoints on the grid. +compare_window <- function(path, start, end, step_ms, max_age_ms, event_id, period, selection, book_a, book_b) { + if (length(start) != 1L || length(end) != 1L) stop("Enter one start and one end.") + bounds <- round(as.numeric(parse_utc(c(start, end))) * 1000) + if (bounds[2] < bounds[1]) stop("The end precedes the start.") + if (!is.numeric(step_ms) || length(step_ms) != 1L || !is.finite(step_ms) || + step_ms <= 0 || step_ms != floor(step_ms)) + stop("Use a positive whole number of milliseconds for the step.") + count <- floor((bounds[2] - bounds[1]) / step_ms) + 1 + if (count > 2000) stop("Choose a shorter window or a larger step (up to 2,000 decisions).") + + rows <- read_log(path) + chosen <- rows$event_id == event_id & rows$period == period & rows$selection == selection & + rows$market == "h2h" & rows$book %in% c(book_a, book_b) + rows <- rows[chosen, , drop = FALSE] + grid <- as.POSIXct((bounds[1] + (seq_len(count) - 1) * step_ms) / 1000, + origin = "1970-01-01", tz = "UTC") + + decisions <- lapply(seq_along(grid), function(i) { + cutoff <- utc_text(grid[i]) + pair <- compare_snapshot(replay_rows(rows, grid[i]), cutoff, max_age_ms, + event_id, period, selection, book_a, book_b) + verdict <- switch(pair$comparison[1], higher = "book_a_higher", lower = "book_b_higher", + tied = "tied", unavailable = "unavailable") + data.frame(cutoff_utc = cutoff, event_id = event_id, market = "h2h", period = period, + selection = selection, max_age_ms = max_age_ms, + book_a = book_a, a_state = pair$state[1], a_age_ms = pair$source_age_ms[1], + a_price = pair$eligible_decimal_price[1], book_b = book_b, + b_state = pair$state[2], b_age_ms = pair$source_age_ms[2], + b_price = pair$eligible_decimal_price[2], comparison = verdict, + stringsAsFactors = FALSE) + }) + do.call(rbind, decisions) +} + +if (sys.nframe() == 0L) { + args <- commandArgs(trailingOnly = TRUE) + if (length(args) != 10L) + stop(paste("Usage: Rscript compare-window.R FILE.csv START_UTC END_UTC STEP_MS", + "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)) + for (file in c("replay.R", "replay-log.R", "compare-books.R")) source(file.path(here, file)) + output <- compare_window(args[1], args[2], args[3], suppressWarnings(as.numeric(args[4])), + suppressWarnings(as.numeric(args[5])), args[6], args[7], args[8], + args[9], args[10]) + write.csv(output, stdout(), row.names = FALSE, na = "") +} diff --git a/tutorials/point-in-time/render-window.R b/tutorials/point-in-time/render-window.R new file mode 100644 index 0000000..f21662e --- /dev/null +++ b/tutorials/point-in-time/render-window.R @@ -0,0 +1,36 @@ +window_example <- function(age_ms) { + compare_window("example-log.csv", "2026-10-01T14:00:00Z", "2026-10-01T14:00:11Z", + 1000, age_ms, "fictional-final", "game", "Harbor Owls", "north", "south") +} + +render_example <- function(template) { + cell <- function(state, price, age) { + if (state == "quoted") return(sprintf("%.2fage %s ms", price, age)) + switch(state, unseen = "Unseen", stale = sprintf("Too oldage %s ms", age), + withdrawn = "Withdrawn", conflict = "Conflicting prices") + } + panel <- function(age_ms) { + rows <- window_example(age_ms) + eligible <- rows$comparison != "unavailable" + labels <- c(book_a_higher = "North", book_b_higher = "South", tied = "Tied", unavailable = "—") + records <- vapply(seq_len(nrow(rows)), function(i) { + sprintf('%s%s%s%s', + if (eligible[i]) ' class="eligible"' else "", + substr(rows$cutoff_utc[i], 12, 19), + cell(rows$a_state[i], rows$a_price[i], rows$a_age_ms[i]), + cell(rows$b_state[i], rows$b_price[i], rows$b_age_ms[i]), labels[[rows$comparison[i]]]) + }, character(1)) + paste0('
', + '', age_ms / 1000, '-second limit', + sum(eligible), ' of ', nrow(rows), ' decisions comparable', + '
', + '', + '', paste(records, collapse = "\n"), '
Deadline UTCNorthSouthHigher price
') + } + html <- paste(readLines(template, warn = FALSE, encoding = "UTF-8"), collapse = "\n") + stopifnot(length(gregexpr("@@TABLES@@", html, fixed = TRUE)[[1]]) == 1L, + grepl("@@TABLES@@", html, fixed = TRUE)) + sub("@@TABLES@@", paste(vapply(c(2000, 4000, 5000), panel, character(1)), collapse = "\n"), + html, fixed = TRUE) +} diff --git a/tutorials/point-in-time/test_compare_window.R b/tutorials/point-in-time/test_compare_window.R new file mode 100644 index 0000000..d180588 --- /dev/null +++ b/tutorials/point-in-time/test_compare_window.R @@ -0,0 +1,45 @@ +for (file in c("replay.R", "replay-log.R", "compare-books.R", "compare-window.R")) source(file) +start <- "2026-10-01T14:00:00Z" +end <- "2026-10-01T14:00:11Z" +run <- function(age, first = start, last = end, step = 1000, path = "example-log.csv", + event = "fictional-final", a = "north", b = "south") { + compare_window(path, first, last, step, age, event, "game", "Harbor Owls", a, b) +} +four <- run(4000) +stopifnot(nrow(four) == 12L, identical(which(four$comparison != "unavailable"), c(6L, 8L)), + four$comparison[6] == "book_b_higher", four$comparison[8] == "book_a_higher", + four$a_state[7] == "stale", four$a_age_ms[7] == 5000, is.na(four$a_price[7]), + four$a_state[10] == "withdrawn", four$b_state[1] == "unseen") +stopifnot(all(run(2000)$comparison == "unavailable"), + identical(which(run(5000)$comparison != "unavailable"), 6:9)) +for (i in seq_len(nrow(four))) { + expected <- compare_books("example-log.csv", four$cutoff_utc[i], 4000, "fictional-final", + "game", "Harbor Owls", "north", "south") + stopifnot(identical(expected$state, c(four$a_state[i], four$b_state[i])), + identical(expected$eligible_decimal_price, c(four$a_price[i], four$b_price[i]))) +} +# The late 2.10 becomes visible at .050 and the interval end need not be on the grid. +edge <- run(6000, "2026-10-01T14:00:06.049Z", "2026-10-01T14:00:06.050Z", 1) +stopifnot(identical(edge$a_price, c(1.9, 2.1)), nrow(run(4000, last = "2026-10-01T14:00:01.999Z")) == 2L, + nrow(run(4000, last = start)) == 1, all(run(4000, event = "other")$a_state == "unseen")) +for (bad in list(0, NA_real_, Inf, 0.5, -1)) stopifnot(inherits(try(run(4000, step = bad), silent = TRUE), "try-error")) +stopifnot(inherits(try(run(4000, first = end, last = start), silent = TRUE), "try-error"), + inherits(try(run(4000, step = 1), silent = TRUE), "try-error"), + inherits(try(run(-1), silent = TRUE), "try-error"), + inherits(try(run(4000, a = "north", b = "north"), silent = TRUE), "try-error")) +local({ + original <- read.csv("example-log.csv", colClasses = "character", na.strings = character()) + file <- tempfile(fileext = ".csv") + on.exit(unlink(file)) + original$decimal_price[3] <- "1.95" + write.csv(original, file, row.names = FALSE) + stopifnot(run(4000, path = file)$comparison[8] == "tied") + changed <- original[3, ]; changed$decimal_price <- "2.12" + write.csv(rbind(original, changed), file, row.names = FALSE) + conflict <- run(4000, path = file) + stopifnot(conflict$a_state[8] == "conflict", conflict$comparison[8] == "unavailable") + write.csv(original[FALSE, ], file, row.names = FALSE) + empty <- run(4000, path = file) + stopifnot(nrow(empty) == 12, all(empty$a_state == "unseen"), all(empty$b_state == "unseen")) +}) +cat("Decision-window checks passed.\n") diff --git a/tutorials/point-in-time/window-template.html b/tutorials/point-in-time/window-template.html new file mode 100644 index 0000000..33e1044 --- /dev/null +++ b/tutorials/point-in-time/window-template.html @@ -0,0 +1,43 @@ + + + + + +When could two books price the Owls? | ParlayAPI for R + + + + + +
+ +

When could two books price the Owls?

+

At 14:00:05, South had the higher price on the Harbor Owls to win. Two seconds later, North had it. In between, a researcher using a four-second age limit had only one eligible quote.

+
+
+
+

Try the same twelve decisions

+

This fictional log follows the same basketball team, game and moneyline at North and South. At each one-second deadline, compare the latest source updates already received from both books. A quote exactly at your age limit still qualifies.

+@@TABLES@@ +

“Unseen” means the collector had no observation for that book and selection yet. “Too old” means the source update exceeded the chosen limit. North’s withdrawal reached the collector at 14:00:09. The counts describe these twelve decisions only.

+Download the four-second results as CSV +
+

Check your own observation window

+

Extract the project and run the example in its folder with base R. The two numbers after the end time set the decision spacing and maximum source age in milliseconds.

+

Download the R project

+
Rscript compare-window.R example-log.csv 2026-10-01T14:00:00Z 2026-10-01T14:00:11Z 1000 4000 fictional-final game "Harbor Owls" north south
+

For your own CSV, keep source update times and local receipt times. A single board capture establishes only its observation window. Inspect the public NBA sample. When you need authenticated requests for your project, create a project key and check the applicable route cost.

+
+ +