-
-
Notifications
You must be signed in to change notification settings - Fork 97
/
__init__.py
1768 lines (1540 loc) · 59.8 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# encoding=utf-8
"""# MLB-StatsAPI
Python wrapper for MLB Stats API
Created by Todd Roberts
https://pypi.org/project/MLB-StatsAPI/
Issues: https://github.com/toddrob99/MLB-StatsAPI/issues
Wiki/Documentation: https://github.com/toddrob99/MLB-StatsAPI/wiki
"""
import sys
import copy
import logging
import requests
from datetime import datetime
from . import version
from . import endpoints
__version__ = version.VERSION
"""Installed version of MLB-StatsAPI"""
BASE_URL = endpoints.BASE_URL
"""Base MLB Stats API URL"""
ENDPOINTS = endpoints.ENDPOINTS
"""MLB Stats API endpoint configuration"""
logger = logging.getLogger("statsapi")
# Python 2 Support Warning
if sys.version_info.major < 3:
logger.warning(
"WARNING: Support for Python 2 has been discontinued. "
"The MLB-StatsAPI module may continue to function, but "
"issues not impacting Python 3 will be closed and support will not be provided."
)
def schedule(
date=None,
start_date=None,
end_date=None,
team="",
opponent="",
sportId=1,
game_id=None,
leagueId=None,
):
"""Get list of games for a given date/range and/or team/opponent."""
if end_date and not start_date:
date = end_date
end_date = None
if start_date and not end_date:
date = start_date
start_date = None
params = {}
if date:
params.update({"date": date})
elif start_date and end_date:
params.update({"startDate": start_date, "endDate": end_date})
if team != "":
params.update({"teamId": str(team)})
if opponent != "":
params.update({"opponentId": str(opponent)})
if game_id:
params.update({"gamePks": game_id})
if leagueId:
params.update({"leagueId": leagueId})
hydrate = (
"decisions,probablePitcher(note),linescore,broadcasts,game(content(media(epg)))"
)
if date == "2014-03-11" or (str(start_date) <= "2014-03-11" <= str(end_date)):
# For some reason the seriesStatus hydration throws a server error on 2014-03-11 only (checked back to 2000)
logger.warning(
"Excluding seriesStatus hydration because the MLB API throws an error for 2014-03-11 which is included in the requested date range."
)
else:
hydrate += ",seriesStatus"
params.update(
{
"sportId": str(sportId),
"hydrate": hydrate,
}
)
r = get("schedule", params)
games = []
if r.get("totalItems") == 0:
return games # TODO: ValueError('No games to parse from schedule object.') instead?
else:
for date in r.get("dates"):
for game in date.get("games"):
game_info = {
"game_id": game["gamePk"],
"game_datetime": game["gameDate"],
"game_date": date["date"],
"game_type": game["gameType"],
"status": game["status"]["detailedState"],
"away_name": game["teams"]["away"]["team"].get("name", "???"),
"home_name": game["teams"]["home"]["team"].get("name", "???"),
"away_id": game["teams"]["away"]["team"]["id"],
"home_id": game["teams"]["home"]["team"]["id"],
"doubleheader": game["doubleHeader"],
"game_num": game["gameNumber"],
"home_probable_pitcher": game["teams"]["home"]
.get("probablePitcher", {})
.get("fullName", ""),
"away_probable_pitcher": game["teams"]["away"]
.get("probablePitcher", {})
.get("fullName", ""),
"home_pitcher_note": game["teams"]["home"]
.get("probablePitcher", {})
.get("note", ""),
"away_pitcher_note": game["teams"]["away"]
.get("probablePitcher", {})
.get("note", ""),
"away_score": game["teams"]["away"].get("score", "0"),
"home_score": game["teams"]["home"].get("score", "0"),
"current_inning": game.get("linescore", {}).get(
"currentInning", ""
),
"inning_state": game.get("linescore", {}).get("inningState", ""),
"venue_id": game.get("venue", {}).get("id"),
"venue_name": game.get("venue", {}).get("name"),
"national_broadcasts": list(
set(
broadcast["name"]
for broadcast in game.get("broadcasts", [])
if broadcast.get("isNational", False)
)
),
"series_status": game.get("seriesStatus", {}).get("result"),
}
if game["content"].get("media", {}).get("freeGame", False):
game_info["national_broadcasts"].append("MLB.tv Free Game")
if game_info["status"] in ["Final", "Game Over"]:
if game.get("isTie"):
game_info.update({"winning_team": "Tie", "losing_Team": "Tie"})
else:
game_info.update(
{
"winning_team": (
game["teams"]["away"]["team"].get("name", "???")
if game["teams"]["away"].get("isWinner")
else game["teams"]["home"]["team"].get(
"name", "???"
)
),
"losing_team": (
game["teams"]["home"]["team"].get("name", "???")
if game["teams"]["away"].get("isWinner")
else game["teams"]["away"]["team"].get(
"name", "???"
)
),
"winning_pitcher": game.get("decisions", {})
.get("winner", {})
.get("fullName", ""),
"losing_pitcher": game.get("decisions", {})
.get("loser", {})
.get("fullName", ""),
"save_pitcher": game.get("decisions", {})
.get("save", {})
.get("fullName"),
}
)
summary = (
date["date"]
+ " - "
+ game["teams"]["away"]["team"].get("name", "???")
+ " ("
+ str(game["teams"]["away"].get("score", ""))
+ ") @ "
+ game["teams"]["home"]["team"].get("name", "???")
+ " ("
+ str(game["teams"]["home"].get("score", ""))
+ ") ("
+ game["status"]["detailedState"]
+ ")"
)
game_info.update({"summary": summary})
elif game_info["status"] == "In Progress":
game_info.update(
{
"summary": date["date"]
+ " - "
+ game["teams"]["away"]["team"]["name"]
+ " ("
+ str(game["teams"]["away"].get("score", "0"))
+ ") @ "
+ game["teams"]["home"]["team"]["name"]
+ " ("
+ str(game["teams"]["home"].get("score", "0"))
+ ") ("
+ game["linescore"]["inningState"]
+ " of the "
+ game["linescore"]["currentInningOrdinal"]
+ ")"
}
)
else:
summary = (
date["date"]
+ " - "
+ game["teams"]["away"]["team"]["name"]
+ " @ "
+ game["teams"]["home"]["team"]["name"]
+ " ("
+ game["status"]["detailedState"]
+ ")"
)
game_info.update({"summary": summary})
games.append(game_info)
return games
def boxscore(
gamePk,
battingBox=True,
battingInfo=True,
fieldingInfo=True,
pitchingBox=True,
gameInfo=True,
timecode=None,
):
"""Get a formatted boxscore for a given game."""
boxData = boxscore_data(gamePk, timecode)
rowLen = 79
"""rowLen is the total width of each side of the box score, excluding the " | " separator"""
fullRowLen = rowLen * 2 + 3
"""fullRowLen is the full table width"""
boxscore = ""
"""boxscore will hold the string to be returned"""
if battingBox:
# Add column headers
awayBatters = boxData["awayBatters"]
homeBatters = boxData["homeBatters"]
# Make sure the home and away batter lists are the same length
blankBatter = {
"namefield": "",
"ab": "",
"r": "",
"h": "",
"rbi": "",
"bb": "",
"k": "",
"lob": "",
"avg": "",
"ops": "",
}
while len(awayBatters) > len(homeBatters):
homeBatters.append(blankBatter)
while len(awayBatters) < len(homeBatters):
awayBatters.append(blankBatter)
# Get team totals
awayBatters.append(boxData["awayBattingTotals"])
homeBatters.append(boxData["homeBattingTotals"])
# Build the batting box!
for i in range(0, len(awayBatters)):
if i == 0 or i == len(awayBatters) - 1:
boxscore += "-" * rowLen + " | " + "-" * rowLen + "\n"
boxscore += "{namefield:<40} {ab:^3} {r:^3} {h:^3} {rbi:^3} {bb:^3} {k:^3} {lob:^3} {avg:^4} {ops:^5} | ".format(
**awayBatters[i]
)
boxscore += "{namefield:<40} {ab:^3} {r:^3} {h:^3} {rbi:^3} {bb:^3} {k:^3} {lob:^3} {avg:^4} {ops:^5}\n".format(
**homeBatters[i]
)
if i == 0 or i == len(awayBatters) - 1:
boxscore += "-" * rowLen + " | " + "-" * rowLen + "\n"
# Get batting notes
awayBattingNotes = boxData["awayBattingNotes"]
homeBattingNotes = boxData["homeBattingNotes"]
while len(awayBattingNotes) > len(homeBattingNotes):
homeBattingNotes.update({len(homeBattingNotes): ""})
while len(awayBattingNotes) < len(homeBattingNotes):
awayBattingNotes.update({len(awayBattingNotes): ""})
for i in range(0, len(awayBattingNotes)):
boxscore += "{:<79} | ".format(awayBattingNotes[i])
boxscore += "{:<79}\n".format(homeBattingNotes[i])
boxscore += " " * rowLen + " | " + " " * rowLen + "\n"
# Get batting and fielding info
awayBoxInfo = {}
homeBoxInfo = {}
boxInfo = [awayBoxInfo, homeBoxInfo]
sides = ["away", "home"]
for infoType in ["BATTING", "FIELDING"]:
if (infoType == "BATTING" and battingInfo) or (
infoType == "FIELDING" and fieldingInfo
):
for i in range(0, len(sides)):
for z in (
x for x in boxData[sides[i]]["info"] if x.get("title") == infoType
):
boxInfo[i].update({len(boxInfo[i]): z["title"]})
for x in z["fieldList"]:
if len(x["label"] + ": " + x.get("value", "")) > rowLen:
words = iter(
(x["label"] + ": " + x.get("value", "")).split()
)
check = ""
lines = []
for word in words:
if len(check) + 1 + len(word) <= rowLen:
if check == "":
check = word
else:
check += " " + word
else:
lines.append(check)
check = " " + word
if len(check):
lines.append(check)
for j in range(0, len(lines)):
boxInfo[i].update({len(boxInfo[i]): lines[j]})
else:
boxInfo[i].update(
{
len(boxInfo[i]): x["label"]
+ ": "
+ x.get("value", "")
}
)
if infoType == "BATTING":
if len(awayBoxInfo):
awayBoxInfo.update({len(awayBoxInfo): " "})
if len(homeBoxInfo):
homeBoxInfo.update({len(homeBoxInfo): " "})
if len(awayBoxInfo) > 0:
while len(awayBoxInfo) > len(homeBoxInfo):
homeBoxInfo.update({len(homeBoxInfo): ""})
while len(awayBoxInfo) < len(homeBoxInfo):
awayBoxInfo.update({len(awayBoxInfo): ""})
# Build info box
for i in range(0, len(awayBoxInfo)):
boxscore += ("{:<%s} | " % rowLen).format(awayBoxInfo[i])
boxscore += ("{:<%s}\n" % rowLen).format(homeBoxInfo[i])
if i == len(awayBoxInfo) - 1:
boxscore += "-" * rowLen + " | " + "-" * rowLen + "\n"
# Get pitching box
if pitchingBox:
awayPitchers = boxData["awayPitchers"]
homePitchers = boxData["homePitchers"]
# Make sure the home and away pitcher lists are the same length
blankPitcher = {
"namefield": "",
"ip": "",
"h": "",
"r": "",
"er": "",
"bb": "",
"k": "",
"hr": "",
"era": "",
}
while len(awayPitchers) > len(homePitchers):
homePitchers.append(blankPitcher)
while len(awayPitchers) < len(homePitchers):
awayPitchers.append(blankPitcher)
# Get team totals
awayPitchers.append(boxData["awayPitchingTotals"])
homePitchers.append(boxData["homePitchingTotals"])
# Build the pitching box!
for i in range(0, len(awayPitchers)):
if i == 0 or i == len(awayPitchers) - 1:
boxscore += "-" * rowLen + " | " + "-" * rowLen + "\n"
boxscore += "{namefield:<43} {ip:^4} {h:^3} {r:^3} {er:^3} {bb:^3} {k:^3} {hr:^3} {era:^6} | ".format(
**awayPitchers[i]
)
boxscore += "{namefield:<43} {ip:^4} {h:^3} {r:^3} {er:^3} {bb:^3} {k:^3} {hr:^3} {era:^6}\n".format(
**homePitchers[i]
)
if i == 0 or i == len(awayPitchers) - 1:
boxscore += "-" * rowLen + " | " + "-" * rowLen + "\n"
# Get game info
if gameInfo:
z = boxData["gameBoxInfo"]
gameBoxInfo = {}
for x in z:
if (
len(x["label"] + (": " if x.get("value") else "") + x.get("value", ""))
> fullRowLen
):
words = iter(
(
x["label"]
+ (": " if x.get("value") else "")
+ x.get("value", "")
).split()
)
check = ""
lines = []
for word in words:
if len(check) + 1 + len(word) <= fullRowLen:
if check == "":
check = word
else:
check += " " + word
else:
lines.append(check)
check = " " + word
if len(check):
lines.append(check)
for i in range(0, len(lines)):
gameBoxInfo.update({len(gameBoxInfo): lines[i]})
else:
gameBoxInfo.update(
{
len(gameBoxInfo): x["label"]
+ (": " if x.get("value") else "")
+ x.get("value", "")
}
)
# Build the game info box
for i in range(0, len(gameBoxInfo)):
boxscore += ("{:<%s}" % fullRowLen + "\n").format(gameBoxInfo[i])
if i == len(gameBoxInfo) - 1:
boxscore += "-" * fullRowLen + "\n"
return boxscore
def boxscore_data(gamePk, timecode=None):
"""Returns a python dict containing boxscore data for a given game."""
boxData = {}
"""boxData holds the dict to be returned"""
params = {
"gamePk": gamePk,
"fields": "gameData,game,teams,teamName,shortName,teamStats,batting,atBats,runs,hits,doubles,triples,homeRuns,rbi,stolenBases,strikeOuts,baseOnBalls,leftOnBase,pitching,inningsPitched,earnedRuns,homeRuns,players,boxscoreName,liveData,boxscore,teams,players,id,fullName,allPositions,abbreviation,seasonStats,batting,avg,ops,obp,slg,era,pitchesThrown,numberOfPitches,strikes,battingOrder,info,title,fieldList,note,label,value,wins,losses,holds,blownSaves",
}
if timecode:
params.update({"timecode": timecode})
r = get("game", params)
boxData.update({"gameId": r["gameData"]["game"]["id"]})
boxData.update({"teamInfo": r["gameData"]["teams"]})
boxData.update({"playerInfo": r["gameData"]["players"]})
boxData.update({"away": r["liveData"]["boxscore"]["teams"]["away"]})
boxData.update({"home": r["liveData"]["boxscore"]["teams"]["home"]})
batterColumns = [
{
"namefield": boxData["teamInfo"]["away"]["teamName"] + " Batters",
"ab": "AB",
"r": "R",
"h": "H",
"doubles": "2B",
"triples": "3B",
"hr": "HR",
"rbi": "RBI",
"sb": "SB",
"bb": "BB",
"k": "K",
"lob": "LOB",
"avg": "AVG",
"ops": "OPS",
"personId": 0,
"substitution": False,
"note": "",
"name": boxData["teamInfo"]["away"]["teamName"] + " Batters",
"position": "",
"obp": "OBP",
"slg": "SLG",
"battingOrder": "",
}
]
# Add away and home column headers
sides = ["away", "home"]
awayBatters = copy.deepcopy(batterColumns)
homeBatters = copy.deepcopy(batterColumns)
homeBatters[0]["namefield"] = boxData["teamInfo"]["home"]["teamName"] + " Batters"
homeBatters[0]["name"] = boxData["teamInfo"]["home"]["teamName"] + " Batters"
batters = [awayBatters, homeBatters]
for i in range(0, len(sides)):
side = sides[i]
for batterId_int in [
x
for x in boxData[side]["batters"]
if boxData[side]["players"].get("ID" + str(x), {}).get("battingOrder")
]:
batterId = str(batterId_int)
namefield = (
str(boxData[side]["players"]["ID" + batterId]["battingOrder"])[0]
if str(boxData[side]["players"]["ID" + batterId]["battingOrder"])[-1]
== "0"
else " "
)
namefield += " " + boxData[side]["players"]["ID" + batterId]["stats"][
"batting"
].get("note", "")
namefield += (
boxData["playerInfo"]["ID" + batterId]["boxscoreName"]
+ " "
+ boxData[side]["players"]["ID" + batterId]["position"]["abbreviation"]
)
if not len(
boxData[side]["players"]["ID" + batterId]
.get("stats", {})
.get("batting", {})
):
# Protect against player with no batting data in the box score (#37)
continue
batter = {
"namefield": namefield,
"ab": str(
boxData[side]["players"]["ID" + batterId]["stats"]["batting"][
"atBats"
]
),
"r": str(
boxData[side]["players"]["ID" + batterId]["stats"]["batting"][
"runs"
]
),
"h": str(
boxData[side]["players"]["ID" + batterId]["stats"]["batting"][
"hits"
]
),
"doubles": str(
boxData[side]["players"]["ID" + batterId]["stats"]["batting"][
"doubles"
]
),
"triples": str(
boxData[side]["players"]["ID" + batterId]["stats"]["batting"][
"triples"
]
),
"hr": str(
boxData[side]["players"]["ID" + batterId]["stats"]["batting"][
"homeRuns"
]
),
"rbi": str(
boxData[side]["players"]["ID" + batterId]["stats"]["batting"]["rbi"]
),
"sb": str(
boxData[side]["players"]["ID" + batterId]["stats"]["batting"][
"stolenBases"
]
),
"bb": str(
boxData[side]["players"]["ID" + batterId]["stats"]["batting"][
"baseOnBalls"
]
),
"k": str(
boxData[side]["players"]["ID" + batterId]["stats"]["batting"][
"strikeOuts"
]
),
"lob": str(
boxData[side]["players"]["ID" + batterId]["stats"]["batting"][
"leftOnBase"
]
),
"avg": str(
boxData[side]["players"]["ID" + batterId]["seasonStats"]["batting"][
"avg"
]
),
"ops": str(
boxData[side]["players"]["ID" + batterId]["seasonStats"]["batting"][
"ops"
]
),
"personId": batterId_int,
"battingOrder": str(
boxData[side]["players"]["ID" + batterId]["battingOrder"]
),
"substitution": (
False
if str(boxData[side]["players"]["ID" + batterId]["battingOrder"])[
-1
]
== "0"
else True
),
"note": boxData[side]["players"]["ID" + batterId]["stats"][
"batting"
].get("note", ""),
"name": boxData["playerInfo"]["ID" + batterId]["boxscoreName"],
"position": boxData[side]["players"]["ID" + batterId]["position"][
"abbreviation"
],
"obp": str(
boxData[side]["players"]["ID" + batterId]["seasonStats"]["batting"][
"obp"
]
),
"slg": str(
boxData[side]["players"]["ID" + batterId]["seasonStats"]["batting"][
"slg"
]
),
}
batters[i].append(batter)
boxData.update({"awayBatters": awayBatters})
boxData.update({"homeBatters": homeBatters})
# Add team totals
sidesBattingTotals = ["awayBattingTotals", "homeBattingTotals"]
for i in range(0, len(sides)):
side = sides[i]
boxData.update(
{
sidesBattingTotals[i]: {
"namefield": "Totals",
"ab": str(boxData[side]["teamStats"]["batting"]["atBats"]),
"r": str(boxData[side]["teamStats"]["batting"]["runs"]),
"h": str(boxData[side]["teamStats"]["batting"]["hits"]),
"hr": str(boxData[side]["teamStats"]["batting"]["homeRuns"]),
"rbi": str(boxData[side]["teamStats"]["batting"]["rbi"]),
"bb": str(boxData[side]["teamStats"]["batting"]["baseOnBalls"]),
"k": str(boxData[side]["teamStats"]["batting"]["strikeOuts"]),
"lob": str(boxData[side]["teamStats"]["batting"]["leftOnBase"]),
"avg": "",
"ops": "",
"obp": "",
"slg": "",
"name": "Totals",
"position": "",
"note": "",
"substitution": False,
"battingOrder": "",
"personId": 0,
}
}
)
# Get batting notes
awayBattingNotes = {}
homeBattingNotes = {}
battingNotes = [awayBattingNotes, homeBattingNotes]
for i in range(0, len(sides)):
for n in boxData[sides[i]]["note"]:
battingNotes[i].update(
{len(battingNotes[i]): n["label"] + "-" + n["value"]}
)
boxData.update({"awayBattingNotes": awayBattingNotes})
boxData.update({"homeBattingNotes": homeBattingNotes})
# Get pitching box
# Add column headers
pitcherColumns = [
{
"namefield": boxData["teamInfo"]["away"]["teamName"] + " Pitchers",
"ip": "IP",
"h": "H",
"r": "R",
"er": "ER",
"bb": "BB",
"k": "K",
"hr": "HR",
"era": "ERA",
"p": "P",
"s": "S",
"name": boxData["teamInfo"]["away"]["teamName"] + " Pitchers",
"personId": 0,
"note": "",
}
]
awayPitchers = copy.deepcopy(pitcherColumns)
homePitchers = copy.deepcopy(pitcherColumns)
homePitchers[0]["namefield"] = boxData["teamInfo"]["home"]["teamName"] + " Pitchers"
homePitchers[0]["name"] = boxData["teamInfo"]["away"]["teamName"] + " Pitchers"
pitchers = [awayPitchers, homePitchers]
for i in range(0, len(sides)):
side = sides[i]
for pitcherId_int in boxData[side]["pitchers"]:
pitcherId = str(pitcherId_int)
if not boxData[side]["players"].get("ID" + pitcherId) or not len(
boxData[side]["players"]["ID" + pitcherId]
.get("stats", {})
.get("pitching", {})
):
# Skip pitcher with no pitching data in the box score (#37)
# Or skip pitcher listed under the wrong team (from comments on #37)
continue
namefield = boxData["playerInfo"]["ID" + pitcherId]["boxscoreName"]
namefield += (
" "
+ boxData[side]["players"]["ID" + pitcherId]["stats"]["pitching"].get(
"note", ""
)
if boxData[side]["players"]["ID" + pitcherId]["stats"]["pitching"].get(
"note"
)
else ""
)
pitcher = {
"namefield": namefield,
"ip": str(
boxData[side]["players"]["ID" + pitcherId]["stats"]["pitching"][
"inningsPitched"
]
),
"h": str(
boxData[side]["players"]["ID" + pitcherId]["stats"]["pitching"][
"hits"
]
),
"r": str(
boxData[side]["players"]["ID" + pitcherId]["stats"]["pitching"][
"runs"
]
),
"er": str(
boxData[side]["players"]["ID" + pitcherId]["stats"]["pitching"][
"earnedRuns"
]
),
"bb": str(
boxData[side]["players"]["ID" + pitcherId]["stats"]["pitching"][
"baseOnBalls"
]
),
"k": str(
boxData[side]["players"]["ID" + pitcherId]["stats"]["pitching"][
"strikeOuts"
]
),
"hr": str(
boxData[side]["players"]["ID" + pitcherId]["stats"]["pitching"][
"homeRuns"
]
),
"p": str(
boxData[side]["players"]["ID" + pitcherId]["stats"]["pitching"].get(
"pitchesThrown",
boxData[side]["players"]["ID" + pitcherId]["stats"][
"pitching"
].get("numberOfPitches", 0),
)
),
"s": str(
boxData[side]["players"]["ID" + pitcherId]["stats"]["pitching"][
"strikes"
]
),
"era": str(
boxData[side]["players"]["ID" + pitcherId]["seasonStats"][
"pitching"
]["era"]
),
"name": boxData["playerInfo"]["ID" + pitcherId]["boxscoreName"],
"personId": pitcherId_int,
"note": boxData[side]["players"]["ID" + pitcherId]["stats"][
"pitching"
].get("note", ""),
}
pitchers[i].append(pitcher)
boxData.update({"awayPitchers": awayPitchers})
boxData.update({"homePitchers": homePitchers})
# Get team totals
pitchingTotals = ["awayPitchingTotals", "homePitchingTotals"]
for i in range(0, len(sides)):
side = sides[i]
boxData.update(
{
pitchingTotals[i]: {
"namefield": "Totals",
"ip": str(boxData[side]["teamStats"]["pitching"]["inningsPitched"]),
"h": str(boxData[side]["teamStats"]["pitching"]["hits"]),
"r": str(boxData[side]["teamStats"]["pitching"]["runs"]),
"er": str(boxData[side]["teamStats"]["pitching"]["earnedRuns"]),
"bb": str(boxData[side]["teamStats"]["pitching"]["baseOnBalls"]),
"k": str(boxData[side]["teamStats"]["pitching"]["strikeOuts"]),
"hr": str(boxData[side]["teamStats"]["pitching"]["homeRuns"]),
"p": "",
"s": "",
"era": "",
"name": "Totals",
"personId": 0,
"note": "",
}
}
)
# Get game info
boxData.update({"gameBoxInfo": r["liveData"]["boxscore"].get("info", [])})
return boxData
def linescore(gamePk, timecode=None):
"""Get formatted linescore for a given game."""
linescore = ""
params = {
"gamePk": gamePk,
"fields": "gameData,teams,teamName,shortName,status,abstractGameState,liveData,linescore,innings,num,home,away,runs,hits,errors",
}
if timecode:
params.update({"timecode": timecode})
r = get("game", params)
header_name = r["gameData"]["status"]["abstractGameState"]
away_name = r["gameData"]["teams"]["away"]["teamName"]
home_name = r["gameData"]["teams"]["home"]["teamName"]
header_row = []
away = []
home = []
for x in r["liveData"]["linescore"]["innings"]:
header_row.append(str(x.get("num", "")))
away.append(str(x.get("away", {}).get("runs", 0)))
home.append(str(x.get("home", {}).get("runs", 0)))
if len(r["liveData"]["linescore"]["innings"]) < 9:
for i in range(len(r["liveData"]["linescore"]["innings"]) + 1, 10):
header_row.append(str(i))
away.append(" ")
home.append(" ")
header_row.extend(["R", "H", "E"])
away_prefix = r["liveData"]["linescore"].get("teams", {}).get("away", {})
away.extend(
[
str(away_prefix.get("runs", 0)),
str(away_prefix.get("hits", 0)),
str(away_prefix.get("errors", 0)),
]
)
home_prefix = r["liveData"]["linescore"].get("teams", {}).get("home", {})
home.extend(
[
str(home_prefix.get("runs", 0)),
str(home_prefix.get("hits", 0)),
str(home_prefix.get("errors", 0)),
]
)
# Build the linescore
for k in [[header_name, header_row], [away_name, away], [home_name, home]]:
linescore += (
"{:<%s}" % str(len(max([header_name, away_name, home_name], key=len)) + 1)
).format(k[0])
linescore += ("{:^2}" * (len(k[1]) - 3)).format(*k[1])
linescore += ("{:^4}" * 3).format(*k[1][-3:])
linescore += "\n"
if len(linescore) > 1:
linescore = linescore[:-1] # strip the extra line break
return linescore
def last_game(teamId):
"""Get the gamePk for the given team's most recent completed game."""
previousSchedule = get(
"team",
{
"teamId": teamId,
"hydrate": "previousSchedule",
"fields": "teams,team,id,previousGameSchedule,dates,date,games,gamePk,gameDate,status,abstractGameCode",
},
)
games = []
for d in previousSchedule["teams"][0]["previousGameSchedule"]["dates"]:
games.extend([x for x in d["games"] if x["status"]["abstractGameCode"] == "F"])
if not len(games):
return None
return games[-1]["gamePk"]
def next_game(teamId):
"""Get the gamePk for the given team's next unstarted game."""
nextSchedule = get(
"team",
{
"teamId": teamId,
"hydrate": "nextSchedule",
"fields": "teams,team,id,nextGameSchedule,dates,date,games,gamePk,gameDate,status,abstractGameCode",
},
)
games = []
for d in nextSchedule["teams"][0]["nextGameSchedule"]["dates"]:
games.extend([x for x in d["games"] if x["status"]["abstractGameCode"] == "P"])
if not len(games):
return None
return games[0]["gamePk"]
def game_scoring_plays(gamePk):
"""Get a text-formatted list of scoring plays for a given game."""
sortedPlays = game_scoring_play_data(gamePk)
scoring_plays = ""
for a in sortedPlays["plays"]:
scoring_plays += "{}\n{} {} - {}: {}, {}: {}\n\n".format(
a["result"]["description"],
a["about"]["halfInning"][0:1].upper() + a["about"]["halfInning"][1:],
a["about"]["inning"],
sortedPlays["away"]["name"],
a["result"]["awayScore"],
sortedPlays["home"]["name"],
a["result"]["homeScore"],
)
if len(scoring_plays) > 1:
scoring_plays = scoring_plays[:-2] # strip the extra line break
return scoring_plays
def game_scoring_play_data(gamePk):
"""Returns a python dict of scoring plays for a given game containing 3 keys:
* home - home team data
* away - away team data
* plays - sorted list of scoring play data
"""
r = get(
"game",
{
"gamePk": gamePk,
"fields": (
"gamePk,link,gameData,game,pk,teams,away,id,name,teamCode,fileCode,"
"abbreviation,teamName,locationName,shortName,home,liveData,plays,"
"allPlays,scoringPlays,scoringPlays,atBatIndex,result,description,"
"awayScore,homeScore,about,halfInning,inning,endTime"
),
},
)
if not len(r["liveData"]["plays"].get("scoringPlays", [])):
return {
"home": r["gameData"]["teams"]["home"],
"away": r["gameData"]["teams"]["away"],
"plays": [],
}
unorderedPlays = {}
for i in r["liveData"]["plays"].get("scoringPlays", []):
play = next(
(p for p in r["liveData"]["plays"]["allPlays"] if p.get("atBatIndex") == i),
None,
)
if play: