soccerdata

repository·master·Indexed 23 days ago

https://github.com/probberechts/soccerdata

A Python library providing a unified interface for scraping soccer data from various websites and APIs, including ClubElo, ESPN, FBref, Football-Data.co.uk, Sofascore, SoFIFA, Understat, and WhoScored. It returns data in standardized Pandas DataFrames and supports local caching of downloaded data.

Tokens
15.9K
Snippets
63
Records
132
Agent score
83%

What's inside soccerdata

  1. Overview of SoccerData features

    master

    SoccerData provides a unified interface for gathering soccer data from multiple sources including Club Elo, ESPN, FBref, FiveThirtyEight, Football-Data.co.uk, Sofascore, SoFIFA, Understat, and WhoScored.

    Key Capabilities:

    • Data Formats: All data is returned as Pandas DataFrames with consistent column names and identifiers, facilitating easy merging across different sources.
    • Caching: Data is downloaded only when necessary and cached locally to optimize subsequent runs.
    • Content Types: Access to fixtures, forecasts, match stats, and event stream data.
    • Integration: Integrates with the socceraction package for advanced event stream analysis.
  2. Use SoccerData scrapers

    master

    SoccerData supports multiple data sources including:

    • Club Elo
    • ESPN
    • FBref
    • Football-Data.co.uk
    • Sofascore
    • SoFIFA
    • Understat
    • WhoScored

    Each scraper returns standardized Pandas DataFrames with matching column names and identifiers across different datasets.

  3. Available Data Sources in soccerdata

    master

    The soccerdata package provides scrapers for several major football data providers. Depending on your needs (e.g., advanced metrics, betting odds, or player abilities), you can choose from the following supported sources:

    • ClubElo: Team relative strengths as Elo ratings for most European leagues (includes history).
    • ESPN: Historical results, statistics, and lineups.
    • FBref: Historical results, lineups, and detailed aggregated statistics (Opta-based).
    • Football-Data.co.uk (MatchHistory): Historical results, betting odds, and match statistics.
    • Sofascore: Results, schedules, lineups, and detailed team/player statistics.
    • SoFIFA: Detailed player ability scores from EA Sports FC.
    • Understat: Advanced statistics (xG, xGBuildup, xGChain) and shot events for top European leagues.
    • WhoScored: Historical results, match previews, and detailed Opta event stream data for major leagues.
  4. Manage test data with DVC

    master

    The project uses Data Version Control (DVC) to manage test data in tests/appdata/data, tracked by tests/appdata/data.dvc. This prevents scraping external websites during test runs.

    • Pull latest test data:
      uv run dvc pull
    • Update test data for a new/modified scraper: Set the SOCCERDATA_DIR environment variable to tests/appdata and run the specific test. This directs the scraper to save data into the test directory instead of external locations:
      SOCCERDATA_DIR=tests/appdata uv run pytest tests/test_MyNewScraper.py
    • Add updated data to DVC: After running the scraper with the environment variable above, add the changes to DVC:
      uv run dvc add tests/appdata/data
      Note: Only maintainers can run dvc push. You must include the updated tests/appdata/data.dvc file in your Pull Request.

    DVC is included in the test dependency group.

    uv run dvc pull
  5. Choose between BaseRequestsReader and BaseSeleniumReader

    master

    The library uses two primary types of base readers depending on the technical requirements of the data source:

    1. BaseRequestsReader: A wrapper around the requests library. Use this (or implement readers based on it) for scrapers that download static content and do not require JavaScript to be executed to render the data.
    2. BaseSeleniumReader: A wrapper around the selenium library. Use this (or implement readers based on it) for scrapers that require a browser engine to execute JavaScript to load or display the data.
  6. Understand the role of Base Readers in soccerdata

    master

    In soccerdata, the logic for downloading data from the web is encapsulated in base classes. These base classes are not intended for direct use by end-users. Instead, they serve as the foundation for specific reader classes (e.g., a Premier League reader) which implement the actual data parsing logic.

    When choosing or extending a reader, the underlying mechanism is determined by whether the source requires JavaScript execution.

  7. Manage data caching and storage

    master

    soccerdata uses caching to speed up runtime and avoid rate limits.

    Customizing the cache directory

    You can set a custom directory for a specific scraper instance using the data_dir parameter:

    fbref = sd.FBref(data_dir="/tmp/FBref")

    Refreshing or disabling cache

    • no_cache=True: Always re-downloads the latest data (overwrites existing cache).
    • force_cache=True: Used in specific methods (like read_schedule) to force the use of cached data even if it seems out-of-date.
    • no_store=True: Disables caching entirely (data is not saved to disk). This is generally not recommended.
    # Always re-download latest data
    fbref = sd.FBref(no_cache=True)
    
    # Force use of cached data for a specific method
    fbref.read_schedule(force_cache=True)
    
    # Disable caching entirely
    fbref = sd.FBref(no_store=True)
    # Create scraper class instance with custom caching directory
    fbref = sd.FBref(data_dir="/tmp/FBref")
  8. Quickstart with SoccerData

    master

    SoccerData provides a collection of scrapers to gather soccer data from various websites (e.g., FBref, ESPN, Sofascore) and returns the data as Pandas DataFrames. Data is downloaded on demand and cached locally.

    To get started, import soccerdata, instantiate a scraper class for your desired league and season, and use the read_* methods to fetch data.

    import soccerdata as sd
    
    # Create a scraper class instance for the 2020/21 Premier League
    fbref = sd.FBref('ENG-Premier League', '2021')
    
    # Fetch data
    games = fbref.read_schedule()
    team_season_stats = fbref.read_team_season_stats(stat_type="passing")
    player_season_stats = fbref.read_player_season_stats(stat_type="standard")
  9. Use a Tor proxy for scraping

    master

    To avoid rate limits or access restricted data, you can route your scraper through a SOCKS5 proxy using Tor.

    1. Install Tor following the official instructions.
    2. Start the Tor service (e.g., by running tor in your terminal).
    3. By default, Tor listens on localhost:9050. To use this default configuration, pass proxy='tor' when initializing your scraper class.

    Note: This assumes Tor is running on the default port 9050.

    ws = sd.WhoScored(proxy='tor')
  10. Set up a development environment for soccerdata

    master

    To test code changes, you need a Python environment with all required dependencies. It is recommended to use uv for environment management.

    1. Install uv (macOS/Linux):
      curl -LsSf https://astral.sh/uv/install.sh | sh
    2. Create and activate a virtual environment with a supported Python version (e.g., 3.10) and sync dependencies:
      uv venv --python 3.10
      uv sync

    Using pip

    Alternatively, you can use standard pip within a virtual environment:

    python3 -m venv .venv
    source .venv/bin/activate
    python -m pip install -e .
    python -m pip install -r requirements.txt
    uv venv --python 3.10
    uv sync
  11. Scrape data using a scraper class instance

    master

    Each supported data source has a dedicated class with a uniform API. For example, use the soccerdata.FBref class to fetch data from fbref.com. Data is returned as a Pandas DataFrame.

    To fetch aggregated shooting stats for all teams:

    import soccerdata as sd
    
    # Create scraper class instance
    fbref = sd.FBref()
    
    # Create dataframes
    season_stats = fbref.read_team_season_stats(stat_type='shooting')
  12. Run the soccerdata test suite

    master

    The project uses pytest for testing. You can run the full suite or target specific data sources.

    • Run all tests: Use make test.
    • Run tests for a specific class: Use make test-class <class_name>. For example, to run tests for ClubElo only:
      make test-class clubelo
    make test