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: 3 additions & 1 deletion .github/workflows/starter.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ on:
pull_request:
paths:
- 'examples/odds_workspace.py'
- 'examples/odds-migration/**'
- 'examples/test_odds_workspace.py'
- 'parlay_api/**'
- 'tests/**'
Expand All @@ -12,6 +13,7 @@ on:
branches: [main]
paths:
- 'examples/odds_workspace.py'
- 'examples/odds-migration/**'
- 'parlay_api/**'
- 'pyproject.toml'
permissions:
Expand All @@ -33,4 +35,4 @@ jobs:
working-directory: ${{ runner.temp }}
run: |
python "$GITHUB_WORKSPACE/tests/test_installed_package.py"
python -m pytest -q --import-mode=importlib "$GITHUB_WORKSPACE/tests/test_odds_coverage.py" "$GITHUB_WORKSPACE/tests/test_first_response.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"
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,13 @@ source counts from a local endpoint. Start with fictional NBA data, then use
your server-side key for a single coverage snapshot. Refreshing the local
endpoint reuses that snapshot.

## Compare an existing odds integration

[Run the local migration check](examples/odds-migration/) against two saved NBA
moneyline responses. It checks the request filters, event identity, bookmaker,
outcome prices and timestamps your application requires. The fictional example
runs with Python alone. Try an empty board or an HTTP 403 to see which check fails.

## Plan a request schedule before polling

Use the free [API workload planner](https://parlay-api.com/tools/api-workload?utm_source=github&utm_medium=sdk_readme&utm_campaign=parlay-api-python)
Expand Down
61 changes: 61 additions & 0 deletions examples/odds-migration/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Check a moneyline migration against saved responses

If you already consume The Odds API v4 and want to evaluate ParlayAPI,
start with one fixture that both feeds identify. This example checks the parts
of a US NBA moneyline that a two-team price consumer needs. It runs locally
with Python 3.9 or later and uses only the standard library.

From the repository root, run the fictional example.

```sh
python3 examples/odds-migration/compare.py examples/odds-migration/example.json
```

Both captures pass. The Owls have a home price of −120 in the first observation
and −125 in the second. The fixture has different event IDs in the two feeds.
A consumer joining by raw ID would need a mapping even for this example.
Different observation times can also produce different prices.

## Use your own captures

1. Copy the example JSON into a private working directory. Fill in the teams
as named by both adapters, the scheduled start with a time zone, and the
bookmaker key. Set `require_market_clock` according to your application.
2. For each side, record the event ID used by **that** provider. Copy the
HTTP method, request path, non-secret query parameters actually sent, the HTTP status
and the decoded JSON response body. Record an error response with its actual
status even when it has no events. Use `null` for an unavailable body.
Remove credentials, headers and private error text from your local copy.
Keep all other query parameters so additional filters show up as a mismatch.
3. Pass the local file to the same command. Read each side’s issues and its
bookmaker and market clock states. A passing comparison reports the two
sets of whole American prices by team and whether the sample IDs match.

The supported request uses `GET /v4/sports/basketball_nba/odds` for The Odds
API and the corresponding `/v1/` or `/v4/` path for ParlayAPI, with
`regions=us`, `markets=h2h` and `oddsFormat=american`. The packet labels each
provider by its previous or candidate role. Credentials and hostnames
stay outside it. Check your provider's plan and cost before collecting new
responses. The script makes zero HTTP requests.

A pass means that the recorded filters, selected fixture, bookmaker, two
team prices and required clock matched these checks. Validate each additional
sport, market, pagination rule and error contract your application uses.
One fixture cannot establish production coverage, freshness, licensing or costs.

## Try three failure cases

Make each change in a separate copy of the example.

| Change to the candidate | What to look for |
| --- | --- |
| Set `status` to `403` and `body` to `null` | The report retains HTTP 403. Check access before comparing prices. |
| Keep `status` at `200` and set `body` to `[]` | Zero matching events. Check which fixture and observation window you selected. |
| Remove the market’s `last_update`, keeping the bookmaker timestamp | The market clock is missing. With `require_market_clock` enabled, the comparison fails. |

Exit codes are `0` for a comparable sample, `1` for a capture that fails a
check and `2` for an unreadable or malformed packet.

For the endpoint contract and migration costs, consult
[The Odds API v4 guide](https://the-odds-api.com/liveapi/guides/v4/) and
[the ParlayAPI migration comparison](https://parlay-api.com/compare/the-odds-api).
150 changes: 150 additions & 0 deletions examples/odds-migration/compare.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
"""Check one locally saved two-provider NBA moneyline comparison."""

import argparse
import json
import re
import sys
from datetime import datetime
from pathlib import Path


SPORT = "basketball_nba"
QUERY = {"regions": "us", "markets": "h2h", "oddsFormat": "american"}
CLOCK = re.compile(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,6})?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)")


class PacketError(ValueError):
"""A structural error whose message contains no capture values."""


def timestamp(value):
if isinstance(value, str) and CLOCK.fullmatch(value):
try:
return datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError:
pass
return None


def object_with(value, required):
if not isinstance(value, dict) or set(value) != set(required):
raise PacketError("Check the packet fields against example.json.")
return value


def nonempty(value):
return isinstance(value, str) and bool(value.strip())


def select(rows, field, value, label):
if not isinstance(rows, list):
raise PacketError(f"Missing or malformed {label} list.")
if any(not isinstance(row, dict) or not nonempty(row.get(field)) for row in rows):
raise PacketError(f"Missing or malformed identifier in {label} list.")
matches = [row for row in rows if row[field] == value]
if len(matches) != 1:
raise PacketError(f"Expected one matching {label}, found {len(matches)}.")
return matches[0]


def clock_state(record):
if record.get("last_update") is None:
return "missing"
return "present" if timestamp(record["last_update"]) else "invalid"


def inspect_capture(side, capture, scope):
object_with(capture, ("event_id", "request", "status", "body"))
request = object_with(capture["request"], ("method", "path", "query"))
event_id, status = capture["event_id"], capture["status"]
if not nonempty(event_id) or type(status) is not int or not 100 <= status <= 599:
raise PacketError("Each capture needs its event ID and an integer HTTP status.")
result = {"http_status": status, "issues": []}
versions = ("v4",) if side == "previous" else ("v1", "v4")
if request["method"] != "GET":
result["issues"].append("Request method differs from GET.")
if request["path"] not in [f"/{v}/sports/{SPORT}/odds" for v in versions]:
result["issues"].append("Request path differs from the supported NBA odds route.")
if request["query"] != QUERY:
result["issues"].append("Request filters differ from the US American-moneyline example.")
if status != 200:
result["issues"].append("Capture did not return HTTP 200.")
if result["issues"]:
return result

try:
event = select(capture["body"], "id", event_id, "event")
if event.get("sport_key") != SPORT or any(
event.get(key) != scope[key] for key in ("home_team", "away_team")
) or timestamp(event.get("commence_time")) != timestamp(scope["commence_time"]):
raise PacketError("Selected event differs in sport, teams or scheduled start.")
book = select(event.get("bookmakers"), "key", scope["book"], "bookmaker")
market = select(book.get("markets"), "key", "h2h", "market")
result["book_clock"] = clock_state(book)
result["market_clock"] = clock_state(market)
outcomes = market.get("outcomes")
if not isinstance(outcomes, list) or len(outcomes) != 2:
raise PacketError("Expected two moneyline outcomes.")
prices = {}
for team in ("home_team", "away_team"):
outcome = select(outcomes, "name", scope[team], "outcome")
price = outcome.get("price")
if type(price) is float and price.is_integer():
price = int(price)
if type(price) is not int or abs(price) < 100:
raise PacketError("Expected a whole American price of magnitude at least 100.")
prices[team] = price
result["american_prices"] = prices
if scope["require_market_clock"] and result["market_clock"] != "present":
raise PacketError("A valid market timestamp is required for this comparison.")
except PacketError as exc:
result["issues"].append(str(exc))
return result


def compare(packet):
object_with(packet, ("scope", "previous", "candidate"))
scope = object_with(packet["scope"], (
"home_team", "away_team", "commence_time", "book", "require_market_clock",
))
if not all(nonempty(scope[k]) for k in ("home_team", "away_team", "book")):
raise PacketError("Set both team names and a bookmaker key.")
if scope["home_team"] == scope["away_team"] or not timestamp(scope["commence_time"]):
raise PacketError("Set distinct teams and a scheduled start with a timezone.")
if type(scope["require_market_clock"]) is not bool:
raise PacketError("Set require_market_clock to true or false.")
report = {side: inspect_capture(side, packet[side], scope) for side in ("previous", "candidate")}
report["comparable"] = all(not capture["issues"] for capture in report.values())
if report["comparable"]:
report["event_ids_equal_in_sample"] = packet["previous"]["event_id"] == packet["candidate"]["event_id"]
return report


def unique_keys(pairs):
result = {}
for key, value in pairs:
if key in result:
raise PacketError("Duplicate JSON field.")
result[key] = value
return result


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("packet", type=Path, help="local JSON packet with keys and headers removed")
args = parser.parse_args()
try:
packet = json.loads(args.packet.read_text(encoding="utf-8"), object_pairs_hook=unique_keys)
report = compare(packet)
except PacketError as exc:
print(str(exc), file=sys.stderr)
return 2
except (OSError, UnicodeError, ValueError, RecursionError):
print("Could not read a valid UTF-8 JSON packet.", file=sys.stderr)
return 2
print(json.dumps(report, indent=2))
return 0 if report["comparable"] else 1


if __name__ == "__main__":
sys.exit(main())
97 changes: 97 additions & 0 deletions examples/odds-migration/example.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
{
"scope": {
"home_team": "Harbor Owls",
"away_team": "Valley Comets",
"commence_time": "2026-11-17T01:00:00Z",
"book": "example_book",
"require_market_clock": true
},
"previous": {
"event_id": "provider-a-17",
"request": {
"method": "GET",
"path": "/v4/sports/basketball_nba/odds",
"query": {
"regions": "us",
"markets": "h2h",
"oddsFormat": "american"
}
},
"status": 200,
"body": [
{
"id": "provider-a-17",
"sport_key": "basketball_nba",
"home_team": "Harbor Owls",
"away_team": "Valley Comets",
"commence_time": "2026-11-17T01:00:00Z",
"bookmakers": [
{
"key": "example_book",
"last_update": "2026-11-17T00:53:21Z",
"markets": [
{
"key": "h2h",
"last_update": "2026-11-17T00:53:21Z",
"outcomes": [
{
"name": "Harbor Owls",
"price": -120
},
{
"name": "Valley Comets",
"price": 105
}
]
}
]
}
]
}
]
},
"candidate": {
"event_id": "provider-b-42",
"request": {
"method": "GET",
"path": "/v1/sports/basketball_nba/odds",
"query": {
"regions": "us",
"markets": "h2h",
"oddsFormat": "american"
}
},
"status": 200,
"body": [
{
"id": "provider-b-42",
"sport_key": "basketball_nba",
"home_team": "Harbor Owls",
"away_team": "Valley Comets",
"commence_time": "2026-11-17T01:00:00Z",
"bookmakers": [
{
"key": "example_book",
"last_update": "2026-11-17T00:56:12Z",
"markets": [
{
"key": "h2h",
"last_update": "2026-11-17T00:56:12Z",
"outcomes": [
{
"name": "Harbor Owls",
"price": -125
},
{
"name": "Valley Comets",
"price": 110
}
]
}
]
}
]
}
]
}
}
Loading
Loading