|
| 1 | +import pandas as pd |
| 2 | +import requests |
| 3 | + |
| 4 | +from ..constants import DEFAULT_SEASON |
| 5 | +from ..enums.statcast_leaderboard import GameType |
| 6 | + |
| 7 | +session = requests.Session() |
| 8 | + |
| 9 | +API_URL = 'https://baseballsavant.mlb.com/leaderboard/services/baserunning' |
| 10 | + |
| 11 | + |
| 12 | +def runner_extra_bases_taken( |
| 13 | + runner_id: str, |
| 14 | + game_type: str | GameType = GameType.REGULAR_SEASON, |
| 15 | + season: str = str(DEFAULT_SEASON), |
| 16 | +) -> pd.DataFrame: |
| 17 | + """ |
| 18 | + Get extra base taken data from each advanced opportunity for a specific runner. |
| 19 | + ref: https://baseballsavant.mlb.com/leaderboard/baserunning |
| 20 | +
|
| 21 | + Args: |
| 22 | + runner_id (str): The MLBAM ID of the runner. (Required) |
| 23 | + game_type (str | GameType): The game type to filter by. Default is "Regular". |
| 24 | + season (str): The season to filter by. The earliest season available is 2016. |
| 25 | + Returns: |
| 26 | + pd.DataFrame: A DataFrame containing the baserunning data. |
| 27 | + """ |
| 28 | + |
| 29 | + if not runner_id: |
| 30 | + raise ValueError('runner_id is required') |
| 31 | + |
| 32 | + if not isinstance(game_type, str) and not isinstance(game_type, GameType): |
| 33 | + raise ValueError(f'Invalid type for game_type: {type(game_type)}') |
| 34 | + |
| 35 | + if not GameType.has_value(game_type): |
| 36 | + raise ValueError(f'Invalid game type: {game_type}') |
| 37 | + |
| 38 | + if int(season) < 2016: |
| 39 | + raise ValueError( |
| 40 | + f'Invalid season: {season}, The earliest season available is 2016' |
| 41 | + ) |
| 42 | + |
| 43 | + params = { |
| 44 | + 'game_type': game_type, |
| 45 | + 'season_start': season, |
| 46 | + 'season_end': season, |
| 47 | + 'n': 0, |
| 48 | + } |
| 49 | + |
| 50 | + response = session.get(f'{API_URL}/{runner_id}', params=params) |
| 51 | + |
| 52 | + if response.status_code == 200: |
| 53 | + result = response.json() |
| 54 | + df = pd.DataFrame(result['data']) |
| 55 | + return df |
| 56 | + else: |
| 57 | + raise Exception( |
| 58 | + f'Failed to fetch data: {response.status_code} - {response.text}' |
| 59 | + ) |
0 commit comments