diff --git a/.github/workflows/starter.yml b/.github/workflows/starter.yml index 48d4750..e840cc9 100644 --- a/.github/workflows/starter.yml +++ b/.github/workflows/starter.yml @@ -3,6 +3,7 @@ on: pull_request: paths: - 'examples/odds_workspace.py' + - 'examples/odds-migration/**' - 'examples/test_odds_workspace.py' - 'parlay_api/**' - 'tests/**' @@ -12,6 +13,7 @@ on: branches: [main] paths: - 'examples/odds_workspace.py' + - 'examples/odds-migration/**' - 'parlay_api/**' - 'pyproject.toml' permissions: @@ -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" diff --git a/README.md b/README.md index b5d47ea..1365dda 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/examples/odds-migration/README.md b/examples/odds-migration/README.md new file mode 100644 index 0000000..9c6bac9 --- /dev/null +++ b/examples/odds-migration/README.md @@ -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). diff --git a/examples/odds-migration/compare.py b/examples/odds-migration/compare.py new file mode 100644 index 0000000..44c8413 --- /dev/null +++ b/examples/odds-migration/compare.py @@ -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()) diff --git a/examples/odds-migration/example.json b/examples/odds-migration/example.json new file mode 100644 index 0000000..eeba9db --- /dev/null +++ b/examples/odds-migration/example.json @@ -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 + } + ] + } + ] + } + ] + } + ] + } +} diff --git a/tests/test_migration_example.py b/tests/test_migration_example.py new file mode 100644 index 0000000..f8b2e8e --- /dev/null +++ b/tests/test_migration_example.py @@ -0,0 +1,108 @@ +import json +import subprocess +import sys +from pathlib import Path + +import pytest + + +EXAMPLE = Path(__file__).resolve().parents[1] / "examples" / "odds-migration" + + +@pytest.fixture +def packet(): + return json.loads((EXAMPLE / "example.json").read_text()) + + +def run_cli(tmp_path, packet): + filename = tmp_path / "packet.json" + filename.write_text(json.dumps(packet) if isinstance(packet, dict) else packet) + return subprocess.run( + [sys.executable, str(EXAMPLE / "compare.py"), str(filename)], + cwd=tmp_path, text=True, capture_output=True, check=False, + ) + + +def test_explicit_crosswalk_and_equivalent_times(tmp_path, packet): + event = packet["candidate"]["body"][0] + event["commence_time"] = "2026-11-16T20:00:00-05:00" + outcomes = event["bookmakers"][0]["markets"][0]["outcomes"] + outcomes.reverse() + outcomes[0]["price"] = 110.0 + result = run_cli(tmp_path, packet) + assert result.returncode == 0 + report = json.loads(result.stdout) + assert report["comparable"] and not report["event_ids_equal_in_sample"] + assert report["previous"]["american_prices"] == {"home_team": -120, "away_team": 105} + assert report["candidate"]["american_prices"] == {"home_team": -125, "away_team": 110} + + +@pytest.mark.parametrize(("status", "body", "message"), [ + (403, {"error": "local-private-error"}, "HTTP 200"), + (429, None, "HTTP 200"), + (200, [], "matching event, found 0"), + (200, {"events": []}, "event list"), +]) +def test_error_and_empty_are_distinct(tmp_path, packet, status, body, message): + packet["candidate"].update(status=status, body=body) + result = run_cli(tmp_path, packet) + assert result.returncode == 1 and "local-private-error" not in result.stdout + side = json.loads(result.stdout)["candidate"] + assert side["http_status"] == status and message in side["issues"][0] + + +@pytest.mark.parametrize(("target", "key", "value", "message"), [ + ("request", "method", "POST", "method"), + ("request", "path", "/v1/try/basketball_nba/odds", "path"), + ("request", "query", {"regions": "us", "apiKey": "local-private-key"}, "filters"), + ("capture", "event_id", "different-id", "matching event"), + ("event", "away_team", "Other Team", "teams"), + ("event", "sport_key", "baseball_mlb", "sport"), + ("event", "commence_time", "2026-11-17T01:00:00", "scheduled start"), + ("event", "bookmakers", [], "bookmaker"), + ("book", "markets", [], "market"), + ("market", "outcomes", [], "two moneyline"), + ("outcome", "name", "Valley Comets", "outcome"), + ("outcome", "price", True, "American price"), + ("outcome", "price", 1.85, "American price"), + ("market", "last_update", "2026-11-16T15:20:36+01:75", "market timestamp"), +]) +def test_scope_mismatch(tmp_path, packet, target, key, value, message): + capture = packet["candidate"] + event = capture["body"][0] + book = event["bookmakers"][0] + market = book["markets"][0] + nodes = {"request": capture["request"], "capture": capture, "event": event, + "book": book, "market": market, "outcome": market["outcomes"][0]} + nodes[target][key] = value + result = run_cli(tmp_path, packet) + assert result.returncode == 1 and "local-private-key" not in result.stdout + report = json.loads(result.stdout) + assert message in report["candidate"]["issues"][0] + assert "event_ids_equal_in_sample" not in report and not report["comparable"] + + +@pytest.mark.parametrize("target", ["event", "book", "market"]) +def test_ambiguous_selection(tmp_path, packet, target): + events = packet["candidate"]["body"] + books = events[0]["bookmakers"] + markets = books[0]["markets"] + rows = {"event": events, "book": books, "market": markets}[target] + rows.append(rows[0]) + result = run_cli(tmp_path, packet) + assert result.returncode == 1 and "found 2" in result.stdout + + +def test_optional_market_clock_stays_missing(tmp_path, packet): + packet["scope"]["require_market_clock"] = False + del packet["candidate"]["body"][0]["bookmakers"][0]["markets"][0]["last_update"] + result = run_cli(tmp_path, packet) + assert result.returncode == 0 + side = json.loads(result.stdout)["candidate"] + assert side["book_clock"] == "present" and side["market_clock"] == "missing" + + +@pytest.mark.parametrize("bad_input", ['{"previous":1,"previous":2}', "{}", "[]", "garbled"]) +def test_malformed_packet(tmp_path, bad_input): + result = run_cli(tmp_path, bad_input) + assert result.returncode == 2 and result.stderr and not result.stdout