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 .github/workflows/R-CMD-check.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/reference.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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: |
Expand Down
21 changes: 21 additions & 0 deletions tutorials/point-in-time/COMPARE-WINDOW.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 2 additions & 0 deletions tutorials/point-in-time/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
27 changes: 27 additions & 0 deletions tutorials/point-in-time/build-window.R
Original file line number Diff line number Diff line change
@@ -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/")
6 changes: 5 additions & 1 deletion tutorials/point-in-time/compare-books.R
Original file line number Diff line number Diff line change
@@ -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)
Expand All @@ -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)
Expand Down
48 changes: 48 additions & 0 deletions tutorials/point-in-time/compare-window.R
Original file line number Diff line number Diff line change
@@ -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 = "")
}
36 changes: 36 additions & 0 deletions tutorials/point-in-time/render-window.R
Original file line number Diff line number Diff line change
@@ -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("<strong>%.2f</strong><small>age %s ms</small>", price, age))
switch(state, unseen = "Unseen", stale = sprintf("Too old<small>age %s ms</small>", 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('<tr%s><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>',
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('<details class="limit"', if (age_ms == 4000) ' open' else '', '><summary>',
'<strong>', age_ms / 1000, '-second limit</strong><span>',
sum(eligible), ' of ', nrow(rows), ' decisions comparable</span></summary>',
'<div class="tablewrap"><table aria-label="Decisions with a ', age_ms / 1000,
'-second maximum source age"><thead><tr><th scope="col">Deadline UTC</th>',
'<th scope="col">North</th><th scope="col">South</th><th scope="col">Higher price</th>',
'</tr></thead><tbody>', paste(records, collapse = "\n"), '</tbody></table></div></details>')
}
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)
}
45 changes: 45 additions & 0 deletions tutorials/point-in-time/test_compare_window.R
Original file line number Diff line number Diff line change
@@ -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")
43 changes: 43 additions & 0 deletions tutorials/point-in-time/window-template.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>When could two books price the Owls? | ParlayAPI for R</title>
<meta name="description" content="Replay twelve basketball decisions with two bookmaker quotes. Choose a source-age limit and download the base R project for your own observation log.">
<link rel="canonical" href="https://jacobiusmakes.github.io/parlayapiR/two-book-window/">
<style>
:root{color-scheme:light;--ink:#132d35;--muted:#435d63;--line:#cbd9d8;--paper:#f6f8f5;--grass:#0c664d}
*{box-sizing:border-box}body{margin:0;color:var(--ink);background:var(--paper);font:1rem/1.55 "Barlow",system-ui,sans-serif}
header{background:#103b37;color:#fff;border-bottom:5px solid #dced71}main,.wrap{max-width:56rem;margin:auto;padding:1.35rem clamp(1rem,4vw,2.3rem)}
header .wrap{padding-block:1.35rem 1.9rem}header a{color:#e2f3c5}h1,h2,p{margin:0 0 .75rem}h1{max-width:17ch;font-size:clamp(2rem,6vw,3.5rem);line-height:1.03;letter-spacing:-.035em}h2{font-size:1.4rem}
header p{max-width:67ch;margin-bottom:0}nav{font-size:.91rem;margin-bottom:1rem}a{color:#075a4a;text-underline-offset:.18em}a:focus-visible,summary:focus-visible{outline:3px solid #bb7514;outline-offset:3px}
section{margin-bottom:1.75rem}.intro{max-width:69ch}.limit{background:white;border:1px solid var(--line);border-radius:6px;margin:.55rem 0;overflow:hidden}
summary{cursor:pointer;padding:.8rem 1rem;line-height:1.4}summary strong{margin:0 .5rem 0 .18rem}summary span{color:var(--muted);font-size:.94rem}
.limit[open] summary{border-bottom:1px solid var(--line);background:#e8f1e9}.tablewrap{padding:.25rem .65rem .6rem}table{width:100%;border-collapse:collapse;font-variant-numeric:tabular-nums;line-height:1.3;font-size:.95rem}th,td{text-align:left;padding:.55rem .4rem;border-bottom:1px solid #e1e8e5}th{color:var(--muted);font-size:.8rem}tr:last-child td{border-bottom:0}tr.eligible{background:#f1f7e9}td small{display:block;color:var(--muted);font-size:.78rem}.call{display:inline-block;padding:.56rem .9rem;background:var(--grass);color:white;border-radius:.25rem;font-weight:650;text-decoration:none}
pre{max-width:100%;overflow:auto;padding:.9rem 1rem;background:#173330;color:#f6f8e9;border-radius:5px;font-size:.87rem;white-space:pre-wrap;overflow-wrap:anywhere}code{font-family:"IBM Plex Mono",ui-monospace,monospace}footer{border-top:1px solid var(--line);padding-top:1rem;color:var(--muted)}
@media(max-width:430px){.tablewrap{padding:.15rem .25rem .4rem}table{font-size:.84rem}th,td{padding:.48rem .2rem}summary{padding:.65rem .55rem}summary span{display:block;margin-left:1.25rem}}
</style>
</head>
<body>
<header><div class="wrap">
<nav aria-label="Breadcrumb"><a href="https://jacobiusmakes.github.io/parlayapiR/">ParlayAPI for R</a> / Basketball research</nav>
<h1>When could two books price the Owls?</h1>
<p>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.</p>
</div></header>
<main>
<section aria-labelledby="cutoff">
<h2 id="cutoff">Try the same twelve decisions</h2>
<p class="intro">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.</p>
@@TABLES@@
<p>“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.</p>
<a href="worked.csv" download>Download the four-second results as CSV</a>
</section>
<section aria-labelledby="run"><h2 id="run">Check your own observation window</h2>
<p>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.</p>
<p><a class="call" href="project.zip" download>Download the R project</a></p>
<pre><code>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</code></pre>
<p>For your own CSV, keep source update times and local receipt times. A single board capture establishes only its observation window. <a href="https://parlay-api.com/try">Inspect the public NBA sample</a>. When you need authenticated requests for your project, <a href="https://parlay-api.com/signup?utm_source=r_reference&amp;utm_medium=tutorial&amp;utm_campaign=two_book_window">create a project key</a> and check the applicable route cost.</p>
</section>
<footer><a href="https://github.com/JacobiusMakes/parlayapiR/tree/main/tutorials/point-in-time">Read the R tutorial and source</a></footer>
</main></body></html>
Loading