Replaying Historical Odds Without Trusting Stale Prices

What a line history series actually records, why the last change isn't the last time a price was seen, what a gap between two points can mean, and how to replay historical lines with an explicit staleness rule, using an availability log you record yourself and a reproducible pandas as-of join.

By PreciseAPI Engineering

Published

Replaying historical lines means asking, for some past moment, "what price could I have seen right now?" Line history answers half of that question. It records when each price changed. It doesn't record whether the price was still on offer an hour later, when nothing changed. A price that sat still because the market was quiet and a price that sat still because the book stopped sending it look identical in a change log.

Backtesting betting models with line history covers look-ahead bias, closing-line grading and a pandas backtest. This post deals with the time semantics underneath: what PreciseAPI's history records, what it leaves out, and how to add the missing availability signal so a replay never uses a stale price as if it were live.

What /v1/history records

/v1/history returns market_id, an open point, a current point and an array of points. Each point has t (ISO 8601, UTC), line and prices. The behaviour below is taken from the recorder itself, not only from the reference page:

There are also limits worth knowing before you rely on a series as a complete record:

Line history is included on every paid plan; see pricing.

Last changed is not last seen

A market from /v1/odds carries several clocks. Only one of them survives into history:

FieldMeaningIn /v1/history?
updated_atWhen PreciseAPI stored the current price: the last change to a price, point or lineYes, as each point's t
source_changed_atThe source's clock when the current price was first seenNo
source_observed_atThe source's clock at the latest read that still showed this priceNo
received_atWhen PreciseAPI last received the market, changed or notNo
suspendedTrue when the source has stopped reportingNo
versionGrows with every change delivered for the market, suspensions includedNo

updated_at and history points answer "when did this price last change?" source_observed_at and received_at answer "when was it last confirmed?" A quiet pre-game moneyline can have an updated_at from this morning and a source_observed_at from a few minutes ago. That's a current price. An updated_at from this morning with no confirmation since is something else.

Even source_observed_at can lag on a healthy market. Books are read every few seconds, but an unchanged price is re-sent only every few minutes. A freshness rule tighter than a few minutes will therefore reject good quiet prices. The API's own max_source_age_ms filter is capped at 300,000 ms (five minutes) for that reason.

What a gap between two points can mean

When two consecutive points are an hour apart, the series alone can't tell you which of these happened in between:

  1. The market was quiet. The price was on offer throughout and didn't change.
  2. The market was suspended. The source stopped reporting, or sent the market as suspended. Suspension is not recorded in history, and neither is the lifting of a suspension that leaves the price as it was.
  3. The market was removed. The source stopped listing it, which is first shown as suspended for 150 seconds while the game hasn't finished. A market suspended with nothing confirming it for 5 minutes, or not sent for 30 minutes, expires. The series keeps its last point, and if the book lists the market again the series continues.
  4. The source was down. /v1/status and /v1/sportsbooks report each source as operational, suspended (it stopped sending, and its prices are withheld) or no_data, with its last_update. History keeps no record of those states.

Cases 2 to 4 are where replays go wrong. The last point before the gap looks like a live price for the whole gap, unless you know otherwise.

Record availability alongside history

The fix is to record the missing signal yourself while it is happening, at a resolution that suits your replay. This recorder polls /v1/odds with include_suspended=true, so suspended markets are listed rather than hidden. For every main market it writes one line of JSON per poll. It also writes a present: false row for any series that was listed on the previous poll and is missing now.

Rows are keyed by series (event, book, market key, period), not by market id. Market ids change when a main line moves, so a market-id key would read every line move as a removal.

import json
import os
import time
from datetime import datetime, timezone

import requests

API = "https://api.preciseapi.com/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['PRECISEAPI_KEY']}"}
FIELDS = ("id", "line", "suspended", "updated_at", "source_observed_at", "received_at", "version")


def poll(leagues, books, last, out):
    r = requests.get(f"{API}/odds", headers=HEADERS, timeout=20, params={
        "league": ",".join(leagues), "books": ",".join(books),
        "markets": "main", "include_suspended": "true",
    })
    r.raise_for_status()  # errors aren't charged; the caller backs off
    polled_at = datetime.now(timezone.utc).isoformat()
    now = set()
    for ev in r.json()["data"]:
        for b in ev["bookmakers"]:
            for m in b["markets"]:
                series = (ev["id"], b["id"], m["key"], m["period"])
                now.add(series)
                row = {k: m.get(k) for k in FIELDS}
                out.write(json.dumps({"polled_at": polled_at, "series": series, "present": True, **row}) + "\n")
    for series in last - now:
        out.write(json.dumps({"polled_at": polled_at, "series": series, "present": False}) + "\n")
    out.flush()
    return now


if __name__ == "__main__":
    last = set()
    with open("availability.jsonl", "a") as out:
        while True:
            try:
                last = poll(["nba", "nhl"], ["pinnacle", "draftkings", "fanduel"], last, out)
            except requests.RequestException as err:
                print("poll failed:", err)
            time.sleep(300)

At one call every five minutes, this costs 2 credits a poll, or 17,280 credits over 30 days if it runs around the clock. On Edge that fits beside other work, and on Sharp and Syndicate credits are unlimited. Your availability log is only as fine as your poll interval: a suspension shorter than five minutes won't show up. On Syndicate, logging the stream instead captures every transition. Deltas carry suspended the moment it changes, and removals carry their reason.

Replay with an explicit staleness rule

With history and the availability log side by side, a replay becomes two as-of joins and one rule. For each moment at, take the last history point at or before at (the price), and the last poll at or before at (the availability). Then use the price only if the market was present, not suspended, and confirmed recently enough.

The example below is self-contained and runs on synthetic data, shaped like the API's responses. The prices and times are invented to show each case. A Pinnacle spread moves from −4.5 to −5 at 18:41, is suspended from 18:50 to 19:00, and is gone from the feed from 19:10.

import pandas as pd

# Synthetic data, shaped like the API's responses. Not real prices.
history = {  # GET /v1/history?market_id=... (Pinnacle full-game spread, American odds)
    "market_id": "mkt_example",
    "open": {"t": "2026-12-01T18:00:04Z", "line": -4.5, "prices": [-108, -102]},
    "points": [
        {"t": "2026-12-01T18:00:04Z", "line": -4.5, "prices": [-108, -102]},
        {"t": "2026-12-01T18:41:37Z", "line": -5.0, "prices": [-105, -105]},
    ],
}
# Your own log: one row per poll of /v1/odds?include_suspended=true for this series.
polls = pd.date_range("2026-12-01T18:00:00Z", "2026-12-01T19:30:00Z", freq="5min")
obs = []
for t in polls:
    if t >= pd.Timestamp("2026-12-01T19:10:00Z"):
        obs.append({"polled_at": t, "present": False, "suspended": None, "source_observed_at": None, "received_at": None})
    else:
        suspended = pd.Timestamp("2026-12-01T18:50:00Z") <= t < pd.Timestamp("2026-12-01T19:00:00Z")
        obs.append({"polled_at": t, "present": True, "suspended": suspended,
                    "source_observed_at": t - pd.Timedelta(seconds=20), "received_at": t - pd.Timedelta(seconds=5)})
obs = pd.DataFrame(obs)

def history_frame(h):
    df = pd.DataFrame(h["points"])
    df["t"] = pd.to_datetime(df["t"], utc=True)
    df[["home", "away"]] = pd.DataFrame(df.pop("prices").tolist(), index=df.index)
    return df.sort_values("t")

def replay(h, obs, at, max_age="5min"):
    """Price and availability of one market at each time in `at`."""
    q = pd.DataFrame({"at": pd.to_datetime(at, utc=True)}).sort_values("at")
    price = pd.merge_asof(q, history_frame(h), left_on="at", right_on="t", direction="backward")
    seen = pd.merge_asof(q, obs.sort_values("polled_at"), left_on="at", right_on="polled_at", direction="backward")
    out = price.join(seen[["present", "suspended", "source_observed_at", "received_at"]])
    # The source's own read time when it gave one, else when PreciseAPI received the market.
    confirmed = pd.to_datetime(out["source_observed_at"].fillna(out["received_at"]), utc=True)
    age = out["at"] - confirmed
    out["usable"] = out["present"].eq(True) & out["suspended"].eq(False) & (age <= pd.Timedelta(max_age))
    out["since_change"] = out["at"] - out["t"]
    return out[["at", "line", "home", "away", "since_change", "suspended", "present", "usable"]]

print(replay(history, obs, ["2026-12-01T18:30:00Z", "2026-12-01T18:52:00Z", "2026-12-01T19:20:00Z"]).to_string(index=False))

Output with pandas 3.0:

                       at  line  home  away    since_change suspended  present  usable
2026-12-01 18:30:00+00:00  -4.5  -108  -102 0 days 00:29:56     False     True    True
2026-12-01 18:52:00+00:00  -5.0  -105  -105 0 days 00:10:23      True     True   False
2026-12-01 19:20:00+00:00  -5.0  -105  -105 0 days 00:38:23      None    False   False

All three rows read a price from history, but only the first was really on offer. At 18:30 the price hadn't changed for half an hour, yet it was confirmed seconds earlier, so it's usable. At 18:52 the latest change is −5 at −105, but the market was suspended. At 19:20 history still ends at −5 −105, and without the log, a replay would treat it as the live price 38 minutes after the change. since_change alone would get two of these three wrong, because it measures change, not confirmation.

To run it for real data, load your availability.jsonl with pd.read_json(..., lines=True), filter to the series you're replaying, and fetch its history with the market id from the log.

Other replay details

The historical odds API page summarizes what is recorded, and line movement explains the concepts behind it.

Frequently asked questions

Does /v1/history show when a market was suspended?

No. History records changes to the line and prices only. A suspension, and its lifting when the price is unchanged, adds no point. Record suspension yourself from /v1/odds?include_suspended=true or from stream deltas.

Is the current point the price right now?

It is the latest recorded change, and its t is when that change was stored. Whether the price is still on offer is a separate question. Check the market in /v1/odds with include_suspended=true, and look at suspended, source_observed_at and received_at.

Why does a series open later than the book first posted the market?

open is the first point PreciseAPI recorded for that book's series, not the book's own opening time. If the book posted before PreciseAPI first received the market, the earlier part of the history isn't there.

How long is line history kept?

Each series is kept for 48 hours after the last change stored into it. Use market_id to fetch a finished game's history after the event can no longer be looked up, and copy what you need into your own storage.

Why aren't timestamps the book's own times?

Points use PreciseAPI's clock, so that every source in a series is on one clock. The source's clocks are on live markets as source_changed_at and source_observed_at. Record them in your availability log if you need them later.

References

Keep reading