DEV Community

citoapi
citoapi

Posted on

Grand Slam, ATP & WTA Head-to-Head, Rankings History & Surface Elo API Tutorial in Python

Building a rich tennis analytics application, broadcast companion, or Grand Slam draw simulator requires stitching together three distinct historical dimensions: career rivalry head-to-head (H2H) breakdowns across surfaces and best-of-five formats, weekly ATP and WTA ranking trajectories spanning more than five million historical rows, and point-in-time surface Elo ratings that react immediately when an injured star returns or a clay-court specialist steps onto Wimbledon grass.

If you try to assemble those views by scraping static HTML tables or maintaining ad-hoc SQL joins across mismatched tournament naming conventions, edge cases multiply rapidly: two-week Grand Slams skip intermediate Monday ranking lists, walkovers inflate naive match-log counts compared to official tour H2H tallies, and WTA Grand Slam archive IDs span five decades back to the Open Era. This tutorial demonstrates how to query reconciled H2H matrices, ranking histories, and surface Elo ratings in Python using the CitoAPI Tennis API and official Python documentation.


How CitoAPI Reconciles H2H Totals, Weekly Rankings & Surface Elo

Every route under https://api.citoapi.com/api/v1/tennis enforces deterministic domain invariants verified against 1.8M+ archived matches (1877 to present) and 5.6M+ weekly ranking rows:

  1. Reconciled Head-to-Head Accounting (/tennis/h2h & /tennis/h2h/matrix): Official tour head-to-head records count played tour matches (including mid-match retirements and defaults) while separating pre-match walkovers and exhibitions into dedicated counters (summary.walkovers, summary.exhibitions). Every /tennis/h2h response guarantees that surface_breakdown (hard, clay, grass, carpet, unknown), level_breakdown (grand_slam, masters_1000, tour_finals, atp_500_250, challenger, itf), and format_breakdown (best_of_3, best_of_5) sum exactly to summary.total_matches, verified via breakdown_totals.reconciles: true.
  2. Full-Depth Weekly Rankings & Unpublished Monday Resolution (/tennis/rankings): Mid-week date queries automatically resolve to the governing Monday publication list (~2,300 ranked singles players per tour). During two-week Grand Slams or Masters events where no intermediate Monday list is published, /tennis/rankings/dates explicitly documents unpublished_mondays so time-series joins never silently drop weeks.
  3. Chronological Overall & Surface Elo (/tennis/rankings/elo & /tennis/players/{id}/elo): Calculated sequentially from 1968 to the present across overall, hard, clay, grass, and indoor splits, returning current Elo, peak_elo_overall, per-match Elo deltas, and calibrated pre-match elo_win_prob.

Archival snapshots and benchmark tables are also published for academic citation on Harvard Dataverse, OpenML (d/48258), Kaggle, Hugging Face, tennisdataset.com, and tennisapi.dev.


Endpoint & JSON Payload Schema Reference

Endpoint Key Query Parameters Core Response Fields
GET /api/v1/tennis/players/search q, `tour=ATP\ WTA, limit`
GET /api/v1/tennis/h2h players=a,b, surface, level summary, surface_breakdown, level_breakdown, format_breakdown, breakdown_totals.reconciles, matches[]
GET /api/v1/tennis/h2h/matrix player_ids=a,b,c,d (2 to 16 IDs) Pairwise NxN win-loss grid inside a contender group or ATP/WTA Finals pool
GET /api/v1/tennis/rankings/history/{player_id} from, to, `order=asc\ desc, limit`
GET /api/v1/tennis/rankings/elo tour, `surface=overall\ hard\
{% raw %}GET /api/v1/tennis/players/{player_id}/elo history_limit=30 Current overall/surface Elo, peak_elo, and chronological match-by-match Elo delta log
GET /api/v1/exports/tennis/players-master.csv.gz Header x-api-key 21-column bulk player bio + multi-surface Elo table (elo_overall, elo_hard, elo_clay, elo_grass, elo_indoor)

curl Snippets: Player Lookup, Rivalry H2H, Elo Leaderboard & Players CSV

# 1. Public zero-auth 21-column players sample CSV (includes multi-surface Elo columns!)
curl -sS "https://api.citoapi.com/api/v1/exports/sample/tennis/players.csv" | head -n 5

# 2. Search players with trigram fuzzy matching & career slam metadata
curl -sS -H "x-api-key: YOUR_CITO_API_KEY"   "https://api.citoapi.com/api/v1/tennis/players/search?q=Alcaraz&tour=ATP&limit=5"

# 3. Fetch grass-court & Grand Slam H2H breakdown between two player IDs
curl -sS -H "x-api-key: YOUR_CITO_API_KEY"   "https://api.citoapi.com/api/v1/tennis/h2h?players=atp_207989,atp_206173"

# 4. Query top active clay-court Elo ratings on the ATP Tour
curl -sS -H "x-api-key: YOUR_CITO_API_KEY"   "https://api.citoapi.com/api/v1/tennis/rankings/elo?tour=ATP&surface=clay&active_only=true&limit=20"
Enter fullscreen mode Exit fullscreen mode

Python Tutorial: Building a Grand Slam Surface Elo & Contender H2H Matrix

The runnable Python script below loads the 21-column players CSV sample to compare grass vs. clay specialization across top athletes, and shows how to pull an NxN contender H2H matrix and weekly ranking history for Grand Slam draw previews:

import io
import os
import requests
import pandas as pd

API_BASE = "https://api.citoapi.com/api/v1"
API_KEY = os.environ.get("CITO_API_KEY", "YOUR_CITO_API_KEY")
HEADERS = {"x-api-key": API_KEY, "Accept": "application/json"}

# 1. Inspect multi-surface Elo specialization from the public 21-column players CSV sample
players_csv = requests.get(f"{API_BASE}/exports/sample/tennis/players.csv", timeout=15)
players_csv.raise_for_status()
df_players = pd.read_csv(io.StringIO(players_csv.text))

elo_cols = ["elo_overall", "elo_hard", "elo_clay", "elo_grass"]
rated = df_players.dropna(subset=elo_cols).copy()
rated["clay_vs_grass_tilt"] = rated["elo_clay"] - rated["elo_grass"]

print("Top Clay-vs-Grass Elo Specialists in Sample:")
print(rated[["player_id", "full_name", "elo_overall", "elo_clay", "elo_grass", "clay_vs_grass_tilt"]].head(8))

# 2. Fetch live H2H matrix & ranking trajectory when an API key is configured
if API_KEY != "YOUR_CITO_API_KEY":
    # Resolve top 4 active ATP clay Elo leaders
    elo_resp = requests.get(
        f"{API_BASE}/tennis/rankings/elo",
        headers=HEADERS,
        params={"tour": "ATP", "surface": "clay", "active_only": "true", "limit": 4},
        timeout=15,
    )
    elo_resp.raise_for_status()
    leaders = elo_resp.json().get("items", [])
    contender_ids = [p["player_id"] for p in leaders]

    if len(contender_ids) >= 2:
        # Build a single-call H2H grid across all 4 contenders
        matrix_resp = requests.get(
            f"{API_BASE}/tennis/h2h/matrix",
            headers=HEADERS,
            params={"player_ids": ",".join(contender_ids)},
            timeout=15,
        )
        matrix_resp.raise_for_status()
        print("Contender H2H Matrix:", matrix_resp.json())

        # Pull weekly ranking history for the #1 clay Elo player
        hist_resp = requests.get(
            f"{API_BASE}/tennis/rankings/history/{contender_ids[0]}",
            headers=HEADERS,
            params={"from": "2024-01-01", "order": "asc"},
            timeout=15,
        )
        hist_resp.raise_for_status()
        hist_data = hist_resp.json()
        print(f"Weeks at #1: {hist_data.get('total_weeks_at_no_1')}, Rows: {len(hist_data.get('items', []))}")
Enter fullscreen mode Exit fullscreen mode

Using /tennis/h2h/matrix collapses N*(N-1)/2 pairwise rivalry requests into one fast response, making it straightforward to render interactive ATP/WTA Finals group tables or Grand Slam quarterfinal previews in under 150 milliseconds.


Documentation & Ecosystem Links

Top comments (0)