Guide: Python
Backtest a betting rule against closing lines
By the end of this guide you will have a Python script that replays a betting rule over a run of finished games and scores every bet two ways: against the fair closing price, which is its closing line value, and against the result. It takes about twenty-five minutes to read, and it needs a Pro key, because the opening and closing snapshots come with Pro and Business only.
Before you start
What you need
- Python
- 3.9 or later, with
requestsinstalled. - A key
- Pro or Business, for
snapshots=opening,closing; the price history comes with every paid plan and Pinnacle with every plan. Graded results are on every plan, so the grading half of the code runs on any key. On another plan the snapshot request is refused or comes back without opening and closing prices, and the script says which: it stops with the API's reason, or reports every game skipped for want of a reference opening. - History
- Recorded prices start on different dates by league, some with gaps, and reach back furthest in the NFL, to 22 Dec 2025 (SockOdds's history page, read 16 Oct 2026), so this guide's example backtests the NFL. AFL and NRL history begins on 8 October 2026, so the first full season you can backtest in either is 2027.
- Time
- About twenty-five minutes to read; a season of one league is a few hundred requests.
The models and backtesting page introduces opening and closing prices. This guide builds the whole test around them.
Status, 13 Oct 2026. /v1 opens to keys shortly; until then requests are redirected to the docs, and the script stops with a message that says so. Written against the SockOdds v1 contract and tested against its schemas, on a mock that serves the v1 shape, including opening and closing snapshots and graded results. A run on real history needs a Pro key and is pending; its window, league and numbers will be added here when it has run.
Why the close
Profit is a slow judge
Backtesting on profit alone asks the noisiest number in betting to settle a small difference. Near even money, a single bet's result swings by about a whole stake, so after 500 bets the ROI is still only known to within about nine points either way. A rule that is really worth 3% cannot be told apart from one worth nothing.
The closing price is the market's last and best-informed view before the game. Measured against a sharp book's close with its margin removed, the price you took has a closing line value:
CLV = price taken × fair closing chance − 1
CLV moves by a few percent a bet rather than a whole stake, so its average settles far sooner. A rule whose bets beat the close on average is usually finding something; one that does not is usually finding noise, whatever its profit says.
The plan
What the script does
- Lists every graded game in a window from
/v1/results. - Reads each game's opening and closing prices with
snapshots=opening,closing. - Removes the margin from the reference book's opening price, and notes when it opened.
- Finds the reference's last price before the start, from the closing snapshot or the history.
- Applies the rule once the reference has opened, using only what was known then.
- Scores each bet against the fair close and against the result.
- Reports both averages with how far each could be off.
Step 1
Settings
import os
import statistics
import sys
import time
from collections import Counter
from datetime import date, datetime, timedelta, timezone
from urllib.parse import urljoin
import requests
API = "https://api.sockodds.com/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['SOCKODDS_KEY']}"}
# Where the rule would bet.
BOOKS = ["sportsbet", "tab", "ladbrokes", "neds", "pointsbet"]
# The sharp price everything is measured against; "betfair_exchange" works too.
REFERENCE = "pinnacle"
# Head to head: one market a game, and no line that can move away from the bet.
MARKETS = "winner"
# Bet when a price beats the reference's fair opening price by 2% or more.
EDGE = 0.02
REFERENCEis the book whose fair price everything is measured against. Pinnacle is the usual choice; the Betfair Exchange is the other sharp price in the feed.MARKETSis head to head on purpose. A line market that moves, say from -12.5 to -14.5, becomes a different market, so a bet at -12.5 has no close on its own number. Testing lines means keeping only the ones whose number held, which quietly drops the bets that moved most.EDGEis the rule's one setting. Choose it before you look at the results, for the reason under "the traps" below.
Step 2
Requests that explain their errors
def get(url, params=None):
"""GET with the key. Waits when the API says to (over the per-minute limit, or briefly
busy); stops with the API's own reason on any other refusal, a used-up month included."""
for _ in range(5):
r = requests.get(url, params=params, headers=HEADERS, timeout=30)
problem = r.json() if "problem+json" in r.headers.get("content-type", "") else {}
if r.status_code in (429, 503) and problem.get("title") != "Monthly allowance reached":
time.sleep(max(1.0, float(r.headers.get("retry-after", 60))))
continue
if r.status_code >= 500:
r.raise_for_status() # a server error: the caller decides whether to try again
if problem:
raise SystemExit(f'{problem["status"]} {problem["title"]}: {problem["detail"]}')
if r.status_code != 200 or "json" not in r.headers.get("content-type", ""):
raise SystemExit(f"{r.status_code} from {r.url}: not a JSON answer from the API")
return r.json()
raise SystemExit(f"{url}: still asked to wait after five tries")
def every(url, params):
"""Every item of a listing, following links.next (which may be relative) across pages."""
while url:
page = get(url, params)
yield from page["data"]
url, params = (urljoin(url, page["links"]["next"]) if page["links"]["next"] else None), None
def when(text):
return datetime.fromisoformat(text.replace("Z", "+00:00"))
def stamp(moment):
return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
Every v1 error is an application/problem+json body holding a title and a detail, so get stops with the API's own sentence instead of a bare status code: a wrong key, a feature the plan does not include, a used-up month. It waits only when waiting helps: a 429 over the per-minute limit, or a 503 while older history is busy, each for its retry-after and at least a second, up to five times. An answer that is not JSON, such as a web page after a redirect, stops it too.
every walks a listing page by page, following links.next, which may be relative, until it is null. when and stamp turn the API's UTC times into Python and back.
Step 3
Graded results
def results(league, start, end):
"""Every graded outcome of the games that started from the start day to the end day."""
after = f"{start}T00:00:00Z"
before = f"{date.fromisoformat(end) + timedelta(days=1)}T00:00:00Z" # the end day included
games = {}
for result in every(f"{API}/results", {"league": league, "starts_after": after,
"starts_before": before, "limit": 100}):
verdicts = games.setdefault(result["event"]["id"], {})
for o in result["outcomes"]:
# A later partial result adds outcomes without changing any verdict; a correction replaces.
if result["status"] == "corrected" or o["id"] not in verdicts:
verdicts[o["id"]] = (o["verdict"], o.get("dead_heat_factor"))
return games
/v1/results lists finished games with a verdict on each settled outcome: won, lost, void or dead_heat, the last with a dead_heat_factor. Outcome IDs are the same ones the prices use, so a bet and its verdict meet on one key. The window runs from the start day to the end day inclusive: starts_before is midnight after the end day.
Two details matter. A game can be graded in parts: one result may settle the head to head while a prop is still pending, and a later result adds the rest without changing what was published, so the first verdict for an outcome is kept. A result whose status is corrected replaces what came before, and stays.
Step 4
The open, and when it happened
def snapshots(event_id):
"""One game's first and last recorded price at your books and the reference (Pro and Business)."""
params = {"markets": MARKETS, "bookmakers": ",".join(BOOKS + [REFERENCE]),
"snapshots": "opening,closing"}
return get(f"{API}/events/{event_id}/odds", params)["data"]
def devig(prices):
"""{outcome ID: decimal price} to {outcome ID: margin-free chance}, multiplicative method."""
total = sum(1 / p for p in prices.values())
return {oid: (1 / p) / total for oid, p in prices.items()}
def reference_markets(event):
"""The markets of the kinds under test that the reference prices, each with the reference's
price on each of its outcomes: (market, {outcome ID: price})."""
found = []
for market in event["markets"]:
ref = {o["id"]: p for o in market["outcomes"] for p in o["prices"] if p["bookmaker"] == REFERENCE}
if market["key"] in MARKETS.split(",") and len(ref) > 1:
found.append((market, ref))
return found
def opening(event):
"""The reference's fair opening chance on each outcome, and when that market had opened."""
fair, opened = {}, {}
for market, ref in reference_markets(event):
firsts = {oid: p.get("opening") for oid, p in ref.items()}
if not all(firsts.values()):
continue
fair.update(devig({oid: s["decimal_odds"] for oid, s in firsts.items()}))
at = max(when(s["observed_at"]) for s in firsts.values())
opened.update({oid: at for oid in ref})
return fair, opened
With snapshots=opening,closing, every price on an outcome carries that book's first and last recorded quote, each with a price, an implied chance and its own observed_at. devig scales a market's implied chances to add up to 100%, the multiplicative method from the fair odds page.
opening returns two things: the reference's fair opening chance on each outcome, and the moment the reference's market had fully opened. The second is what keeps the rule honest in step 6.
Step 5
The close: the last price before the start
def last_before(event, market, outcome_ids, start):
"""The reference's last recorded price on each outcome in the 24 hours before the start,
from the history (paid plans). None if it withdrew or was not quoted in that window."""
params = {"event_id": event["id"], "from": stamp(start - timedelta(hours=24)), "to": stamp(start),
"markets": market["key"], "bookmakers": REFERENCE, "limit": 1000}
last = {} # outcome ID -> its latest change; changes come in the order they were observed
for change in every(f"{API}/odds/history", params):
if change["market"]["id"] == market["id"] and when(change["observed_at"]) <= start:
last[change["outcome"]["id"]] = change
if set(last) != set(outcome_ids):
return None
if any(c["kind"] == "withdrawn" or not c["decimal_odds"] for c in last.values()):
return None
prices = {oid: c["decimal_odds"] for oid, c in last.items()}
return prices, max(when(c["observed_at"]) for c in last.values())
def closing(event):
"""The reference's fair chance at the close, which here means its last quotes before the
start. Uses the closing snapshot when it was seen before the start (whichever way the API
defines it), otherwise the history. Returns (fair, how found, minutes before the start)."""
start, fair, found, gaps = when(event["scheduled_start"]), {}, [], []
for market, ref in reference_markets(event):
lasts = {oid: p.get("closing") for oid, p in ref.items()}
if all(lasts.values()) and all(when(s["observed_at"]) <= start for s in lasts.values()):
prices = {oid: s["decimal_odds"] for oid, s in lasts.items()}
seen, how = max(when(s["observed_at"]) for s in lasts.values()), "snapshot"
else:
standing = last_before(event, market, set(ref), start)
if standing is None:
continue
(prices, seen), how = standing, "history"
fair.update(devig(prices))
found.append(how)
gaps.append((start - seen).total_seconds() / 60)
return fair, found, gaps
The close here is defined by what matters to a backtest, not by any one field: the reference's last price before the scheduled start. A feed's last quote need not come before the start, so a "last quote" can come from during the game, which is no close at all.
- When the reference's
closingsnapshot was seen before the start, it is that last price however the API definesclosing, and it is used. - Otherwise
last_beforereads the reference's recorded changes in the 24 hours up to the start from/v1/odds/historyand takes the latest on each outcome. A market the reference withdrew before the start, or did not quote in that window, has no close.
A game with no close is skipped and counted, never scored against a guess. closing also reports how each close was found and how long before the start it was seen, and the summary prints both, because a close seen hours early is a weaker test than one seen minutes early.
Step 6
The rule under test
def pick(event, fair_open, opened):
"""The rule under test: the best opening price at your books on each outcome, kept when it
beats the reference's fair opening price by EDGE. A price a book opened with before the
reference had opened is left out: it may have been gone before the reference's view existed."""
best = {} # outcome ID -> (price, book, name)
for market in event["markets"]:
for o in market["outcomes"]:
if o["id"] not in fair_open:
continue
for p in o["prices"]:
first = p.get("opening")
if p["bookmaker"] not in BOOKS or not first or when(first["observed_at"]) < opened[o["id"]]:
continue
if first["decimal_odds"] > best.get(o["id"], (0,))[0]:
best[o["id"]] = (first["decimal_odds"], p["bookmaker"], o["name"])
return [(oid, *bet) for oid, bet in best.items() if bet[0] * fair_open[oid] - 1 >= EDGE]
The example rule is a classic: once the reference has opened, take the best opening price among your books when it beats the reference's fair opening price by 2%. "Once the reference has opened" is the important part. A book that opened before the reference may have changed its price before the reference's view existed, so its opening price is left out: the backtest may only use what a bettor could have seen at the moment of the bet.
Replace pick with your own model and keep its inputs and its return shape: the outcome ID, the price, the book and a name to print. Any rule you write here should obey the same limit on what it reads.
Step 7
Settle, and say how sure
def profit(price, verdict, dead_heat_factor=None):
"""Profit on a one-unit stake, settled the way the API grades it."""
if verdict == "won":
return price - 1
if verdict == "dead_heat":
return dead_heat_factor * price - 1
if verdict == "void":
return 0.0
return -1.0
def spread(values):
"""Two standard errors of the mean: roughly how far the true average could sit from this one."""
if len(values) < 2:
return float("inf")
return 2 * statistics.stdev(values) / len(values) ** 0.5
Profit is per unit staked, settled the way the API grades it. A dead heat pays the factor's share of the stake at the price and loses the rest, so 0.5 at 1.80 returns 0.90 for a loss of 0.10.
spread is two standard errors of an average: a quick measure of how far the true value could sit from the one measured. Printing it beside both averages is what keeps a lucky streak from reading like an edge.
Step 8
Score every bet both ways
def main(league, start, end):
games = results(league, start, end)
bets, skipped, sources, gaps, unsettled = [], Counter(), Counter(), [], 0
for event_id, verdicts in games.items():
event = snapshots(event_id)
fair_open, opened = opening(event)
if not fair_open:
skipped["no reference opening"] += 1
continue
fair_close, found, waits = closing(event)
if not fair_close:
skipped["no reference price standing at the start"] += 1
continue
sources.update(found)
gaps += waits
for oid, price, book, name in pick(event, fair_open, opened):
if oid not in verdicts:
unsettled += 1
continue
if oid not in fair_close:
continue # this market had no reference price standing at the start
clv = price * fair_close[oid] - 1
pnl = profit(price, *verdicts[oid])
bets.append((clv, pnl))
print(f'{event["scheduled_start"][:10]} {event["name"]}: {name} {price:.2f} at {book}, '
f"fair close {1 / fair_close[oid]:.2f}, CLV {clv:+.1%}, {verdicts[oid][0]} {pnl:+.2f}")
print(f"\n{league.upper()}, {start} to {end}. Games graded: {len(games)}. Bets: {len(bets)}.")
if gaps:
print(f'Closes: {sources["snapshot"]} from snapshots, {sources["history"]} from history, '
f"seen a median {statistics.median(gaps):.0f} minutes before the start.")
reasons = ", ".join(f"{n} {why}" for why, n in skipped.items()) or "no games"
print(f"Skipped: {reasons}; {unsettled} bets not yet graded.")
if bets:
clv, pnl = [b[0] for b in bets], [b[1] for b in bets]
beat = sum(c > 0 for c in clv) / len(clv)
print(f"Closing line: average CLV {statistics.mean(clv):+.1%}, give or take "
f"{spread(clv):.1%}; {beat:.0%} of bets beat the close.")
print(f"Results: {sum(pnl):+.2f} units on {len(pnl)} staked, "
f"ROI {statistics.mean(pnl):+.1%}, give or take {spread(pnl):.1%}.")
One line per bet, then the summary: games graded, bets placed, how the closes were found and how long before the start, what was skipped and why, the average CLV with its spread and share of bets that beat the close, and the result in units with its own spread. The skip counts are part of the answer: if many games have no close, the sample has a hole in it.
The whole file
clv_backtest.py
Save it, install requests, set a Pro key and give it a league and a window:
python3 -m pip install requests
export SOCKODDS_KEY="paste-your-pro-key-here"
python3 clv_backtest.py nfl 2026-09-01 2026-10-13
"""Backtest a betting rule against closing lines: did the prices it took beat the close?
export SOCKODDS_KEY="your-pro-key" # opening and closing prices are on Pro and Business
python clv_backtest.py nfl 2026-09-01 2026-10-13
python clv_backtest.py nfl # the last 30 days
The rule tested here: once the reference book has opened, back any outcome whose best opening
price at your books beats the reference's fair (margin-free) opening price by EDGE or more.
Swap pick() for your own.
"""
import os
import statistics
import sys
import time
from collections import Counter
from datetime import date, datetime, timedelta, timezone
from urllib.parse import urljoin
import requests
API = "https://api.sockodds.com/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['SOCKODDS_KEY']}"}
# Where the rule would bet.
BOOKS = ["sportsbet", "tab", "ladbrokes", "neds", "pointsbet"]
# The sharp price everything is measured against; "betfair_exchange" works too.
REFERENCE = "pinnacle"
# Head to head: one market a game, and no line that can move away from the bet.
MARKETS = "winner"
# Bet when a price beats the reference's fair opening price by 2% or more.
EDGE = 0.02
def get(url, params=None):
"""GET with the key. Waits when the API says to (over the per-minute limit, or briefly
busy); stops with the API's own reason on any other refusal, a used-up month included."""
for _ in range(5):
r = requests.get(url, params=params, headers=HEADERS, timeout=30)
problem = r.json() if "problem+json" in r.headers.get("content-type", "") else {}
if r.status_code in (429, 503) and problem.get("title") != "Monthly allowance reached":
time.sleep(max(1.0, float(r.headers.get("retry-after", 60))))
continue
if r.status_code >= 500:
r.raise_for_status() # a server error: the caller decides whether to try again
if problem:
raise SystemExit(f'{problem["status"]} {problem["title"]}: {problem["detail"]}')
if r.status_code != 200 or "json" not in r.headers.get("content-type", ""):
raise SystemExit(f"{r.status_code} from {r.url}: not a JSON answer from the API")
return r.json()
raise SystemExit(f"{url}: still asked to wait after five tries")
def every(url, params):
"""Every item of a listing, following links.next (which may be relative) across pages."""
while url:
page = get(url, params)
yield from page["data"]
url, params = (urljoin(url, page["links"]["next"]) if page["links"]["next"] else None), None
def when(text):
return datetime.fromisoformat(text.replace("Z", "+00:00"))
def stamp(moment):
return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def results(league, start, end):
"""Every graded outcome of the games that started from the start day to the end day."""
after = f"{start}T00:00:00Z"
before = f"{date.fromisoformat(end) + timedelta(days=1)}T00:00:00Z" # the end day included
games = {}
for result in every(f"{API}/results", {"league": league, "starts_after": after,
"starts_before": before, "limit": 100}):
verdicts = games.setdefault(result["event"]["id"], {})
for o in result["outcomes"]:
# A later partial result adds outcomes without changing any verdict; a correction replaces.
if result["status"] == "corrected" or o["id"] not in verdicts:
verdicts[o["id"]] = (o["verdict"], o.get("dead_heat_factor"))
return games
def snapshots(event_id):
"""One game's first and last recorded price at your books and the reference (Pro and Business)."""
params = {"markets": MARKETS, "bookmakers": ",".join(BOOKS + [REFERENCE]),
"snapshots": "opening,closing"}
return get(f"{API}/events/{event_id}/odds", params)["data"]
def devig(prices):
"""{outcome ID: decimal price} to {outcome ID: margin-free chance}, multiplicative method."""
total = sum(1 / p for p in prices.values())
return {oid: (1 / p) / total for oid, p in prices.items()}
def reference_markets(event):
"""The markets of the kinds under test that the reference prices, each with the reference's
price on each of its outcomes: (market, {outcome ID: price})."""
found = []
for market in event["markets"]:
ref = {o["id"]: p for o in market["outcomes"] for p in o["prices"] if p["bookmaker"] == REFERENCE}
if market["key"] in MARKETS.split(",") and len(ref) > 1:
found.append((market, ref))
return found
def opening(event):
"""The reference's fair opening chance on each outcome, and when that market had opened."""
fair, opened = {}, {}
for market, ref in reference_markets(event):
firsts = {oid: p.get("opening") for oid, p in ref.items()}
if not all(firsts.values()):
continue
fair.update(devig({oid: s["decimal_odds"] for oid, s in firsts.items()}))
at = max(when(s["observed_at"]) for s in firsts.values())
opened.update({oid: at for oid in ref})
return fair, opened
def last_before(event, market, outcome_ids, start):
"""The reference's last recorded price on each outcome in the 24 hours before the start,
from the history (paid plans). None if it withdrew or was not quoted in that window."""
params = {"event_id": event["id"], "from": stamp(start - timedelta(hours=24)), "to": stamp(start),
"markets": market["key"], "bookmakers": REFERENCE, "limit": 1000}
last = {} # outcome ID -> its latest change; changes come in the order they were observed
for change in every(f"{API}/odds/history", params):
if change["market"]["id"] == market["id"] and when(change["observed_at"]) <= start:
last[change["outcome"]["id"]] = change
if set(last) != set(outcome_ids):
return None
if any(c["kind"] == "withdrawn" or not c["decimal_odds"] for c in last.values()):
return None
prices = {oid: c["decimal_odds"] for oid, c in last.items()}
return prices, max(when(c["observed_at"]) for c in last.values())
def closing(event):
"""The reference's fair chance at the close, which here means its last quotes before the
start. Uses the closing snapshot when it was seen before the start (whichever way the API
defines it), otherwise the history. Returns (fair, how found, minutes before the start)."""
start, fair, found, gaps = when(event["scheduled_start"]), {}, [], []
for market, ref in reference_markets(event):
lasts = {oid: p.get("closing") for oid, p in ref.items()}
if all(lasts.values()) and all(when(s["observed_at"]) <= start for s in lasts.values()):
prices = {oid: s["decimal_odds"] for oid, s in lasts.items()}
seen, how = max(when(s["observed_at"]) for s in lasts.values()), "snapshot"
else:
standing = last_before(event, market, set(ref), start)
if standing is None:
continue
(prices, seen), how = standing, "history"
fair.update(devig(prices))
found.append(how)
gaps.append((start - seen).total_seconds() / 60)
return fair, found, gaps
def pick(event, fair_open, opened):
"""The rule under test: the best opening price at your books on each outcome, kept when it
beats the reference's fair opening price by EDGE. A price a book opened with before the
reference had opened is left out: it may have been gone before the reference's view existed."""
best = {} # outcome ID -> (price, book, name)
for market in event["markets"]:
for o in market["outcomes"]:
if o["id"] not in fair_open:
continue
for p in o["prices"]:
first = p.get("opening")
if p["bookmaker"] not in BOOKS or not first or when(first["observed_at"]) < opened[o["id"]]:
continue
if first["decimal_odds"] > best.get(o["id"], (0,))[0]:
best[o["id"]] = (first["decimal_odds"], p["bookmaker"], o["name"])
return [(oid, *bet) for oid, bet in best.items() if bet[0] * fair_open[oid] - 1 >= EDGE]
def profit(price, verdict, dead_heat_factor=None):
"""Profit on a one-unit stake, settled the way the API grades it."""
if verdict == "won":
return price - 1
if verdict == "dead_heat":
return dead_heat_factor * price - 1
if verdict == "void":
return 0.0
return -1.0
def spread(values):
"""Two standard errors of the mean: roughly how far the true average could sit from this one."""
if len(values) < 2:
return float("inf")
return 2 * statistics.stdev(values) / len(values) ** 0.5
def main(league, start, end):
games = results(league, start, end)
bets, skipped, sources, gaps, unsettled = [], Counter(), Counter(), [], 0
for event_id, verdicts in games.items():
event = snapshots(event_id)
fair_open, opened = opening(event)
if not fair_open:
skipped["no reference opening"] += 1
continue
fair_close, found, waits = closing(event)
if not fair_close:
skipped["no reference price standing at the start"] += 1
continue
sources.update(found)
gaps += waits
for oid, price, book, name in pick(event, fair_open, opened):
if oid not in verdicts:
unsettled += 1
continue
if oid not in fair_close:
continue # this market had no reference price standing at the start
clv = price * fair_close[oid] - 1
pnl = profit(price, *verdicts[oid])
bets.append((clv, pnl))
print(f'{event["scheduled_start"][:10]} {event["name"]}: {name} {price:.2f} at {book}, '
f"fair close {1 / fair_close[oid]:.2f}, CLV {clv:+.1%}, {verdicts[oid][0]} {pnl:+.2f}")
print(f"\n{league.upper()}, {start} to {end}. Games graded: {len(games)}. Bets: {len(bets)}.")
if gaps:
print(f'Closes: {sources["snapshot"]} from snapshots, {sources["history"]} from history, '
f"seen a median {statistics.median(gaps):.0f} minutes before the start.")
reasons = ", ".join(f"{n} {why}" for why, n in skipped.items()) or "no games"
print(f"Skipped: {reasons}; {unsettled} bets not yet graded.")
if bets:
clv, pnl = [b[0] for b in bets], [b[1] for b in bets]
beat = sum(c > 0 for c in clv) / len(clv)
print(f"Closing line: average CLV {statistics.mean(clv):+.1%}, give or take "
f"{spread(clv):.1%}; {beat:.0%} of bets beat the close.")
print(f"Results: {sum(pnl):+.2f} units on {len(pnl)} staked, "
f"ROI {statistics.mean(pnl):+.1%}, give or take {spread(pnl):.1%}.")
if __name__ == "__main__":
league = sys.argv[1] if len(sys.argv) > 1 else "nfl"
end = sys.argv[3] if len(sys.argv) > 3 else date.today().isoformat()
start = sys.argv[2] if len(sys.argv) > 2 else (date.fromisoformat(end) - timedelta(days=30)).isoformat()
main(league, start, end)
This file and its tests are going into a public repository; the link goes here when it exists. Until then, the file above is the one the tests run.
A run
What it prints
This is not the output of the command above, which needs a Pro key and real history. It is a run on 16 Oct 2026 against the v1 schema mock, with the mock's own window, python3 clv_backtest.py nfl 2027-01-01 2027-01-31: one illustrative NFL game with made-up opening and closing prices and a graded result. Two bets prove nothing about a rule; the run shows the report's shape, and how wide the uncertainty is at that size.
2027-01-03 Kansas City Chiefs v Buffalo Bills: Kansas City Chiefs 1.77 at sportsbet, fair close 1.72, CLV +2.8%, won +0.77
2027-01-03 Kansas City Chiefs v Buffalo Bills: Buffalo Bills 2.75 at tab, fair close 2.39, CLV +15.3%, lost -1.00
NFL, 2027-01-01 to 2027-01-31. Games graded: 1. Bets: 2.
Closes: 1 from snapshots, 0 from history, seen a median 102 minutes before the start.
Skipped: no games; 0 bets not yet graded.
Closing line: average CLV +9.0%, give or take 12.5%; 100% of bets beat the close.
Results: -0.23 units on 2 staked, ROI -11.5%, give or take 177.0%.
Reading it
Where the numbers come from
Pinnacle opened at 1.71 and 2.35, which is 101.03% implied; with the margin removed Kansas City's fair chance is 57.88%, a fair price of 1.73. Sportsbet's opening 1.77 beat it by 2.45%, inside the rule.
1.77 × 58.08% − 1 = +2.8% CLV
At the close Pinnacle's 1.66 and 2.30 leave Kansas City a fair 58.08%, a fair price of 1.72, so the bet beat the close. The two bets average +9.0% CLV and lost 0.23 units between them: at this size the profit's spread is 177 points and the CLV's 12.5, which is the argument for CLV in one line.
The mock's Pinnacle quotes were last seen 102 minutes before the start, so this close came from the closing snapshot and the summary says how early it was. On real data the same line shows at a glance whether the closes are near the start or need a closer look.
Reading a real one
What good looks like, and the traps
- An average CLV above zero whose spread does not reach zero is the result worth having. More than half the bets beating the close says the same thing another way.
- Skips and gaps are data. Many games with no reference price standing at the start, or closes seen hours before it, mean the reference is a poor fit for that league, and the averages need that caveat.
- Tuning is testing. Trying twenty values of
EDGEand keeping the best one overfits. Choose on one window and confirm on a later one. - The open is thin. Opening prices often come with low limits, so the price was real but the stake may not have been.
Changing it
Your rule, your timing, more data
- Your own rule: rewrite
pick, keeping its inputs and return shape. - A time other than the open:
/v1/odds/historygives every recorded move for a single event, no more than 24 hours per request; the price at your decision time is each book's last move before it. - Seasons in bulk:
/v1/history/filesoffers the archive as Parquet downloads, a file for each league on each full UTC day. - Another reference:
REFERENCE = "betfair_exchange". - Another league:
python3 clv_backtest.py nba 2026-01-05 2026-01-25; any league with results and a reference price works, inside its recorded history.
The limits, said plainly. A backtest is a test of the past, run on prices recorded each time they changed, from its league's start date; it cannot show what you could have got on, or at what size. Positive CLV is evidence of an edge, not a promise of profit. Fast Odds API supplies data only; whether and how you bet is your call.
Why measure against Pinnacle's close?
A low-margin book that takes large bets moves its price toward the best available information, so its last price before the start is the hardest one to beat. The Betfair Exchange's close does the same job and is the other sharp reference in the feed.
Can I run this on the free plan?
Not all of it. Graded results and Pinnacle are on every plan, but the snapshots of each opening and closing price need Pro or Business. On another plan the script either stops with the API's reason or skips every game for want of a reference opening, and says which.
How far back does the price history go?
To 22 Dec 2025 at the earliest, in the leagues whose older recordings were carried over, and to 8 Oct 2026 in the rest, the AFL and NRL among them (SockOdds's history page, read 16 Oct 2026). No recorded price is older than its league's date, so a backtest window starts there at the earliest.
Does positive CLV mean the rule makes money?
It means the rule took better prices than the market settled on, which over enough bets is how an edge shows itself. It cannot cover limits, voided bets or the price you could not get, so treat it as the best early evidence, not a guarantee.
Start now
Your first Australian price is one request away.
Free key, no card, AFL and NRL included. Keys are issued on sockodds.com.