Skip to content

Commit 56642eb

Browse files
committed
build out player_stats()
1 parent d5fb0c9 commit 56642eb

File tree

2 files changed

+102
-5
lines changed

2 files changed

+102
-5
lines changed

README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,3 +114,11 @@ use `statsapi.league_leaders()`
114114
```
115115
print(statsapi.league_leaders('doubles',statGroup='hitting',limit=10))
116116
```
117+
118+
### Print Chase Utley's career hitting stats
119+
120+
use `statsapi.get()` to call the sports_players endpoint for the 2008 World Series,
121+
lookup Chase Utley's person id from the results, and pass it into `statsapi.player_stats()`
122+
using `type='hitting'` and `group='career'`
123+
124+
print( statsapi.player_stats(next(x['id'] for x in statsapi.get('sports_players',{'season':2008,'gameType':'W'})['people'] if x['fullName']=='Chase Utley'), 'hitting', 'career') )

statsapi/__init__.py

Lines changed: 94 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -621,14 +621,103 @@ def linescore(gamePk,timecode=None):
621621

622622
return linescore
623623

624-
def player_stats(personId):
625-
"""Get stats for a given player.
624+
def player_stats(personId,group='[hitting,pitching,fielding]',type='season'):
625+
"""Get current season or career stats for a given player.
626+
627+
For group use 'hitting', 'pitching', or 'fielding'.
628+
Include multiple groups in the following format (this is a string, not actually a list):
629+
group='[hitting,pitching]'
630+
631+
For type use 'career' or 'season'.
632+
Include multiple types in the following format (this is a string, not actually a list):
633+
group='[career,season]'
634+
635+
Example use:
636+
637+
Print Chase Utley's career hitting stats (using sports_players endpoint to look up person id)
638+
639+
print( statsapi.player_stats(next(x['id'] for x in statsapi.get('sports_players',{'season':2008,'gameType':'W'})['people'] if x['fullName']=='Chase Utley'), 'hitting', 'career') )
640+
641+
Output:
642+
643+
Chase "Silver Fox" Utley, 2B (2003-2018)
644+
645+
Career Hitting
646+
gamesPlayed: 1937
647+
groundOuts: 1792
648+
runs: 1103
649+
doubles: 411
650+
triples: 58
651+
homeRuns: 259
652+
strikeOuts: 1193
653+
baseOnBalls: 724
654+
intentionalWalks: 62
655+
hits: 1885
656+
hitByPitch: 204
657+
avg: .275
658+
atBats: 6857
659+
obp: .358
660+
slg: .465
661+
ops: .823
662+
caughtStealing: 22
663+
stolenBases: 154
664+
groundIntoDoublePlay: 93
665+
numberOfPitches: 31043
666+
plateAppearances: 7863
667+
totalBases: 3189
668+
rbi: 1025
669+
leftOnBase: 2780
670+
sacBunts: 6
671+
sacFlies: 72
672+
babip: .297
673+
groundOutsToAirouts: 0.84
626674
"""
627-
r = get('person',{'personId':personId})
675+
params = {'personId':personId,'hydrate':'stats(group='+group+',type='+type+'),currentTeam'}
676+
r = get('person',params)
677+
678+
stats = ''
679+
stat_groups = []
680+
681+
bio = {
682+
'id' : r['people'][0]['id'],
683+
'first_name' : r['people'][0]['useName'],
684+
'last_name' : r['people'][0]['lastName'],
685+
'active' : r['people'][0]['active'],
686+
'current_team' : r['people'][0]['currentTeam']['name'],
687+
'position' : r['people'][0]['primaryPosition']['abbreviation'],
688+
'nickname' : r['people'][0].get('nickName'),
689+
'active' : r['people'][0]['active'],
690+
'last_played' : r['people'][0].get('lastPlayedDate'),
691+
'mlb_debut' : r['people'][0]['mlbDebutDate'],
692+
'bat_side' : r['people'][0]['batSide']['description'],
693+
'pitch_hand' : r['people'][0]['pitchHand']['description']
694+
}
695+
696+
for s in r['people'][0].get('stats',[]):
697+
stat_group = {
698+
'type' : s['type']['displayName'],
699+
'group' : s['group']['displayName'],
700+
'stats' : s['splits'][0]['stat'] #there should only be one item in the list for career stats
701+
}
702+
stat_groups.append(stat_group)
628703

629-
704+
if len(stat_groups)==0:
705+
raise ValueError('No stats found for given player, type, and group.')
706+
707+
stats += bio['first_name']
708+
if bio['nickname']: stats += ' "{nickname}"'.format(**bio)
709+
stats += ' {last_name}, {position} ({mlb_debut:.4}-'.format(**bio)
710+
if not bio['active']: stats += '{last_played:.4}'.format(**bio)
711+
stats += ')\n\n'
712+
713+
for x in stat_groups:
714+
stats += x['type'][0:1].upper() + x['type'][1:] + ' ' + x['group'][0:1].upper() + x['group'][1:] + '\n'
715+
for y in x['stats'].keys():
716+
if y=='position': continue
717+
stats += '{}: {}\n'.format(y,x['stats'][y])
718+
stats += '\n'
630719

631-
return "This function is not yet available."
720+
return stats
632721

633722
def team_leaders(teamId,leaderCategories,season=datetime.now().year,leaderGameTypes='R',limit=10):
634723
"""Get stat leaders for a given team.

0 commit comments

Comments
 (0)