diff --git a/README.md b/README.md index a04d646..10f6210 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. +[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). 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 73c136b..2c88034 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/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.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. To regenerate the example in the extracted directory: @@ -20,4 +20,22 @@ 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. +## 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). + +From the extracted Python kit or this example directory, run the following with the supplied fictional pair. Its collector had both rows at 14:00:06 UTC. + +```sh +python3 replay_pair.py fictional-pair.csv --event fictional-final --team "Harbor Owls" --books north south --received-at 2026-10-01T14:00:06Z > replay.csv +``` + +After the command succeeds, give the R kit the path to that CSV. From its extracted directory, run: + +```sh +Rscript compare-books.R /path/to/replay.csv 2026-10-01T14:00:06Z 2000 fictional-final nba_preview_unspecified "Harbor Owls" north south +``` + +South’s 2.05 leads at the 2,000 ms limit. Change the limit to 1,000 ms and North’s 1,500 ms source age rules out the comparison. The public preview omits the period, so its exported rows have their own scope. A missing market clock, ambiguous price or update later than receipt stops the conversion before it writes any rows. Use a known receipt for each snapshot and keep the original files. + For a larger private project, [set up your own API key](https://parlay-api.com/signup?utm_source=github&utm_medium=python_tutorial&utm_campaign=nba_csv_report&utm_content=reader). Check plan access and endpoint cost for your request. diff --git a/examples/nba-csv-report/fictional-pair.csv b/examples/nba-csv-report/fictional-pair.csv new file mode 100644 index 0000000..8b37c11 --- /dev/null +++ b/examples/nba-csv-report/fictional-pair.csv @@ -0,0 +1,3 @@ +event_id,sport_key,home_team,away_team,commence_time,bookmaker_key,bookmaker_title,bookmaker_last_update,market_key,market_last_update,outcome_name,point,price +fictional-final,basketball_nba,Harbor Owls,Valley Foxes,,north,Fictional north,,h2h,2026-10-01T14:00:04.500Z,Harbor Owls,,-110 +fictional-final,basketball_nba,Harbor Owls,Valley Foxes,,south,Fictional south,,h2h,2026-10-01T14:00:05.500Z,Harbor Owls,,105 diff --git a/examples/nba-csv-report/replay_pair.py b/examples/nba-csv-report/replay_pair.py new file mode 100644 index 0000000..7734f4f --- /dev/null +++ b/examples/nba-csv-report/replay_pair.py @@ -0,0 +1,83 @@ +"""Convert two selected NBA moneyline prices and one recorded receipt to a local replay CSV.""" + +import argparse +import csv +import datetime as dt +import re +import sys +from decimal import Decimal +from pathlib import Path + +from report import american_price, load_rows + + +COLUMNS = ("event_id", "book", "market", "period", "selection", "updated_utc", + "received_utc", "state", "decimal_price") +CLOCK = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}" + r"(?:\.([0-9]+))?(?:Z|[+-](?:[01][0-9]|2[0-3]):[0-5][0-9])") + + +def utc_ms(text): + match = CLOCK.fullmatch(text) + if not match or text.endswith("-00:00"): + raise ValueError("Use a recorded timestamp with a known UTC offset.") + fraction = match.group(1) or "" + if fraction[3:].strip("0"): + raise ValueError("This replay needs timestamps representable in whole milliseconds.") + if fraction: + # Python 3.9 accepts three or six fractional digits. + text = text[:20] + fraction[:3].ljust(3, "0") + text[20 + len(fraction):] + instant = dt.datetime.fromisoformat(text.replace("Z", "+00:00")).astimezone(dt.timezone.utc) + return instant.isoformat(timespec="milliseconds").replace("+00:00", "Z") + + +def replay_pair(source, *, event, team, books, received_at): + if len(books) != 2 or books[0] == books[1]: + raise ValueError("Choose two different bookmaker keys.") + receipt = utc_ms(received_at) + events, groups = load_rows(source) + if event not in events or team not in events[event]: + raise ValueError("Choose an event ID and team present in this NBA export.") + result = [] + for book in books: + matched = [r for r in groups.get((event, book), []) if r["outcome_name"] == team] + if len(matched) != 1: + raise ValueError(f"{book}: expected one selected team price, found {len(matched)}.") + row = matched[0] + price_text = american_price(row) + if price_text is None or not row["market_last_update"]: + raise ValueError(f"{book}: a valid American price and market update time are required.") + updated = utc_ms(row["market_last_update"]) + if updated > receipt: + raise ValueError(f"{book}: the market update falls after your recorded receipt.") + price = Decimal(price_text) + decimal = 1 + (price / 100 if price > 0 else 100 / abs(price)) + if not 1 < float(decimal) < float("inf"): + raise ValueError(f"{book}: decimal price cannot be represented by the R reader.") + # The public preview does not specify the period or settlement rule. + result.append((event, book, "h2h", "nba_preview_unspecified", team, updated, + receipt, "quoted", str(decimal))) + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("csv_file", type=Path) + 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.") + 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) + 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") + writer.writerow(COLUMNS) + writer.writerows(rows) + + +if __name__ == "__main__": + main() diff --git a/examples/nba-csv-report/test_replay_pair.py b/examples/nba-csv-report/test_replay_pair.py new file mode 100644 index 0000000..009ae35 --- /dev/null +++ b/examples/nba-csv-report/test_replay_pair.py @@ -0,0 +1,41 @@ +import io +import unittest +from pathlib import Path + +from replay_pair import replay_pair, utc_ms + + +class PairTest(unittest.TestCase): + def setUp(self): + self.text = Path(__file__).with_name("fictional-pair.csv").read_text() + self.args = dict(event="fictional-final", team="Harbor Owls", + books=["north", "south"], received_at="2026-10-01T14:00:06Z") + + def test_fixture(self): + a, b = replay_pair(io.StringIO(self.text), **self.args) + self.assertEqual([a[1], b[1]], self.args["books"]) + self.assertEqual(a[3], "nba_preview_unspecified") + self.assertEqual(a[6], "2026-10-01T14:00:06.000Z") + self.assertAlmostEqual(float(a[-1]), 1 + 100 / 110) + self.assertEqual(float(b[-1]), 2.05) + + def test_exact_offsets_and_precision(self): + self.assertEqual(utc_ms("2026-10-01T10:00:05.50-04:00"), "2026-10-01T14:00:05.500Z") + self.assertEqual(utc_ms("2026-10-01T14:00:05.12300000+00:00"), "2026-10-01T14:00:05.123Z") + for clock in ["2026-10-01T14:00:05.1234Z","2026-10-01T14:00:05", + "2026-10-01T14:00:05-00:00","2026-10-01T14:00:05+01:71"]: + with self.subTest(clock=clock), self.assertRaises(ValueError): + utc_ms(clock) + + def test_missing_ambiguous_future_and_wrong_scope(self): + for text in [self.text.replace("14:00:05.500Z","14:01:05.500Z"), + self.text.replace("2026-10-01T14:00:05.500Z",""), + self.text.replace("fictional-final","rematch",1), + self.text + self.text.splitlines()[-1] + "\n", + self.text.replace(",105\n",",N/A\n"), + self.text.replace("basketball_nba","baseball_mlb",1)]: + with self.subTest(text=text), self.assertRaises(ValueError): + replay_pair(io.StringIO(text), **self.args) + for books in [["north","north"],["north","absent"]]: + with self.subTest(books=books), self.assertRaises(ValueError): + replay_pair(io.StringIO(self.text), **dict(self.args, books=books))