Backtesting Betting Models with Line History (Without Fooling Yourself)
Backtest a betting model on timestamped odds with decision-time snapshots, sharp closing lines, CLV grading and no look-ahead bias, plus a pandas sketch.
Most attempts at backtesting betting models go wrong in the same direction: they look better than reality. Usually it's not the model. It's the prices. A backtest that assumes you could bet at the closing line, or at the best price across ten books at any moment, or at a price that only existed after the news broke, will find price discrepancies that were never there.
The fix is to backtest on line history: timestamped prices per book, so that every simulated bet uses a price that actually existed at the moment you would have placed it. This post covers what data you need for backtesting betting models, the common forms of look-ahead bias, why closing line value is the right grading metric, and a working Python and pandas pipeline.
Line history: the data for backtesting betting models
For each market at each book, you want the full series of changes: the opening price, every move with a timestamp and the line at that time, and the last price before the event started. With that you can answer the two questions a backtest needs:
- What price was actually available at decision time? That is the last price at or before the decision timestamp at the book being simulated.
- What was the market's best estimate at the close? That is the de-vigged closing price at a sharp book, which is used to grade the simulated bet.
PreciseAPI's /v1/history endpoint returns exactly this for main full-game markets (moneyline, spread and total) per book: an open point, a current point and an array of points, each with t (ISO 8601 UTC), line and prices. Prices are in the market's outcome order: home then away for moneylines and spreads (with line from the home side's perspective), over then under for totals, and home, draw, away for three-way soccer moneylines.
Step 1: Archive history and results yourself
Two practical constraints shape the pipeline. Finished events can be looked up for at least four hours after they end, and stored history is kept for 48 hours after each market’s last update, not as a multi-season archive. So the robust pattern is a scheduled job that finds newly finished events and copies their history and final scores into your own storage. Once the historical odds data is yours, the backtest never depends on anyone's retention policy.
import os
from pathlib import Path
import pandas as pd
import requests
API = "https://api.preciseapi.com/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['PRECISEAPI_KEY']}"}
BOOKS = ["pinnacle", "draftkings", "fanduel"]
MARKETS = ["moneyline", "spread", "total"]
OUT = Path("lines.parquet")
def get(path, **params):
r = requests.get(f"{API}{path}", params=params, headers=HEADERS, timeout=15)
if r.status_code == 404:
return None # event expired, market not offered, or no history stored
r.raise_for_status()
return r.json()["data"]
def archive_finals(league):
existing = pd.read_parquet(OUT) if OUT.exists() else pd.DataFrame()
done = set(existing["event_id"]) if len(existing) else set()
rows = []
for ev in get("/scores", league=league, status="final") or []:
if ev["id"] in done:
continue
for book in BOOKS:
for market in MARKETS:
h = get("/history", event_id=ev["id"], book=book, market=market, format="decimal")
if not h:
continue
for p in [h["open"], *h["points"]]:
rows.append({
"event_id": ev["id"], "league": league, "start_time": ev["start_time"],
"home": ev["home"]["abbr"], "away": ev["away"]["abbr"],
"home_score": ev["score"]["home"], "away_score": ev["score"]["away"],
"book": book, "market": market, "market_id": h["market_id"],
"t": p["t"], "line": p["line"],
**{f"price_{i}": x for i, x in enumerate(p["prices"])},
})
if rows:
merged = pd.concat([existing, pd.DataFrame(rows)]).drop_duplicates(["market_id", "t"])
merged.to_parquet(OUT)
return len(rows)
if __name__ == "__main__":
for league in ["nba", "nhl"]:
print(league, archive_finals(league), "rows archived")
Run it hourly (cron, a scheduled container, anything) so every final is captured inside its four-hour window. Requesting format=decimal makes the downstream math simpler. On cost: /v1/history is 3 credits per call and /v1/scores is 1, so a ten-game night across three books and three markets is 90 history calls, or 270 credits. Skipping events you have already archived keeps hourly runs from paying for the same game twice. Line history is included on every paid plan, and pricing lists the monthly credits for each. You need pip install requests pandas pyarrow.
Include at least one sharp book in BOOKS. You will need it to compute fair closing probabilities.
Step 2: Avoid look-ahead bias
Look-ahead bias means using information in the backtest that you would not have had at decision time. In betting data it shows up in a handful of predictable places:
- In-play prices in the "close". A market's history can keep recording after the game starts, and in-play prices move toward the result. If you define the close as the last point in the series, you are grading bets against prices that already know the score. Always filter to
t < start_time. - Pricing at the close. If your model's decision time is two hours before start, the simulation must use the price that existed two hours before start, not the close.
- Features computed with future data. Season averages that include the game being predicted, final injury reports pulled after your decision time, or ratings fitted on the whole season.
- Best-of-all-books pricing. Assuming the best price across every book was obtainable only holds with accounts, limits and reaction time at every book. Simulate a specific book or set of books.
- Survivorship. If your archive only contains events that finished normally, postponed or voided games are missing, along with the money that sat in them.
- Time zones. Parse every timestamp as UTC. A local-time parse can shift your decision snapshot past the start of an evening game.
Step 3: Snapshot at decision time, grade at the close
With the archive in a DataFrame, the core of the backtest is two snapshots and a join:
import numpy as np
import pandas as pd
df = pd.read_parquet("lines.parquet")
df["t"] = pd.to_datetime(df["t"], utc=True)
df["start_time"] = pd.to_datetime(df["start_time"], utc=True)
pre = df[df["t"] < df["start_time"]].sort_values("t") # never use in-play points
keys = ["event_id", "book", "market"]
def snapshot(frame, hours_before):
cutoff = frame["start_time"] - pd.Timedelta(hours=hours_before)
return frame[frame["t"] <= cutoff].groupby(keys).tail(1).set_index(keys)
decision = snapshot(pre, 2) # what you could see 2h before start
close = pre.groupby(keys).tail(1).set_index(keys)
def fair_home(snap, book):
s = snap.xs((book, "moneyline"), level=["book", "market"])
p0, p1 = 1 / s["price_0"], 1 / s["price_1"]
return p0 / (p0 + p1)
ml = pd.DataFrame({
"fair_dec": fair_home(decision, "pinnacle"), # sharp fair prob at decision time
"dk_home": decision.xs(("draftkings", "moneyline"), level=["book", "market"])["price_0"],
"fair_close": fair_home(close, "pinnacle"), # sharp fair prob at the close
}).dropna()
results = pre.groupby("event_id")[["home_score", "away_score"]].first()
ml = ml.join(results)
The example rule is deliberately simple and uses only decision-time information: select the home moneyline at DraftKings whenever its decimal price is at least 2% above the de-vigged Pinnacle price at the decision snapshot. It is a placeholder; replace it with your model's output. The test itself, fair probability times decimal price minus one, is the edge the EV calculator reports for a single bet.
bets = ml[ml["fair_dec"] * ml["dk_home"] - 1 >= 0.02].copy()
bets["won"] = bets["home_score"] > bets["away_score"]
bets["profit"] = np.where(bets["won"], bets["dk_home"] - 1, -1.0)
bets["clv"] = bets["fair_close"] * bets["dk_home"] - 1
n = len(bets)
print(f"bets: {n}")
print(f"avg CLV (vs no-vig close): {bets['clv'].mean():+.2%} (share positive {(bets['clv'] > 0).mean():.0%})")
print(f"ROI: {bets['profit'].mean():+.2%} +/- {bets['profit'].std(ddof=1) / np.sqrt(n):.2%} (1 s.e.)")
This sketch handles two-way moneylines. Spreads and totals work the same way, with one extra rule: only compare prices at the same line, or convert between lines with a distribution model.
Step 4: Grade by CLV, not just realized results
clv measures how the price each simulated bet took compares with the de-vigged closing price, treating the close as the reference probability. It is the most useful single number a backtest produces, for the reasons covered in closing line value explained: it has far less noise than realized results, and it measures the thing a model actually controls, which is the price it selected.
The standard error in the last line is the reality check. With 50 bets at typical odds, a ±15 to 20% standard error on ROI is normal, which means realized ROI alone tells you almost nothing. A consistently positive average CLV over a few hundred bets is real evidence; a large ROI over fifty bets is not.
When we ran the code above on a synthetic archive where we knew the true probabilities, the leak was obvious: a "closing" price that included in-play points correlated perfectly with the result, while the honest pre-game close had a correlation of about 0.23. That gap is exactly the illusory performance a careless backtest will report.
Making the simulation realistic
A few refinements separate a toy backtest from one you can trust:
- Latency. Add a delay between your signal and execution, and use the price at signal time plus the delay. Price discrepancies that disappear with a 30-second delay were never actually available.
- Limits. Cap stake size per book and market. Soft-book prices with tiny limits shouldn't count the same as liquid ones.
- Line availability. If the book has suspended the market or moved the line at your decision time, there is no bet.
- Out-of-sample discipline. Choose thresholds on one season and evaluate on another. Re-tuning on the test set is look-ahead bias by another name.
- Multiple testing. If you try 40 variants and report the best one, expect it to look good by chance. Keep a log of everything you tried.
Even a well-built backtest describes the past. Markets adapt, books limit accounts that consistently take soft prices, and a model that would have worked last season can stop working. Treat positive results as a reason for further out-of-sample testing, not a forecast of returns; outcomes vary.
Next steps
The sports betting model data page describes how teams backtesting betting models typically combine live feeds and history, and the historical odds API page summarizes what is recorded. If you're new to the API, start with the quickstart and make one /v1/history call by hand before scheduling the collector.