From 0c63b14e9dc8ec50f50bf5c7c3b13430094ebc21 Mon Sep 17 00:00:00 2001 From: Esther-MacMini Date: Fri, 4 Dec 2026 22:17:39 -0500 Subject: [PATCH 1/2] Fix incomplete moneyline comparisons in the PyPI-linked Python example --- .github/workflows/starter.yml | 6 + CHANGELOG.md | 2 + README.md | 2 +- examples/arb_finder.py | 229 ++++++++++++++++++++-------------- examples/price-pair.ipynb | 98 +++++++++++++++ tests/test_price_pair.py | 91 ++++++++++++++ 6 files changed, 331 insertions(+), 97 deletions(-) create mode 100644 examples/price-pair.ipynb create mode 100644 tests/test_price_pair.py diff --git a/.github/workflows/starter.yml b/.github/workflows/starter.yml index 83f71b2..011ec03 100644 --- a/.github/workflows/starter.yml +++ b/.github/workflows/starter.yml @@ -2,6 +2,8 @@ name: Installed Python starter on: pull_request: paths: + - 'examples/arb_finder.py' + - 'examples/price-pair.ipynb' - 'examples/odds_workspace.py' - 'examples/odds-migration/**' - 'examples/websocket_stream.py' @@ -17,6 +19,9 @@ on: push: branches: [main] paths: + - 'examples/arb_finder.py' + - 'examples/price-pair.ipynb' + - 'tests/test_price_pair.py' - 'examples/odds_workspace.py' - 'examples/odds-migration/**' - 'examples/websocket_stream.py' @@ -47,6 +52,7 @@ jobs: working-directory: ${{ runner.temp }} run: | python "$GITHUB_WORKSPACE/tests/test_installed_package.py" + python "$GITHUB_WORKSPACE/tests/test_price_pair.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 run: python -B -m unittest discover -s examples/final-score diff --git a/CHANGELOG.md b/CHANGELOG.md index fbde690..63492fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ # Changelog +Using the [0.3.3 package on PyPI](https://pypi.org/project/parlay-api/0.3.3/)? [Run its price converters in Jupyter](https://jupyter.org/try-jupyter/lab/index.html?fromURL=https%3A%2F%2Fraw.githubusercontent.com%2FJacobiusMakes%2Fparlay-api-python%2Fmain%2Fexamples%2Fprice-pair.ipynb) with two fictional basketball quotes. Change the away price from +110 to −110 to see why the modeled surplus disappears. The notebook needs no account or API key. + ## 0.3.5 - 2026-12-01 - Handle nested service errors on authenticated requests. Monthly credit exhaustion diff --git a/README.md b/README.md index 0d152bf..b66e198 100644 --- a/README.md +++ b/README.md @@ -266,7 +266,7 @@ The repository also contains: - [Bruno private-research collection](examples/bruno): keyless discovery and individually enabled requests using your own key, with a visible sport selector. - [Compare a complete three-way soccer market in Python](https://github.com/JacobiusMakes/parlayapi-betting-agent-starter#four-books-three-complete-markets). Run the fictional match with no key. See why a missing draw price changes which books contribute to a consensus. - [ev_scanner.py](https://github.com/JacobiusMakes/parlay-api-python/blob/main/examples/ev_scanner.py): illustrates a chosen fair-price baseline and an edge calculation. Results depend on assumptions and available inputs. -- [arb_finder.py](https://github.com/JacobiusMakes/parlay-api-python/blob/main/examples/arb_finder.py): illustrates implied-probability and stake calculations. Quotes and execution can change; a computed opportunity does not guarantee profit. +- [Compare two fictional basketball quotes](https://github.com/JacobiusMakes/parlay-api-python/blob/main/examples/arb_finder.py) with `python examples/arb_finder.py --example --bankroll 100` from a checkout with the SDK installed. Two +110 prices leave a 4.76-point gap in implied probability and a modeled net of 5.00 units on 100. [Change one price in a browser Python notebook](https://jupyter.org/try-jupyter/lab/index.html?fromURL=https%3A%2F%2Fraw.githubusercontent.com%2FJacobiusMakes%2Fparlay-api-python%2Fmain%2Fexamples%2Fprice-pair.ipynb) and rerun the calculation. - [websocket_stream.py](https://github.com/JacobiusMakes/parlay-api-python/blob/main/examples/websocket_stream.py): illustrates consuming a WebSocket stream with your own account. These additional files are repository examples. Download or clone them separately; diff --git a/examples/arb_finder.py b/examples/arb_finder.py index 75c2370..b71b276 100644 --- a/examples/arb_finder.py +++ b/examples/arb_finder.py @@ -1,123 +1,160 @@ -"""Two-book arbitrage finder. +"""Compare two-team h2h prices from different bookmakers. -For every game line and player prop, check whether any pair of books -in the response combine to an implied probability under 100. If yes, -that pair is an arbitrage and we print the optimal stake split for a -given total bankroll. - -This is a more conservative tool than ev_scanner.py: arbitrage is rare -but bulletproof when it exists. A 1.5% arb on $1,000 returns $15 -guaranteed. - -Usage: - export PARLAY_API_KEY=... - python arb_finder.py basketball_nba --bankroll 1000 - python arb_finder.py baseball_mlb --markets player_strikeouts --min-edge 1.0 +With parlay-api installed, run `python arb_finder.py --example` for a +fictional basketball comparison. The example makes no requests. For an +account request, set PARLAY_API_KEY and supply a sport such as basketball_nba. +The two-outcome calculation does not cover a regulation soccer draw. """ from __future__ import annotations import argparse +from collections import Counter +import math import os +from pathlib import Path import sys -sys.path.insert(0, "..") +# A standalone download uses the installed SDK. Also support an uninstalled checkout. +if (Path(__file__).resolve().parents[1] / "parlay_api" / "__init__.py").is_file(): + sys.path.append(str(Path(__file__).resolve().parents[1])) from parlay_api import ParlayAPI, ParlayAPIError -def find_h2h_arbs(api: ParlayAPI, sport: str, min_edge_pct: float) -> list[dict]: - events = api.odds(sport, markets="h2h", odds_format="american") - arbs = [] - for ev in events: - # Build {team_name: [(book, price), ...]} - team_prices: dict[str, list[tuple[str, int]]] = {} - for book in ev.get("bookmakers", []): - for m in book.get("markets", []): - if m.get("key") != "h2h": - continue - for o in m.get("outcomes", []): - name, price = o.get("name"), o.get("price") - if name is None or price is None: - continue - team_prices.setdefault(name, []).append((book["key"], price)) +def named(value): + return isinstance(value, str) and bool(value.strip()) + + +def american_price(value): + return type(value) in (int, float) and math.isfinite(value) and abs(value) >= 100 + - if len(team_prices) != 2: +def complete_quotes(event, teams): + """Keep each identified book's single, two-sided market together.""" + books = event.get("bookmakers") + if not isinstance(books, list): + return [] + counts = Counter(b["key"].strip().casefold() for b in books + if isinstance(b, dict) and named(b.get("key"))) + complete = [] + for book in books: + if not isinstance(book, dict) or not isinstance(book.get("markets"), list): continue - teams = list(team_prices.keys()) - a_options = team_prices[teams[0]] - b_options = team_prices[teams[1]] - - for a_book, a_price in a_options: - for b_book, b_price in b_options: - if a_book == b_book: - continue # arbing within one book is impossible - a_imp = ParlayAPI.american_to_implied(a_price) - b_imp = ParlayAPI.american_to_implied(b_price) - total = a_imp + b_imp - edge = (1.0 - total) * 100 - if edge >= min_edge_pct: - arbs.append({ - "matchup": f"{ev.get('away_team','?')} @ {ev.get('home_team','?')}", - "team_a": teams[0], - "team_b": teams[1], - "book_a": a_book, - "book_b": b_book, - "price_a": a_price, - "price_b": b_price, - "edge_pct": edge, - "implied_total": total * 100, - }) - return sorted(arbs, key=lambda x: -x["edge_pct"]) - - -def stake_split(price_a: int, price_b: int, bankroll: float) -> tuple[float, float, float]: - """Returns (stake_a, stake_b, guaranteed_profit) for a 2-leg arb.""" + markets = [m for m in book["markets"] if isinstance(m, dict) and m.get("key") == "h2h"] + for market in markets: + outcomes = market.get("outcomes") + if isinstance(outcomes, list) and any( + isinstance(row, dict) and named(row.get("name")) and row["name"] not in teams + for row in outcomes + ): + return [] # Another selection makes this a different outcome set. + key = book.get("key") + if not named(key) or counts[key.strip().casefold()] != 1 or len(markets) != 1: + continue + outcomes = markets[0].get("outcomes") + if not isinstance(outcomes, list) or len(outcomes) != 2: + continue + prices = {row["name"]: row["price"] for row in outcomes + if isinstance(row, dict) and named(row.get("name")) and american_price(row.get("price"))} + if set(prices) == set(teams): + complete.append((key, prices)) + return complete + + +def compare_events(events, sport, min_edge_pct): + if not isinstance(events, list): + raise ValueError("Expected a list of events") + matches = [] + if sport.casefold().startswith("soccer"): + return matches + for event in events: + if not isinstance(event, dict) or event.get("sport_key") != sport or not named(event.get("id")): + continue + home, away = event.get("home_team"), event.get("away_team") + if not all(named(team) for team in (home, away)): + continue + names = {team.strip().casefold() for team in (home, away)} + if len(names) != 2 or names.intersection({"draw", "tie"}): + continue + books = complete_quotes(event, (home, away)) + for home_book, home_prices in books: + for away_book, away_prices in books: + if home_book == away_book: + continue + home_price, away_price = home_prices[home], away_prices[away] + total = ParlayAPI.american_to_implied(home_price) + ParlayAPI.american_to_implied(away_price) + gap = (1.0 - total) * 100 + if gap > 1e-10 and gap >= min_edge_pct: + matches.append(dict(event_id=event["id"], matchup=f"{away} @ {home}", + team_a=home, team_b=away, book_a=home_book, book_b=away_book, + price_a=home_price, price_b=away_price, edge_pct=gap, + implied_total=total * 100)) + return sorted(matches, key=lambda row: -row["edge_pct"]) + + +def find_h2h_arbs(api: ParlayAPI, sport: str, min_edge_pct: float) -> list[dict]: + if sport.casefold().startswith("soccer"): + return [] + return compare_events(api.odds(sport, markets="h2h", odds_format="american"), sport, min_edge_pct) + + +def stake_split(price_a: float, price_b: float, bankroll: float) -> tuple[float, float, float]: + """Equal-payout arithmetic for two mutually exclusive, exhaustive outcomes.""" dec_a = ParlayAPI.american_to_decimal(price_a) dec_b = ParlayAPI.american_to_decimal(price_b) - # Equal-payout split: stake_a * dec_a == stake_b * dec_b - # stake_a + stake_b = bankroll - # stake_a * dec_a = stake_b * dec_b - # stake_b = stake_a * dec_a / dec_b - # stake_a (1 + dec_a/dec_b) = bankroll - # stake_a = bankroll / (1 + dec_a/dec_b) stake_a = bankroll / (1.0 + dec_a / dec_b) - stake_b = bankroll - stake_a - payout = stake_a * dec_a # equals stake_b * dec_b - return stake_a, stake_b, payout - bankroll + return stake_a, bankroll - stake_a, stake_a * dec_a - bankroll + + +def fictional_event(): + teams = ("Comets", "Owls") + books = [] + for book, prices in (("North", (110, -130)), ("South", (-130, 110))): + outcomes = [{"name": team, "price": price} for team, price in zip(teams, prices)] + books.append({"key": book, "markets": [{"key": "h2h", "outcomes": outcomes}]}) + return {"id": "fictional-comets-owls", "sport_key": "basketball_nba", + "home_team": teams[0], "away_team": teams[1], "bookmakers": books} def main() -> int: parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("sport") - parser.add_argument("--min-edge", type=float, default=0.5, - help="Min arb edge in percentage points (default 0.5)") - parser.add_argument("--bankroll", type=float, default=1000.0) + parser.add_argument("sport", nargs="?") + parser.add_argument("--example", action="store_true", help="Run the fictional basketball example offline") + parser.add_argument("--min-edge", type=float, default=0.5, help="Minimum implied-total gap in percentage points") + parser.add_argument("--bankroll", type=float, default=1000.0, help="Illustrative total for payout arithmetic") parser.add_argument("--top", type=int, default=10) parser.add_argument("--api-key", default=os.environ.get("PARLAY_API_KEY")) args = parser.parse_args() - - if not args.api_key: - print("error: set PARLAY_API_KEY env var or pass --api-key", file=sys.stderr) - return 2 - - api = ParlayAPI(api_key=args.api_key) - try: - arbs = find_h2h_arbs(api, args.sport, args.min_edge) - except ParlayAPIError as e: - print(f"error: {e}", file=sys.stderr) - return 1 - - if not arbs: - print(f"no arbs over {args.min_edge}% on {args.sport} h2h right now") + if args.example == bool(args.sport): + parser.error("Choose --example or supply one sport") + if not math.isfinite(args.min_edge) or args.min_edge < 0 or args.top < 1: + parser.error("Use a nonnegative finite threshold and a positive --top") + if not math.isfinite(args.bankroll) or args.bankroll <= 0: + parser.error("Use a positive finite illustrative amount") + if args.example: + event = fictional_event() + rows = compare_events([event], event["sport_key"], args.min_edge) + print("Fictional basketball prices") + else: + if args.sport.casefold().startswith("soccer"): + parser.error("This two-outcome example excludes soccer. A regulation result can include a draw.") + if not args.api_key: + parser.error("Set PARLAY_API_KEY for an account request or use --example") + try: + rows = find_h2h_arbs(ParlayAPI(api_key=args.api_key), args.sport, args.min_edge) + except (ParlayAPIError, ValueError) as error: + print(f"Request failed: {error}", file=sys.stderr) + return 1 + if not rows: + print("No eligible two-book pair met the threshold in these records.") return 0 - - print(f"\n{min(args.top, len(arbs))} arbs on {args.sport} (bankroll ${args.bankroll:,.0f}):\n") - for a in arbs[:args.top]: - sa, sb, profit = stake_split(a["price_a"], a["price_b"], args.bankroll) - print(f" {a['matchup']}") - print(f" {a['team_a'][:30]:32} {a['price_a']:+5} @ {a['book_a']:12} stake ${sa:>7.2f}") - print(f" {a['team_b'][:30]:32} {a['price_b']:+5} @ {a['book_b']:12} stake ${sb:>7.2f}") - print(f" -> guaranteed profit ${profit:+.2f} ({a['edge_pct']:+.2f}%)\n") - + for row in rows[:args.top]: + first, second, difference = stake_split(row["price_a"], row["price_b"], args.bankroll) + print(f"{row['matchup']} ({row['event_id']})") + print(f" {row['team_a']} {row['price_a']:+g} at {row['book_a']}, modeled amount {first:.2f}") + print(f" {row['team_b']} {row['price_b']:+g} at {row['book_b']}, modeled amount {second:.2f}") + print(f" Implied total {row['implied_total']:.2f}% | Gap below 100% {row['edge_pct']:.2f} percentage points") + print(f" Modeled net {difference:+.2f} on {args.bankroll:.2f}, before fees") + print("Assumes both quotes are accepted on identical settlement terms and exactly one side wins.") return 0 diff --git a/examples/price-pair.ipynb b/examples/price-pair.ipynb new file mode 100644 index 0000000..55e8d20 --- /dev/null +++ b/examples/price-pair.ipynb @@ -0,0 +1,98 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "question", + "metadata": {}, + "source": [ + "# Does a 4.76-point gap mean a 4.76% payout?\n", + "\n", + "North quotes the Comets at +110. South quotes the Owls at +110. Both are fictional, full-game basketball moneylines. Compare what the prices imply with what an equal-payout split would return under the assumptions below.\n", + "\n", + "In JupyterLite, choose **Python (Pyodide)** if prompted. Then choose **Run → Run All Cells**. The first run downloads the public Python package. You can run this notebook locally with `python -m pip install parlay-api==0.3.3`. Both calculations use the package’s price converters and fictional inputs. No API key is needed." + ] + }, + { + "cell_type": "code", + "id": "package", + "metadata": {}, + "execution_count": null, + "outputs": [], + "source": [ + "import sys\n", + "from importlib.metadata import version\n", + "\n", + "if sys.platform == \"emscripten\":\n", + " import piplite\n", + " await piplite.install(\"https://files.pythonhosted.org/packages/51/a8/8246c56847273ede712084cbecbeed721c8236ab315122c2a8f70a9035b0/parlay_api-0.3.3-py3-none-any.whl#sha256=62cdfe96c5d4e81c71328db85d0e2318602d4eaed3bcea04cb0e5e5f8731780a\", deps=False)\n", + "\n", + "from parlay_api import ParlayAPI\n", + "print(\"Installed SDK:\", version(\"parlay-api\"))" + ] + }, + { + "cell_type": "markdown", + "id": "change-price", + "metadata": {}, + "source": [ + "## Change the Owls’ price\n", + "\n", + "Run the calculation with the two opening quotes. Then change `AWAY_PRICE` to `-110` in the next cell and run it again. Does the modeled surplus survive the price change?" + ] + }, + { + "cell_type": "code", + "id": "calculation", + "metadata": {}, + "execution_count": null, + "outputs": [], + "source": [ + "HOME_PRICE = 110\n", + "AWAY_PRICE = 110\n", + "TOTAL = 100.0\n", + "\n", + "if not all(type(p) is int and abs(p) >= 100 for p in (HOME_PRICE, AWAY_PRICE)):\n", + " raise ValueError(\"Use an American price of +100 or higher, or -100 or lower.\")\n", + "if TOTAL <= 0:\n", + " raise ValueError(\"Use a positive total.\")\n", + "\n", + "home = ParlayAPI.american_to_decimal(HOME_PRICE)\n", + "away = ParlayAPI.american_to_decimal(AWAY_PRICE)\n", + "implied = ParlayAPI.american_to_implied(HOME_PRICE) + ParlayAPI.american_to_implied(AWAY_PRICE)\n", + "home_amount = TOTAL * away / (home + away)\n", + "away_amount = TOTAL - home_amount\n", + "payout = home_amount * home\n", + "\n", + "print(f\"Comets {HOME_PRICE:+d} at North | Owls {AWAY_PRICE:+d} at South\")\n", + "print(f\"Implied total: {implied:.2%}\")\n", + "print(f\"100% minus implied total: {(1 - implied) * 100:.2f} percentage points\")\n", + "print(f\"Modeled split: {home_amount:.2f} on Comets / {away_amount:.2f} on Owls\")\n", + "print(f\"Modeled net on {TOTAL:.2f}: {payout - TOTAL:+.2f}\")" + ] + }, + { + "cell_type": "markdown", + "id": "next", + "metadata": {}, + "source": [ + "At +110 and +110 the two implied probabilities sum to 95.24%. The gap is **4.76 percentage points**. Under equal-payout assumptions the modeled net is **5.00 units on 100**. With the Owls at −110 the total reaches 100% and the modeled net falls to zero.\n", + "\n", + "This arithmetic assumes both quotes are accepted on identical settlement terms, one side wins, and there are no fees. A regulation soccer draw, a void, a limit or a changed price can change the outcome. The numbers describe an exercise using fictional quotes.\n", + "\n", + "[Run the full Python example on a fictional board](https://github.com/JacobiusMakes/parlay-api-python/blob/main/examples/arb_finder.py) to see how it checks the two team names at each bookmaker. To work with your own account, [get a ParlayAPI key for a research project](https://parlay-api.com/signup?utm_source=jupyter&utm_medium=python_package&utm_campaign=python_price_pair)." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/tests/test_price_pair.py b/tests/test_price_pair.py new file mode 100644 index 0000000..611e3d9 --- /dev/null +++ b/tests/test_price_pair.py @@ -0,0 +1,91 @@ +import sys +import unittest +from copy import deepcopy +from pathlib import Path +from unittest.mock import Mock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "examples")) +import arb_finder as example + + +class PricePairTests(unittest.TestCase): + def setUp(self): + self.event = example.fictional_event() + self.sport = self.event["sport_key"] + self.books = self.event["bookmakers"] + + def scan(self): + return example.compare_events([self.event], self.sport, 0.5) + + def test_complete_pair_and_units(self): + row, = self.scan() + self.assertEqual((row["team_a"], row["book_a"], row["team_b"], row["book_b"]), + ("Comets", "North", "Owls", "South")) + self.assertAlmostEqual(row["edge_pct"], 4.76190476) + self.assertAlmostEqual(row["implied_total"], 95.23809524) + self.assertEqual(example.stake_split(row["price_a"], row["price_b"], 100), (50, 50, 5)) + self.books[1]["markets"][0]["outcomes"].reverse() + self.assertEqual(self.scan(), [row]) + + def test_missing_sides_at_separate_books(self): + self.books[0]["markets"][0]["outcomes"].pop() + self.books[1]["markets"][0]["outcomes"].pop(0) + self.assertEqual(self.scan(), []) + + def test_soccer_refused_before_account_request(self): + api = Mock() + self.event["sport_key"] = "soccer_epl" + self.assertEqual(example.compare_events([self.event], "soccer_epl", 0.5), []) + self.assertEqual(example.find_h2h_arbs(api, "soccer_epl", 0.5), []) + api.odds.assert_not_called() + + def test_draw_at_another_book_invalidates_two_outcome_assumption(self): + self.books.append({"key": "Third", "markets": [{"key": "h2h", "outcomes": [{"name": "Draw"}]}]}) + self.assertEqual(self.scan(), []) + + def test_repeated_market_or_book_cannot_supply_a_side(self): + self.books[0]["markets"].append(deepcopy(self.books[0]["markets"][0])) + self.assertEqual(self.scan(), []) + self.books[0]["markets"].pop() + twin = deepcopy(self.books[0]) + twin["key"] = " north " + self.books.append(twin) + self.assertEqual(self.scan(), []) + + def test_duplicate_team_or_unpriced_side(self): + rows = self.books[0]["markets"][0]["outcomes"] + for value in [None, True, 0, 1.91, "110", float("nan"), float("inf")]: + with self.subTest(price=value): + rows[0]["price"] = value + self.assertEqual(self.scan(), []) + rows[:] = [{"name": "Comets", "price": 110}] * 2 + self.assertEqual(self.scan(), []) + + def test_reject_mismatched_sport_or_missing_event_identity(self): + self.event["sport_key"] = "soccer_epl" + self.assertEqual(self.scan(), []) + self.event["sport_key"] = self.sport + del self.event["id"] + self.assertEqual(self.scan(), []) + + def test_break_even_is_not_a_positive_gap(self): + self.books[1]["markets"][0]["outcomes"][1]["price"] = -110 + self.assertEqual(example.compare_events([self.event], self.sport, 0), []) + + def test_empty_board_and_request_shape(self): + api = Mock() + api.odds.return_value = [] + self.assertEqual(example.find_h2h_arbs(api, self.sport, 0.5), []) + api.odds.assert_called_once_with(self.sport, markets="h2h", odds_format="american") + with self.assertRaises(ValueError): + example.compare_events({"detail": "unavailable"}, self.sport, 0.5) + + def test_example_never_opens_a_transport(self): + with patch.object(sys, "argv", ["arb_finder.py", "--example", "--bankroll", "100"]), \ + patch("urllib.request.urlopen", side_effect=AssertionError("Unexpected HTTP request")), \ + patch.dict("os.environ", {"PARLAY_API_KEY": "unused-fixture"}), patch("builtins.print"): + self.assertEqual(example.main(), 0) + + +if __name__ == "__main__": + unittest.main() From 04af086a4f9bb191ef3340dfb258ffba24fd4386 Mon Sep 17 00:00:00 2001 From: Esther-MacMini Date: Fri, 4 Dec 2026 22:18:52 -0500 Subject: [PATCH 2/2] Display break-even cleanly after changing the quote --- examples/price-pair.ipynb | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/examples/price-pair.ipynb b/examples/price-pair.ipynb index 55e8d20..469565e 100644 --- a/examples/price-pair.ipynb +++ b/examples/price-pair.ipynb @@ -19,6 +19,7 @@ "execution_count": null, "outputs": [], "source": [ + "import math\n", "import sys\n", "from importlib.metadata import version\n", "\n", @@ -53,7 +54,7 @@ "\n", "if not all(type(p) is int and abs(p) >= 100 for p in (HOME_PRICE, AWAY_PRICE)):\n", " raise ValueError(\"Use an American price of +100 or higher, or -100 or lower.\")\n", - "if TOTAL <= 0:\n", + "if not math.isfinite(TOTAL) or TOTAL <= 0:\n", " raise ValueError(\"Use a positive total.\")\n", "\n", "home = ParlayAPI.american_to_decimal(HOME_PRICE)\n", @@ -61,13 +62,14 @@ "implied = ParlayAPI.american_to_implied(HOME_PRICE) + ParlayAPI.american_to_implied(AWAY_PRICE)\n", "home_amount = TOTAL * away / (home + away)\n", "away_amount = TOTAL - home_amount\n", - "payout = home_amount * home\n", + "payout = TOTAL / implied\n", + "net_display = round(payout - TOTAL, 2) or 0.0\n", "\n", "print(f\"Comets {HOME_PRICE:+d} at North | Owls {AWAY_PRICE:+d} at South\")\n", "print(f\"Implied total: {implied:.2%}\")\n", "print(f\"100% minus implied total: {(1 - implied) * 100:.2f} percentage points\")\n", "print(f\"Modeled split: {home_amount:.2f} on Comets / {away_amount:.2f} on Owls\")\n", - "print(f\"Modeled net on {TOTAL:.2f}: {payout - TOTAL:+.2f}\")" + "print(f\"Modeled net on {TOTAL:.2f}: {net_display:+.2f}\")" ] }, { @@ -77,7 +79,7 @@ "source": [ "At +110 and +110 the two implied probabilities sum to 95.24%. The gap is **4.76 percentage points**. Under equal-payout assumptions the modeled net is **5.00 units on 100**. With the Owls at −110 the total reaches 100% and the modeled net falls to zero.\n", "\n", - "This arithmetic assumes both quotes are accepted on identical settlement terms, one side wins, and there are no fees. A regulation soccer draw, a void, a limit or a changed price can change the outcome. The numbers describe an exercise using fictional quotes.\n", + "This arithmetic assumes both quotes are accepted on identical settlement terms, one side wins, and there are no fees. Displayed amounts are rounded after the calculation. A regulation soccer draw, a void, a limit or a changed price can change the outcome. The numbers describe an exercise using fictional quotes.\n", "\n", "[Run the full Python example on a fictional board](https://github.com/JacobiusMakes/parlay-api-python/blob/main/examples/arb_finder.py) to see how it checks the two team names at each bookmaker. To work with your own account, [get a ParlayAPI key for a research project](https://parlay-api.com/signup?utm_source=jupyter&utm_medium=python_package&utm_campaign=python_price_pair)." ]