# jldbc/pybaseball architecture

> Architecture diagram of the GitHub repository jldbc/pybaseball, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-05-12). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/jldbc/pybaseball
- Repository: https://github.com/jldbc/pybaseball

## Overview

##### Project Type and Purpose
- pybaseball is a Python library/package (not a web app or service) whose purpose is to provide a unified, programmatic API for scraping, caching, transforming, and analyzing baseball data from multiple external sources (Baseball Savant/Statcast, FanGraphs, Baseball Reference, Retrosheet, Chadwick Bureau, and Lahman CSV).

##### File Structure
- Top-level folders/files:
- pybaseball/            ← main package
- docs/                  ← documentation pages
- EXAMPLES/              ← Jupyter notebooks demonstrating usage
- scripts/               ← utility scripts (CLI entry points)
- tests/                 ← unit & integration tests
- setup.py, pyproject.toml, Makefile, CI workflows ← packaging & CI
- Within pybaseball/:
- datasources/           ← modules that fetch raw HTML/JSON from external sites
- cache/                 ← local-disk caching layer (enable/disable, store/retrieve raw data)
- datahelpers/           ← transformation utilities (column mappers, post-processing, unit conversions, singleton patterns)
- analysis/              ← higher-level algorithms (projections: marcels, trajectories: batted_balls)
- enums/                 ← enumeration definitions for data columns & API parameters
- top-level modules      ← user-facing API functions (statcast, batting_stats, standings, schedule_and_record, etc.)
- utils.py, profiling.py ← miscellany

##### README for Additional Insights
- Confirms primary data sources & functions (statcast, statcast_batter, statcast_pitcher, batting_stats, pitching_stats, standings, etc.)
- Mentions optional caching, multiprocessing considerations, and primary dependencies (pandas, requests, beautifulsoup/pandas.read_html)

a. Components
1. External Data Sources
- Baseball Savant (Statcast API/CSV)
- FanGraphs (HTML tables / endpoints)
- Baseball Reference (season-level & range queries)
- Retrosheet / Chadwick / Lahman CSVs (local/static data)
2. Data Acquisition Layer (pybaseball/datasources)
- Modules: statcast.py, fangraphs.py, bref.py, html_table_processor.py
- Responsibilities: perform HTTP requests, parse HTML/CSV, return raw DataFrames
3. Caching Layer (pybaseball/cache)
- Modules: cache.py, cache_config.py, cache_record.py
- Responsibilities: intercept raw downloads, store to disk, manage TTL, purge/enable/disable
4. Data Processing Layer (pybaseball/datahelpers + utils)
- Modules: column_mapper.py, postprocessing.py, transform.py, unit_conversions.py, statcast_utils.py
- Responsibilities: clean & normalize raw DataFrames, map column names/enums, convert units, fill missing data
5. Core API Layer (pybaseball top-level modules)
- Functions: statcast(), batting_stats(), pitching_stats(), schedule_and_record(), standings(), playerid_lookup(), etc.
- Responsibilities: orchestrate acquisition → caching → processing → return final pandas.DataFrame or list of DataFrames
6. Analysis Layer (pybaseball/analysis)
- Subpackages: projections/marcels (age adjustment, batting & pitching projection), trajectories/batted_balls (calculator, parameters)
- Responsibilities: apply statistical algorithms to processed DataFrames, output enhanced metrics or model projections
7. Examples & Scripts
- EXAMPLES notebooks for interactive exploration
- scripts/*.py for ad-hoc utilities (e.g., validate_cache.py, statcast_timing.py)
8. Tests & CI
- tests/pybaseball & tests/integration ensure correctness across modules
- GitHub workflows trigger pytest and publish to PyPI

b. Relationships & Data Flow
1. User calls a Core API function (e.g., statcast(start, end))
2. Core API invokes Data Acquisition module →
3. Acquisition layer checks Caching layer:
– If cache miss: fetch from External Data Sources → pass raw DataFrame to Caching layer → store on disk → forward to Data Processing
– If cache hit: load raw DataFrame from disk → forward to Data Processing
4. Data Processing layer cleans and normalizes → returns final DataFrame
5. Analysis layer (if called explicitly) takes DataFrame → runs projection/trajectory algorithms → returns enhanced results
6. Output delivered back to the user’s code or notebook

c. Architectural Patterns & Principles
- Layered Architecture (Separation of Concerns)
- Decorator/Singleton in caching module for transparent caching
- Modular design: datasources can be extended with new providers; analysis algorithms can be swapped/extended
- Use of pandas DataFrames as canonical data structure across layers

d. Key Technologies & Libraries
- Python 3.x
- pandas, numpy
- requests (or pandas.read_html under the hood)
- BeautifulSoup or lxml (via pandas)
- pytest for testing
- mypy for static typing
- GitHub Actions for CI/CD

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% External Data Sources
    subgraph "External Data Sources"
        BD["Baseball Savant"]:::external
        FG["FanGraphs"]:::external
        BR["Baseball Reference"]:::external
        RS["Retrosheet/Chadwick/Lahman CSV"]:::external
    end

    %% Data Acquisition Layer
    subgraph "Data Acquisition Layer"
        SC["statcast.py"]:::acquisition
        FGDS["fangraphs.py"]:::acquisition
        BRDS["bref.py"]:::acquisition
        HTMLP["html_table_processor.py"]:::acquisition
    end

    %% Caching Layer
    subgraph "Caching Layer"
        CAPI["cache.py"]:::caching
        CCFG["cache_config.py"]:::caching
        CREC["cache_record.py"]:::caching
        DU["dataframe_utils.py"]:::caching
        FU["file_utils.py"]:::caching
        FU2["func_utils.py"]:::caching
    end

    %% Data Processing Layer
    subgraph "Data Processing Layer"
        CM["column_mapper.py"]:::processing
        PP["postprocessing.py"]:::processing
        TR["transform.py"]:::processing
        UC["unit_conversions.py"]:::processing
        SU["statcast_utils.py"]:::processing
        SN["singleton.py"]:::processing
        UTL["utils.py"]:::processing
        PROF["profiling.py"]:::processing
    end

    %% Core API Layer
    subgraph "Core API Layer"
        STAT["statcast.py"]:::api
        STB["statcast_batter.py"]:::api
        STP["statcast_pitcher.py"]:::api
        STF["statcast_fielding.py"]:::api
        STR["statcast_running.py"]:::api
        SPSPIN["statcast_pitcher_spin.py"]:::api
        BUS["batting_stats.py"]:::api
        PUS["pitching_stats.py"]:::api
        STDG["standings.py"]:::api
        SCR["schedule_and_record.py"]:::api
        PIL["playerid_lookup.py"]:::api
        TIL["teamid_lookup.py"]:::api
    end

    %% Analysis Layer
    subgraph "Analysis Layer"
        subgraph "projections/marcels"
            ADJ["age_adjustment.py"]:::analysis
            MB["marcels_base.py"]:::analysis
            MBB["marcels_batting.py"]:::analysis
            MBP["marcels_pitching.py"]:::analysis
        end
        subgraph "trajectories/batted_balls"
            CALC["calculator.py"]:::analysis
            PAR["parameters.py"]:::analysis
        end
        TU["unit_conversions.py"]:::analysis
        TA["utils.py"]:::analysis
    end

    %% Examples & Scripts
    subgraph "Examples & Scripts"
        EX["EXAMPLES Notebooks"]:::misc
        STT["scripts/statcast_timing.py"]:::misc
        SVD["scripts/statcast_valid_dates.py"]:::misc
        VC["scripts/validate_cache.py"]:::misc
    end

    %% Tests & CI
    subgraph "Tests & CI"
        UT["tests/"]:::misc
        INT["tests/integration/"]:::misc
        CI1[".github/workflows/pytest.yml"]:::misc
        CI2[".github/workflows/python-publish.yml"]:::misc
    end

    %% User
    USER["User Code/Notebook"]:::external

    %% Data Flow
    USER -->|"calls Core API"| STAT
    STAT -->|"invokes acquisition"| SC
    STAT -->|"invokes acquisition"| FGDS
    STAT -->|"invokes acquisition"| BRDS
    STAT -->|"invokes acquisition"| HTMLP

    BD -->|"raw HTML/CSV"| SC
    FG -->|"raw HTML/CSV"| FGDS
    BR -->|"raw HTML/CSV"| BRDS
    RS -->|"raw CSV"| HTMLP

    SC -->|"check cache"| CAPI
    FGDS -->|"check cache"| CAPI
    BRDS -->|"check cache"| CAPI
    HTMLP -->|"check cache"| CAPI

    CAPI -->|"cached/raw DataFrame"| CM
    CCFG --> CM
    CREC --> CM
    DU --> CM
    FU --> CM
    FU2 --> CM

    CM -->|"cleaned DataFrame"| STAT
    PP --> STAT
    TR --> STAT
    UC --> STAT
    SU --> STAT
    SN --> STAT
    UTL --> STAT
    PROF --> STAT

    CM -->|"optional analysis input"| ADJ
    ADJ --> MB
    MB --> MBB
    MB --> MBP
    CALC --> TA
    PAR --> TA
    TU --> TA
    TA --> USER

    STAT -->|"returns DataFrame"| USER

    EX --> USER
    STT --> USER
    SVD --> USER
    VC --> USER

    UT -->|"CI tests"| CI1
    UT -->|"CI tests"| CI2
    INT -->|"CI integration"| CI1
    INT -->|"CI integration"| CI2

    %% Click Events
    click SC "https://github.com/jldbc/pybaseball/blob/master/pybaseball/datasources/statcast.py"
    click FGDS "https://github.com/jldbc/pybaseball/blob/master/pybaseball/datasources/fangraphs.py"
    click BRDS "https://github.com/jldbc/pybaseball/blob/master/pybaseball/datasources/bref.py"
    click HTMLP "https://github.com/jldbc/pybaseball/blob/master/pybaseball/datasources/html_table_processor.py"
    click CAPI "https://github.com/jldbc/pybaseball/blob/master/pybaseball/cache/cache.py"
    click CCFG "https://github.com/jldbc/pybaseball/blob/master/pybaseball/cache/cache_config.py"
    click CREC "https://github.com/jldbc/pybaseball/blob/master/pybaseball/cache/cache_record.py"
    click DU "https://github.com/jldbc/pybaseball/blob/master/pybaseball/cache/dataframe_utils.py"
    click FU "https://github.com/jldbc/pybaseball/blob/master/pybaseball/cache/file_utils.py"
    click FU2 "https://github.com/jldbc/pybaseball/blob/master/pybaseball/cache/func_utils.py"
    click CM "https://github.com/jldbc/pybaseball/blob/master/pybaseball/datahelpers/column_mapper.py"
    click PP "https://github.com/jldbc/pybaseball/blob/master/pybaseball/datahelpers/postprocessing.py"
    click TR "https://github.com/jldbc/pybaseball/blob/master/pybaseball/datahelpers/transform.py"
    click UC "https://github.com/jldbc/pybaseball/blob/master/pybaseball/datahelpers/unit_conversions.py"
    click SU "https://github.com/jldbc/pybaseball/blob/master/pybaseball/datahelpers/statcast_utils.py"
    click SN "https://github.com/jldbc/pybaseball/blob/master/pybaseball/datahelpers/singleton.py"
    click UTL "https://github.com/jldbc/pybaseball/blob/master/pybaseball/utils.py"
    click PROF "https://github.com/jldbc/pybaseball/blob/master/pybaseball/profiling.py"
    click STAT "https://github.com/jldbc/pybaseball/blob/master/pybaseball/statcast.py"
    click STB "https://github.com/jldbc/pybaseball/blob/master/pybaseball/statcast_batter.py"
    click STP "https://github.com/jldbc/pybaseball/blob/master/pybaseball/statcast_pitcher.py"
    click STF "https://github.com/jldbc/pybaseball/blob/master/pybaseball/statcast_fielding.py"
    click STR "https://github.com/jldbc/pybaseball/blob/master/pybaseball/statcast_running.py"
    click SPSPIN "https://github.com/jldbc/pybaseball/blob/master/pybaseball/statcast_pitcher_spin.py"
    click BUS "https://github.com/jldbc/pybaseball/blob/master/pybaseball/batting_stats.py"
    click PUS "https://github.com/jldbc/pybaseball/blob/master/pybaseball/pitching_stats.py"
    click STDG "https://github.com/jldbc/pybaseball/blob/master/pybaseball/standings.py"
    click SCR "https://github.com/jldbc/pybaseball/blob/master/pybaseball/schedule_and_record.py"
    click PIL "https://github.com/jldbc/pybaseball/blob/master/pybaseball/playerid_lookup.py"
    click TIL "https://github.com/jldbc/pybaseball/blob/master/pybaseball/teamid_lookup.py"
    click ADJ "https://github.com/jldbc/pybaseball/blob/master/pybaseball/analysis/projections/marcels/age_adjustment.py"
    click MB "https://github.com/jldbc/pybaseball/blob/master/pybaseball/analysis/projections/marcels/marcels_base.py"
    click MBB "https://github.com/jldbc/pybaseball/blob/master/pybaseball/analysis/projections/marcels/marcels_batting.py"
    click MBP "https://github.com/jldbc/pybaseball/blob/master/pybaseball/analysis/projections/marcels/marcels_pitching.py"
    click CALC "https://github.com/jldbc/pybaseball/blob/master/pybaseball/analysis/trajectories/batted_balls/calculator.py"
    click PAR "https://github.com/jldbc/pybaseball/blob/master/pybaseball/analysis/trajectories/batted_balls/parameters.py"
    click TU "https://github.com/jldbc/pybaseball/blob/master/pybaseball/analysis/trajectories/unit_conversions.py"
    click TA "https://github.com/jldbc/pybaseball/blob/master/pybaseball/analysis/trajectories/utils.py"

    %% Styles
    classDef external fill:#E3D5FF,stroke:#8B66CC
    classDef acquisition fill:#D0E7FF,stroke:#4A90E2
    classDef caching fill:#B2D8E7,stroke:#2E8BC0
    classDef processing fill:#D5F5D5,stroke:#28A745
    classDef api fill:#FFE5B4,stroke:#FF8C00
    classDef analysis fill:#FFD5D5,stroke:#D73A49
    classDef misc fill:#EEEEEE,stroke:#A0A0A0
```
