An odds comparison page answers one question: where is the best price right now? Building one is mostly plumbing: fetch odds, reshape them into a table, highlight the winners, and keep it fresh without hammering the API.
In this tutorial we build a Streamlit dashboard that compares bookmaker odds for a match, highlights the best price per outcome, shows each bookmaker’s margin and the market’s fair probabilities, and charts line movement over time. Because Streamlit runs your Python on the server, your API key never reaches the browser, and you can build the whole thing in mock mode with no API key.
Disclosure: I work on Orbistats, the data source used here. The structure works with any odds API once you adapt one function.
What we are building
A comparison table: bookmakers as rows, outcomes as columns, best price highlighted.
Metric cards: best price per outcome and which bookmaker offers it.
Margin and fair probability: each bookmaker’s built-in margin, plus de-vigged probabilities.
A line-movement chart of the best price over time.
Auto-refresh and caching, so ten viewers cost one upstream call.
Mock mode, so the UI works before you have a key.
Prerequisites
Python 3.10+ and a terminal.
Basic pandas. We use pivot_table and a little styling.
An Orbistats key is optional until the last step. You can look at real JSON in the sandbox first. Odds terms are explained in the glossary.
Step 1: Project setup
bash
mkdir odds-dashboard && cd odds-dashboard
python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
requirements.txt:
text
streamlit>=1.37
pandas
requests
python-dotenv
pytest
bash
pip install -r requirements.txt
.env (add it to .gitignore):
bash
USE_MOCK=1
ORBISTATS_API_KEY=your_key_here
ORBISTATS_BASE=https://api.orbistats.com/v1
streamlit>=1.37 matters because we use st.fragment with auto-refresh, which arrived in that version.
Step 2: The odds math (small, pure, testable)
Keep the maths separate from the UI so you can test it without opening a browser. Create odds_math.py:
python
OUTCOME_ORDER = ["home", "draw", "away"]
def margin(odds: list[float]) -> float:
"""Bookmaker margin (overround): sum of implied probabilities minus 1."""
return sum(1 / o for o in odds) - 1
def devig(odds: dict[str, float]) -> dict[str, float]:
"""Remove the margin proportionally to get 'fair' probabilities."""
total = sum(1 / o for o in odds.values())
return {k: (1 / o) / total for k, o in odds.items()}
Quick sanity check with the example odds from the Orbistats docs, home 1.91, draw 3.40, away 4.20:
Implied probabilities: 52.4%, 29.4%, 23.8%
They sum to about 105.6%, so the margin is about 5.6%.
Add test_odds_math.py:
python
from odds_math import devig, margin
def test_margin():
assert round(margin([1.91, 3.40, 4.20]), 4) == 0.0558
def test_devig_sums_to_one():
fair = devig({"home": 1.91, "draw": 3.40, "away": 4.20})
assert abs(sum(fair.values()) - 1) < 1e-9
bash
pytest -q
Step 3: The data layer (real API and mock in one place)
Only this file knows what the API looks like. The endpoint pattern follows the odds reference (GET /v1/{sport}/odds?match_id=...&market=1x2) and the fixtures pattern (/v1/{sport}/fixtures?date=today). The response shapes inside normalize_* are assumptions: adjust them to the real payload in the API reference.
Create source.py:
python
import os
import random
import requests
import streamlit as st
from dotenv import load_dotenv
load_dotenv()
BASE = os.getenv("ORBISTATS_BASE", "https://api.orbistats.com/v1")
KEY = os.getenv("ORBISTATS_API_KEY")
USE_MOCK = os.getenv("USE_MOCK") == "1" or not KEY
SPORTS = ["football", "basketball", "american-football", "cricket", "tennis",
"baseball", "esports", "combat-sports", "volleyball", "handball",
"ice-hockey", "golf", "horse-racing"]
---------- real API (cached so many viewers share one upstream call) ----------
@st.cache_data(ttl=15, show_spinner=False)
def _get(path: str, params: tuple = ()):
r = requests.get(
f"{BASE}{path}",
headers={"Authorization": f"Bearer {KEY}"},
params=dict(params),
timeout=10,
)
r.raise_for_status()
return r.json()
def normalize_fixtures(raw) -> list[dict]:
items = raw if isinstance(raw, list) else raw.get("data", [])
out = []
for m in items:
match_id = m.get("match_id") or m.get("id")
home, away = m.get("home") or {}, m.get("away") or {}
label = (f"{home.get('name')} vs {away.get('name')}"
if home and away else m.get("name", str(match_id)))
if match_id:
out.append({"match_id": str(match_id), "label": label})
return out
def normalize_odds(raw) -> list[dict]:
"""Return rows of {bookmaker, outcome, odds}.
ASSUMPTION: a list of {bookmaker, odds: {home, draw, away}}; adjust to the docs."""
items = raw if isinstance(raw, list) else raw.get("data", [raw])
rows = []
for it in items:
book = it.get("bookmaker") or it.get("book") or "feed"
if isinstance(book, dict):
book = book.get("name", "feed")
for outcome, price in (it.get("odds") or {}).items():
try:
price = float(price)
except (TypeError, ValueError):
continue
if price > 1.0:
rows.append({"bookmaker": str(book), "outcome": str(outcome).lower(), "odds": price})
return rows
---------- mock data (a random walk, so the charts move) ----------
_BOOKS = ["Book A", "Book B", "Book C", "Book D", "Book E"]
_BASE = {"home": 1.91, "draw": 3.40, "away": 4.20}
_state: dict = {}
_MOCK_FIXTURES = [
{"match_id": "mock_1", "label": "Blue Rovers vs Red City"},
{"match_id": "mock_2", "label": "Northside FC vs Harbor United"},
]
def _mock_odds(match_id: str) -> list[dict]:
rows = []
for book in _BOOKS:
cur = _state.setdefault(
(match_id, book),
{k: v * random.uniform(0.97, 1.03) for k, v in _BASE.items()},
)
for outcome in cur:
cur[outcome] = max(1.05, round(cur[outcome] * random.uniform(0.99, 1.01), 2))
rows.append({"bookmaker": book, "outcome": outcome, "odds": cur[outcome]})
return rows
---------- public functions the app uses ----------
def get_fixtures(sport: str) -> list[dict]:
if USE_MOCK:
return _MOCK_FIXTURES
return normalize_fixtures(_get(f"/{sport}/fixtures", (("date", "today"),)))
def get_odds(sport: str, match_id: str, market: str) -> list[dict]:
if USE_MOCK:
return _mock_odds(match_id)
raw = _get(f"/{sport}/odds", (("match_id", match_id), ("market", market)))
return normalize_odds(raw)
Three things worth noticing:
st.cache_data(ttl=15) is your quota shield. However many people open the dashboard, the same match and market cost at most one upstream call every 15 seconds, which is about 4 a minute.
Params are passed as a tuple so Streamlit can hash them for the cache key.
Mock bookmakers are generic names (“Book A”), so the demo never implies real prices from real companies.
Step 4: The dashboard
Create app.py:
python
import pandas as pd
import requests
import streamlit as st
from odds_math import OUTCOME_ORDER, devig, margin
from source import SPORTS, USE_MOCK, get_fixtures, get_odds
st.set_page_config(page_title="Odds Comparison", page_icon="📊", layout="wide")
st.title("📊 Odds Comparison Dashboard")
if USE_MOCK:
st.info("Mock mode: simulated odds. Set ORBISTATS_API_KEY in .env (and USE_MOCK=0) for real data.")
def highlight_best(col: pd.Series):
best = col.max()
return ["background-color: rgba(34,197,94,.35); font-weight: 700" if v == best else ""
for v in col]
def board(sport: str, match_id: str, market: str):
try:
rows = get_odds(sport, match_id, market)
except requests.RequestException as e:
st.error(f"API error: {e}")
return
if not rows:
st.warning("No odds returned for this match and market yet.")
return
# 1) bookmakers x outcomes table
df = pd.DataFrame(rows)
table = df.pivot_table(index="bookmaker", columns="outcome", values="odds", aggfunc="max")
ordered = [c for c in OUTCOME_ORDER if c in table.columns]
odds_cols = ordered + [c for c in table.columns if c not in ordered]
table = table[odds_cols]
2) margin per bookmaker (only where every outcome is present)
complete = table.dropna()
table["margin %"] = (complete.apply(lambda r: margin(r.tolist()), axis=1) * 100)
3) best price per outcome
best = table[odds_cols].max()
best_book = table[odds_cols].idxmax()
cols = st.columns(len(odds_cols) + 1)
for c, name in zip(cols, odds_cols):
c.metric(f"Best {name}", f"{best[name]:.2f}")
c.caption(f"at {best_book[name]}")
cols[-1].metric(
"Best-price margin", f"{margin(best.tolist()) * 100:.2f}%",
help="Below 0% usually means stale or mismatched prices, not free money.",
)
st.dataframe(
table.style.apply(highlight_best, subset=odds_cols)
.format("{:.2f}", subset=odds_cols, na_rep="–")
.format("{:.2f}%", subset=["margin %"], na_rep="–")
)
4) fair probabilities (margin removed), averaged across bookmakers
if len(complete):
fair = pd.DataFrame([devig(r.to_dict()) for _, r in complete.iterrows()],
index=complete.index)
st.subheader("Fair probability (margin removed)")
st.bar_chart((fair.mean() * 100).round(1))
5) line movement of the best price
key = (sport, match_id, market)
history = st.session_state.setdefault("history", [])
history.append({"key": key, "ts": pd.Timestamp.now(), **{o: float(best[o]) for o in odds_cols}})
del history[:-300] # keep memory bounded
mine = [h for h in history if h["key"] == key]
if len(mine) > 1:
st.subheader("Best price over time")
st.line_chart(pd.DataFrame(mine).set_index("ts")[odds_cols])
st.caption(f"Updated {pd.Timestamp.now():%H:%M:%S}")
---------- sidebar controls ----------
with st.sidebar:
sport = st.selectbox("Sport", SPORTS, format_func=lambda s: s.replace("-", " ").title())
market = st.text_input("Market", value="1x2",
help="Check the supported markets in the Odds API docs.")
refresh = st.select_slider("Auto-refresh (seconds)", options=[10, 20, 30, 60], value=30)
try:
fixtures = get_fixtures(sport)
except requests.RequestException as e:
st.error(f"Could not load fixtures: {e}")
st.stop()
if not fixtures:
st.warning("No fixtures found for today.")
st.stop()
options = {f["label"]: f["match_id"] for f in fixtures}
label = st.sidebar.selectbox("Match", list(options))
match_id = options[label]
st.subheader(label)
st.fragment(run_every=refresh)(board)(sport, match_id, market)
Run it:
bash
streamlit run app.py
You should see a table of five mock bookmakers, a green highlight on the best price in each column, margin values around 3 to 8 percent, a fair-probability bar chart, and a line chart that starts moving after the second refresh.
How it works (the parts worth understanding)
st.fragment(run_every=...) refreshes only the odds board. Your sidebar selections stay put, and the rest of the page does not rerun every 30 seconds.
pivot_table(..., aggfunc="max") guards against a bookmaker listing the same outcome twice by keeping the higher price.
The best-price margin is a data-quality signal, not a strategy. If the best prices across bookmakers sum to less than 100%, the dashboard shows a negative margin. In practice that nearly always means stale odds, different lines or mismatched markets. Real prices at that level disappear fast and often cannot be taken at the shown stake.
Fair probability is an estimate. Proportional de-vigging is the simplest method. It is fine for a dashboard, but it is not a prediction and not betting advice.
Step 5: Switch to real data
Get access. Request access. Your plan’s access time starts when you open the activation link, so do this only when the UI is ready.
Confirm the endpoints and payload in the API reference and the Odds API page. Adjust normalize_fixtures and normalize_odds if the field names differ.
Edit .env: set USE_MOCK=0 and paste your key.
Run streamlit run app.py again.
The Odds API covers pre-match and live odds normalized across bookmakers, so you do not write a parser per bookmaker. Fixtures come from the Sports Data API. Check supported markets for your sport in the documentation before changing the Market box.
Common problems
Symptom Likely cause Fix
“No odds returned” Wrong market value, or match_id from a different sport Take the market name from the docs and pick the match from the same sport’s fixtures
Only one row called “feed” The payload has no per-bookmaker list in the shape you assumed Print the raw JSON and adjust normalize_odds
Empty or odd columns Outcome names differ (for example 1, x, 2) Map them to home, draw, away inside normalize_odds
401 error Key missing, or .env not loaded Check ORBISTATS_API_KEY, and that load_dotenv() runs in source.py
429 error Too many refreshes or many sessions Increase the refresh interval or the cache ttl
Best-price margin is negative Stale, mismatched or different-line odds Treat it as a data-quality flag, and compare timestamps if the API provides them
Line chart restarts when you change match History is keyed by sport, match and market That is intended, so each selection keeps its own series
App feels slow Network calls made outside the cache Keep every API call inside _get, which is cached
Nothing is highlighted Only one bookmaker, or all values tied Add more sources, since ties highlight every tied cell by design
Deploying it
Streamlit Community Cloud is the quickest option. Push the repo to GitHub, add your key under the app’s secrets, and confirm that ORBISTATS_API_KEY is visible to the app as an environment variable.
Any small server or container also works: streamlit run app.py --server.port 8501.
Protect your quota. A public Streamlit app lets anyone use your API key indirectly. The cache helps, but also consider a login or a password gate, and keep refresh intervals generous.
Read the licence before displaying odds publicly or commercially: data licensing. Odds data is for comparison and analysis, and betting rules differ by country.
Where to go next
Convert formats: add decimal, American and fractional views with the helpers from Odds Converter in JS & Python, and use the odds tools page to sanity-check your results.
Go further with maths: see Build a +EV Bet Finder in Python for edge and stake sizing.
Stream instead of poll: the WebSocket API suits live odds, and Building a Sports Betting Dashboard with Next.js shows a relay pattern.
Keep history: save snapshots to SQLite and backfill with the Historical Sports Data API for real line-movement charts.
Add markets: one tab each for totals and handicaps, once you have confirmed them in the docs.
Check the basics: pricing is on the pricing page.
Wrap-up
You built a dashboard that normalizes bookmaker odds into one table, highlights the best price, exposes each bookmaker’s margin, estimates fair probabilities and tracks movement, with a cache that protects your quota and a mock mode that lets you build before you pay for anything.
If you want to see it on real odds, request the free hour and run Step 5. Which tab should come next: totals and handicaps, or a saved line-movement history? Tell me in the comments.
Top comments (0)