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
3 changes: 3 additions & 0 deletions .github/workflows/R-CMD-check.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ jobs:
Rscript test_replay.R
Rscript test_replay_log.R
Rscript test_compare_books.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"
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

Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/reference.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ jobs:
- name: Render and check the decision-clock report
working-directory: tutorials/point-in-time
run: Rscript build-clock-report.R ../../docs/clock-report
- 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: Build and install the documented source package
id: source-package
run: |
Expand Down
2 changes: 2 additions & 0 deletions pkgdown/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ In a twelve-second fictional log, a withdrawal and two delayed prices change wha

At 14:00:04 an analyst had seen a price of 1.90. A 2.10 update stamped 14:00:03 reached the analyst at 14:00:06. Use the six-message fictional log to find when each price became available. You can run the tutorial in base R or in your browser.

[Compare two deadlines in your own log](decision-changes/). The worked report shows how one millisecond changed one of three fictional quotes. The download includes everything needed to run the comparison in base R.

[Open the replay tutorial](https://github.com/JacobiusMakes/parlayapiR/tree/main/tutorials/point-in-time). The tutorial appears in [R Weekly, issue 49 of 2026](https://rweekly.org/2026-W49.html).

## How often did an NFL team make an extra point?
Expand Down
15 changes: 15 additions & 0 deletions tutorials/point-in-time/CHANGE-REPORT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Compare two moneyline decisions with base R

Extract the ZIP to a directory. From that directory, write a report to a new file:

```sh
Rscript change-report.R example-log.csv 2026-10-01T14:00:06.049Z 2026-10-01T14:00:06.050Z > comparison.html
```

Open `comparison.html` in your browser. North’s Harbor Owls quote changes from 1.90 to 2.10. North’s Valley Foxes quote and South’s Harbor Owls quote keep their earlier prices. Set the second cutoff to `2026-10-01T14:00:09Z` to see North’s withdrawal. All observations in the supplied CSV are fictional.

For your own report, replace the CSV filename and both UTC cutoffs. Use the nine columns in `example-log.csv`. The five identity fields are event_id, book, market (h2h), period and selection. Supply updated_utc and received_utc as UTC timestamps ending in Z with up to three fractional digits. Receipt must be at or after the source update. For state quoted, decimal_price must exceed 1. For withdrawn, leave decimal_price empty. The two cutoffs must be in increasing order. No R packages, network requests or API key are required. Use a new output filename each time you want to keep a previous report.

The report includes event IDs, books, markets, periods, selections, source timestamps, states and prices from your file. Anyone you give the HTML to can read those values. Only selections observed by the second cutoff are shown. A later message with an older source update cannot roll a price back. Conflicting observations with the same latest update have an unknown price. The comparison describes the two endpoints; a selection may change and revert in between.

To check the supplied example and the other cases, run `Rscript test_change_report.R` from the extracted directory.
2 changes: 2 additions & 0 deletions tutorials/point-in-time/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ 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.

[See which selections changed between two deadlines](https://jacobiusmakes.github.io/parlayapiR/decision-changes/). In the worked report, one millisecond changes North’s Owls price from 1.90 to 2.10 while two other quotes stay put. Download the project there to generate an HTML comparison from your own CSV with base R.

## 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.
Expand Down
23 changes: 23 additions & 0 deletions tutorials/point-in-time/build-change-report.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Build the public worked example and downloadable project from the same source.
source("replay.R")
source("replay-log.R")
source("change-report.R")
source("register-report.R")
args <- commandArgs(trailingOnly = TRUE)
stopifnot(length(args) == 1L)
dir.create(args[1L], recursive = TRUE, showWarnings = FALSE)
dest <- normalizePath(args[1L], mustWork = TRUE)
before <- "2026-10-01T14:00:06.049Z"
after <- "2026-10-01T14:00:06.050Z"
rows <- decision_changes("example-log.csv", before, after)
stopifnot(nrow(rows) == 3L, sum(rows$change == "Price changed") == 1L)
html <- render_changes(rows, before, after, "change-report.html", example = TRUE)
writeLines(enc2utf8(html), file.path(dest, "index.html"), useBytes = TRUE)
files <- c("CHANGE-REPORT.md", "change-report.R", "change-report.html", "example-log.csv",
"replay.R", "replay-log.R", "test_change_report.R")
archive <- file.path(dest, "project.zip")
if (file.exists(archive)) unlink(archive)
stopifnot(utils::zip(archive, files, flags = "-qX") == 0L)
stopifnot(setequal(utils::unzip(archive, list = TRUE)$Name, files))
register_report(file.path(dirname(dest), "sitemap.xml"),
"https://jacobiusmakes.github.io/parlayapiR/decision-changes/")
13 changes: 2 additions & 11 deletions tutorials/point-in-time/build-clock-report.R
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ build_report <- function(destination) {
dir.create(destination, showWarnings = FALSE, recursive = TRUE)
destination <- normalizePath(destination, mustWork = TRUE)
source("replay.R", local = TRUE)
source("register-report.R", local = TRUE)
t0 <- example_start()
intervals <- clock_intervals(example_log(), "home", t0, t0 + 12)
utc <- function(x) format(x, "%Y-%m-%dT%H:%M:%SZ", tz = "UTC")
Expand Down Expand Up @@ -58,17 +59,7 @@ build_report <- function(destination) {
params = list(start_second = 8, end_second = 9))
check_render(file.path(extracted, "index.html"), "1 second of the 1-second window", 1L)

sitemap <- file.path(dirname(destination), "sitemap.xml")
xml <- xml2::read_xml(sitemap)
locate <- function(x) xml2::xml_text(xml2::xml_find_all(x, "//*[local-name()='loc']"))
before <- locate(xml)
if (!url %in% before) {
node <- xml2::xml_add_child(xml2::xml_root(xml), "url")
xml2::xml_add_child(node, "loc", url)
xml2::write_xml(xml, sitemap)
}
after <- locate(xml2::read_xml(sitemap))
stopifnot(identical(after[after != url], before[before != url]), sum(after == url) == 1L)
register_report(file.path(dirname(destination), "sitemap.xml"), url)
}

args <- commandArgs(trailingOnly = TRUE)
Expand Down
103 changes: 103 additions & 0 deletions tutorials/point-in-time/change-report.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# Source replay.R and replay-log.R before using the functions interactively.
decision_changes <- function(path, before_utc, after_utc) {
before <- parse_utc(before_utc)
after <- parse_utc(after_utc)
if (length(before) != 1L || length(after) != 1L || before >= after)
stop("Choose two increasing UTC decision times.")

rows <- read_log(path)
first <- replay_rows(rows, before)
last <- replay_rows(rows, after)
fields <- c("event_id", "book", "market", "period", "selection")
# A length prefix keeps a separator inside a team or bookmaker name unambiguous.
identity_key <- function(frame) {
if (!nrow(frame)) return(character())
parts <- lapply(frame[fields], function(v) {
v <- enc2utf8(v)
paste0(nchar(v, type = "bytes"), ":", v)
})
do.call(paste0, unname(parts))
}
prior <- match(identity_key(last), identity_key(first))
result <- last[fields]
result$before_state <- first$state[prior]
result$before_state[is.na(prior)] <- "unseen"
result$before_price <- first$decimal_price[prior]
result$before_updated <- first$updated_utc[prior]
result$after_state <- last$state
result$after_price <- last$decimal_price
result$after_updated <- last$updated_utc
change <- rep("Unchanged", nrow(last))
repriced <- result$before_state == "quoted" & result$after_state == "quoted" &
result$before_price != result$after_price
change[repriced] <- "Price changed"
change[result$before_state != result$after_state] <- "State changed"
change[is.na(prior)] <- "First observed"
result$change <- change
result[order(change == "Unchanged", method = "radix"), , drop = FALSE]
}

escape_text <- function(x) {
x <- gsub("&", "&amp;", x, fixed = TRUE)
x <- gsub("<", "&lt;", x, fixed = TRUE)
gsub(">", "&gt;", x, fixed = TRUE)
}

render_changes <- function(rows, before_utc, after_utc, template, example = FALSE) {
quote_label <- function(state, price) {
switch(state, quoted = if (price == round(price, 2)) sprintf("%.2f", price) else as.character(price), withdrawn = "Withdrawn",
conflict = "Conflicting observations", unseen = "Unseen")
}
observation <- function(label, value, updated) {
clock <- if (is.na(updated)) "" else paste0("<small>Source update <time>", escape_text(updated), "</time></small>")
paste0("<div><dt>", label, "</dt><dd>", escape_text(value), "</dd>", clock, "</div>")
}
card <- function(i) {
row <- rows[i, , drop = FALSE]
left <- quote_label(row$before_state, row$before_price)
right <- quote_label(row$after_state, row$after_price)
if (row$change == "Price changed" && identical(left, right)) {
left <- sprintf("%.17g", row$before_price)
right <- sprintf("%.17g", row$after_price)
}
paste0('<article class="selection"><header><h3>', escape_text(row$selection),
'</h3><span>', escape_text(row$change), '</span></header><p class="identity">Book <b>', escape_text(row$book),
'</b> · Event <b>', escape_text(row$event_id), '</b> · Market <b>', escape_text(row$market),
'</b> · Period <b>', escape_text(row$period), '</b></p><dl>',
observation("Before", left, row$before_updated),
observation("After", right, row$after_updated), '</dl></article>')
}
n <- nrow(rows)
count <- sum(rows$change != "Unchanged")
text <- readLines(template, warn = FALSE, encoding = "UTF-8")
# Expand complete marker lines. User text is inserted only as escaped text.
slots <- list(
"<!-- canonical -->" = if (example) '<link rel="canonical" href="https://jacobiusmakes.github.io/parlayapiR/decision-changes/">' else character(),
"<!-- intro -->" = if (example)
"<p>Fictional basketball final. North received a new Harbor Owls price exactly at the second cutoff. South still had 1.95 on the same team.</p>" else
"<p>Selections are matched by event, book, market, period and outcome. Only observations received by each cutoff are eligible.</p>",
"<!-- times -->" = paste0('<dl class="times"><div><dt>First cutoff · UTC</dt><dd>', escape_text(before_utc),
'</dd></div><div><dt>Second cutoff · UTC</dt><dd>', escape_text(after_utc), '</dd></div></dl>'),
"<!-- count -->" = if (n) paste0("<h2>", count, " of ", n, " ",
if (n == 1L) "selection" else "selections", " changed</h2>") else "<h2>No observations yet</h2>",
"<!-- selections -->" = if (n) vapply(seq_len(n), card, character(1)) else
"<p>No selection in this file had been received by the second cutoff.</p>",
"<!-- example links -->" = if (example) c(
'<p><a href="project.zip" download>Download the base R project (ZIP)</a> to generate this report from your own nine-column moneyline CSV.</p>',
'<p>For a collector that uses an account, <a href="https://parlay-api.com/signup?utm_source=r_reference&amp;utm_medium=report&amp;utm_campaign=decision_change_report&amp;utm_content=worked_example">get a ParlayAPI key</a>.</p>'
) else character()
)
for (name in names(slots)) stopifnot(sum(text == name) == 1L)
unlist(lapply(text, function(line) if (line %in% names(slots)) slots[[line]] else line), use.names = FALSE)
}

if (sys.nframe() == 0L) {
args <- commandArgs(trailingOnly = TRUE)
if (length(args) != 3L) stop("Usage: Rscript change-report.R FILE.csv BEFORE_UTC AFTER_UTC", call. = FALSE)
script <- sub("^--file=", "", grep("^--file=", commandArgs(FALSE), value = TRUE))
folder <- dirname(normalizePath(script))
source(file.path(folder, "replay.R"))
source(file.path(folder, "replay-log.R"))
changes <- decision_changes(args[1L], args[2L], args[3L])
writeLines(enc2utf8(render_changes(changes, args[2L], args[3L], file.path(folder, "change-report.html"))), stdout(), useBytes = TRUE)
}
43 changes: 43 additions & 0 deletions tutorials/point-in-time/change-report.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">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'">
<meta name="referrer" content="no-referrer">
<title>Moneyline changes between two deadlines | ParlayAPI</title>
<meta name="description" content="Compare the prices and quote states known at two UTC decision times. Generate the same local report from your moneyline observation log with base R.">
<!-- canonical -->
<style>
*{box-sizing:border-box}body{margin:0;background:#f3f4ef;color:#172d2a;font:1rem/1.55 system-ui,sans-serif}
main{max-width:50rem;margin:0 auto;padding:clamp(1rem,5vw,3.7rem)}h1,h2,h3,p{margin:0 0 .75rem}
h1{font:700 clamp(2.3rem,6vw,4rem)/1.02 Georgia,serif;letter-spacing:-.035em;margin:.75rem 0 1.25rem}
h2{font:700 clamp(1.55rem,3.5vw,2.15rem)/1.15 Georgia,serif;margin:2rem 0 .6rem}
h3{font:700 1.35rem/1.22 Georgia,serif;margin:0}a{color:#185944;text-underline-offset:.18em}
.times,.selection dl{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.9rem; margin:1rem 0 0}
.times{background:#173f37;color:#fff;padding:1rem 1.2rem;border-top:4px solid #d1a15c}
dt,small,.identity{font-size:.88rem}.times dt{color:#c8e3d7}dd{margin:0;overflow-wrap:anywhere}
.times dd,time{font-family:ui-monospace,monospace}.times dd{font-size:.95rem}
.selection{background:#fff;padding:1.05rem 1.2rem;margin:1rem 0;border:1px solid #c8d3c8;border-left:4px solid #577965;break-inside:avoid}
.selection header{display:flex;justify-content:space-between;align-items:baseline;gap:.6rem;flex-wrap:wrap}
.selection header span{color:#305d4a;font-weight:650}.selection h3,.identity,small{overflow-wrap:anywhere}
.selection dd{font-size:1.3rem;font-weight:700}.identity{color:#42534b;margin:.45rem 0}
small{display:block;color:#46574c}small time{display:block}.times div,.selection dl div{min-width:0}
footer{margin-top:2rem;border-top:1px solid #b4c4b7;padding-top:1rem}
@media(max-width:34rem){.times{grid-template-columns:1fr}.selection{padding:.9rem}.selection dl{gap:.55rem}small time{font-size:.76rem}}
@media print{body{background:white}main{padding:0;max-width:none}a{color:inherit}}
</style>
</head>
<body><main>
<p>ParlayAPI · Decision replay</p>
<h1>Moneyline changes between two deadlines</h1>
<!-- intro -->
<!-- times -->
<!-- count -->
<p>A difference means the selection first appeared, its quote state changed or its decimal price changed. An unchanged row can have a newer source timestamp. The report compares two snapshots of the file. Changes between those instants can cancel out.</p>
<!-- selections -->
<footer>
<!-- example links -->
<p><a href="https://github.com/JacobiusMakes/parlayapiR/tree/main/tutorials/point-in-time">Read the replay method</a>. This report uses source updates and your collector’s receipt times.</p>
</footer>
</main></body></html>
12 changes: 12 additions & 0 deletions tutorials/point-in-time/register-report.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
register_report <- function(sitemap, url) {
xml <- xml2::read_xml(sitemap)
locate <- function(x) xml2::xml_text(xml2::xml_find_all(x, "//*[local-name()='loc']"))
before <- locate(xml)
if (!url %in% before) {
node <- xml2::xml_add_child(xml2::xml_root(xml), "url")
xml2::xml_add_child(node, "loc", url)
xml2::write_xml(xml, sitemap)
}
after <- locate(xml2::read_xml(sitemap))
stopifnot(identical(after[after != url], before[before != url]), sum(after == url) == 1L)
}
5 changes: 4 additions & 1 deletion tutorials/point-in-time/replay-log.R
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,10 @@ read_log <- function(file) {
replay_file <- function(path, cutoff_text) {
cutoff <- parse_utc(cutoff_text)
stopifnot(length(cutoff) == 1L)
rows <- read_log(path)
replay_rows(read_log(path), cutoff)
}

replay_rows <- function(rows, cutoff) {
rows <- rows[rows$received <= cutoff, , drop = FALSE]
fields <- c("event_id", "book", "market", "period", "selection")
empty <- rows[FALSE, fields, drop = FALSE]
Expand Down
44 changes: 44 additions & 0 deletions tutorials/point-in-time/test_change_report.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
source("replay.R")
source("replay-log.R")
source("change-report.R")
before <- "2026-10-01T14:00:06.049Z"
after <- "2026-10-01T14:00:06.050Z"
changes <- decision_changes("example-log.csv", before, after)
stopifnot(nrow(changes) == 3L, identical(changes$change, c("Price changed", "Unchanged", "Unchanged")),
changes$before_price[1L] == 1.9, changes$after_price[1L] == 2.1)
empty <- decision_changes("example-log.csv", "2026-01-01T00:00:00Z", "2026-01-02T00:00:00Z")
stopifnot(nrow(empty) == 0L)
withdraw <- decision_changes("example-log.csv", after, "2026-10-01T14:00:09Z")
stopifnot(withdraw$change[1] == "State changed", withdraw$after_state[1] == "withdrawn", is.na(withdraw$after_price[1]))
late <- decision_changes("example-log.csv", after, "2026-10-01T14:00:07Z")
stopifnot(all(late$change == "Unchanged"))
bad <- function(x) inherits(try(x, silent = TRUE), "try-error")
stopifnot(bad(decision_changes("example-log.csv", after, before)),
bad(decision_changes("example-log.csv", after, after)),
bad(decision_changes("example-log.csv", "bad", after)))

log <- read.csv("example-log.csv", colClasses = "character", na.strings = character())
extra <- log[3L, ]
extra$decimal_price <- "2.20"
log <- rbind(log, extra)
log$selection[log$selection == "Harbor Owls"] <- '<Harbor & "Owls">'
tmp <- tempfile(fileext = ".csv")
write.csv(log, tmp, row.names = FALSE)
both <- decision_changes(tmp, before, after)
stopifnot(both$after_state[1] == "conflict", is.na(both$after_price[1]))
html <- paste(render_changes(both, before, after, "change-report.html"), collapse = "\n")
stopifnot(grepl('&lt;Harbor &amp; "Owls"&gt;', html, fixed = TRUE),
!grepl("<Harbor", html, fixed = TRUE), !grepl("project.zip", html, fixed = TRUE),
!grepl('rel="canonical"', html, fixed = TRUE))
# These identities would collide if their fields were joined with a separator.
log <- log[c(1L, 2L), ]
log$event_id <- c("A|B", "A")
log$book <- c("C", "B|C")
log$selection <- "Same team"
log$decimal_price <- c("1.9", "1.8")
write.csv(log, tmp, row.names = FALSE)
new <- decision_changes(tmp, "2026-10-01T14:00:02Z", after)
stopifnot(nrow(new) == 2L, new$change[1] == "First observed",
new$before_state[1] == "unseen", new$after_price[1] == 1.8)
unlink(tmp)
cat("Decision-change report checks passed.\n")
Loading