-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgamelogs.py
executable file
·279 lines (121 loc) · 5.97 KB
/
gamelogs.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
#hitter + pitcher stats previous 5 game logs
import requests
import pandas as pd
from datetime import datetime, timedelta
# Function to get the previous day's date in YYYY-MM-DD format
def get_previous_date():
yesterday = datetime.now() - timedelta(1)
return yesterday.strftime('%Y-%m-%d')
# Function to fetch and process stats for all hitters and pitchers from the previous day
def fetch_mlb_stats():
previous_date = get_previous_date()
url = f"https://statsapi.mlb.com/api/v1/schedule?sportId=1&date={previous_date}"
response = requests.get(url)
if response.status_code != 200:
print(f"Failed to fetch data: {response.status_code}")
return pd.DataFrame(), pd.DataFrame()
games = response.json().get('dates', [])[0].get('games', [])
batting_stats = []
pitching_stats = []
for game in games:
game_id = game.get('gamePk')
boxscore_url = f"https://statsapi.mlb.com/api/v1/game/{game_id}/boxscore"
boxscore_response = requests.get(boxscore_url)
if boxscore_response.status_code != 200:
continue
boxscore = boxscore_response.json()
for team in ['home', 'away']:
players = boxscore['teams'][team]['players']
for player_id, player_info in players.items():
batting = player_info['stats'].get('batting')
if batting:
batting_stats.append({
'name': player_info['person']['fullName'],
'team': boxscore['teams'][team]['team']['name'],
'hits': batting.get('hits', 0),
'atBats': batting.get('atBats', 0),
'homeRuns': batting.get('homeRuns', 0),
'strikeOuts': batting.get('strikeOuts', 0)
})
pitching = player_info['stats'].get('pitching')
if pitching:
pitching_stats.append({
'name': player_info['person']['fullName'],
'team': boxscore['teams'][team]['team']['name'],
'player_id': player_info['person']['id'],
'hitsAllowed': pitching.get('hits', 0),
'runsAllowed': pitching.get('runs', 0),
'homeRunsAllowed': pitching.get('homeRuns', 0),
'walks': pitching.get('baseOnBalls', 0),
'strikeOuts': pitching.get('strikeOuts', 0),
'outs': pitching.get('outs', 0),
'inningsPitched': pitching.get('inningsPitched', 0)
})
if not batting_stats:
print("No hitting stats found for the previous day.")
if not pitching_stats:
print("No pitching stats found for the previous day.")
# Convert to DataFrame for better readability
batting_df = pd.DataFrame(batting_stats)
pitching_df = pd.DataFrame(pitching_stats)
return batting_df, pitching_df
# Function to fetch recent game logs for a pitcher
def fetch_recent_games_stats(player_id):
recent_games_url = f"https://statsapi.mlb.com/api/v1/people/{player_id}/stats/game"
params = {
"stats": "gameLog",
"group": "pitching",
"gameType": "R",
"leagueListId": "mlb_milb_aaa",
"limit": 5
}
response = requests.get(recent_games_url, params=params)
if response.status_code != 200:
print(f"Failed to fetch recent games data: {response.status_code}")
return pd.DataFrame()
recent_games = response.json().get('stats', [])[0].get('splits', [])
if not recent_games:
print(f"No recent games data found for player with ID: {player_id}")
return pd.DataFrame()
game_stats = []
for game in recent_games:
game_data = game.get('stat', {})
game_stats.append({
'date': game['date'],
'team': game['team']['name'],
'hitsAllowed': game_data.get('hits', 0),
'runsAllowed': game_data.get('runs', 0),
'homeRunsAllowed': game_data.get('homeRuns', 0),
'walks': game_data.get('baseOnBalls', 0),
'strikeOuts': game_data.get('strikeOuts', 0),
'outs': game_data.get('outs', 0),
'inningsPitched': game_data.get('inningsPitched', 0)
})
return pd.DataFrame(game_stats)
# Fetch the stats in the background
batting_stats_df, pitching_stats_df = fetch_mlb_stats()
# Function to search and display stats for a player
def search_player_stats(player_name, batting_df, pitching_df):
batting_stats = batting_df[batting_df['name'].str.contains(player_name, case=False, na=False)]
pitching_stats = pitching_df[pitching_df['name'].str.contains(player_name, case=False, na=False)]
if batting_stats.empty and pitching_stats.empty:
print(f"No stats found for player: {player_name}")
else:
if not batting_stats.empty:
print("Batting Stats:")
print(batting_stats)
if not pitching_stats.empty:
print("Pitching Stats:")
print(pitching_stats)
# Fetch recent games stats for pitchers
player_id = pitching_stats['player_id'].values[0]
recent_games_stats = fetch_recent_games_stats(player_id)
if not recent_games_stats.empty:
print("Recent Games Stats:")
print(recent_games_stats)
# Prompt the user to enter a player's name and search for their stats
while True:
player_name = input("Which player are you searching for? (type 'exit' to quit): ")
if player_name.lower() == 'exit':
break
search_player_stats(player_name, batting_stats_df, pitching_stats_df)