From 7e0934735a12478f71353d1fca83b0a28d134b8b Mon Sep 17 00:00:00 2001 From: Esther-MacMini Date: Sat, 5 Dec 2026 04:22:34 -0500 Subject: [PATCH 1/2] Record a local receipt with a one-request NBA preview --- .github/workflows/starter.yml | 4 +- README.md | 2 +- examples/nba-csv-report/README.md | 22 ++++- examples/nba-csv-report/capture.py | 87 ++++++++++++++++++++ examples/nba-csv-report/replay_pair.py | 21 ++++- examples/nba-csv-report/report.py | 4 +- examples/nba-csv-report/test_capture.py | 104 ++++++++++++++++++++++++ 7 files changed, 235 insertions(+), 9 deletions(-) create mode 100644 examples/nba-csv-report/capture.py create mode 100644 examples/nba-csv-report/test_capture.py diff --git a/.github/workflows/starter.yml b/.github/workflows/starter.yml index e4185da..c809908 100644 --- a/.github/workflows/starter.yml +++ b/.github/workflows/starter.yml @@ -45,12 +45,12 @@ jobs: python: ['3.9', '3.13'] steps: - uses: actions/checkout@v4 - - name: Check the local moneyline report - run: python3 -m unittest discover -s examples/nba-csv-report - uses: actions/setup-python@v5 with: python-version: ${{ matrix.python }} - run: python -m pip install ".[ws]" pytest + - name: Check the local moneyline report + run: python -m unittest discover -s examples/nba-csv-report - name: Exercise the installed CLI outside the checkout working-directory: ${{ runner.temp }} run: | diff --git a/README.md b/README.md index 324d891..974f481 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Open `odds.csv` and look for an event, bookmaker, outcome and price. A header alone means there were no usable rows in this response. You can also [inspect the NBA demo in your browser](https://parlay-api.com/v1/try/basketball_nba/odds). -[Turn your NBA CSV into an offline game-by-game report](examples/nba-csv-report/). See both team prices from each bookmaker, along with missing sides and market clocks. The kit includes a fictional report you can open immediately. If your collector saved the receipt time, [compare two books at that deadline](examples/nba-csv-report/README.md#can-you-compare-both-prices-at-a-deadline). +[Turn your NBA CSV into an offline game-by-game report](examples/nba-csv-report/). See both team prices from each bookmaker, along with missing sides and market clocks. The kit includes a fictional report you can open immediately. [Record the receipt time with your next NBA preview](examples/nba-csv-report/README.md#record-a-board-for-a-deadline-replay) to compare two books at a deadline. The downloadable recorder also saves an HTML report and keeps earlier captures. For a DataFrame, [watch the five-minute Python walkthrough](https://www.youtube.com/watch?v=y-OUqORA8wo) or [open the notebook and transcript](https://jacobiusmakes.github.io/parlayapi-notebooks/first-request/). diff --git a/examples/nba-csv-report/README.md b/examples/nba-csv-report/README.md index 2c88034..5194f88 100644 --- a/examples/nba-csv-report/README.md +++ b/examples/nba-csv-report/README.md @@ -2,7 +2,7 @@ Which bookmaker supplied both team prices? Which market supplied a timestamp? Generate a standalone HTML report with Python 3.9 or newer. The reporter reads a local CSV and the resulting page works offline. -[Download the report kit](https://github.com/JacobiusMakes/parlay-api-python/releases/download/nba-csv-report-v1.1/nba-csv-report.zip). Open `fictional-report.html` to see the example immediately. North has both prices. South has only the Owls price, with its market time missing. +[Download the report kit](https://github.com/JacobiusMakes/parlay-api-python/releases/download/nba-csv-report-v1.2/nba-csv-report.zip). Open `fictional-report.html` to see the example immediately. North has both prices. South has only the Owls price, with its market time missing. To regenerate the example in the extracted directory: @@ -20,6 +20,26 @@ python3 -m parlay_api --sport basketball_nba > odds.csv && python3 report.py odd Open `nba-report.html`. Each game retains its event ID, and each row uses one bookmaker’s NBA moneyline outcomes. A dash marks a missing or unusable price. Conflicting or extra selections make the row ambiguous. If the market clock is missing, the page leaves that visible. A header-only export gives an empty report. Check the starter’s diagnostics for skipped rows. +## Record a board for a deadline replay + +The previous CSV on disk may have been copied hours after the game. To record when **your computer** had a board, run this command from the extracted report kit with Python 3.9 or later. The kit includes the CSV reader and needs no install or account. + +```sh +python3 capture.py +``` + +It makes one request to the public NBA preview, ignores API keys and prints the path to a new folder. Open `report.html` for the matchups and per-book prices. Keep `receipt.json` with `odds.csv`. The receipt records the time just after the response body was read on your machine, rounded up to the next whole millisecond when needed. The market update times remain in the CSV. Clock accuracy depends on your computer. + +A successful empty board produces a receipt with zero events. The receipt also counts exported rows and validation issues, so five events with no usable prices can be distinguished from zero events. Each run creates its own folder. A refused or incomplete request produces no snapshot. + +To replay a selected team, use the printed folder path, an event ID, team and two book keys from the report. For example, adapt the following fictional identifiers to your own capture. + +```sh +python3 replay_pair.py nba-preview-YOUR-FOLDER/odds.csv --receipt nba-preview-YOUR-FOLDER/receipt.json --event fictional-final --team "Harbor Owls" --books north south +``` + +The converter checks the receipt against the CSV’s exact bytes. Keep each receipt with its original capture. Identical CSV rows can recur at different times. Both selections need a valid price and market time. For a private integration that needs more than this sample, [create a project API key](https://parlay-api.com/signup?utm_source=github&utm_medium=python_tutorial&utm_campaign=nba_csv_report&utm_content=recorder) and check the cost of the route you intend to use. + ## Can you compare both prices at a deadline? The starter CSV records the market update time. A replay also needs the time your collector had the response. File modification time cannot recover that observation. If you recorded both clocks, the included converter can export one team from two named books to the [base-R replay kit](https://github.com/JacobiusMakes/parlayapiR/releases/tag/two-book-replay-v1). diff --git a/examples/nba-csv-report/capture.py b/examples/nba-csv-report/capture.py new file mode 100644 index 0000000..5426cee --- /dev/null +++ b/examples/nba-csv-report/capture.py @@ -0,0 +1,87 @@ +"""Record one public NBA moneyline preview into a new local folder.""" +import argparse +from collections import Counter +from datetime import datetime, timezone +from hashlib import sha256 +import http.client +import io +import json +from pathlib import Path +import shutil +import tempfile +import time +from urllib.error import HTTPError, URLError +from urllib.request import Request, build_opener + +import odds_workspace as workspace +from report import render + +MAX_BYTES = 10_000_000 + + +def record(parent): + args = workspace.parse_args(["--sport", "basketball_nba"]) + url = workspace.request_url(args) + request = Request(url, headers={"Accept": "application/json", "User-Agent": workspace.USER_AGENT}) + with build_opener(workspace.NoRedirect()).open(request, timeout=30) as response: + if response.status != 200: + raise ValueError("Expected an HTTP 200 response.") + body = response.read(MAX_BYTES + 1) + received_ns = time.time_ns() + if len(body) > MAX_BYTES: + raise ValueError("The response exceeds 10 MB.") + length = response.headers.get("Content-Length") + if length is not None and int(length) != len(body): + raise ValueError("The response length disagrees with Content-Length.") + + payload = json.loads(body) + rows, issues = workspace.validate_response(payload, args) + if (payload.get("sport_key") != args.sport or type(payload.get("events_returned")) is not int + or payload["events_returned"] != len(payload["events"])): + raise ValueError("The preview did not confirm the sport and returned event count.") + + # A millisecond-resolution replay must never place receipt before the body was read. + seconds, ms = divmod((received_ns + 999_999) // 1_000_000, 1000) + instant = datetime.fromtimestamp(seconds, timezone.utc).replace(microsecond=ms * 1000) + received = instant.isoformat(timespec="milliseconds").replace("+00:00", "Z") + csv_text = workspace.to_csv(rows) + csv_bytes = csv_text.encode("utf-8") + receipt = { + "format": "parlay-nba-preview-receipt-v1", "url": url, "received_utc": received, + "events_returned": len(payload["events"]), "exported_rows": len(rows), + "validation_issues": dict(Counter(issue["code"] for issue in issues)), + "csv_sha256": sha256(csv_bytes).hexdigest(), + } + page = render(io.StringIO(csv_text), received_utc=received) + folder = Path(tempfile.mkdtemp(prefix="nba-preview-", dir=parent)) + try: + (folder / "odds.csv").write_bytes(csv_bytes) + (folder / "receipt.json").write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8") + (folder / "report.html").write_text(page, encoding="utf-8") + except OSError: + shutil.rmtree(folder) + raise + return folder, receipt + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output-dir", type=Path, default=Path.cwd(), help="Existing parent directory.") + args = parser.parse_args() + if not args.output_dir.is_dir(): + parser.error("Choose an existing output directory.") + try: + folder, receipt = record(args.output_dir) + except HTTPError as exc: + exc.close() + parser.exit(1, f"HTTP {exc.code}. No snapshot saved.\n") + except (OSError, ValueError, URLError, http.client.HTTPException) as exc: + parser.exit(1, f"Could not record this request: {exc}\n") + print(f"{receipt['events_returned']} events, {receipt['exported_rows']} exported rows, " + f"{sum(receipt['validation_issues'].values())} validation issues.") + print(f"Local receipt (UTC): {receipt['received_utc']}") + print(f"Open {folder / 'report.html'}") + + +if __name__ == "__main__": + main() diff --git a/examples/nba-csv-report/replay_pair.py b/examples/nba-csv-report/replay_pair.py index 7734f4f..8836ef3 100644 --- a/examples/nba-csv-report/replay_pair.py +++ b/examples/nba-csv-report/replay_pair.py @@ -3,6 +3,9 @@ import argparse import csv import datetime as dt +from hashlib import sha256 +import io +import json import re import sys from decimal import Decimal @@ -66,12 +69,22 @@ def main(): parser.add_argument("--event", required=True) parser.add_argument("--team", required=True) parser.add_argument("--books", required=True, nargs=2, metavar=("BOOK_A", "BOOK_B")) - parser.add_argument("--received-at", required=True, help="When your collector had this snapshot.") + clock = parser.add_mutually_exclusive_group(required=True) + clock.add_argument("--received-at", help="When your collector had this snapshot.") + clock.add_argument("--receipt", type=Path, help="Local capture.py receipt for the same CSV.") args = parser.parse_args() try: - with args.csv_file.open(newline="", encoding="utf-8-sig") as source: - rows = replay_pair(source, event=args.event, team=args.team, books=args.books, - received_at=args.received_at) + raw = args.csv_file.read_bytes() + received = args.received_at + if args.receipt: + receipt = json.loads(args.receipt.read_text(encoding="utf-8")) + if (not isinstance(receipt, dict) or receipt.get("format") != "parlay-nba-preview-receipt-v1" + or receipt.get("csv_sha256") != sha256(raw).hexdigest() + or not isinstance(receipt.get("received_utc"), str)): + raise ValueError("Use the recorder receipt that matches these CSV bytes.") + received = receipt["received_utc"] + with io.StringIO(raw.decode("utf-8-sig"), newline="") as source: + rows = replay_pair(source, event=args.event, team=args.team, books=args.books, received_at=received) except (ValueError, OverflowError, ArithmeticError, OSError, csv.Error) as exc: parser.exit(1, f"Cannot export the selected pair: {exc}\n") writer = csv.writer(sys.stdout, lineterminator="\n") diff --git a/examples/nba-csv-report/report.py b/examples/nba-csv-report/report.py index 79a006a..f00ac1b 100644 --- a/examples/nba-csv-report/report.py +++ b/examples/nba-csv-report/report.py @@ -90,13 +90,15 @@ def describe(rows, teams): """ -def render(file, example=False): +def render(file, example=False, received_utc=None): events, groups = load_rows(file) parts = ['', '', 'NBA moneyline CSV report
', '

NBA moneyline report

', '

American prices from the supplied CSV, grouped by event and bookmaker. The clock comes from the market’s update field.

'] + if received_utc is not None: + parts.append(f'

Local collector received this response by .

') if example: parts.append('

Fictional example. The teams, bookmakers and prices below are for rehearsal.

') for event, keys in itertools.groupby(sorted(groups), key=lambda key: key[0]): diff --git a/examples/nba-csv-report/test_capture.py b/examples/nba-csv-report/test_capture.py new file mode 100644 index 0000000..2ae9ef1 --- /dev/null +++ b/examples/nba-csv-report/test_capture.py @@ -0,0 +1,104 @@ +import csv +import io +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +from capture import record + +BASE = Path(__file__).parent +URL = "https://parlay-api.com/v1/try/basketball_nba/odds" + + +class Response(io.BytesIO): + def __init__(self, body, status=200, length=None): + super().__init__(body) + self.status = status + self.headers = {"Content-Length": str(len(body) if length is None else length)} + + +def demo(events): + return {"demo": True, "sport_key": "basketball_nba", "events_returned": len(events), "events": events} + + +def fixture(): + book = {"key": "north", "markets": [{"key": "h2h", "last_update": "2026-01-01T00:00:00Z", + "outcomes": [{"name": "Owls", "price": -110}, {"name": "Foxes", "price": 105}]}]} + return demo([{"id": "demo-game", "sport_key": "basketball_nba", "home_team": "Owls", + "away_team": "Foxes", "bookmakers": [book, {**book, "key": "south"}]}]) + + +class CaptureTest(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.parent = Path(temp.name) + + def capture(self, data, **response_options): + response = Response(json.dumps(data).encode(), **response_options) + def measured(): + self.assertEqual(response.tell(), len(response.getvalue())) + return 1767225600000000001 + with patch("capture.build_opener") as opener, patch("capture.time.time_ns", measured), \ + patch.dict(os.environ, {"PARLAY_API_KEY": "dummy", "PARLAYAPI_KEY": "dummy"}): + opener.return_value.open.return_value = response + try: + return record(self.parent) + finally: + opener.return_value.open.assert_called_once() + request = opener.return_value.open.call_args.args[0] + self.assertEqual(request.full_url, URL) + self.assertEqual(request.get_method(), "GET") + self.assertEqual(set(dict(request.header_items())), {"Accept", "User-agent"}) + + def replay(self, folder): + return subprocess.run([sys.executable, str(BASE / "replay_pair.py"), str(folder / "odds.csv"), + "--receipt", str(folder / "receipt.json"), "--event", "demo-game", + "--team", "Owls", "--books", "north", "south"], capture_output=True, text=True) + + def test_receipt_rounds_up_and_replays_exact_csv(self): + folder, receipt = self.capture(fixture()) + self.assertEqual(receipt["exported_rows"], 4) + self.assertEqual(receipt["received_utc"], "2026-01-01T00:00:00.001Z") + self.assertIn(receipt["received_utc"], (folder / "report.html").read_text()) + replay = self.replay(folder) + self.assertEqual(replay.returncode, 0, replay.stderr) + rows = list(csv.DictReader(io.StringIO(replay.stdout))) + self.assertEqual([row["received_utc"] for row in rows], [receipt["received_utc"]] * 2) + with (folder / "odds.csv").open("ab") as f: + f.write(b"\n") + replay = self.replay(folder) + self.assertEqual(replay.returncode, 1) + self.assertEqual(replay.stdout, "") + self.assertIn("matches these CSV bytes", replay.stderr) + + def test_empty_then_unpriced_keeps_both_captures(self): + folder, first = self.capture(demo([])) + unpriced = fixture() + unpriced["events"][0]["bookmakers"] = [] + second_folder, second = self.capture(unpriced) + self.assertEqual((first["events_returned"], first["exported_rows"]), (0, 0)) + self.assertEqual((second["events_returned"], second["exported_rows"]), (1, 0)) + self.assertNotEqual(folder, second_folder) + self.assertEqual(json.loads((folder / "receipt.json").read_text()), first) + + def test_rejected_responses_create_no_folder(self): + for data, options in ((demo([]), {"length": 900}), (demo([]), {"status": 429}), + ({**demo([]), "sport_key": "icehockey_nhl"}, {}), + ({**demo([]), "events_returned": 2}, {}), ([], {})): + with self.subTest(data=data, options=options): + with self.assertRaises(ValueError): + self.capture(data, **options) + self.assertEqual(list(self.parent.iterdir()), []) + + def test_failed_write_removes_only_its_capture(self): + original, _ = self.capture(demo([])) + with patch.object(Path, "write_bytes", side_effect=OSError("full disk")): + with self.assertRaises(OSError): + self.capture(demo([])) + self.assertEqual(list(self.parent.iterdir()), [original]) From 16be964d8245955a9722e3aeb5b07a98a5a6df7c Mon Sep 17 00:00:00 2001 From: Esther-MacMini Date: Sat, 5 Dec 2026 04:23:46 -0500 Subject: [PATCH 2/2] Preserve fractional source clocks when reading the report with Python 3.9 --- examples/nba-csv-report/report.py | 4 +++- examples/nba-csv-report/test_capture.py | 3 ++- examples/odds_workspace.py | 4 +++- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/examples/nba-csv-report/report.py b/examples/nba-csv-report/report.py index f00ac1b..6acc046 100644 --- a/examples/nba-csv-report/report.py +++ b/examples/nba-csv-report/report.py @@ -60,7 +60,9 @@ def clock_label(rows): if not re.fullmatch(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})", value): return "Market time missing an offset or unreadable" try: - dt.datetime.fromisoformat(value.replace("Z", "+00:00")) + # Validate the calendar fields on Python 3.9, retaining all supplied fraction digits in the export. + whole_second = re.sub(r"\.[0-9]+(?=Z|[+-])", "", value) + dt.datetime.fromisoformat(whole_second.replace("Z", "+00:00")) except ValueError: return "Market time unreadable" if len(set(values)) != 1: diff --git a/examples/nba-csv-report/test_capture.py b/examples/nba-csv-report/test_capture.py index 2ae9ef1..a4cc50b 100644 --- a/examples/nba-csv-report/test_capture.py +++ b/examples/nba-csv-report/test_capture.py @@ -27,7 +27,7 @@ def demo(events): def fixture(): - book = {"key": "north", "markets": [{"key": "h2h", "last_update": "2026-01-01T00:00:00Z", + book = {"key": "north", "markets": [{"key": "h2h", "last_update": "2025-12-31T23:59:59.1230000Z", "outcomes": [{"name": "Owls", "price": -110}, {"name": "Foxes", "price": 105}]}]} return demo([{"id": "demo-game", "sport_key": "basketball_nba", "home_team": "Owls", "away_team": "Foxes", "bookmakers": [book, {**book, "key": "south"}]}]) @@ -64,6 +64,7 @@ def replay(self, folder): def test_receipt_rounds_up_and_replays_exact_csv(self): folder, receipt = self.capture(fixture()) self.assertEqual(receipt["exported_rows"], 4) + self.assertIn("2025-12-31T23:59:59.1230000Z", (folder / "odds.csv").read_text()) self.assertEqual(receipt["received_utc"], "2026-01-01T00:00:00.001Z") self.assertIn(receipt["received_utc"], (folder / "report.html").read_text()) replay = self.replay(folder) diff --git a/examples/odds_workspace.py b/examples/odds_workspace.py index 355402a..5dafb4d 100644 --- a/examples/odds_workspace.py +++ b/examples/odds_workspace.py @@ -113,7 +113,9 @@ def stamp(value, event_id, book_key=None, market_key=None): r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})", value ): raise ValueError() - datetime.fromisoformat(value.replace("Z", "+00:00")) + # Validate the calendar fields on Python 3.9, retaining all supplied fraction digits in the export. + whole_second = re.sub(r"\.[0-9]+(?=Z|[+-])", "", value) + datetime.fromisoformat(whole_second.replace("Z", "+00:00")) return value except ValueError: issue("invalid_timestamp", event_id, book_key, market_key)