Skip to content

Tutorial

Track odds movement in Python

This tutorial tracks odds movement in Python. One request returns every football match the bookmaker prices today with its opening and current odds; from those, a short script ranks the biggest moves, turns prices into probabilities, measures the bookmaker's margin, and saves a snapshot every few minutes so you can see when a price moved, not only how far.

  • Pro plan key
  • 20 min
  • Python
  • pandas
  • Updated

What you will build

Three small scripts that answer the questions people ask of a price list:

  • Which prices moved most since they opened? movers.py reads the day's odds in one request and prints the matches whose price changed most, with the kick-off time and the league.
  • What does a price say, and what does the bookmaker keep? markets.py lists every market of one match and turns the result prices into probabilities, with and without the margin.
  • When did it move? snapshot.py saves the day's prices every five minutes, and a few lines of pandas find the moves of the last hour.

One thing to know before you start: the prices come from one bookmaker, the one our data source follows. This is not a comparison of bookmakers, which needs a feed from each of them. What you can compare is a price with itself: where it opened, where it is now, and what happened in between. Prices are information, not advice. 18+ only; please gamble responsibly.

1. Install the client and set your key

The datasportsapi package on PyPI has no dependencies and needs Python 3.10 or later. Its get() adds your key, returns the JSON envelope as a dict and raises DataSportsAPIError for any answer that is not a success.

Terminal
pip install datasportsapi
export DATASPORTSAPI_API_KEY="sk_live_…"

Without the package, any HTTP client works: send Authorization: Bearer sk_live_… to https://api.datasportsapi.com.

2. One request for the whole day

GET /v2/odds?sport=football returns the headline market of every fixture the bookmaker prices that day: the three-way result in sports with draws, the winner in the others. Add date=YYYY-MM-DD for another day; without it you get the current UTC day. On 21 November it listed 1,721 football matches. One of them:

Response (one fixture)
{
  "data": [
    {
      "fixtureId": 689573,
      "market": {
        "key": "result", "kind": "result", "name": "Full time", "period": "match",
        "line": null, "live": false, "suspended": false, "settledBy": null,
        "choices": [
          { "name": "1", "outcome": "home", "decimal": 3.4, "openingDecimal": 2.85,
            "fractional": "12/5", "openingFractional": "37/20", "change": "up", "winning": null },
          { "name": "X", "outcome": "draw", "decimal": 3.7, "openingDecimal": 3.5,
            "fractional": "27/10", "openingFractional": "5/2", "change": "up", "winning": null },
          { "name": "2", "outcome": "away", "decimal": 2.01, "openingDecimal": 2.2,
            "fractional": "101/100", "openingFractional": "6/5", "change": "down", "winning": null }
        ]
      }
    },
    …
  ],
  "meta": { "count": 1721, "date": "2026-11-21", "sport": "football" }
}

That is Palmeiras v Flamengo. Flamengo opened at 2.20 and are now 2.01, so money has come in for the away side; Palmeiras drifted from 2.85 to 3.40. change gives the direction of the latest move only, so compare openingDecimal with decimal for the whole journey. The answer carries no team names, to stay small: the next step fetches them for the handful of matches you print.

3. From prices to probabilities

A decimal price of 2.01 implies a probability of 1 / 2.01, about 49.8%. Add up the implied probabilities of every choice in a market and you get more than 100%; the excess is the bookmaker's margin. For this match:

ChoicePriceImpliedFair
1 (Palmeiras)3.4029.4%27.7%
X (draw)3.7027.0%25.5%
2 (Flamengo)2.0149.8%46.9%
Total106.2%100%

The margin is 6.2%. The fair column divides each implied figure by the total, which takes the margin out and leaves probabilities that add up to 100%. Two consequences for the code: a move is best measured in implied probability (a price going from 1.17 to 1.37 is a bigger move than one going from 11 to 12), and margins differ a lot between matches. Across that day's list they ran from 4.0% to 13.3%, so compare moves in probability, never raw prices, from one match to another.

4. Rank the biggest moves

Save this as movers.py. moves() works on the day's list alone: for every fixture it keeps the choice whose implied probability moved most since the market opened. upcoming_movers() then walks down that ranking, fetches each match from GET /v2/fixtures/{id} for its teams, league and kick-off, and skips matches that have started or finished, whose pre-match prices are frozen. In-play markets are left out too: their prices follow the score.

movers.py
import sys
import time

from datasportsapi import DataSportsAPI, DataSportsAPIError

client = DataSportsAPI()  # reads DATASPORTSAPI_API_KEY


def call(path, **params):
    """GET with a polite retry: waits out 429 rate_limited and brief network errors."""
    for attempt in range(4):
        try:
            return client.get(path, **params)
        except DataSportsAPIError as e:
            if e.status == 429 and e.code == "rate_limited" and attempt < 3:
                time.sleep((e.retry_after or 60) + 1)
                continue
            raise
        except OSError:
            if attempt < 3:
                time.sleep(5 * 2**attempt)
                continue
            raise


def margin(choices, field="decimal"):
    """The bookmaker's margin: how far the implied probabilities add up past 100%."""
    return sum(1 / c[field] for c in choices) - 1


def moves(day):
    """The biggest price move of each fixture since its market opened."""
    best = {}
    for item in day:
        market = item["market"]
        if market["live"] or market["suspended"]:
            continue  # in-play prices follow the score, not the market's opinion
        for c in market["choices"]:
            was, now = c["openingDecimal"], c["decimal"]
            if not was or not now or was == now:
                continue
            # the move in implied probability, in percentage points:
            # positive = the price shortened (money came in), negative = it drifted
            shift = (1 / now - 1 / was) * 100
            row = {"fixture": item["fixtureId"], "pick": c["name"], "open": was, "now": now,
                   "shift": shift, "margin": margin(market["choices"]) * 100}
            if abs(shift) > abs(best.get(item["fixtureId"], {"shift": 0})["shift"]):
                best[item["fixtureId"]] = row
    return sorted(best.values(), key=lambda r: -abs(r["shift"]))


_fixtures = {}


def fixture(fixture_id):
    """Teams, league and kick-off of a fixture; they do not change, so ask once."""
    if fixture_id not in _fixtures:
        _fixtures[fixture_id] = call(f"/v2/fixtures/{fixture_id}")["data"]
    return _fixtures[fixture_id]


def upcoming_movers(sport="football", top=6):
    day = call("/v2/odds", sport=sport)["data"]
    out = []
    for row in moves(day):
        f = fixture(row["fixture"])
        if f["status"]["type"] != "notstarted":
            continue  # started or over: its pre-match prices are frozen
        out.append({**row, "match": f"{f['home']['shortName']} v {f['away']['shortName']}",
                    "league": f["league"]["name"], "kickoff": f["startTime"][11:16]})
        if len(out) == top:
            break
    return out


if __name__ == "__main__":
    try:
        rows = upcoming_movers()
    except DataSportsAPIError as e:
        sys.exit(f"API error {e.status} {e.code}: {e.message}")
    print(f"{'UTC':<6}{'Match':<24}{'League':<24}{'Pick':>4}{'Open':>7}{'Now':>7}{'Move':>7}{'Margin':>8}")
    for r in rows:
        print(f"{r['kickoff']:<6}{r['match'][:23]:<24}{r['league'][:23]:<24}{r['pick']:>4}"
              f"{r['open']:>7.2f}{r['now']:>7.2f}{r['shift']:>+7.1f}{r['margin']:>7.1f}%")
Terminal
python movers.py
Output (21 November, morning)
UTC   Match                   League                  Pick   Open    Now   Move  Margin
21:15 ABB v Club Aurora       División Profesional       2   1.76   2.58  -18.1   10.2%
14:00 Mafra v Arouca          Taça de Portugal           2   1.33   1.73  -17.4   11.5%
17:45 Dundee v Hearts         Scottish Premiership       2   1.62   2.10  -14.1    6.9%
15:00 Kilmarnock v Aberdeen   Scottish Premiership       2   2.01   2.75  -13.4    7.9%
17:30 Kalamata v AEK          Stoiximan Super League     2   1.17   1.37  -12.5    8.5%
16:30 GAIS v Västerås         Allsvenskan                1   1.76   2.25  -12.4    8.1%

Move is the change in implied probability in percentage points: negative means the price drifted (the market rates that pick lower than when it opened), positive means it shortened. On this morning the biggest moves were all drifts, among them Hearts at Dundee and Aberdeen at Kilmarnock in the Scottish Premiership. The call() helper is the same as in the other guides: it waits out 429 rate_limited with the Retry-After the API sends and retries brief network errors, but never 429 quota_exceeded.

5. Every market of one match

The day's list has one market per fixture. GET /v2/fixtures/{id}/odds has all of them: result, double chance, draw no bet, both teams to score, goal totals at every line, Asian handicap, cards, corners, first to score and more, each with opening and current prices. markets.py prints them with their margins and then the fair probabilities of the result:

markets.py
from movers import call, fixture, margin

FIXTURE_ID = 689573  # Palmeiras v Flamengo
# Choices that overlap (1X, X2, 12 each cover two results) add up to 200%, not 100%
OVERLAPPING = {"doubleChance"}

f = fixture(FIXTURE_ID)
odds = call(f"/v2/fixtures/{FIXTURE_ID}/odds")["data"]
print(f"{f['home']['name']} v {f['away']['name']}, prices of {odds['updatedAt'][:16]} UTC")
for m in odds["markets"]:
    if m["live"] or m["suspended"]:
        continue
    picks = "  ".join(f"{c['name']} {c['openingDecimal']:.2f}>{c['decimal']:.2f}" for c in m["choices"])
    edge = "  —  " if m["kind"] in OVERLAPPING else f"{margin(m['choices']) * 100:>4.1f}%"
    print(f"{m['key']:<20}{edge:>6}  {picks}")

# The three result prices, turned into probabilities with the margin taken out
result = next(m for m in odds["markets"] if m["key"] == "result")
total = sum(1 / c["decimal"] for c in result["choices"])
for c in result["choices"]:
    print(f"{c['name']}: implied {100 / c['decimal']:.1f}%, fair {100 / c['decimal'] / total:.1f}%")
Output (8 of 17 markets)
Palmeiras v Flamengo, prices of 2026-11-21T10:40 UTC
result                6.2%  1 2.85>3.40  X 3.50>3.70  2 2.20>2.01
doubleChance           —    1X 1.62>1.73  X2 1.40>1.30  12 1.29>1.29
result:half1          7.5%  1 3.60>4.00  X 2.20>2.25  2 2.88>2.63
drawNoBet             6.7%  1 2.10>2.50  2 1.67>1.50
bothTeamsToScore      7.5%  Yes 1.75>1.67  No 2.00>2.10
totalGoals:2.5        5.6%  Over 1.85>1.80  Under 1.95>2.00
asianHandicap:0.25    4.3%  (0.25) Palmeiras 1.85>2.05  (-0.25) Flamengo 2.00>1.80
firstToScore         11.6%  Palmeiras 2.10>2.20  No goal 11.00>12.00  Flamengo 1.83>1.73
…
1: implied 29.4%, fair 27.7%
X: implied 27.0%, fair 25.5%
2: implied 49.8%, fair 46.9%

Each market has a key that never changes for the life of the fixture: the kind, plus the period, the line and :live where they apply (result:half1, totalGoals:2.5, asianHandicap:0.25). Store prices under that key and you can follow a market across calls. A line that moves makes a new market with a new key; once the match starts, an in-play market (live: true) appears beside the pre-match one, which stays frozen at its last price.

Double chance shows no margin on purpose. Its choices overlap (1X, X2 and 12 each cover two results), so their implied probabilities add up to about 200%, and the 100% rule does not apply. Watch for this in any market whose choices are not mutually exclusive.

6. Keep snapshots

Opening and current prices tell you how far a price moved, not when. For that, save the list at regular intervals. /v2/odds is renewed every few minutes, so a five-minute loop sees each change without asking twice for the same data:

snapshot.py
import csv
import time
from datetime import datetime, timezone
from pathlib import Path

from movers import call

EVERY = 300  # seconds: /v2/odds is renewed every few minutes


def snapshot(sport="football"):
    """Append the headline price of every fixture of the day to a CSV, one row per choice."""
    stamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
    day = call("/v2/odds", sport=sport)["data"]
    path = Path(f"odds-{sport}-{stamp[:10]}.csv")
    new = not path.exists()
    with path.open("a", newline="") as fh:
        w = csv.writer(fh)
        if new:
            w.writerow(["at", "fixture", "market", "outcome", "decimal", "live", "suspended"])
        for item in day:
            m = item["market"]
            for c in m["choices"]:
                w.writerow([stamp, item["fixtureId"], m["key"], c["outcome"], c["decimal"], m["live"], m["suspended"]])
    return len(day)


if __name__ == "__main__":
    while True:
        print(datetime.now().strftime("%H:%M"), snapshot(), "fixtures")
        time.sleep(EVERY)

Every row is one choice at one moment. A busy football day is about 5,000 rows a snapshot (some 300 KB), so a full day of five-minute snapshots comes close to 90 MB: write to SQLite or a gzipped file if that matters (pandas reads .csv.gz as it is). Leave it running in a terminal, or schedule snapshot() with cron and drop the loop. With the rows in hand, pandas finds the moves of the last hour:

last_hour.py
import pandas as pd

df = pd.read_csv("odds-football-2026-11-21.csv", parse_dates=["at"])
df = df[~df["live"] & ~df["suspended"]]
df["implied"] = 100 / df["decimal"]

# one column per snapshot, one row per fixture and outcome
wide = df.pivot_table(index=["fixture", "outcome"], columns="at", values="implied")

# the move over the last hour, in percentage points, largest first
hour = wide.columns[wide.columns >= wide.columns[-1] - pd.Timedelta(hours=1)]
move = (wide[hour[-1]] - wide[hour[0]]).dropna()
print(move.reindex(move.abs().sort_values(ascending=False).index).head(10))

The same frame answers other questions: a line chart of one fixture over the day (wide.loc[fixture_id].T.plot()), the moment a price crossed a threshold, or the moves in the half hour before each kick-off.

7. When five minutes is too slow

Polling the day's list suits a dashboard or a daily report. To see each price change of a match within about a second, subscribe to its odds:{id} channel on the WebSocket, which sends every changed market in full under its key. The WebSocket starts on the Business plan. The WebSocket, webhooks or polling guide compares the three ways in.

  • Prices in fractional form are in every choice too (fractional, openingFractional); the odds converter turns between formats.
  • Settled markets fill winning on each choice once the source flags the result; settledBy says who did. Not every market is ever settled, so treat null as unknown, not as a loss.
  • Past days work with date=, as far back as your plan's history reaches; earlier dates answer 403 history_not_in_plan.

More guides

Try it with your own key.

The Free plan answers 100 requests a day. No card, no sales call.