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: 4 additions & 0 deletions .github/workflows/starter.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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/**'
Expand All @@ -20,6 +21,7 @@ on:
- 'examples/websocket_stream.py'
- 'examples/websocket-replay/**'
- 'examples/support-report/**'
- 'examples/nba-csv-report/**'
- 'parlay_api/**'
- 'pyproject.toml'
permissions:
Expand All @@ -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 }}
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 23 additions & 0 deletions examples/nba-csv-report/README.md
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 4 additions & 0 deletions examples/nba-csv-report/fictional.csv
Original file line number Diff line number Diff line change
@@ -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
136 changes: 136 additions & 0 deletions examples/nba-csv-report/report.py
Original file line number Diff line number Diff line change
@@ -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 = ['<!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 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]):
home, away = events[event]
parts += [f'<section><h2>{escape(away)} at {escape(home)}</h2><p class="id">Event {escape(event)}</p>',
'<table><caption>One bookmaker per row</caption><thead><tr><th scope="col">Book</th>',
f'<th scope="col">{escape(away)}</th><th scope="col">{escape(home)}</th>',
'<th scope="col">Price check and market time</th></tr></thead><tbody>']
for key in keys:
rows = groups[key]
prices, status = describe(rows, (away, home))
parts.append(f'<tr><th scope="row">{escape(key[1])}</th><td>{escape(prices[0])}</td>'
f'<td>{escape(prices[1])}</td><td>{status}<br>{escape(clock_label(rows))}</td></tr>')
parts.append('</tbody></table></section>')
if not groups:
parts.append('<p><strong>No rows in this CSV.</strong> Check the starter’s exit status and diagnostics before interpreting the export.</p>')
parts.append('<p>This report covers the supplied rows. An omitted selection, book or event leaves its status unknown. The market clock alone cannot establish delivery time.</p></main></body></html>')
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()
72 changes: 72 additions & 0 deletions examples/nba-csv-report/test_report.py
Original file line number Diff line number Diff line change
@@ -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('<td>+105</td><td>-115</td>', page)
self.assertNotIn("<script", page)

def test_split_books(self):
self.rows[1]["bookmaker_key"] = "second"
self.assertNotIn("Both prices", self.render_rows(self.rows))

def test_conflicting_duplicate(self):
self.assertIn("Ambiguous outcomes", self.render_rows(self.rows + self.rows[:1]))

def test_unusable_american_price(self):
for value in ["", "0", "NaN", "inf", "1.95", "1_10", "111foo"]:
self.rows[0]["price"] = value
self.assertNotIn("Both prices", self.render_rows(self.rows))

def test_distinct_fixture(self):
self.rows[1]["event_id"] = "rematch"
self.assertEqual(self.render_rows(self.rows).count("<section>"), 2)
self.assertNotIn("Both prices", self.render_rows(self.rows))

def test_escaped_identity(self):
self.rows[0]["bookmaker_key"] = "<North>"
self.assertIn("&lt;North&gt;", 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]))
Loading