Ejemplo n.º 1
0
def getHittingData(batterID):
    try:
        r = statsapi.player_stat_data(batterID, group="hitting",
                                      type="career")["stats"][0]['stats']
        return [r['avg'], r['slg'], r['strikeOuts']]
    except IndexError:
        return None
Ejemplo n.º 2
0
def getPitchingData(pitcherID):
    try:
        r = statsapi.player_stat_data(pitcherID,
                                      group="pitching",
                                      type="career")['stats'][0]['stats']
        return [r['avg'], r['obp'], r['homeRunsPer9']]
    except IndexError:
        return None
Ejemplo n.º 3
0
 def setYearlyPlayerStats(self):
     for years in statsapi.player_stat_data(self._playerID,
                                            type='yearByYear')['stats']:
         if (years.get('group') == self._playerStats[str(
                 self._playerID)]['type']):
             statsDict = {}
             statsDict[years.get('season')] = years.get('stats')
             self._playerStats[str(self._playerID)][years.get(
                 'season')] = statsDict[years.get('season')]
Ejemplo n.º 4
0
def get_total_errors(player_id):
    fielding_stats = statsapi.player_stat_data(player_id,
                                               group="[fielding]",
                                               type="[season]")
    try:
        total_errors = fielding_stats.get("stats")[0].get("stats").get(
            "errors")
    except IndexError:
        total_errors = 0
    return total_errors
Ejemplo n.º 5
0
    def post(self, request):
        data = request.data["action"]

        last_url = request.get_full_path().split("/")[-1]
        if last_url == "pitcher-stat":
            position = "pitcher"
        else:
            position = "hitter"

        with open(f"configure_package/available_{position}_stats.json"
                  ) as pitcher_json:
            available_pitcher_stats = json.load(pitcher_json)
        request_stat = data["parameters"][f"{position}_stat"]["value"]
        player = data["parameters"][position]["value"]

        player_stat = available_pitcher_stats[request_stat]

        return_stat = statsapi.player_stat_data(
            self.player_id[player], self.default_group[player],
            "season")["stats"][0]["stats"][player_stat]
        if type(return_stat) is str:
            return_stat = float(return_stat)
        else:
            return_stat = str(return_stat) + "회"

        if position == "pitcher":
            response_builder = {
                "version": "2.0",
                "resultCode": "OK",
                "output": {
                    "pitcher": player,
                    "pitcher_stat": request_stat,
                    "return_pitcher_stat": return_stat,
                },
            }
        else:
            response_builder = {
                "version": "2.0",
                "resultCode": "OK",
                "output": {
                    "hitter": player,
                    "hitter_stat": request_stat,
                    "return_hitter_stat": return_stat,
                },
            }
        return Response(response_builder)
Ejemplo n.º 6
0
def generatePlayer(lookup_value, year, playerId=None):
	"""
		returns a Player object based on lookup_vaue and year
		currently creates a Player object based on career stats, switch to year
	"""
	if playerId == None:
		playerId = findPlayer(lookup_value, year)

	playerData = statsapi.player_stat_data(playerId, type="yearByYear")
	# get player data
	playerName = "{} {}".format(playerData['first_name'], playerData['last_name'])
	playerPosition = playerData['position']
	outfieldPositions = ["RF", "CF", "LF"]
	if playerPosition in outfieldPositions:
		playerPosition = "OF"

	isPitcher = playerPosition == "P"
	playerStatGroup = "pitching" if isPitcher else "hitting"

	playerStats = None
	for statGroup in playerData['stats']:
		if statGroup['season'] == str(year) and statGroup['group'] == playerStatGroup:
			playerStats = statGroup['stats']
		
	plateAppearences = playerStats['battersFaced'] if playerPosition == "P" else playerStats['plateAppearances']
	playerStatsSimple = {
		"PA": plateAppearences,
		"1B": playerStats['hits'] - playerStats['doubles'] - playerStats['triples'] - playerStats['homeRuns'], # Hits - 2B - 3B - HR
		"2B": playerStats['doubles'],
		"3B": playerStats['triples'],
		"HR": playerStats['homeRuns'],
		"SO": playerStats['strikeOuts'],
		"BB": playerStats['baseOnBalls'],
		"HBP": playerStats['hitByPitch'],
		"HitOut": plateAppearences - playerStats['baseOnBalls'] - playerStats['hitByPitch'] - playerStats['hits'] - playerStats['strikeOuts']# PA - BB - HBP - Hits - SO
	}

	startingPitcher = False
	if playerPosition == "P":
		gamesPlayed = playerStats['gamesPlayed']
		gamesStarted = playerStats['gamesStarted']
		if gamesStarted >= gamesPlayed * .6:
			startingPitcher = True
	playerObject = Player(playerName, playerPosition, year, playerStatsSimple, startingPitcher=startingPitcher)
	return playerObject
Ejemplo n.º 7
0
def get_player_data(name, group="hitting", lookupyear=None):
    if lookupyear is not None:
        players = statsapi.lookup_player(name, season=lookupyear)
    else:
        for year in range(2020, 1900, -1):
            players = statsapi.lookup_player(name, season=year)
            if len(players) > 0:
                break
    if len(players) > 1:
        print("Results are not unique")
        return None
    elif len(players) == 0:
        print("No results")
        return None

    pid = players[0]["id"]
    data = statsapi.player_stat_data(pid, group, type="yearByYear")

    df = pd.DataFrame(buildyears(data))
    df = df.rename(columns=trans)

    return df
Ejemplo n.º 8
0
def lambda_handler(event, context):
    player_name = event['queryStringParameters']['player_name']
    year = event['queryStringParameters']['year']
    stat_group = event['queryStringParameters']['stat_group']

    print('Started to retrieve player data for player {} in year {}'.format(player_name, year))
    updated_year = 'career' if ('~' == year) else 'yearByYear'
    formatted_stat_group = '[{0}]'.format(stat_group)
    last_year = datetime.now().year - 1 # Cant use current year until season starts

    person_id = statsapi.lookup_player(player_name, season=last_year)[0].get('id')
    player_data = statsapi.player_stat_data(person_id, group=formatted_stat_group, type=updated_year)

    if updated_year == 'yearByYear':
        filtered_year_list = [stat_year for stat_year in player_data.get('stats') if stat_year.get('season') == year]
        player_data['stats'] = filtered_year_list

    print('Successfully Returning player data for player {}'.format(player_name))
    return {
        'statusCode': 200,
        'body': json.dumps(player_data)
    }
Ejemplo n.º 9
0
    def handle(self, *args, **options):

        # self.update_team()
        # # PitcherStats.objects.all().delete()
        # # HitterStats.objects.all().delete()
        players = Player.objects.all()

        for player in players:

            if ("P" in player.position):
                group = "pitching"
            else:
                group = "hitting"

            stats = statsapi.player_stat_data(personId=player.player_id,
                                              group=group,
                                              type='yearByYear')
            start_season = int(stats['mlb_debut'].split("-")[0])

            season = start_season
            for player_season in stats['stats']:
                dummy_team = Team.objects.get(team_id=108)

                if (group == "hitting"):
                    player_id_and_season = str(player.player_id) + str(season)
                    games = player_season['stats']['gamesPlayed']
                    # hitter = HitterStats.objects.get(player_id_and_season=player_id_and_season)
                    # hitter.games = games
                    # hitter.save(update_fields=["games"])
                    # print("Success")
                    plate_appearances = player_season['stats'][
                        'plateAppearances']
                    at_bats = player_season['stats']['atBats']
                    runs = player_season['stats']['runs']
                    hits = player_season['stats']['hits']
                    doubles = player_season['stats']['doubles']
                    triples = player_season['stats']['triples']
                    home_runs = player_season['stats']['homeRuns']
                    runs_batted_in = player_season['stats']['rbi']
                    stolen_bases = player_season['stats']['stolenBases']
                    caught_stealing = player_season['stats']['caughtStealing']
                    strikeouts = player_season['stats']['strikeOuts']
                    batting_average = player_season['stats']['avg']
                    obp = player_season['stats']['obp']
                    slg = player_season['stats']['slg']
                    ops = player_season['stats']['ops']
                    new_hitter = HitterStats(
                        team=dummy_team,
                        games=games,
                        player_id_and_season=player_id_and_season,
                        player=player,
                        season=season,
                        plate_appearances=plate_appearances,
                        at_bats=at_bats,
                        runs=runs,
                        hits=hits,
                        doubles=doubles,
                        triples=triples,
                        home_runs=home_runs,
                        runs_batted_in=runs_batted_in,
                        stolen_bases=stolen_bases,
                        caught_stealing=caught_stealing,
                        strikeouts=strikeouts,
                        batting_average=batting_average,
                        obp=obp,
                        slg=slg,
                        ops=ops)
                    new_hitter.save()
                    print("Successfully saved")

                else:
                    player_id_and_season = str(player.player_id) + str(season)
                    games_played = player_season['stats']['gamesPlayed']
                    games_started = player_season['stats']['gamesStarted']
                    wins = player_season['stats']['wins']
                    losses = player_season['stats']['losses']
                    era = player_season['stats']['era']
                    games_finished = player_season['stats']['gamesFinished']
                    complete_games = player_season['stats']['completeGames']
                    shutouts = player_season['stats']['shutouts']
                    saves = player_season['stats']['saves']
                    innings_pitched = player_season['stats']['inningsPitched']
                    hits = player_season['stats']['hits']
                    runs = player_season['stats']['runs']
                    earned_runs = player_season['stats']['earnedRuns']
                    home_runs = player_season['stats']['homeRuns']
                    walks = player_season['stats']['baseOnBalls']
                    strikeouts = player_season['stats']['strikeOuts']
                    whip = player_season['stats']['whip']
                    new_pitcher = PitcherStats(
                        team=dummy_team,
                        player_id_and_season=player_id_and_season,
                        player=player,
                        season=season,
                        games_played=games_played,
                        games_started=games_started,
                        wins=wins,
                        losses=losses,
                        era=era,
                        games_finished=games_finished,
                        complete_games=complete_games,
                        shutouts=shutouts,
                        saves=saves,
                        innings_pitched=innings_pitched,
                        hits=hits,
                        runs=runs,
                        earned_runs=earned_runs,
                        home_runs=home_runs,
                        walks=walks,
                        strikeouts=strikeouts,
                        whip=whip)
                    new_pitcher.save()
                    print("Successfully Saved")
                season += 1
        self.update_team()
Ejemplo n.º 10
0
async def pstats(ctx, *, args):
    players = statsapi.lookup_player(args)
    if (len(players)) == 0:
        await ctx.send("I couldn't find anyone with that name.")
    elif (len(players)) > 1:
        allPlayers = "Found %s players\n" % (len(players))
        for x in players:
            allPlayers = allPlayers + (x['fullName']) + "\n"
        await ctx.send(allPlayers)
    else:
        player = players[0]
        title = "%s | %s - %s" % (player['primaryNumber'], player['fullName'],
                                  player['primaryPosition']['abbreviation'])
        playerStats = statsapi.player_stat_data(player['id'],
                                                group="[pitching]",
                                                type="season")
        team = playerStats['current_team']
        stats = playerStats['stats']
        if (len(stats)) == 0:
            await ctx.send("I don't have any data for that player.")
        else:
            stats = stats[0]['stats']
            record = "%s - %s (%s)" % (stats['wins'], stats['losses'],
                                       stats['saves'])
            embed = createEmbed(title, team)
            embed.add_field(name="Record", value=record, inline=True)
            embed.add_field(name="Saves", value=stats['saves'], inline=True)
            embed.add_field(name="ERA", value=stats['era'], inline=True)
            embed.add_field(name="WHIP", value=stats['whip'], inline=True)
            embed.add_field(
                name="Opp. Batting",
                value=(
                    "%s/%s/%s/%s" %
                    (stats['avg'], stats['obp'], stats['slg'], stats['ops'])),
                inline=True)
            embed.add_field(name="Earned Runs",
                            value=stats['earnedRuns'],
                            inline=True)
            embed.add_field(name="Innings Pitched",
                            value=stats['inningsPitched'],
                            inline=True)
            embed.add_field(name="Hits", value=stats['hits'], inline=True)
            embed.add_field(name="Walks",
                            value=stats['baseOnBalls'],
                            inline=True)
            embed.add_field(name="Homeruns",
                            value=stats['homeRuns'],
                            inline=True)
            embed.add_field(name="Strikeouts",
                            value=stats['strikeOuts'],
                            inline=True)
            embed.add_field(name="Strike %",
                            value=stats['strikePercentage'],
                            inline=True)
            embed.add_field(name="Pitches/Inning",
                            value=stats['pitchesPerInning'],
                            inline=True)
            embed.add_field(name="K/BB Ratio",
                            value=stats['strikeoutWalkRatio'],
                            inline=True)
            embed.add_field(name="K/9",
                            value=stats['strikeoutsPer9Inn'],
                            inline=True)
            embed.add_field(name="BB/9",
                            value=stats['walksPer9Inn'],
                            inline=True)
            embed.add_field(name="Hits/9",
                            value=stats['hitsPer9Inn'],
                            inline=True)
            embed.add_field(name="HR/9",
                            value=stats['homeRunsPer9'],
                            inline=True)
            await ctx.send(embed=embed)
Ejemplo n.º 11
0
async def stats(ctx, *, args):
    players = statsapi.lookup_player(args)
    if (len(players)) == 0:
        await ctx.send("I couldn't find anyone with that name.")
    elif (len(players)) > 1:
        allPlayers = "Found %s players\n" % (len(players))
        for x in players:
            allPlayers = allPlayers + (x['fullName']) + "\n"
        await ctx.send(allPlayers)
    else:
        player = players[0]
        title = "%s | %s - %s" % (player['primaryNumber'], player['fullName'],
                                  player['primaryPosition']['abbreviation'])
        playerStats = statsapi.player_stat_data(player['id'],
                                                group="[hitting]",
                                                type="season")
        team = playerStats['current_team']
        stats = playerStats['stats']
        if (len(stats)) == 0:
            await ctx.send("I don't have any data for that player.")
        else:
            print(stats)
            stats = stats[0]['stats']
            embed = createEmbed(title, team)
            embed.add_field(
                name="AVG/OBP/SLG/OPS",
                value=(
                    "%s/%s/%s/%s" %
                    (stats['avg'], stats['obp'], stats['slg'], stats['ops'])),
                inline=False)
            embed.add_field(name="Games Played",
                            value=stats['gamesPlayed'],
                            inline=True)
            embed.add_field(name="Runs", value=stats['runs'], inline=True)
            embed.add_field(name="RBIs", value=stats['rbi'], inline=True)
            embed.add_field(name="BABIP", value=stats['babip'], inline=True)
            embed.add_field(name="ABs", value=stats['atBats'], inline=True)
            embed.add_field(name="PAs",
                            value=stats['plateAppearances'],
                            inline=True)
            embed.add_field(name="Hits", value=stats['hits'], inline=True)
            embed.add_field(name="BB", value=stats['baseOnBalls'], inline=True)
            embed.add_field(name="HRs", value=stats['homeRuns'], inline=True)
            embed.add_field(name="Triples",
                            value=stats['triples'],
                            inline=True)
            embed.add_field(name="Doubles",
                            value=stats['doubles'],
                            inline=True)
            embed.add_field(name="IBB",
                            value=stats['intentionalWalks'],
                            inline=True)
            embed.add_field(name="HBP", value=stats['hitByPitch'], inline=True)
            embed.add_field(name="Total Bases",
                            value=stats['totalBases'],
                            inline=True)
            embed.add_field(name="Strikeouts",
                            value=stats['strikeOuts'],
                            inline=True)
            embed.add_field(name="LOB", value=stats['leftOnBase'], inline=True)
            embed.add_field(name="Stolen Bases",
                            value=stats['stolenBases'],
                            inline=True)
            embed.add_field(name="SB %",
                            value=stats['stolenBasePercentage'],
                            inline=True)
            await ctx.send(embed=embed)