Before a big match, everyone asks the same three questions. Who leads the head-to-head? Does the surface change it? How did the last meeting go? The answers are spread across tennis sites, in tables that are made for reading, not for pandas.

This tutorial pulls them into Python in a few lines:

  • the head-to-head record between any two players, split by surface;
  • every past meeting, with the score, round and tournament;
  • a player's match history, including serve stats per match;
  • a couple of charts you can drop into an article or a model.

All the code is in github.com/arman-007/tennis-h2h-python.

Where the data comes from

The official ATP and WTA data feeds are licensed to bookmakers and broadcasters. Sofascore shows head-to-heads and full match histories for every tour, from Grand Slams down to ITF events, but it has no public API.

We'll use the Tennis Player Stats & H2H Scraper on Apify. You give it player names or pairs like "Sinner vs Alcaraz", and it returns one clean row per match. You pay per match returned ($2.50 per 1,000). Apify's free plan includes $5 of credit every month, and this whole tutorial uses about $0.55 of it.

1. Get a token and install

Create a free Apify account and copy your API token from Settings → API & Integrations. Then:

git clone https://github.com/arman-007/tennis-h2h-python cd tennis-h2h-python python -m venv .venv && . .venv/bin/activate pip install -r requirements.txt export APIFY_TOKEN=your_token_here 

2. Run the actor from Python

Everything goes through one helper. It starts the actor, waits for it to finish, and returns the rows:

import os from apify_client import ApifyClient client = ApifyClient(os.environ["APIFY_TOKEN"]) run = client.actor("incognito_mode/tennis-player-stats-h2h-scraper").call( run_input={"matchups": ["Sinner vs Alcaraz"]} ) rows = list(client.dataset(run.default_dataset_id).iterate_items()) 

(This is apify-client 3.x, where call() returns a typed Run. On older versions it was a dict: run["defaultDatasetId"].)

The input is plain: matchups takes "A vs B" strings, and players takes names. A Sofascore ID or a Sofascore player link works too, which helps when two players share a surname.

3. One head-to-head

python h2h.py "Sinner vs Alcaraz" 
Run SUCCEEDED: 19 rows, cost $0.045 Jannik Sinner 7-11 Carlos Alcaraz (18 meetings) Jannik Sinner Carlos Alcaraz hard 3 8 grass 2 0 clay 2 3 

The summary comes from a row the actor marks rowType: "h2h", and it is free:

summary = next(r for r in rows if r["rowType"] == "h2h") summary["playerAWins"], summary["playerBWins"], summary["bySurface"] 

Every meeting is also its own row, numbered from the oldest. Each row is written from player A's side: won, scoreForPlayer, setsWon, gamesWon, plus the tournament, round and surface. h2h.py prints the last five and saves them all to h2h.csv:

 date tournament round surface won score result_type 2025-07-13 Wimbledon, Men Final grass True 4-6 6-4 6-4 6-4 completed 2025-08-18 Cincinnati Final hard False 0-5 retired 2025-09-07 US Open, Men Final hard False 2-6 6-3 1-6 4-6 completed 2025-11-16 ATP Finals Final hard True 7-6(4) 7-5 completed 2026-04-12 Monte Carlo Final clay True 7-6(5) 6-3 completed 

Look at Cincinnati: Sinner retired at 0-5 in the first set. result_type tells a retirement or a walkover apart from a finished match, so you can decide whether it counts in your own numbers.

The 18 meetings also include their first one, a 2019 Challenger match in Alicante. Some official head-to-head counts leave out Challenger matches. To count only tour level, add "tourLevels": ["atp", "team"] to the input.

4. A player's form, this season and last

python career.py "Iga Swiatek" 

This asks for every match since 1 January last year, so a re-run next month still covers two whole seasons:

since = f"{date.today().year - 1}-01-01" run_input = {"players": ["Iga Swiatek"], "maxMatchesPerPlayer": 0, "dateFrom": since} 

maxMatchesPerPlayer: 0 means "no cap". dateFrom also takes relative values such as "6 months" or "2 years". Filters are applied before anything is charged, so a clay-only pull costs only for the clay matches:

{"players": ["Iga Swiatek"], "surface": ["clay"], "maxMatchesPerPlayer": 50} 

The script turns the rows into a DataFrame and pivots win rate by season and surface, with a match count next to each rate:

df["season"] = df["date"].dt.year rate = df.pivot_table(index="season", columns="surface", values="won", aggfunc="mean") * 100 count = pd.crosstab(df["season"], df["surface"]) 
Iga Swiatek: 139 matches since 2025-01-01, 76% won surface hard clay grass season 2025 78.2% of 55 73.3% of 15 90.9% of 11 2026 75.6% of 41 69.2% of 13 50.0% of 4 

Iga Swiatek: matches won by surface

Keep the counts in view. The 2026 grass bar says 50%, but it stands on four matches, so it says little about her grass game.

5. Serve stats per match

Add "matchDetails": ["statistics"] to the input (or run python career.py "Iga Swiatek" --stats). Each match row then carries Sofascore's statistics: aces, double faults, first-serve %, break points, winners, unforced errors and more, for the whole match and for each set.

One detail catches people out. The statistics are stored home/away (player1 = home), not from the player's side. So pick the side that matches perspectivePlayer:

def stat_for_player(row, key): side = "player1" if row["player1"]["id"] == row["perspectivePlayer"]["id"] else "player2" for stat in row.get("statistics") or []: if stat["period"] == "ALL" and stat["key"] == key and stat.get(f"{side}Total"): return 100 * stat[side] / stat[f"{side}Total"] 

stat_for_player(row, "firstServeAccuracy") gives the share of first serves that went in. One match is noisy, so the script plots each match as a dot and a 10-match rolling average as the line:

points["first_serve"].rolling(10).mean() 

Iga Swiatek: first-serve % per match

Of her 139 matches, 138 have statistics. The other was a walkover, where no point was played.

Odds work the same way: "matchDetails": ["odds"] adds opening and closing prices for the match winner, the first set and total games.

6. What it costs

  • Sinner vs Alcaraz (18 meetings, plus 1 free summary row): $0.045
  • A player's last 50 matches: ~$0.13
  • The same with serve stats and odds: ~$0.23
  • Swiatek, this season and last, with stats (139 matches): $0.49

Each run prints its cost. The Actor charges per event (a match row, a statistics add-on), and the prices come back with the run, so common.py works it out from what you got:

events = run.pricing_info.pricing_per_event.actor_charge_events price = {name: event.event_price_usd for name, event in events.items()} cost = price["apify-actor-start"] + len(matches) * price["match"] 

Don't use run.usage_total_usd for this. On a pay-per-event Actor, that is the platform usage the Actor's developer pays, not your bill.

Where to go next

  • Several pairs at once: "matchups": ["Sinner vs Alcaraz", "Swiatek vs Sabalenka", "Djokovic vs Zverev"] returns one summary row per pair.
  • Build a feature table for a model. Join each player's recent form (win rate over the last 20 matches, first-serve %) onto upcoming fixtures. The main tennis scraper gives you fixtures and results by date. Both actors share eventId, so the data joins cleanly.
  • Rankings over time: the ATP & WTA rankings scraper pulls the full ranking tables.

The full code is in the example repo. If you build something with it, I'd like to see it.