# OddsPortal, ESPN, Sofascore & FBref Sports Odds Scraper (`vesper_studio/sports-stats-odds-extractor`) Actor

Extract flat, analytics-ready sports matches, lineups, team & player stats, and pre-match or historical bookmaker odds (1X2, Moneyline, Over/Under) from OddsPortal, ESPN API, Football-Data, Sofascore, and FBref. Clean JSON/CSV/Parquet output ready for pandas, R & quant models.

- **URL**: https://apify.com/vesper_studio/sports-stats-odds-extractor.md
- **Developed by:** [Xavier Richard](https://apify.com/vesper_studio) (community)
- **Categories:** Sports, Developer tools, Automation
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $5.00 / 1,000 match extracted (events, stats, lineups & odds)s

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Sports Stats & Odds Extractor

Production Apify Actor for extracting **flat, analytics-ready sports match events, team & player statistics, lineups, and pre-match / historical multi-bookmaker odds** (1X2, Moneyline, Spread, Over/Under) ready for **pandas, R, DuckDB, Parquet, and predictive modeling**.

Built with Python 3.12, `apify` (`~=4.1`), `curl_cffi` TLS fingerprint impersonation (Chrome/Safari/Firefox rotation), `selectolax` (`LexborHTMLParser`), `pydantic` v2, and adaptive per-domain rate limiting.

***

### Verified Live Sources & Modes (`source`)

| Mode (`source`) | Coverage | Live Status (No Proxy) | Emitted `recordType`s |
| :--- | :--- | :--- | :--- |
| `oddsportal` *(default)* | Upcoming pre-match & historical (`/results/`) multi-bookmaker odds across Football, Basketball, Hockey, NFL, Tennis | **200 OK** direct | `match`, `odds` |
| `espn` | Events, scores, starting lineups (`rosters`), team boxscores, player stats, and open/close DraftKings odds (EPL, La Liga, Serie A, Bundesliga, Ligue 1, UCL, NBA, NFL, NHL, MLB) | **200 OK** direct | `match`, `odds`, `team_stat`, `player_stat` |
| `football_data` | Full-season historical European football results, shots, shots on target, corners, fouls, cards + Pinnacle / Bet365 / William Hill / Market Max & Avg 1X2 & O/U 2.5 odds | **200 OK** direct | `match`, `odds`, `team_stat` |
| `sofascore` | Sofascore JSON API (`/scheduled-events`, `/lineups`, `/statistics`, `/odds/1/all`) | May return `403 challenge` on datacenter IPs (use Residential `proxyConfiguration`) | `match`, `odds`, `team_stat`, `player_stat` |
| `fbref` | FBref HTML & `<!-- ... -->` HTML-commented stat tables with strict 3.5–6s Sports-Reference rate limit | May return `403 cf-mitigated: challenge` on datacenter IPs (use Residential `proxyConfiguration`) | `table_row` |

> **Note:** `bet365` is intentionally excluded in v1 due to aggressive Cloudflare protection.

***

### Input Parameters

```json
{
  "source": "oddsportal",
  "sport": "football",
  "leagueOrUrl": "england/premier-league",
  "dateFrom": "2026-11-01",
  "dateTo": "2026-11-30",
  "oddsPortalMarketType": "both",
  "maxMatches": 50,
  "includeLineups": true,
  "includeStats": true,
  "includeOdds": true,
  "requestDelayMs": 1000,
  "proxyConfiguration": { "useApifyProxy": false }
}
```

- **`source`**: `oddsportal` | `espn` | `football_data` | `sofascore` | `fbref`
- **`sport`**: `football`, `basketball`, `hockey`, `american-football`, `baseball`, `tennis`
- **`leagueOrUrl`**: Preset slug (`england/premier-league`, `spain/laliga`, `italy/serie-a`, `germany/bundesliga`, `france/ligue-1`, `europe/champions-league`, `usa/nba`, `usa/nhl`, `usa/nfl`, `eng.1`, `E0`, `today`) or full URL
- **`dateFrom` / `dateTo`**: Optional `YYYY-MM-DD` date window
- **`includeLineups` / `includeStats` / `includeOdds`**: Toggle granular child records
- **`requestDelayMs`**: Minimum per-domain adaptive delay in ms (automatically floored at `>= 3500 ms` for `fbref.com`)
- **`maxTotalChargeUsd`**: Optional hard USD spending cap alongside Apify Pay-Per-Event limits

***

### Flat Analytical Output Schema

Every dataset item is strictly **flat** (no nested dicts or arrays) for effortless CSV, Parquet, pandas, and R ingestion, linked by a deterministic canonical `matchId` (`sport:YYYY-MM-DD:home-slug_vs_away-slug`):

- **`recordType = "match"`**: Match metadata, scores, winner, venue, average/max 1X2 odds, O/U line & odds, implied probabilities, market overround %, possession, shots, shots on target, xG.
- **`recordType = "odds"`**: One row per bookmaker & market (`1X2`, `ML`, `O/U`), with decimal odds, opening odds (when available), bookmaker payout %, implied probabilities, overround %, and timestamp.
- **`recordType = "team_stat"`**: Long-format team match statistics (`shots`, `shotsOnTarget`, `foulsCommitted`, `possessionPct`, `corners`, etc.).
- **`recordType = "player_stat"`**: Long-format player lineup & boxscore statistics (`isStarter`, `position`, `jersey`, `minutes`, `points`, `goals`, etc.).
- **`recordType = "table_row"`**: Flattened rows from FBref HTML and unwrapped HTML-commented `<!-- <table> -->` tables.

***

### Pay-Per-Event Billing

- **`match-extracted`**: Charged once per unique match unit (including all its `odds`, `team_stat`, and `player_stat` child rows).
- **`table-extracted`**: Charged once per extracted FBref table unit.

***

### Ready-to-Use Analytics Snippets

#### Python (`pandas` + `pyarrow` Parquet)

```python
import pandas as pd
from apify_client import ApifyClient

client = ApifyClient("<YOUR_APIFY_TOKEN>")
dataset_id = "<DATASET_ID>"

items = list(client.dataset(dataset_id).iterate_items())
df = pd.DataFrame(items)

## Split cleanly by analytical table
matches = df[df["recordType"] == "match"].dropna(axis=1, how="all")
odds = df[df["recordType"] == "odds"].dropna(axis=1, how="all")
team_stats = df[df["recordType"] == "team_stat"].dropna(axis=1, how="all")
player_stats = df[df["recordType"] == "player_stat"].dropna(axis=1, how="all")

## Compute vig-free (fair) implied probabilities on 1X2 bookmaker odds
m1x2 = odds[odds["market"] == "1X2"].copy()
inv_sum = (1 / m1x2["oddsHome"]) + (1 / m1x2["oddsDraw"]) + (1 / m1x2["oddsAway"])
m1x2["fairProbHome"] = (1 / m1x2["oddsHome"]) / inv_sum
m1x2["fairProbDraw"] = (1 / m1x2["oddsDraw"]) / inv_sum
m1x2["fairProbAway"] = (1 / m1x2["oddsAway"]) / inv_sum

## Join best available Home odds onto matches & export to Parquet
best_odds = m1x2.groupby("matchId", as_index=False).agg(
    bestHomeOdds=("oddsHome", "max"),
    avgFairProbHome=("fairProbHome", "mean"),
)
modeling_df = matches.merge(best_odds, on="matchId", how="left")
modeling_df.to_parquet("matches_modeling.parquet", index=False)
print(modeling_df[["matchId", "homeTeam", "awayTeam", "homeScore", "awayScore", "bestHomeOdds", "avgFairProbHome"]].head())
```

#### R (`jsonlite` + `dplyr` + `tidyr`)

```r
library(jsonlite)
library(dplyr)
library(tidyr)

## Load directly from Apify Dataset JSON or exported CSV
url <- "https://api.apify.com/v2/datasets/<DATASET_ID>/items?format=json&clean=true"
raw <- fromJSON(url, flatten = TRUE)

matches <- raw %>% filter(recordType == "match")
odds    <- raw %>% filter(recordType == "odds", market == "1X2")
tstats  <- raw %>% filter(recordType == "team_stat")

## Compute Shin/basic normalized fair probabilities per bookmaker
odds_norm <- odds %>%
  mutate(
    inv_sum = (1 / oddsHome) + (1 / oddsDraw) + (1 / oddsAway),
    fair_home = (1 / oddsHome) / inv_sum,
    fair_draw = (1 / oddsDraw) / inv_sum,
    fair_away = (1 / oddsAway) / inv_sum
  )

## Pivot team stats wide for predictive modeling
team_wide <- tstats %>%
  select(matchId, teamName, isHome, statName, statValue) %>%
  pivot_wider(names_from = statName, values_from = statValue)

head(matches %>% select(matchId, matchDate, homeTeam, awayTeam, homeScore, awayScore, overroundPct))
```

# Actor input Schema

## `source` (type: `string`):

Select extraction backend. 'oddsportal' (upcoming & historical multi-bookmaker odds, 200 OK without proxy), 'espn' (JSON API for fixtures, lineups, player/team stats, and open/close odds, 200 OK without proxy), 'football_data' (historical match stats + multi-bookmaker CSV odds, 200 OK without proxy), 'sofascore' (Sofascore API JSON; may require residential proxy if 403 challenge), 'fbref' (FBref HTML + commented tables with 3.5-6s rate limit; may require residential proxy if 403 Cloudflare challenge).

## `sport` (type: `string`):

Target sport discipline.

## `leagueOrUrl` (type: `string`):

League preset/slug (e.g., 'england/premier-league', 'spain/laliga', 'italy/serie-a', 'germany/bundesliga', 'france/ligue-1', 'europe/champions-league', 'usa/nba', 'usa/nhl', 'usa/nfl', 'eng.1', 'E0', 'today') OR a full source URL (e.g., 'https://www.oddsportal.com/football/england/premier-league/' or 'https://fbref.com/en/comps/9/Premier-League-Stats').

## `dateFrom` (type: `string`):

Optional inclusive start date filter (YYYY-MM-DD).

## `dateTo` (type: `string`):

Optional inclusive end date filter (YYYY-MM-DD).

## `season` (type: `string`):

Optional season code for Football-Data.co.uk (e.g. '2526', '2425') or FBref URLs.

## `oddsPortalMarketType` (type: `string`):

For 'oddsportal': fetch 'upcoming' pre-match odds, 'results' historical closing odds, or 'both'.

## `maxMatches` (type: `integer`):

Maximum number of matches (or FBref table rows cap multiplier) to extract.

## `includeLineups` (type: `boolean`):

Extract starting lineups, bench/substitutions, and per-player match statistics when supported by the source.

## `includeStats` (type: `boolean`):

Extract team-level match statistics (shots, possession, fouls, corners, rebounds, etc.).

## `includeOdds` (type: `boolean`):

Extract bookmaker-level odds rows (1X2, Moneyline, Spread, Over/Under, implied probabilities, overround).

## `requestDelayMs` (type: `integer`):

Minimum adaptive delay between requests to the same domain in milliseconds. Automatically raised to >= 3500 ms for fbref.com to respect Sports-Reference strict 429 limits.

## `concurrency` (type: `integer`):

Maximum concurrent HTTP requests (per-domain rate limiter still serializes bursts).

## `requestTimeoutSeconds` (type: `integer`):

Per-request timeout in seconds.

## `maxTotalChargeUsd` (type: `number`):

Optional hard USD spending cap enforced alongside Apify Pay-Per-Event pricing limits.

## `proxyConfiguration` (type: `object`):

Optional proxy settings. Zero proxy by default — OddsPortal, ESPN API, and Football-Data.co.uk work directly with curl_cffi TLS impersonation. Use Apify Residential proxies if querying Sofascore/FBref or if your datacenter IP receives a 403.

## Actor input object example

```json
{
  "source": "oddsportal",
  "sport": "football",
  "leagueOrUrl": "england/premier-league",
  "oddsPortalMarketType": "both",
  "maxMatches": 50,
  "includeLineups": true,
  "includeStats": true,
  "includeOdds": true,
  "requestDelayMs": 250,
  "concurrency": 4,
  "requestTimeoutSeconds": 20,
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}
```

# Actor output Schema

## `sportsRecords` (type: `string`):

Flat, analytics-ready dataset rows (recordType: match, odds, team_stat, player_stat, table_row) ready for pandas, R, DuckDB, CSV, or Parquet export.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "source": "oddsportal",
    "sport": "football",
    "leagueOrUrl": "england/premier-league",
    "maxMatches": 50
};

// Run the Actor and wait for it to finish
const run = await client.actor("vesper_studio/sports-stats-odds-extractor").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "source": "oddsportal",
    "sport": "football",
    "leagueOrUrl": "england/premier-league",
    "maxMatches": 50,
}

# Run the Actor and wait for it to finish
run = client.actor("vesper_studio/sports-stats-odds-extractor").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "source": "oddsportal",
  "sport": "football",
  "leagueOrUrl": "england/premier-league",
  "maxMatches": 50
}' |
apify call vesper_studio/sports-stats-odds-extractor --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,vesper_studio/sports-stats-odds-extractor"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/rqgtg8ck8Es62iXO8/builds/4xmlKLTKCYXktr0e4/openapi.json
