Logo di Pybaseball

Pybaseball

Community
WalrusQuant
pybaseball

Load MLB Statcast, batting, pitching, standings, and player lookup data directly with pybaseball. Use for bounded pitch-level pulls, season tables, schema checks, and user-owned baseball data artifacts.

Panoramica

AutoreWalrusQuant
Repositorysports-analytic-skills
Nome della skillpybaseball
Stelle
53
Fork
4
File inclusi
3
LicenzaMIT
Link
  • Istruzioni in Markdown

    Un file SKILL.md che il modello carica quando serve, consumando token solo quando una richiesta è effettivamente pertinente.

  • Funziona con qualsiasi LLM

    Le skill IA sono in semplice Markdown, non in codice specifico di un fornitore, quindi funzionano con GPT, Claude, Gemini, Grok o un modello locale.

  • 3 file inclusi

    Script, modelli di documento e riferimenti che il modello può leggere mentre lavora. I file sono di sola lettura e non vengono mai eseguiti.

  • Open source

    Pubblicata da WalrusQuant su GitHub. Leggi i sorgenti prima di installarla.

Installazione

Installa la skill IA Pybaseball in TypingMind per usarla con qualsiasi LLM, oppure copiala in un altro agente in grado di leggere SKILL.md.

1

Installa in TypingMind

TypingMind installa una skill direttamente dalla sua cartella GitHub: legge SKILL.md, raccoglie i file delle risorse e salva il risultato in locale.

  1. Apri l'app e vai su Plugin → Skill.
  2. Scegli "Installa da GitHub".
  3. Incolla l'URL della cartella della skill riportato qui sotto e conferma.
    https://github.com/WalrusQuant/sports-analytic-skills/tree/main/skills/pybaseball
  4. Attiva la skill in ogni chat in cui vuoi averla a disposizione.
Plugin → Skill → Nuova skill → Da URL GitHub, poi incolla l'URL della cartella e premi Continua.
2

Installa in un altro agente

Qualsiasi agente che legge il formato Agent Skills può usare questa skill: copia la cartella nella cartella delle skill di quell'agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/WalrusQuant/sports-analytic-skills.git /tmp/sports-analytic-skills
mkdir -p .claude/skills
cp -r /tmp/sports-analytic-skills/skills/pybaseball .claude/skills/pybaseball
Dopo la copia, riavvia Claude Code per caricare la nuova skill.

Usala in TypingMind

Attiva Pybaseball in qualsiasi chat di TypingMind e al resto pensa il modello. Il nome e la descrizione della skill sono nel prompt di sistema e, non appena arriva una richiesta pertinente, il modello carica da solo le istruzioni complete: non devi mai richiamarla manualmente e non consuma token finché non viene effettivamente usata.

Il modello carica automaticamente Pybaseball non appena riceve una richiesta pertinente.

Funziona con qualsiasi modello IA

Le skill IA sono semplici istruzioni in Markdown, non codice specifico di un fornitore, quindi Pybaseball non è vincolata al modello per cui è stata scritta. Installala una sola volta in TypingMind e usala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modello locale che esegui tu, sempre con le tue chiavi API.

  • Caricata solo quando serve

    Il prompt di sistema contiene solo il nome e la descrizione. Le istruzioni vengono recuperate alla prima richiesta pertinente, quindi una skill inutilizzata non costa nulla.

  • Cambia modello durante la chat

    Poiché la skill è composta da istruzioni e non da codice, continua a funzionare anche se cambi modello: il nuovo modello legge lo stesso file SKILL.md.

Istruzioni della skill

Questo è il contenuto di SKILL.md che il modello carica. Leggilo prima dell'installazione: una skill è un insieme di istruzioni che il tuo modello seguirà.

pybaseball

Outcome

Create a bounded, documented MLB artifact at pitch, player-season, team-season, or schedule grain. Record the function and arguments, package version, retrieval time, schema, coverage, natural key, qualifier rules, and transformations.

Pybaseball is especially useful for Statcast depth and public batting/pitching tables. Source convenience does not make every returned field legal for a pre-pitch or pregame model.

When to use this skill

Use for pitch-level Statcast analysis, player-specific pitch pulls, season batting and pitching tables, player identifier lookup, and selected team records. For a general full-league schedule panel, evaluate whether a schedule-oriented source is narrower and more stable. Use a multi-sport source for other leagues.

Installation

bash
python -m pip install pybaseball pandas pyarrow

Public endpoints can be slow or change. Start small, cache successful pulls, record versions, and avoid aggressive retries.

Provider-health boundary

Pybaseball is a collection of clients and scrapers over multiple upstream providers, not one uniform service. A successful import proves nothing about FanGraphs, Baseball Savant, Baseball Reference, Chadwick, or Retrosheet health. Probe the exact function family required for the analysis and record the provider separately.

In particular, batting_stats and pitching_stats are FanGraphs-backed. The upstream project has reports of FanGraphs returning HTTP 403/CAPTCHA responses; see pybaseball issue #507. This is a provider/interface-health warning, not evidence that every pybaseball function is unavailable. Statcast uses Baseball Savant and must be probed independently. Do not bypass access controls or hammer retries. If the required provider is unhealthy, fail visibly, preserve the error and retrieval time, and use a documented licensed/official alternative or a previously verified snapshot rather than treating an empty frame as data.

Choose the correct loader

NeedDirect functionGrainImportant caveat
Player-season battingbatting_stats(start, end)player-seasonqualifiers and provider definitions
Player-season pitchingpitching_stats(start, end)player-seasoninnings/qualification filters
League pitch datastatcast(start_dt, end_dt)pitchpotentially large; bound dates
Batter-specific pitchesstatcast_batter(start_dt, end_dt, player_id)pitchuse stable MLBAM ID
Pitcher-specific pitchesstatcast_pitcher(start_dt, end_dt, player_id)pitchuse stable MLBAM ID
Player identifierplayerid_lookup(last, first)candidate person matchesresolve ambiguity explicitly
Team schedule/recordschedule_and_record(season, team)team-gamenot automatically a full-league panel

Read references/pull_patterns.md for concise season-table and Statcast call patterns. Read references/statcast_bounds.md before any multi-day, multi-player, or repeated Statcast acquisition.

Example loads

python
from pybaseball import batting_stats, pitching_stats, statcast

batters = batting_stats(2023, 2024, qual=100)
pitchers = pitching_stats(2024, 2024, qual=50)
pitches = statcast(start_dt="2024-04-01", end_dt="2024-04-07")

Use a short date window first. Inspect the returned schema and units before requesting a larger interval.

Acquisition workflow

  1. Lock the question, grain, date/season range, entity, and required fields.
  2. Define decision time if the artifact may feed a prospective model.
  3. Choose the narrowest direct function and stable identifiers.
  4. Probe one player, one season table, or a short date interval.
  5. Inspect rows, columns, dtypes, nulls, duplicates, units, and category values.
  6. For long intervals, define non-overlapping chunks with retry and stop rules.
  7. Save each successful immutable chunk before requesting the next.
  8. Check chunk coverage, overlap, schema consistency, and key uniqueness.
  9. Concatenate only validated chunks; retain raw artifacts separately.
  10. Save Parquet plus a manifest containing exact function arguments.

Statcast planning

Estimate scope before pulling:

text
date_start / date_end
league-wide or player-specific
expected active days
required columns
chunk interval
natural pitch key
retry/backoff limit
raw chunk naming
coverage and overlap check

Prefer days or weeks for exploration. A full season can contain hundreds of thousands of pitches and may be unnecessary. Do not loop player-by-player when a single bounded league-wide pull plus local filter answers the question.

Validation checks

All artifacts

  • observed dates or seasons match the request;
  • player IDs resolve to intended people;
  • natural keys are unique at declared grain or duplicates are explained;
  • package version, function, arguments, and retrieval time are recorded;
  • missing values are distinguished from structural zeroes;
  • source columns and any renamed fields have a mapping.

Statcast

  • pitch/game identifiers and event dates are plausible;
  • chunk boundaries have neither gaps nor overlapping duplicate rows;
  • handedness, coordinate systems, velocity/distance units, and event labels are understood;
  • pitch outcomes and plate-appearance outcomes are not mixed silently;
  • post-pitch or postgame variables are not treated as pre-pitch/pregame information.

Season tables

  • qualifier, minimum plate appearances/innings, and year semantics are recorded;
  • counting and rate statistics are not compared without opportunity context;
  • provider-specific definitions are not assumed equivalent to another source;
  • multi-year results are checked for one-row-per-player-year versus aggregated rows.

Baseball-specific caveats

  • Statcast coverage and field definitions vary by era; avoid claiming uniform measurement across years without checking.
  • Pitch rows are nested within plate appearances, games, pitchers, and batters. Row-level independence is usually false.
  • Expected metrics, run values, and final event labels may use information not available at the decision time of a prospective model.
  • Two players can share names and players can change display names. Join on IDs.
  • Park, weather, handedness, count, opponent, and role changes can confound raw comparisons.
  • End-of-season leaderboards contain future information for in-season prediction.
  • Schedule and record functions are team-scoped; assembling a league panel requires explicit deduplication and game-key validation.

Snapshot manifest

text
source: pybaseball and underlying public provider
package_version
function_and_exact_arguments
retrieval_timestamp_utc
requested_and_observed_window
entity_ids_and_resolution_notes
grain_and_natural_key
row_count_and_schema
qualifier_or_minimums
raw_chunks_and_checksums
combined_artifact_and_checksum
units_and_definition_notes
filters_transformations_and_known_gaps

Hard constraints and integrity rules

  1. Never request unbounded Statcast history.
  2. Never use display names as join keys when stable IDs are available.
  3. Never mix season aggregates with pitch rows without explicit aggregation.
  4. Never infer pre-event availability from a field produced after the event.
  5. Respect public services; cache pulls and bound retries.
  6. Snapshot every dataset supporting a durable claim.
  7. Record qualifiers and provider-specific metric definitions.
  8. Validate chunk gaps, overlaps, and schema drift before concatenation.
  9. Do not return an empty frame as a successful acquisition when the source failed.
  10. Do not treat missing numeric values as zero without semantic evidence.

Anti-patterns

  • a full-season Statcast pull for a question answerable with three days;
  • no local snapshot or provenance manifest;
  • silent retries that look like a hanging process;
  • joining players by display name;
  • mixing FanGraphs, Baseball Reference, and Statcast definitions without mapping;
  • end-of-season rates used as pregame features;
  • concatenating overlapping chunks and inflating pitch counts;
  • comparing rate leaders without opportunity thresholds;
  • assuming every Statcast column existed or meant the same thing in every era.

Worked examples

Bounded pitch analysis

Resolve the player ID, pull a three-to-seven-day interval, validate the player's identity and date coverage, record units and pitch key, save raw Parquet, then expand only if the small pull answers the schema and volume questions.

python
from pybaseball import statcast_pitcher

pitches = statcast_pitcher("2024-06-01", "2024-06-07", player_id=123456)

Season batting comparison

Call batting_stats with an explicit qualifier, preserve the Season and stable player identifier columns, report opportunity, and state the provider's metric definition before ranking players.

Helper

bash
python <path-to-pybaseball>/scripts/smoke_load.py --season 2024

The helper parses arguments before importing pybaseball and performs one bounded FanGraphs-backed season-table probe. It exits nonzero on import errors, provider errors, and zero-row or zero-column responses. It is not a Statcast health check or a complete snapshot.

Output contract

Return artifact paths, package version, function and arguments, retrieval time, grain, natural key, rows, schema, filters, qualifier, identifiers, date/season coverage, chunk audit, units, known gaps, and validation results.

Resources

File inclusi

Il modello legge questi file quando servono, mentre la skill è caricata. Sono accessibili in sola lettura e non vengono mai eseguiti.

Domande frequenti

Cosa fa la skill IA Pybaseball?

Load MLB Statcast, batting, pitching, standings, and player lookup data directly with pybaseball. Use for bounded pitch-level pulls, season tables, schema checks, and user-owned baseball data artifacts.

Perché usare Pybaseball su TypingMind?

Perché la installi una volta e la usi con qualsiasi modello. Pybaseball è scritta in semplice Markdown anziché in codice specifico di un fornitore, quindi la stessa skill funziona con GPT-5, Claude, Gemini, Grok o un modello locale, e puoi cambiare modello durante la chat senza che smetta di funzionare. TypingMind usa le tue chiavi API, quindi paghi direttamente i fornitori anziché un abbonamento per posto utente, e le tue skill e chat restano nel tuo spazio di archiviazione.

Come installo Pybaseball in TypingMind?

Apri Plugin → Skill → Installa da GitHub in TypingMind e incolla https://github.com/WalrusQuant/sports-analytic-skills/tree/main/skills/pybaseball. TypingMind legge il file SKILL.md, include i file associati e installa la skill, che puoi abilitare per ogni singola chat.

Quali modelli IA possono usare Pybaseball?

Qualsiasi modello che colleghi in TypingMind. Le skill IA sono semplici istruzioni in Markdown anziché codice specifico di un fornitore, quindi GPT, Claude, Gemini, Grok e i modelli locali possono tutti caricare questa skill quando una richiesta corrisponde al suo scopo.

Quanti modelli IA posso usare con Pybaseball?

Quanti ne vuoi. Se un modello supporta le skill, puoi usarlo con Pybaseball: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e molti altri, tutti su TypingMind con le tue chiavi API.

La skill IA Pybaseball è gratuita?

Sì. È pubblicata su GitHub da WalrusQuant con licenza MIT. Paghi solo il tuo fornitore IA per i token che usi.

Cosa sono le skill IA?

Una skill IA è un pacchetto di istruzioni riutilizzabili che insegna a un modello IA come svolgere un'attività specifica. Segue il formato aperto Agent Skills: un file SKILL.md con un nome e una descrizione, più eventuali script, modelli o file di riferimento di cui il modello potrebbe aver bisogno. Il modello legge le istruzioni solo quando la tua richiesta corrisponde alla skill, quindi una skill installata non comporta costi finché non viene usata.

In cosa si differenziano le skill IA dai plugin o dai server MCP?

Un plugin o un server MCP fornisce a un modello nuovi strumenti da richiamare: codice che viene eseguito da qualche parte e restituisce un risultato. Una skill IA, invece, fornisce al modello conoscenze e procedure: come affrontare un'attività, quali passaggi seguire e quali caratteristiche deve avere un buon output. Le skill sono semplici istruzioni in Markdown, quindi non richiedono server, chiavi API né ambienti di esecuzione e funzionano con qualsiasi modello.

Vedi tutti

Crea subito la tua area di lavoro IA

Iscriviti alla nostra newsletter per ricevere aggiornamenti sulle nuove funzionalità e sulle prossime iniziative a premi 👇