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 @@ -5,6 +5,7 @@ on:
- 'examples/arb_finder.py'
- 'examples/ev_scanner.py'
- 'examples/price-pair.ipynb'
- 'examples/finals-forecast.ipynb'
- 'examples/odds_workspace.py'
- 'examples/odds-migration/**'
- 'examples/websocket_stream.py'
Expand All @@ -23,7 +24,9 @@ on:
- 'examples/arb_finder.py'
- 'examples/ev_scanner.py'
- 'examples/price-pair.ipynb'
- 'examples/finals-forecast.ipynb'
- 'tests/test_price_pair.py'
- 'tests/test_finals_forecast.py'
- 'tests/test_prop_comparison.py'
- 'examples/odds_workspace.py'
- 'examples/odds-migration/**'
Expand Down Expand Up @@ -56,6 +59,7 @@ jobs:
run: |
python "$GITHUB_WORKSPACE/tests/test_installed_package.py"
python "$GITHUB_WORKSPACE/tests/test_price_pair.py"
python "$GITHUB_WORKSPACE/tests/test_finals_forecast.py"
python "$GITHUB_WORKSPACE/tests/test_prop_comparison.py"
python -m pytest -q --import-mode=importlib "$GITHUB_WORKSPACE/tests/test_odds_coverage.py" "$GITHUB_WORKSPACE/tests/test_first_response.py" "$GITHUB_WORKSPACE/tests/test_migration_example.py"
- name: Check the saved final-score reader
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,10 @@ was `0.3.3`. That version supports `--sport basketball_nba`. Use the linked
wheel for the multi-sport sample finder and structured access-error examples.
Both verification commands run locally before you make a request.

## Backtest forecasts against the 2024 NBA Finals

Boston lost Game 4 by 38. How much better would a forecast look if you let the model revise it the next morning? [Read the worked example](examples/finals-forecast.ipynb) or [change a forecast in browser Python](https://jupyter.org/try-jupyter/lab/index.html?fromURL=https%3A%2F%2Fraw.githubusercontent.com%2FJacobiusMakes%2Fparlay-api-python%2Fmain%2Fexamples%2Ffinals-forecast.ipynb). The notebook uses official final scores and fictional probabilities. It runs without an API key.

## Compare an existing odds integration

[Run the local migration check](examples/odds-migration/) against two saved NBA
Expand Down
239 changes: 239 additions & 0 deletions examples/finals-forecast.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
{
"nbformat": 4,
"nbformat_minor": 5,
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python",
"version": "3.9"
}
},
"cells": [
{
"id": "intro",
"cell_type": "markdown",
"metadata": {},
"source": [
"# Would your forecast have counted before Game 4?\n",
"\n",
"Boston arrived in Dallas one win from the 2024 NBA title. Dallas won Game 4 by 38. A model file that gets edited the next morning can make that result look much easier to predict.\n",
"\n",
"Grade five forecasts at a fixed deadline. The final scores are real. Every probability and observation time below is invented for this exercise. The deadline is noon Eastern (16:00 UTC) on each game date. Run the cells in order with Python 3.9 or later. All calculations use the standard library and run offline.\n",
"\n",
"[Official NBA Finals results](https://www.nba.com/news/2024-nba-finals-schedule)"
]
},
{
"id": "results",
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"source": [
"import csv\n",
"from datetime import date, datetime, time, timezone\n",
"from decimal import Decimal, InvalidOperation\n",
"from io import StringIO\n",
"\n",
"# Game number, June date, Boston points, Dallas points (Boston first at both venues).\n",
"FINALS = [\n",
" (1, \"2024-06-06\", 107, 89),\n",
" (2, \"2024-06-09\", 105, 98),\n",
" (3, \"2024-06-12\", 106, 99),\n",
" (4, \"2024-06-14\", 84, 122),\n",
" (5, \"2024-06-17\", 106, 88),\n",
"]"
],
"outputs": []
},
{
"id": "change",
"cell_type": "markdown",
"metadata": {},
"source": [
"## Enter the forecasts\n",
"\n",
"Each probability is for **Boston to win**, including the games in Dallas. Use the time the forecast first became available to you. Game 3 has only a next-day record. Game 4 has a pregame forecast and a next-day revision.\n",
"\n",
"To try your own numbers, edit the CSV and run the remaining cells. A row at the deadline counts. A missing forecast leaves the game unscored."
]
},
{
"id": "observations",
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"source": [
"FORECASTS = \"\"\"game,available_at,boston_win_probability\n",
"1,2024-06-06T15:30:00Z,0.60\n",
"2,2024-06-09T12:00:00-04:00,0.55\n",
"3,2024-06-13T10:00:00Z,0.90\n",
"4,2024-06-14T15:45:00Z,0.58\n",
"4,2024-06-15T10:00:00Z,0.05\n",
"5,2024-06-17T15:35:00Z,0.62\n",
"\"\"\""
],
"outputs": []
},
{
"id": "read",
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"source": [
"def observations(text):\n",
" reader = csv.DictReader(StringIO(text.strip()))\n",
" if reader.fieldnames != [\"game\", \"available_at\", \"boston_win_probability\"]:\n",
" raise ValueError(\"Use the three column headings shown in the example.\")\n",
" records = {game: {} for game, *_ in FINALS}\n",
" for row in reader:\n",
" try:\n",
" if None in row or None in row.values():\n",
" raise ValueError(\"Expected three fields\")\n",
" game = int(row[\"game\"])\n",
" if game not in records:\n",
" raise ValueError(\"Unknown game\")\n",
" stamp = row[\"available_at\"].strip()\n",
" if stamp.endswith(\"Z\"):\n",
" stamp = stamp[:-1] + \"+00:00\"\n",
" seen = datetime.fromisoformat(stamp)\n",
" if seen.utcoffset() is None:\n",
" raise ValueError(\"Include Z or a numeric UTC offset\")\n",
" p = Decimal(row[\"boston_win_probability\"])\n",
" if not p.is_finite() or not 0 <= p <= 1:\n",
" raise ValueError(\"Use a probability from 0 to 1\")\n",
" if seen in records[game]:\n",
" raise ValueError(\"Duplicate observation time for this game\")\n",
" records[game][seen] = p\n",
" except (ValueError, InvalidOperation) as error:\n",
" raise ValueError(f\"Forecast CSV line {reader.line_num}: {error}\") from error\n",
" return records\n",
"\n",
"\n",
"def score_finals(text):\n",
" records = observations(text)\n",
" report = []\n",
" for game, day, boston, dallas in FINALS:\n",
" cutoff = datetime.combine(date.fromisoformat(day), time(16), tzinfo=timezone.utc)\n",
" available = records[game]\n",
" seen = max((stamp for stamp in available if stamp <= cutoff), default=None)\n",
" p = available[seen] if seen is not None else None\n",
" outcome = int(boston > dallas)\n",
" report.append({\n",
" \"game\": game, \"boston\": boston, \"dallas\": dallas, \"outcome\": outcome,\n",
" \"seen\": seen, \"probability\": p,\n",
" \"error\": (p - outcome) ** 2 if p is not None else None,\n",
" \"latest\": available[max(available)] if available else None,\n",
" })\n",
" return report"
],
"outputs": []
},
{
"id": "method",
"cell_type": "markdown",
"metadata": {},
"source": [
"## Score the same games\n",
"\n",
"For each eligible forecast, square the difference between Boston’s probability and its result (1 for a win, 0 for a loss). The average is the binary Brier score. Lower is better. A 50% forecast scores 0.25 on either result. Compare it on exactly the same games as the model."
]
},
{
"id": "grade",
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"source": [
"rows = score_finals(FORECASTS)\n",
"graded = [row for row in rows if row[\"error\"] is not None]\n",
"print(\"Game Boston–Dallas P(Boston) Squared error\")\n",
"for row in rows:\n",
" score = f\"{row['boston']}–{row['dallas']}\"\n",
" probability = row[\"probability\"]\n",
" if probability is None:\n",
" detail = \" — no eligible forecast\"\n",
" else:\n",
" detail = f\"{probability:7.1%} {row['error']:.4f}\"\n",
" print(f\"{row['game']:>3} {score:>11} {detail}\")\n",
"print(f\"\\nCoverage: {len(graded)} of {len(rows)} games\")\n",
"if graded:\n",
" mean_error = sum(row[\"error\"] for row in graded) / len(graded)\n",
" print(f\"Forecast Brier: {mean_error:.4f}\")\n",
" print(\"50/50 Brier on the same games: 0.2500\")\n",
"else:\n",
" print(\"No games to score.\")"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Game Boston–Dallas P(Boston) Squared error\n",
" 1 107–89 60.0% 0.1600\n",
" 2 105–98 55.0% 0.2025\n",
" 3 106–99 — no eligible forecast\n",
" 4 84–122 58.0% 0.3364\n",
" 5 106–88 62.0% 0.1444\n",
"\n",
"Coverage: 4 of 5 games\n",
"Forecast Brier: 0.2108\n",
"50/50 Brier on the same games: 0.2500\n"
]
}
]
},
{
"id": "leak",
"cell_type": "markdown",
"metadata": {},
"source": [
"## What happens if you ignore the clock?\n",
"\n",
"Keep the same set of scored games and substitute the last forecast in each game’s file, even when it arrived after the deadline. With the supplied records, only Game 4 changes. A 5% Boston forecast looks convincing after a Dallas blowout. It was unavailable at decision time."
]
},
{
"id": "contrast",
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"source": [
"if graded:\n",
" unrestricted = sum((row[\"latest\"] - row[\"outcome\"]) ** 2 for row in graded) / len(graded)\n",
" print(f\"At the deadline: {mean_error:.4f}\")\n",
" print(f\"Using the last records, including late edits: {unrestricted:.4f}\")\n",
" for row in graded:\n",
" if row[\"latest\"] != row[\"probability\"]:\n",
" print(f\"Game {row['game']}: {row['probability']:.0%} at the deadline; \"\n",
" f\"{row['latest']:.0%} in the final record.\")\n",
"else:\n",
" print(\"No matched games for the comparison.\")"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"At the deadline: 0.2108\n",
"Using the last records, including late edits: 0.1274\n",
"Game 4: 58% at the deadline; 5% in the final record.\n"
]
}
]
},
{
"id": "next",
"cell_type": "markdown",
"metadata": {},
"source": [
"Delete the next-day Game 4 row and rerun. The two averages now agree. Then give Game 3 a forecast before noon and see how the denominator changes. Five games can illustrate the scoring procedure. Evaluating a model's predictive performance takes a larger held-out sample.\n",
"\n",
"**Try this with your own observations.** [Open the public odds preview](https://parlay-api.com/try?utm_source=github&utm_medium=python_notebook&utm_campaign=finals_forecast_cutoff) to inspect a current board. For a future game, save the event ID, your forecast, and the time you first observed it. Keep the final score separately until grading."
]
}
]
}
68 changes: 68 additions & 0 deletions tests/test_finals_forecast.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
"""Run the published notebook and exercise its decision-time boundary."""
from contextlib import redirect_stdout
from decimal import Decimal
from io import StringIO
import json
from pathlib import Path
import unittest


NOTEBOOK = Path(__file__).resolve().parents[1] / "examples" / "finals-forecast.ipynb"


class FinalsForecastTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cells = json.loads(NOTEBOOK.read_text())["cells"]
cls.scope = {}
cls.captured = {}
for cell in cls.cells:
if cell["cell_type"] == "code":
output = StringIO()
with redirect_stdout(output):
exec(compile("".join(cell["source"]), cell["id"], "exec"), cls.scope)
cls.captured[cell["id"]] = output.getvalue()

def test_saved_outputs_match_execution(self):
for cell in self.cells:
if cell["cell_type"] == "code":
saved = "".join("".join(o["text"]) for o in cell["outputs"])
self.assertEqual(saved, self.captured[cell["id"]])
self.assertIn("Coverage: 4 of 5 games", self.captured["grade"])
self.assertIn("Forecast Brier: 0.2108", self.captured["grade"])
self.assertIn("late edits: 0.1274", self.captured["contrast"])

def score(self, *csv_rows):
return self.scope["score_finals"]("\n".join(["game,available_at,boston_win_probability", *csv_rows]))

def test_snapshot_selection_is_independent_of_input_order(self):
_, *observations = self.scope["FORECASTS"].splitlines()
self.assertEqual(self.score(*reversed(observations)), self.scope["rows"])
third, fourth = self.scope["rows"][2:4]
self.assertIsNone(third["probability"])
self.assertEqual((fourth["probability"], fourth["latest"], fourth["error"]),
(Decimal(".58"), Decimal(".05"), Decimal(".3364")))

def test_cutoff_is_inclusive_and_offset_aware(self):
rows = self.score("1,2024-06-06T12:00:00-04:00,0",
"1,2024-06-06T16:00:00.000001Z,1")
self.assertEqual(rows[0]["probability"], 0)
self.assertEqual(rows[0]["error"], 1)
self.assertIsNone(rows[1]["error"])

def test_empty_input_scores_nothing(self):
self.assertTrue(all(row["error"] is None for row in self.score()))

def test_bad_input_fails_before_scoring(self):
for bad in ("1,2024-06-06T12:00:00,.5", "6,2024-06-06T16:00:00Z,.5",
"1,2024-06-06T16:00:00Z,NaN", "1,2024-06-06T16:00:00Z,-.1",
"1,2024-06-06T16:00:00Z,1.1", "1,,.5", "1,2024-06-06T16:00:00Z",
"1,2024-06-06T16:00:00Z,.5,extra"):
with self.subTest(row=bad), self.assertRaisesRegex(ValueError, "line 2"):
self.score(bad)
with self.assertRaisesRegex(ValueError, "Duplicate observation time"):
self.score("1,2024-06-06T16:00:00Z,.5", "1,2024-06-06T12:00:00-04:00,.9")


if __name__ == "__main__":
unittest.main()
Loading