toddrob99 / MLB-StatsAPI

Python wrapper for MLB Stats API
GNU General Public License v3.0
533 stars 100 forks source link

How to get minor league stats? #87

Closed ForceConstant closed 2 years ago

ForceConstant commented 2 years ago

Seems that player_stat_data() only returns major league stats, how can I get current season stats for a minor leaguer?

toddrob99 commented 2 years ago

Using player_stat_data() you can currently only get MLB stats. You can get MiLB stats using the MLB-StatsAPI module, but you will have to recreate what player_stat_data() is doing with a small modification to add sportId to the hydrate parameter. You will need to provide a sportId (see: https://statsapi.mlb.com/api/v1/sports), e.g. 11 for AAA, 12 for AA, 13 for A+.

def player_stat_data_modified(personId, group="[hitting,pitching,fielding]", type="season", sportId=1):
    """Returns a list of current season or career stat data for a given player."""
    params = {
        "personId": personId,
        "hydrate": "stats(group=" + group + ",type=" + type + ",sportId=" + str(sportId) + "),currentTeam",
    }
    r = statsapi.get("person", params)

    stat_groups = []

    player = {
        "id": r["people"][0]["id"],
        "first_name": r["people"][0]["useName"],
        "last_name": r["people"][0]["lastName"],
        "active": r["people"][0]["active"],
        "current_team": r["people"][0]["currentTeam"]["name"],
        "position": r["people"][0]["primaryPosition"]["abbreviation"],
        "nickname": r["people"][0].get("nickName"),
        "last_played": r["people"][0].get("lastPlayedDate"),
        "mlb_debut": r["people"][0].get("mlbDebutDate"),
        "bat_side": r["people"][0]["batSide"]["description"],
        "pitch_hand": r["people"][0]["pitchHand"]["description"],
    }

    for s in r["people"][0].get("stats", []):
        for i in range(0, len(s["splits"])):
            stat_group = {
                "type": s["type"]["displayName"],
                "group": s["group"]["displayName"],
                "season": s["splits"][i].get("season"),
                "stats": s["splits"][i]["stat"],
            }
            stat_groups.append(stat_group)

    player.update({"stats": stat_groups})

    return player

personId = 691725  # Andrew Painter
sportId = 13  # A+
painter = player_stat_data_modified(691725, sportId=13)

I will add the sportId parameter (with default value of 1) to player_stat_data() in the next version, at which point you will be able to do statsapi.player_stat_data(691725, sportId=13).

toddrob99 commented 2 years ago

v1.5 is available on pypi now (pip install --upgrade mlb-statsapi)

ForceConstant commented 2 years ago

Great thanks