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/reference.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ 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"))
- 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 and install the documented source package
id: source-package
run: |
Expand Down
4 changes: 4 additions & 0 deletions pkgdown/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

Start with a reproducible example or look up the inputs and return value of a function in the [R package reference](reference/index.html).

## How long did a basketball backtest see a different price?

In a twelve-second fictional log, a withdrawal and two delayed prices change what the analyst could have known. [Read the worked quote history](clock-report/) or [download the editable R Markdown report](clock-report/project.zip).

## Which price was known at the decision time?

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.
Expand Down
2 changes: 1 addition & 1 deletion tutorials/point-in-time/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

At 14:00:04, an analyst records the home team's price as **1.90**. The archive later shows a **2.10** update stamped 14:00:03. Was 1.90 a mistake? Check when the update arrived. The analyst received it at 14:00:06, two seconds after the decision. Giving the analyst 2.10 in a backtest introduces look-ahead bias.

[Compare the two clocks at eight decision times in your browser][interactive]. The interactive version loads R and Shiny in your browser and uses the six fictional messages below. For the offline version, download [replay.R](replay.R) and run `Rscript replay.R` with base R.
[Compare the two clocks at eight decision times in your browser][interactive]. The interactive version loads R and Shiny in your browser and uses the six fictional messages below. [Read the twelve-second report](https://jacobiusmakes.github.io/parlayapiR/clock-report/) to see how long the two histories disagreed. It opens without starting R. To reproduce both columns at all eight decision times, [download the report project](https://jacobiusmakes.github.io/parlayapiR/clock-report/project.zip), extract it and run `Rscript replay.R` in that directory with base R.

| Selection | Source updated (UTC) | Received (UTC) | Decimal price |
|---|---|---|---:|
Expand Down
66 changes: 66 additions & 0 deletions tutorials/point-in-time/build-clock-report.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Run in this directory after pkgdown builds the reference site.
build_report <- function(destination) {
dir.create(destination, showWarnings = FALSE, recursive = TRUE)
destination <- normalizePath(destination, mustWork = TRUE)
source("replay.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")
csv <- data.frame(
start_utc = utc(intervals$cutoff), end_utc = utc(intervals$end),
duration_seconds = intervals$seconds, received_state = intervals$state,
received_price = intervals$price, source_state = intervals$source_state,
source_price = intervals$source_price, different = intervals$different
)
csv_name <- "decision-clock-intervals.csv"
write.csv(csv, file.path(destination, csv_name), row.names = FALSE, na = "")

render <- function(input, out, params = NULL) {
rmarkdown::render(input, output_file = "index.html", output_dir = out,
params = params, envir = new.env(parent = globalenv()), quiet = TRUE)
}
check_render <- function(path, expected, row_count) {
html <- xml2::read_html(path)
result <- xml2::xml_text(xml2::xml_find_first(html, "//*[@class='result']"))
stopifnot(grepl(expected, gsub("[[:space:]]+", " ", result), fixed = TRUE),
length(xml2::xml_find_all(html, "//table/tbody/tr")) == row_count)
}
render("clock-report.Rmd", destination)
check_render(file.path(destination, "index.html"), "7 seconds of the 12-second window", nrow(csv))
stage <- tempfile()
dir.create(stage)
on.exit(unlink(stage, recursive = TRUE), add = TRUE)
sources <- c("clock-report.Rmd", "replay.R", "test_replay.R")
assets <- c("index.html", csv_name)
stopifnot(all(file.copy(sources, stage)), all(file.copy(file.path(destination, assets), stage)))
project <- file.path(destination, "project.zip")
previous <- setwd(stage)
on.exit(setwd(previous), add = TRUE, after = FALSE)
if (file.exists(project)) unlink(project)
stopifnot(utils::zip(project, c(sources, assets), flags = "-q") == 0L,
setequal(utils::unzip(project, list = TRUE)$Name, c(sources, assets)))
extracted <- file.path(stage, "extracted")
utils::unzip(project, exdir = extracted)
stopifnot(identical(unname(tools::md5sum(c(sources, assets))),
unname(tools::md5sum(file.path(extracted, c(sources, assets))))))
render(file.path(extracted, "clock-report.Rmd"), extracted,
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)
url <- "https://jacobiusmakes.github.io/parlayapiR/clock-report/"
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)
}

args <- commandArgs(trailingOnly = TRUE)
stopifnot(length(args) == 1L)
build_report(args[[1L]])
83 changes: 83 additions & 0 deletions tutorials/point-in-time/clock-report.Rmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
---
title: "How long did the basketball backtest see a different price?"
lang: en
output:
html_document:
theme: null
highlight: null
mathjax: null
self_contained: true
header-includes:
- '<link rel="canonical" href="https://jacobiusmakes.github.io/parlayapiR/clock-report/" />'
params:
start_second: 0
end_second: 12
---

<style>
body { box-sizing: border-box; max-width: 48rem; margin: 2rem auto 5rem; padding: 0 1.25rem; background: #fffdf9; color: #182a30; font: 1.06rem/1.55 "Atkinson Hyperlegible Next", Arial, sans-serif; }
h1, h2 { line-height: 1.15; text-wrap: balance; }
h1 { font-size: clamp(2rem, 6vw, 3.25rem); }
h2 { margin-top: 2rem; }
a { color: #155b70; text-underline-offset: .16em; }
.result { border-left: .25rem solid #b9572a; padding: .45rem 1rem; background: #f5eee3; }
table { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; }
th, td { text-align: left; padding: .45rem .55rem; border-bottom: 1px solid #cbd5d4; }
th { vertical-align: bottom; }
caption { text-align: left; margin-bottom: .5rem; font-weight: 600; }
pre { overflow-x: auto; background: #edf2f2; padding: .75rem; }
@media(max-width: 460px) { th, td { padding: .35rem .2rem; } table { font-size: .91rem; } }
</style>

```{r setup, include=FALSE}
source("replay.R", local = TRUE)
t0 <- example_start()
start <- params$start_second
end <- params$end_second
stopifnot(is.numeric(start), is.numeric(end), length(start) == 1L,
length(end) == 1L, is.finite(start), is.finite(end),
start == floor(start), end == floor(end), 0 <= start, start < end, end <= 12)
intervals <- clock_intervals(example_log(), "home", t0 + start, t0 + end)
disagreement <- sum(intervals$seconds[intervals$different])
fmt <- function(state, price) {
labels <- c(unseen = "Unseen", withdrawn = "Withdrawn", conflict = "Conflict")
ifelse(state == "quoted", sprintf("%.2f", price), unname(labels[state]))
}
```

At 14:00:04 in a fictional basketball game, the analyst had decimal odds of **1.90** on the home team. A later archive search turns up **2.10** with a timestamp of 14:00:03. That update reached the analyst at 14:00:06. A backtest that uses it two seconds earlier gives the analyst a price they had yet to see.

::: {.result}
From second **`r start`** up to second **`r end`**, the two histories disagreed for **`r disagreement` `r if (disagreement == 1) "second" else "seconds"`** of the **`r end - start`-second window**. A disagreement means the quoted prices differed or the two clocks gave different availability states.
:::

## Follow the home moneyline

Times below are seconds after 14:00:00 UTC. Each row starts when its first second begins and ends just before the next boundary. A newly arrived message can leave the displayed price unchanged if a newer source update is already known.

```{r intervals-table, echo=FALSE, results='asis'}
display <- data.frame(
Interval = paste(as.numeric(difftime(intervals$cutoff, t0, units = "secs")),
as.numeric(difftime(intervals$end, t0, units = "secs")), sep = "–"),
Analyst = fmt(intervals$state, intervals$price),
Archive = fmt(intervals$source_state, intervals$source_price),
Seconds = intervals$seconds
)
knitr::kable(display, format = "html", row.names = FALSE,
col.names = c("Seconds", "Analyst received", "Source clock", "Duration (s)"),
caption = "Home-team quote history in the selected window")
```

Look at seconds 8–9 in the full log. The source withdrew the quote at second 8. For one more second, the analyst’s last received update still showed 2.10. The log records what the analyst could see. It cannot tell us whether a sportsbook would have accepted a bet.

## Reproduce the report

[Download the R Markdown project and the full twelve-second CSV](https://jacobiusmakes.github.io/parlayapiR/clock-report/project.zip). Extract the ZIP and open a terminal in that directory. Run `Rscript replay.R` with base R to see both clocks at eight selected decision times. Three of those eight decisions differ. The elapsed-time table counts how long each difference lasted.

To change the report window, run the following in R with **rmarkdown**, **knitr** and **Pandoc** installed. It renders a local HTML file. In the window from second 8 up to second 9, the two histories disagree for the entire second.

```r
rmarkdown::render("clock-report.Rmd", params = list(start_second = 8, end_second = 9))
```

[Inspect a public NBA odds sample](https://parlay-api.com/try?utm_source=r_reference&utm_medium=rmarkdown_report&utm_campaign=decision_clock_seconds). To repeat the exercise with your own observations, save the reported market time and record the UTC time your client received each response. A single snapshot cannot reconstruct earlier receipts.
38 changes: 33 additions & 5 deletions tutorials/point-in-time/replay.R
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,38 @@ quote_at <- function(log, stream, cutoff, clock = c("received", "updated")) {
result
}

if (sys.nframe() == 0L) {
log <- example_log()
replay <- lapply(c(0, 4, 6, 7, 9, 11), function(s) {
quote_at(log, "home", example_start() + s)
# Keep the original receipt-based columns and add the retrospective result.
compare_clocks <- function(log, stream, cutoffs) {
stopifnot(inherits(cutoffs, "POSIXct"), length(cutoffs) > 0L)
rows <- lapply(seq_along(cutoffs), function(i) {
received <- quote_at(log, stream, cutoffs[i])
source <- quote_at(log, stream, cutoffs[i], clock = "updated")
received$source_state <- source$state
received$source_updated <- source$updated
received$source_price <- source$price
received$different <- received$state != source$state ||
(received$state == "quoted" && received$price != source$price)
received
})
print(do.call(rbind, replay), row.names = FALSE)
do.call(rbind, rows)
}

# Neither view changes between source or receipt timestamps for this stream.
# Evaluate the left edge of every interval; the end of the window is excluded.
clock_intervals <- function(log, stream, start, end) {
stopifnot(inherits(start, "POSIXct"), inherits(end, "POSIXct"),
length(start) == 1L, length(end) == 1L,
is.finite(start), is.finite(end), end > start)
selected <- log[log$stream == stream, , drop = FALSE]
changes <- c(selected$updated, selected$received)
bounds <- sort(unique(c(start, changes[changes > start & changes < end], end)))
rows <- compare_clocks(log, stream, head(bounds, -1L))
rows$end <- tail(bounds, -1L)
rows$seconds <- as.numeric(difftime(rows$end, rows$cutoff, units = "secs"))
rows
}

if (sys.nframe() == 0L) {
times <- example_start() + c(0, 4, 6, 7, 8, 9, 10, 11)
print(compare_clocks(example_log(), "home", times), row.names = FALSE)
}
21 changes: 21 additions & 0 deletions tutorials/point-in-time/test_replay.R
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,25 @@ stopifnot(from_source(0)$state == "unseen", from_source(4)$price == 2.10,
from_source(9)$state == at(9)$state, from_source(11)$price == at(11)$price,
from_source(4, conflicting)$state == "conflict",
is.na(from_source(4, conflicting)$price))

# Counting deliberately selected cutoffs and measuring elapsed time answer
# different questions. Verify the half-open windows and the two input clocks.
t0 <- example_start()
times <- t0 + c(0, 4, 6, 7, 8, 9, 10, 11)
decisions <- compare_clocks(log, "home", times)
stopifnot(identical(decisions$cutoff[decisions$different], t0 + c(4, 8, 10)),
identical(decisions$source_state[decisions$different], c("quoted", "withdrawn", "quoted")),
identical(decisions$price[decisions$different], c(1.90, 2.10, NA_real_)))
windows <- clock_intervals(log, "home", t0, t0 + 12)
stopifnot(all(windows$seconds > 0), sum(windows$seconds) == 12,
sum(windows$seconds[windows$different]) == 7,
identical(windows, clock_intervals(log[nrow(log):1, ], "home", t0, t0 + 12)))
price_difference <- windows$different & windows$state == "quoted" & windows$source_state == "quoted"
stopifnot(sum(windows$seconds[price_difference]) == 4)
clipped <- clock_intervals(log, "home", t0 + 5.75, t0 + 6.25)
stopifnot(identical(clipped$seconds, c(0.25, 0.25)),
identical(clipped$different, c(TRUE, FALSE)))
missing <- clock_intervals(log, "unknown", t0, t0 + 2)
stopifnot(nrow(missing) == 1L, !missing$different, missing$seconds == 2)
stopifnot(inherits(try(clock_intervals(log, "home", t0, t0), silent = TRUE), "try-error"))
cat("Point-in-time replay checks passed.\n")
Loading