Skip to main content

polars-baseball

PyPI version Python versions Documentation CI Codecov License Downloads

Languages: English | Traditional Chinese

polars-baseball is a typed, async-first Python library for retrieving MLB and baseball analytics data from Statcast, Baseball Savant, FanGraphs, Baseball Reference, Lahman, Retrosheet, and the MLB Stats API—landing directly in polars.DataFrame without going through pandas first.

Why use polars-baseball instead of pybaseball?

pybaseball is useful and established. polars-baseball is aimed at a different execution model: async data ingestion, native Polars output, and one consistent entry point across multiple baseball data providers.

Feature pybaseball polars-baseball
Polars native No Yes
Async data fetching No Yes
Statcast / Baseball Savant Yes Yes
FanGraphs Yes Yes
MLB Stats API Limited Yes
Lahman / Retrosheet workflows Partial Yes
Built-in cache Partial Yes
Typed public API Partial Yes

Typical pandas-first workflow:

pybaseball -> pandas -> convert to Polars -> analysis

polars-baseball workflow:

polars-baseball -> Polars -> analysis

Key Features

  • Public data-fetching APIs return polars.DataFrame by default (unless an endpoint explicitly documents a non-tabular contract).
  • Every data-fetching API is async def, so you can compose queries concurrently with asyncio.
  • Unified access to Statcast, Baseball Savant, FanGraphs, Baseball Reference, Lahman, Retrosheet, MLB Stats API, and player ID lookups.
  • Opt-in local Parquet caching avoids redundant network requests across large queries.
  • BaseballClient gives long-running services explicit control over HTTP connection pools and cache lifecycles.
  • HttpClient exposes timeout, retry, and Baseball Reference rate-limit settings.

Installation

pip install polars-baseball

For local development:

git clone https://github.com/nicko4o/polars-baseball
cd polars-baseball
uv sync --all-extras

To run visualization examples:

pip install "polars-baseball[plot]"

Quick Start

Statcast pitch-level data

import asyncio

from polars_baseball import BaseballClient


async def main() -> None:
    async with BaseballClient() as client:
        df = await client.savant.statcast(start_date="2026-06-01", end_date="2026-06-01")
        print(df.head(5))


if __name__ == "__main__":
    asyncio.run(main())

Aggregate directly with Polars

import polars as pl
from polars_baseball import BaseballClient

async with BaseballClient() as client:
    df = await client.savant.pitcher(
        start_date="2026-06-01",
        end_date="2026-06-01",
        # Use await client.lookup.playerid_lookup("Judge", "Aaron") to find player IDs
        player_id=506433,
    )
    summary = df.group_by("pitch_type").agg(
        pl.col("release_speed").mean().alias("mean_speed"),
        pl.len().alias("pitch_count"),
    )
    print(summary.sort("pitch_count", descending=True))

FanGraphs leaderboard

from polars_baseball import BaseballClient

async with BaseballClient() as client:
    df = await client.fangraphs.batting(
        start_season=2026,
        end_season=2026,
        qual=100,
        max_results=20,
    )
    print(df.head(10))

Examples

Scripts (CLI-ready)

Runnable .py examples live in examples/:

Notebooks (interactive)

Interactive Jupyter notebooks live in notebooks/:

Benchmarking

Do not trust performance claims without a reproducible command:

python -m benchmarks run statcast_7day_cold

List available profiles:

python -m benchmarks run list

Full command reference:

python -m benchmarks run <profile> [--json] [--json-file PATH] [--baseline] [--fail-if-regression]
python -m benchmarks baseline show
python -m benchmarks baseline clear

The runner reports wall time, CPU time, peak Python memory (via tracemalloc), GC collections, and result shape. Use the --baseline flag to save results and compare against historical data. Use the same date range, cache state, Python version, and machine when comparing against pandas-first workflows.

Web Services & Concurrency

Long-running concurrent services should manage their own BaseballClient and pass it into API calls for explicit resource and connection pool management:

from contextlib import asynccontextmanager

from fastapi import FastAPI

import polars_baseball as pb


@asynccontextmanager
async def lifespan(app: FastAPI):
    async with pb.BaseballClient() as client:
        app.state.pb_client = client
        yield


app = FastAPI(lifespan=lifespan)


@app.get("/statcast")
async def get_statcast() -> dict[str, int]:
    client: pb.BaseballClient = app.state.pb_client
    df = await client.savant.statcast(
        start_date="2026-06-01",
        end_date="2026-06-02",
    )
    return {"rows": df.height}

API Namespace Policy

The package root (import polars_baseball as pb) exposes provider namespaces (pb.savant, pb.fangraphs, pb.bref, pb.mlb, pb.retrosheet, pb.lahman, pb.lookup), the client class (pb.BaseballClient), and universal enums (Position, KeyType).

Provider-specific workflows and enums live in their dedicated namespaces (e.g. pb.fangraphs.*, pb.mlb.*). Modules prefixed with _, including _schemas, are internal implementation details and are not part of the compatibility contract.

Documentation & Resources

Community & Governance

We welcome contributions! Please review our repository policies before submitting PRs or issues:

polars-baseball is a data retrieval library and does not claim ownership of upstream datasets:

  • Retrosheet: The information used here was obtained free of charge from and is copyrighted by Retrosheet. Interested parties may contact Retrosheet at www.retrosheet.org.
  • Statcast & MLB Stats API: Data provided courtesy of Major League Baseball / Baseball Savant.
  • FanGraphs & Baseball Reference: Data provided courtesy of FanGraphs and Baseball Reference. Please respect upstream terms of service and rate limits.
  • Lahman: Lahman's Baseball Database by Sean Lahman.

Citation

If you use polars-baseball in research, academic work, or software projects, please cite it using CITATION.cff.

Author

Created and maintained by Nick.

License

This project is licensed under the MIT License.

Metadata

Release files for polars-baseball 0.30.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for polars-baseball 0.30.0
File Size Uploaded Provenance Actions
polars_baseball-0.30.0.tar.gz 144.7 kB With provenance Details for polars_baseball-0.30.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for polars-baseball 0.30.0
File Interpreter ABI Platform Actions
polars_baseball-0.30.0-py3-none-any.whl Python 3 none any Details for polars_baseball-0.30.0-py3-none-any.whl

Total release size: 313.4 kB

Release files / polars_baseball-0.30.0.tar.gz

Download URL polars_baseball-0.30.0.tar.gz
Size 144.7 kB
Tags Source
SHA-256 checksum
How to use checksums
8bf9b39a70ac4c1dfec6aad55c5c64e202a90eea605ec1a67b4e499f3d18fefe
BLAKE2b-256 checksum
How to use checksums
af6469392df9fe550ec802fb3859ce029f7a8bca23e09385f331470a971f43b7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Release files / polars_baseball-0.30.0-py3-none-any.whl

Download URL polars_baseball-0.30.0-py3-none-any.whl
Size 168.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
18d937fa2f26bc9ccb3bfdc35edc22354bf7e63eeb8e33aee633bce45e0eb299
BLAKE2b-256 checksum
How to use checksums
b5a9bc6b01db54dcf0e14d92e702424833581cab8915b0330507ca27ec508d16
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Security for polars-baseball 0.30.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for polars_baseball-0.30.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.30.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page