Logotipo de Pybaseball

Pybaseball

Comunidad
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.

Descripción general

EditorWalrusQuant
Repositoriosports-analytic-skills
Nombre de la habilidadpybaseball
Estrellas
53
Forks
4
Archivos incluidos
3
LicenciaMIT
Enlaces
  • Instrucciones en Markdown

    Un archivo SKILL.md que el modelo carga cuando lo necesita, de modo que solo consume tokens cuando una petición es realmente relevante.

  • Funciona con cualquier LLM

    Las habilidades de IA están en Markdown, no en código específico de un proveedor, por lo que funcionan con GPT, Claude, Gemini, Grok o un modelo local.

  • 3 archivos incluidos

    Scripts, plantillas y referencias que el modelo puede leer mientras trabaja. Los archivos son de solo lectura y nunca se ejecutan.

  • Código abierto

    Publicada por WalrusQuant en GitHub. Revisa el contenido original antes de instalarla.

Instalación

Instala la habilidad de IA Pybaseball en TypingMind para usarla con cualquier LLM, o añádela a otro agente que lea SKILL.md.

1

Instalar en TypingMind

TypingMind instala una habilidad directamente desde su carpeta de GitHub: lee SKILL.md, empaqueta los archivos de recursos y guarda el resultado localmente.

  1. Abre la aplicación y ve a Plugins → Habilidades.
  2. Elige «Instalar desde GitHub».
  3. Pega la URL de la carpeta de la habilidad que se muestra a continuación y confirma.
    https://github.com/WalrusQuant/sports-analytic-skills/tree/main/skills/pybaseball
  4. Activa la habilidad en cada chat en el que quieras tenerla disponible.
Plugins → Habilidades → Añadir habilidad → Desde URL de GitHub; después, pega la URL de la carpeta y pulsa Continuar.
2

Instalar en otro agente

Cualquier agente que lea el formato Agent Skills puede usar esta habilidad: copia la carpeta en el directorio de habilidades de ese 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
Reinicia Claude Code después de copiarla para que detecte la nueva habilidad.

Úsala en TypingMind

Activa Pybaseball en cualquier chat de TypingMind y el modelo se encargará del resto. Su nombre y descripción se incluyen en el prompt del sistema y, en cuanto una petición es relevante, el modelo carga las instrucciones completas por sí solo. No tienes que invocarla manualmente y no consume tokens hasta que se utiliza.

El modelo carga Pybaseball automáticamente en cuanto una petición es relevante para esa habilidad.

Funciona con cualquier modelo de IA

Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que Pybaseball no está vinculada al modelo para el que se creó. Instálala una sola vez en TypingMind y úsala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modelo local que ejecutes tú, todo con tus propias claves API.

  • Se carga solo cuando se necesita

    El prompt del sistema solo incluye el nombre y la descripción. Las instrucciones se cargan con la primera petición relevante, por lo que una habilidad que no se usa no supone ningún coste.

  • Cambia de modelo durante el chat

    Como la habilidad contiene instrucciones y no código, cambiar de modelo no impide que funcione: el nuevo modelo lee el mismo archivo SKILL.md.

Instrucciones de la habilidad

Este es el contenido de SKILL.md que carga el modelo. Léelo antes de instalar la habilidad: contiene instrucciones que tu modelo 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

Archivos incluidos

El modelo los lee según los necesita mientras la habilidad está cargada. Se ofrecen como archivos de lectura y nunca se ejecutan.

Preguntas frecuentes

¿Qué hace la habilidad de 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.

¿Por qué usar Pybaseball en TypingMind?

Porque la instalas una vez y la usas con cualquier modelo. Pybaseball está escrita en Markdown, no en código específico de un proveedor, por lo que la misma habilidad funciona con GPT-5, Claude, Gemini, Grok o un modelo local, y puedes cambiar de modelo en mitad del chat sin que deje de funcionar. TypingMind utiliza tus propias claves API, de modo que pagas directamente a los proveedores en lugar de pagar una suscripción por puesto, y tus habilidades y chats permanecen en tu propio almacenamiento.

¿Cómo instalo Pybaseball en TypingMind?

Abre Plugins → Habilidades → Instalar desde GitHub en TypingMind y pega https://github.com/WalrusQuant/sports-analytic-skills/tree/main/skills/pybaseball. TypingMind lee su archivo SKILL.md, empaqueta sus archivos y la instala como una habilidad que puedes activar en cada chat.

¿Qué modelos de IA pueden usar Pybaseball?

Cualquier modelo que conectes en TypingMind. Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que GPT, Claude, Gemini, Grok y los modelos locales pueden cargar esta habilidad cuando una solicitud se corresponda con ella.

¿Con cuántos modelos de IA puedo usar Pybaseball?

Con tantos como quieras. Siempre que un modelo admita habilidades, puedes usar Pybaseball con él: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama y muchos más, todos en TypingMind con tus propias claves API.

¿Es gratuita la habilidad de IA Pybaseball?

Sí. WalrusQuant la ha publicado en GitHub bajo la licencia MIT. Solo pagas a tu proveedor de IA por los tokens que utilizas.

¿Qué son las habilidades de IA?

Una habilidad de IA es un conjunto de instrucciones reutilizables que enseña a un modelo de IA a realizar una tarea concreta. Sigue el formato abierto Agent Skills: un archivo SKILL.md con un nombre y una descripción, además de los scripts, plantillas o archivos de referencia que pueda necesitar el modelo. El modelo solo lee las instrucciones cuando tu solicitud se corresponde con la habilidad, por lo que una habilidad instalada no supone ningún coste hasta que se utiliza.

¿En qué se diferencian las habilidades de IA de los plugins o los servidores MCP?

Un plugin o un servidor MCP proporciona al modelo nuevas herramientas que puede invocar: código que se ejecuta en algún lugar y devuelve un resultado. En cambio, una habilidad de IA aporta conocimientos y procedimientos al modelo: cómo abordar una tarea, qué pasos seguir y qué se considera un buen resultado. Las habilidades son instrucciones en Markdown, por lo que no necesitan servidor, clave API ni entorno de ejecución, y funcionan con cualquier modelo.

Ver todos

Crea ya tu propio espacio de trabajo IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇