DEV Community

Tools for Bettors
Tools for Bettors

Posted on

Storing Odds Snapshots in SQLite: Schema, Indexes and Time-Bucket Queries in Python

If you poll a pricing feed every few seconds, you quickly end up with millions of rows. A flat CSV stops being pleasant around the first hundred thousand lines, and a full database server is often overkill for a personal research project. SQLite sits in a nice middle ground: a single file, transactional writes, real indexes and window functions.

This walkthrough builds a small snapshot store for decimal odds (Pinnacle is used here only as an example data source; the code is source-agnostic). We will cover:

  1. A schema that avoids storing duplicate rows
  2. Fast batched inserts with executemany
  3. Indexes that match the queries you actually run
  4. Time-bucket (OHLC-style) aggregation in SQL
  5. Querying the price "as of" a given timestamp

Everything uses the Python standard library.

1. The schema

Two ideas keep the database small and fast:

  • Separate the static part from the changing part. Event names, market types and selection labels repeat on every poll. Store them once in a selections table and reference them by integer id.
  • Only store changes. If a price did not move since the previous poll, there is nothing new to record.
import sqlite3

SCHEMA = """
PRAGMA journal_mode = WAL;
PRAGMA synchronous = NORMAL;

CREATE TABLE IF NOT EXISTS selections (
    id          INTEGER PRIMARY KEY,
    event_id    TEXT NOT NULL,
    market      TEXT NOT NULL,      -- e.g. 'moneyline', 'total:2.5'
    selection   TEXT NOT NULL,      -- e.g. 'home', 'over'
    UNIQUE (event_id, market, selection)
);

CREATE TABLE IF NOT EXISTS prices (
    selection_id INTEGER NOT NULL REFERENCES selections(id),
    ts           INTEGER NOT NULL,  -- unix epoch, milliseconds
    price        REAL    NOT NULL,  -- decimal odds
    PRIMARY KEY (selection_id, ts)
) WITHOUT ROWID;
"""

def connect(path="odds.db"):
    conn = sqlite3.connect(path)
    conn.executescript(SCHEMA)
    return conn
Enter fullscreen mode Exit fullscreen mode

A few notes:

  • WAL mode lets a reader (your notebook) query while the collector writes.
  • synchronous = NORMAL is a reasonable durability trade-off in WAL mode for data you can re-collect.
  • WITHOUT ROWID with a composite primary key (selection_id, ts) stores rows clustered by selection and time. That is exactly the access pattern for "give me the history of this selection", so range scans read contiguous pages.
  • Timestamps are integers in milliseconds. Integer comparison is cheap and avoids time-zone parsing inside SQL.

2. Resolving selection ids

Each poll returns rows like (event_id, market, selection, price). We need the integer id for each selection, creating it if it is new. A small in-memory cache avoids a lookup per row.

class SelectionCache:
    def __init__(self, conn):
        self.conn = conn
        self.ids = {}
        for row in conn.execute("SELECT id, event_id, market, selection FROM selections"):
            self.ids[row[1:]] = row[0]

    def get(self, event_id, market, selection):
        key = (event_id, market, selection)
        sid = self.ids.get(key)
        if sid is None:
            cur = self.conn.execute(
                "INSERT INTO selections (event_id, market, selection) VALUES (?, ?, ?) "
                "ON CONFLICT(event_id, market, selection) DO UPDATE SET market = excluded.market "
                "RETURNING id",
                key,
            )
            sid = cur.fetchone()[0]
            self.ids[key] = sid
        return sid
Enter fullscreen mode Exit fullscreen mode

RETURNING needs SQLite 3.35 or newer (sqlite3.sqlite_version tells you what Python is linked against).

3. Writing only changes, in batches

Keep the last stored price per selection in memory and skip unchanged values. Then write the whole poll in a single transaction; one transaction per row is the most common reason SQLite "feels slow".

import time

class SnapshotWriter:
    def __init__(self, conn):
        self.conn = conn
        self.cache = SelectionCache(conn)
        self.last = dict(conn.execute(
            """SELECT selection_id, price FROM prices p
               WHERE ts = (SELECT MAX(ts) FROM prices WHERE selection_id = p.selection_id)"""
        ).fetchall())

    def write(self, rows, ts_ms=None):
        ts_ms = ts_ms or int(time.time() * 1000)
        batch = []
        for event_id, market, selection, price in rows:
            sid = self.cache.get(event_id, market, selection)
            if self.last.get(sid) == price:
                continue
            batch.append((sid, ts_ms, price))
            self.last[sid] = price
        with self.conn:  # one transaction
            self.conn.executemany(
                "INSERT OR IGNORE INTO prices (selection_id, ts, price) VALUES (?, ?, ?)",
                batch,
            )
        return len(batch)
Enter fullscreen mode Exit fullscreen mode

INSERT OR IGNORE makes a retried poll with the same timestamp harmless instead of raising an integrity error.

Usage with a fake poll:

conn = connect(":memory:")
w = SnapshotWriter(conn)
w.write([("evt1", "moneyline", "home", 1.95), ("evt1", "moneyline", "away", 1.95)], ts_ms=1_000)
w.write([("evt1", "moneyline", "home", 1.95), ("evt1", "moneyline", "away", 1.95)], ts_ms=2_000)  # stores 0 rows
w.write([("evt1", "moneyline", "home", 1.90), ("evt1", "moneyline", "away", 2.00)], ts_ms=3_000)  # stores 2 rows
print(conn.execute("SELECT COUNT(*) FROM prices").fetchone())  # (4,)
Enter fullscreen mode Exit fullscreen mode

4. Indexes that match your queries

The primary key already covers "history of one selection over a time range". The other frequent question is "what changed across all selections in the last N minutes?". That needs time first:

conn.execute("CREATE INDEX IF NOT EXISTS idx_prices_ts ON prices (ts)")
Enter fullscreen mode Exit fullscreen mode

Check that a query actually uses it:

plan = conn.execute(
    "EXPLAIN QUERY PLAN SELECT * FROM prices WHERE ts > ?", (0,)
).fetchall()
print(plan)  # look for 'USING INDEX idx_prices_ts' (or 'USING COVERING INDEX')
Enter fullscreen mode Exit fullscreen mode

Do not add indexes speculatively: each one costs write time on every insert. Run EXPLAIN QUERY PLAN on the queries you actually use and add an index only when you see a full table SCAN.

5. Time-bucket aggregation (open / high / low / close)

Raw changes are irregular. For charts or feature engineering you usually want fixed buckets, for example one row per selection per 5 minutes. Integer division on the millisecond timestamp gives the bucket, and window functions give open and close:

BUCKET_SQL = """
WITH b AS (
    SELECT selection_id,
           (ts / :bucket_ms) * :bucket_ms AS bucket,
           ts, price
    FROM prices
    WHERE selection_id = :sid AND ts BETWEEN :start AND :end
),
w AS (
    SELECT selection_id, bucket, price,
           FIRST_VALUE(price) OVER (PARTITION BY bucket ORDER BY ts
               ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS open,
           LAST_VALUE(price)  OVER (PARTITION BY bucket ORDER BY ts
               ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS close
    FROM b
)
SELECT bucket, MIN(open) AS open, MAX(price) AS high, MIN(price) AS low,
       MIN(close) AS close, COUNT(*) AS changes
FROM w
GROUP BY bucket
ORDER BY bucket;
"""

def buckets(conn, sid, start, end, bucket_ms=300_000):
    return conn.execute(BUCKET_SQL, {"sid": sid, "start": start, "end": end,
                                     "bucket_ms": bucket_ms}).fetchall()
Enter fullscreen mode Exit fullscreen mode

The explicit frame ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING matters: the default frame for LAST_VALUE ends at the current row, which silently returns the current price instead of the bucket's last one. Inside each bucket open and close are constant, so MIN() just picks that value.

Empty buckets (no change) do not appear. If you need a dense series, forward-fill in pandas afterwards:

import pandas as pd

df = pd.DataFrame(buckets(conn, 1, 0, 10_000, bucket_ms=1_000),
                  columns=["bucket", "open", "high", "low", "close", "changes"])
df = df.set_index("bucket").reindex(range(0, 10_000, 1_000))
df["close"] = df["close"].ffill()
Enter fullscreen mode Exit fullscreen mode

6. "As of" queries

Because only changes are stored, the price at an arbitrary moment is the latest row at or before that moment. With the (selection_id, ts) primary key this is a single index seek:

def price_as_of(conn, sid, ts_ms):
    row = conn.execute(
        "SELECT price FROM prices WHERE selection_id = ? AND ts <= ? "
        "ORDER BY ts DESC LIMIT 1",
        (sid, ts_ms),
    ).fetchone()
    return row[0] if row else None

print(price_as_of(conn, 1, 2_500))  # 1.95, the value written at ts=1000
Enter fullscreen mode Exit fullscreen mode

This is the building block for comparing a price you recorded against the final price before an event started, without storing a separate "closing" table.

7. Housekeeping

  • Run PRAGMA optimize; before closing long-lived connections so the query planner has fresh statistics.
  • Periodically VACUUM (offline) if you delete old events, or keep one database file per month and attach them with ATTACH DATABASE when you need cross-month queries.
  • Back up a live WAL database with conn.backup(other_conn) rather than copying the file, which can capture a half-written state.

Testing it

A tiny pytest check guards the change-only logic, which is the part most likely to regress:

def test_unchanged_prices_are_skipped():
    conn = connect(":memory:")
    w = SnapshotWriter(conn)
    assert w.write([("e", "ml", "home", 2.0)], ts_ms=1) == 1
    assert w.write([("e", "ml", "home", 2.0)], ts_ms=2) == 0
    assert w.write([("e", "ml", "home", 2.1)], ts_ms=3) == 1
    assert price_as_of(conn, 1, 2) == 2.0
Enter fullscreen mode Exit fullscreen mode

Wrap-up

A change-only table with a clustered (selection_id, ts) key, batched transactions and WAL mode covers most personal odds-research workloads in one portable file. Window functions handle bucketing, and "as of" lookups are a single index seek. When you outgrow it, the same schema ports almost unchanged to PostgreSQL or DuckDB.

A ready-made alternative

If you would rather start from a product that already stores Pinnacle price history and grades pre-match drops, Pinnacle Terminal's move grading is built around that workflow. The SQLite pattern above still applies if you want your own archive.


Editorial note: Tools for Bettors publishes independent reviews and guides on betting tools and odds data.

Top comments (0)