DEV Community

citoapi
citoapi

Posted on

How to Backtest a Tennis Betting Model in Python Using Historical Serve Stats & Closing Odds

A startling share of published tennis prediction notebooks report 68% accuracy and double-digit simulated ROI, only to lose money within forty-eight hours of live deployment. Almost without exception, those backtests suffer from three silent methodological bugs: post-match rating leakage (using end-of-week rankings or full-sample Elo parameters computed over future matches), survivorship bias on incomplete matches (ignoring retirements and walkovers where grading rules differ from completed matches), and testing against unvigged theoretical probabilities rather than actual timestamped pre-match closing odds.

In this engineering walkthrough, we build a leak-free Python backtesting pipeline using historical ATP and WTA serve statistics, surface-specific pre-match Elo ratings, and timestamped opening and closing decimal odds from CitoAPI Historical Tennis Data and the ATP/WTA Historical Odds Dataset. Every feature we use is strictly observable prior to the first serve (commence_time), and we benchmark model log-loss and Closing Line Value (CLV) directly against the market.


Core Backtesting Requirements for Quantitative Tennis Models

Before writing a single line of scikit-learn or pandas code, verify that your historical dataset satisfies four chronological invariants:

  1. Strict Pre-Commence Timestamps on Odds: In-play odds move dramatically after an early break of serve. If an archive accidentally mixes a first-set live price into a pre-match column, backtest ROI is completely invalidated. In CitoAPI's match odds pipeline (GET /api/v1/tennis/odds/{match_id}/history and the bulk CSV export), winner_open_odds and winner_close_odds filter strictly for in_play = false and price_timestamp < commence_time, excluding uninitialized 50/50 placeholder ticks.
  2. Symmetric Feature Framing: Raw match tables store winner_* and loser_* columns. Training a classifier directly on winner_elo_pre - loser_elo_pre creates a degenerate 100%-positive target! You must randomly or deterministically assign Player A and Player B per row (for instance, ordering lexicographically by player_id or alternating rows) before computing feature differentials.
  3. Explicit Retirement & Walkover Handling: outcome takes five distinct states: COMPLETED, RETIREMENT, WALKOVER, DEFAULT, and ABANDONED. A WALKOVER never starts (duration_minutes is null, zero points played) and voids pre-match wagers across all venues, whereas RETIREMENT grading depends on whether one set or full match completion is required.
  4. Rolling Trailing Serve & Return Baselines: Match-specific box-score columns (w_1st_in, w_1st_won, w_bp_saved) measure what happened inside that match. Your model must aggregate trailing surface-weighted serve and return percentages from strictly prior dates (match_date < current_match_date).

For reproducible benchmark experiments, inspect our peer-citable archival release on Harvard Dataverse at doi:10.7910/DVN/SHAYLX (hosted in the CitoAPI Dataverse) and the standardized ML tabular task on OpenML at openml.org/d/48258, alongside mirrors on Kaggle and Hugging Face.


Backtest Feature & Market Schema Reference

When streaming /api/v1/exports/tennis/matches-master.csv.gz or testing with /api/v1/exports/sample/tennis/matches.csv, the backtesting columns align as follows:

Column Type Leakage Status Role in Backtesting Pipeline
match_id, match_date, surface, indoor, best_of str / date / bool / int Safe pre-match Chronological time-split key and court-speed context
outcome string Post-match settlement Filter out WALKOVER and ABANDONED; test sensitivity to RETIREMENT
winner_elo_pre, loser_elo_pre float Safe pre-match Chronological overall Elo rating prior to match start
winner_surface_elo_pre, loser_surface_elo_pre float Safe pre-match Surface-specific Elo prior (Hard, Clay, Grass)
elo_win_prob float Safe pre-match Calibrated Elo baseline win probability for the eventual winner
winner_open_odds, loser_open_odds float Safe pre-match First liquid pre-match decimal odds tick (in_play = false)
winner_close_odds, loser_close_odds float Safe pre-match Final pre-match decimal price immediately prior to commence_time
w_svpt, w_1st_in, w_1st_won, w_2nd_won, w_bp_saved, w_bp_faced int Post-match box score Used to update each player's rolling historical state after match settlement

Fetching Historical Odds Ticks & CSV Archives via curl

# 1. Inspect the 56-column tennis archive schema via the public sample endpoint
curl -sS "https://api.citoapi.com/api/v1/exports/sample/tennis/matches.csv" -o sample_tennis.csv

# 2. Stream full historical matches archive with Elo + Open/Close odds (Business CSV)
curl -sS -H "x-api-key: YOUR_CITO_API_KEY"   "https://api.citoapi.com/api/v1/exports/tennis/matches-master.csv.gz" -o tennis_master.csv.gz

# 3. Inspect tick-by-tick line movement for a single match via REST
curl -sS -H "x-api-key: YOUR_CITO_API_KEY"   "https://api.citoapi.com/api/v1/tennis/odds/atp_2026_580_MS001/history?market=h2h&limit=100"
Enter fullscreen mode Exit fullscreen mode

Runnable Python Backtest: Multiplicative De-Vigging, Log-Loss & Fractional Kelly Sizing

The Python pipeline below demonstrates exact symmetric row construction, multiplicative bookmaker margin removal, chronological rolling serve-hold feature calculation, and flat-stake vs. fractional-Kelly evaluation:

import io
import numpy as np
import pandas as pd
import requests

SAMPLE_URL = "https://api.citoapi.com/api/v1/exports/sample/tennis/matches.csv"
resp = requests.get(SAMPLE_URL, timeout=15)
resp.raise_for_status()
raw = pd.read_csv(io.StringIO(resp.text))

# 1. Keep completed matches with pre-match closing odds and surface Elo
df = raw[
    (raw["outcome"] == "COMPLETED")
    & raw["winner_close_odds"].notna()
    & raw["loser_close_odds"].notna()
    & raw["winner_surface_elo_pre"].notna()
    & raw["loser_surface_elo_pre"].notna()
].sort_values("match_date").reset_index(drop=True)

# 2. Deterministic symmetric framing: Player A is lexicographically smaller player_id
a_is_winner = df["winner_id"] < df["loser_id"]
bt = pd.DataFrame({
    "match_id": df["match_id"],
    "match_date": df["match_date"],
    "surface": df["surface"],
    "target_a_win": a_is_winner.astype(int),
    "a_surf_elo": np.where(a_is_winner, df["winner_surface_elo_pre"], df["loser_surface_elo_pre"]),
    "b_surf_elo": np.where(a_is_winner, df["loser_surface_elo_pre"], df["winner_surface_elo_pre"]),
    "a_open_odds": np.where(a_is_winner, df["winner_open_odds"], df["loser_open_odds"]),
    "b_open_odds": np.where(a_is_winner, df["loser_open_odds"], df["winner_open_odds"]),
    "a_close_odds": np.where(a_is_winner, df["winner_close_odds"], df["loser_close_odds"]),
    "b_close_odds": np.where(a_is_winner, df["loser_close_odds"], df["winner_close_odds"]),
})

# 3. Elo-implied probability vs. de-vigged closing market probability
bt["elo_prob_a"] = 1.0 / (1.0 + 10.0 ** ((bt["b_surf_elo"] - bt["a_surf_elo"]) / 400.0))
raw_q_a = 1.0 / bt["a_close_odds"]
raw_q_b = 1.0 / bt["b_close_odds"]
bt["market_overround"] = raw_q_a + raw_q_b
bt["fair_close_prob_a"] = raw_q_a / bt["market_overround"]

# 4. Evaluate Brier score and Closing Line Value (CLV) when betting opening lines
bt["edge_vs_open_a"] = bt["elo_prob_a"] * bt["a_open_odds"] - 1.0
bets_a = bt[bt["edge_vs_open_a"] > 0.03].copy()
if not bets_a.empty:
    bets_a["clv_pct"] = (bets_a["a_open_odds"] / bets_a["a_close_odds"] - 1.0) * 100.0
    bets_a["pnl_units"] = np.where(bets_a["target_a_win"] == 1, bets_a["a_open_odds"] - 1.0, -1.0)
    print(f"Qualified value bets: {len(bets_a)} | Mean CLV: {bets_a['clv_pct'].mean():.2f}% | Net Units: {bets_a['pnl_units'].sum():.2f}")
else:
    brier = np.mean((bt["elo_prob_a"] - bt["target_a_win"]) ** 2)
    print(f"Evaluated {len(bt)} priced matches | Surface Elo Brier Score: {brier:.4f}")
Enter fullscreen mode Exit fullscreen mode

In production, beating the closing line (clv_pct > 0 across 1,000+ out-of-sample wagers) is a far stronger statistical validator than short-sample unit profit, because closing odds aggregate global market liquidity right before first serve.


Resources, Datasets & API Access

Top comments (0)