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
4 changes: 2 additions & 2 deletions .github/workflows/starter.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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: |
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/).
Expand Down
22 changes: 21 additions & 1 deletion examples/nba-csv-report/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand All @@ -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).
Expand Down
87 changes: 87 additions & 0 deletions examples/nba-csv-report/capture.py
Original file line number Diff line number Diff line change
@@ -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()
21 changes: 17 additions & 4 deletions examples/nba-csv-report/replay_pair.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down
8 changes: 6 additions & 2 deletions examples/nba-csv-report/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -90,13 +92,15 @@ def describe(rows, teams):
"""


def render(file, example=False):
def render(file, example=False, received_utc=None):
events, groups = load_rows(file)
parts = ['<!doctype html><html lang="en"><head><meta charset="utf-8">',
'<meta name="viewport" content="width=device-width,initial-scale=1">',
'<title>NBA moneyline CSV report</title><style>' + STYLE + '</style></head><body><main>',
'<h1>NBA moneyline report</h1>',
'<p>American prices from the supplied CSV, grouped by event and bookmaker. The clock comes from the market’s update field.</p>']
if received_utc is not None:
parts.append(f'<p>Local collector received this response by <time>{escape(received_utc)}</time>.</p>')
if example:
parts.append('<p><strong>Fictional example.</strong> The teams, bookmakers and prices below are for rehearsal.</p>')
for event, keys in itertools.groupby(sorted(groups), key=lambda key: key[0]):
Expand Down
105 changes: 105 additions & 0 deletions examples/nba-csv-report/test_capture.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
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": "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"}]}])


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.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)
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])
4 changes: 3 additions & 1 deletion examples/odds_workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading