From 4bf2db2cfd52093ef2b7e0fe0c447f5338c7a31b Mon Sep 17 00:00:00 2001 From: Esther-MacMini Date: Thu, 3 Dec 2026 08:36:00 -0500 Subject: [PATCH] Render the first NBA CSV as a private offline market report --- .github/workflows/starter.yml | 4 + README.md | 2 + examples/nba-csv-report/README.md | 23 +++++ examples/nba-csv-report/fictional.csv | 4 + examples/nba-csv-report/report.py | 136 +++++++++++++++++++++++++ examples/nba-csv-report/test_report.py | 72 +++++++++++++ 6 files changed, 241 insertions(+) create mode 100644 examples/nba-csv-report/README.md create mode 100644 examples/nba-csv-report/fictional.csv create mode 100644 examples/nba-csv-report/report.py create mode 100644 examples/nba-csv-report/test_report.py diff --git a/.github/workflows/starter.yml b/.github/workflows/starter.yml index 336727b..a161b44 100644 --- a/.github/workflows/starter.yml +++ b/.github/workflows/starter.yml @@ -7,6 +7,7 @@ on: - 'examples/websocket_stream.py' - 'examples/websocket-replay/**' - 'examples/support-report/**' + - 'examples/nba-csv-report/**' - 'examples/test_odds_workspace.py' - 'parlay_api/**' - 'tests/**' @@ -20,6 +21,7 @@ on: - 'examples/websocket_stream.py' - 'examples/websocket-replay/**' - 'examples/support-report/**' + - 'examples/nba-csv-report/**' - 'parlay_api/**' - 'pyproject.toml' permissions: @@ -33,6 +35,8 @@ 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 }} diff --git a/README.md b/README.md index 78096d2..72db076 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,8 @@ 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. + 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/). The lesson starts with two fictional outcomes and shows how to keep each diff --git a/examples/nba-csv-report/README.md b/examples/nba-csv-report/README.md new file mode 100644 index 0000000..73c136b --- /dev/null +++ b/examples/nba-csv-report/README.md @@ -0,0 +1,23 @@ +# Read an NBA odds CSV by game and bookmaker + +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. + +To regenerate the example in the extracted directory: + +```sh +python3 report.py --example > local-example.html +``` + +## Read your first API response + +Use a Python environment with the [ParlayAPI Python SDK](https://github.com/JacobiusMakes/parlay-api-python#readme) installed. This shell command uses the public NBA preview. The report runs after the fetch exits successfully. + +```sh +python3 -m parlay_api --sport basketball_nba > odds.csv && python3 report.py odds.csv > nba-report.html +``` + +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. + +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.csv b/examples/nba-csv-report/fictional.csv new file mode 100644 index 0000000..19a3e25 --- /dev/null +++ b/examples/nba-csv-report/fictional.csv @@ -0,0 +1,4 @@ +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:01Z,Harbor Owls,,-115 +fictional-final,basketball_nba,Harbor Owls,Valley Foxes,,north,Fictional north,,h2h,2026-10-01T14:00:01Z,Valley Foxes,,105 +fictional-final,basketball_nba,Harbor Owls,Valley Foxes,,south,Fictional south,,h2h,,Harbor Owls,,110 diff --git a/examples/nba-csv-report/report.py b/examples/nba-csv-report/report.py new file mode 100644 index 0000000..79a006a --- /dev/null +++ b/examples/nba-csv-report/report.py @@ -0,0 +1,136 @@ +"""Render an offline HTML report from the ParlayAPI Python starter's NBA CSV.""" + +import argparse +import csv +import datetime as dt +import itertools +import re +import sys +from collections import defaultdict +from decimal import Decimal, InvalidOperation +from html import escape +from pathlib import Path + +REQUIRED = { + "event_id", "sport_key", "home_team", "away_team", "bookmaker_key", + "market_key", "market_last_update", "outcome_name", "point", "price", +} + + +def load_rows(file): + reader = csv.DictReader(file, strict=True) + fields = reader.fieldnames or [] + if not REQUIRED.issubset(fields) or len(fields) != len(set(fields)): + raise ValueError("Use the Python starter CSV with all required columns.") + events = {} + groups = defaultdict(list) + for row in reader: + if None in row or any(value is None for value in row.values()): + raise ValueError("A CSV row has the wrong number of fields.") + event, book = row["event_id"], row["bookmaker_key"] + teams = row["home_team"], row["away_team"] + if row["sport_key"] != "basketball_nba" or row["market_key"] != "h2h" or row["point"]: + raise ValueError("Use an NBA h2h export with no point or line.") + if not all(value.strip() for value in (event, book, *teams)) or teams[0] == teams[1]: + raise ValueError("An event, bookmaker or team identity is missing or ambiguous.") + if events.setdefault(event, teams) != teams: + raise ValueError("The same event ID has inconsistent teams.") + groups[event, book].append(row) + return events, groups + + +def american_price(row): + raw = row["price"].strip() + if not re.fullmatch(r"[+-]?[0-9]+(?:\.[0-9]+)?", raw): + return None + try: + price = Decimal(raw) + except InvalidOperation: + return None + if not price.is_finite() or price.copy_abs() < 100: + return None + return raw if raw[0] in "+-" else "+" + raw + + +def clock_label(rows): + values = [row["market_last_update"] for row in rows] + if not all(values): + return "Market time missing" + for value in values: + 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")) + except ValueError: + return "Market time unreadable" + if len(set(values)) != 1: + return "Market time fields differ" + return values[0] + + +def describe(rows, teams): + by_team = defaultdict(list) + for row in rows: + by_team[row["outcome_name"]].append(row) + if set(by_team) - set(teams) or any(len(side) > 1 for side in by_team.values()): + return ["—", "—"], "Ambiguous outcomes" + prices = [american_price(by_team[team][0]) if by_team[team] else None for team in teams] + status = "Both prices" if all(prices) else "Missing or invalid price" + return [price or "—" for price in prices], status + + +STYLE = """ +*{box-sizing:border-box}body{margin:0;background:#fbfaf5;color:#162d37;font:16px/1.5 system-ui,sans-serif} +main{max-width:58rem;margin:auto;padding:2.5rem 1rem}h1{font-size:clamp(2rem,6vw,3.6rem);line-height:1.05;margin:0 0 .7rem} +h2{margin-bottom:.25rem;line-height:1.2}p{max-width:68ch}section{margin-top:2rem;border-top:3px solid #286251} +table{width:100%;border-collapse:collapse;background:white}caption,p.id{text-align:left;color:#43565b} +caption{padding:0 0 .6rem}th,td{text-align:left;vertical-align:top;border-bottom:1px solid #c8d4ce;padding:.65rem;overflow-wrap:anywhere} +.id{font: .86rem ui-monospace,monospace;overflow-wrap:anywhere}thead{background:#e3eee7}th[scope=row]{font-family:ui-monospace,monospace} +@media(max-width:580px){main{padding:1.2rem .75rem}th,td{padding:.35rem;font-size:.85rem}.market{display:block}} +""" + + +def render(file, example=False): + 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 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]): + home, away = events[event] + parts += [f'

{escape(away)} at {escape(home)}

Event {escape(event)}

', + '', + f'', + ''] + for key in keys: + rows = groups[key] + prices, status = describe(rows, (away, home)) + parts.append(f'' + f'') + parts.append('
One bookmaker per row
Book{escape(away)}{escape(home)}Price check and market time
{escape(key[1])}{escape(prices[0])}{escape(prices[1])}{status}
{escape(clock_label(rows))}
') + if not groups: + parts.append('

No rows in this CSV. Check the starter’s exit status and diagnostics before interpreting the export.

') + parts.append('

This report covers the supplied rows. An omitted selection, book or event leaves its status unknown. The market clock alone cannot establish delivery time.

') + return "\n".join(parts) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + source_group = parser.add_mutually_exclusive_group(required=True) + source_group.add_argument("csv_file", type=Path, nargs="?") + source_group.add_argument("--example", action="store_true", help="Render the bundled fictional fixture.") + args = parser.parse_args() + try: + input_path = Path(__file__).with_name("fictional.csv") if args.example else args.csv_file + with input_path.open(encoding="utf-8-sig", newline="") as source: + page = render(source, example=args.example) + except (OSError, UnicodeError, csv.Error, ValueError) as exc: + parser.exit(1, f"Could not generate the report: {exc}\n") + sys.stdout.write(page + "\n") + + +if __name__ == "__main__": + main() diff --git a/examples/nba-csv-report/test_report.py b/examples/nba-csv-report/test_report.py new file mode 100644 index 0000000..d534eeb --- /dev/null +++ b/examples/nba-csv-report/test_report.py @@ -0,0 +1,72 @@ +import csv +import io +import unittest +from pathlib import Path + +from report import render, clock_label + + +class ReportTest(unittest.TestCase): + def setUp(self): + with Path(__file__).with_name("fictional.csv").open() as source: + reader = csv.DictReader(source) + self.rows = list(reader) + self.fields = reader.fieldnames + + def render_rows(self, rows): + text = io.StringIO() + writer = csv.DictWriter(text, fieldnames=self.fields) + writer.writeheader() + writer.writerows(rows) + text.seek(0) + return render(text) + + def test_sample(self): + page = self.render_rows(self.rows) + self.assertIn("Both prices", page) + self.assertIn("Missing or invalid price", page) + self.assertIn("Market time missing", page) + self.assertIn('+105-115', page) + self.assertNotIn(""), 2) + self.assertNotIn("Both prices", self.render_rows(self.rows)) + + def test_escaped_identity(self): + self.rows[0]["bookmaker_key"] = "" + self.assertIn("<North>", self.render_rows(self.rows)) + + def test_empty_export(self): + self.assertIn("No rows in this CSV", self.render_rows([])) + + def test_wrong_sport_and_event_conflict(self): + self.rows[1]["away_team"] = "other" + with self.assertRaises(ValueError): + self.render_rows(self.rows) + self.rows[1]["sport_key"] = "soccer_epl" + with self.assertRaises(ValueError): + self.render_rows(self.rows[1:2]) + + def test_clock_precision_and_missing_offset(self): + a, b = self.rows[:2] + a["market_last_update"] = "2026-10-01T14:00:01.1234567Z" + b["market_last_update"] = a["market_last_update"] + self.assertEqual(clock_label([a,b]), a["market_last_update"]) + b["market_last_update"] = "2026-10-01T14:00:01.1234568Z" + self.assertEqual(clock_label([a,b]), "Market time fields differ") + b["market_last_update"] = "2026-10-01T14:00:01" + self.assertIn("unreadable", clock_label([b]))