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
6 changes: 6 additions & 0 deletions .github/workflows/starter.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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'
Expand Down Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
229 changes: 133 additions & 96 deletions examples/arb_finder.py
Original file line number Diff line number Diff line change
@@ -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


Expand Down
Loading
Loading