def getGames(): print('Fetching January games...') month = mlbgame.games(year, 1, home=team, away=team) for i in range(2,12): dateMonth = datetime.datetime(year, i, 1) print("Fetching "+dateMonth.strftime("%B")+" games...") month = month + mlbgame.games(year, i, home=team, away=team) return month
def getGames(game_dict): current_date = datetime.now() # Used until season restarts # current_date = date.fromisoformat('2019-05-02') # current_date = datetime.combine(current_date, datetime.min.time()) current_year = current_date.year current_month = current_date.month next_month_date = current_date + relativedelta(months=+1) next_month = next_month_date.month # use current year when season comes back month = mlbgame.games(2020, current_month, home=Static.teamname, away=Static.teamname) month2 = mlbgame.games(current_year, next_month, home=Static.teamname, away=Static.teamname) games_future_month = mlbgame.combine_games(month2) games = mlbgame.combine_games(month) key = 0 game_dict.clear() for game in games: # s = Game_data() diff = game.date - current_date diff_days = diff.days diff_seconds = diff.seconds if key == 10: break elif diff_days > -2 or (diff_days == 0 and diff_seconds > 0): # print(game) # print(game.date) game_dict.update({key: game}) key += 1 if key != 10: # Less than 10 games left in current month for game in games_future_month: # s = Game_data() diff = game.date - current_date diff_days = diff.days diff_seconds = diff.seconds if key == 10: break elif diff_days > -2 or (diff_days == 0 and diff_seconds > 0): # print(game) # print(game.date) game_dict.update({key: game}) key += 1 # gameid = '2019_05_31_nynmlb_arimlb_1' # Eventually do an In-Game check, with game_dict[0] (since that's the closest game to current time return game_dict
def get_games(self, args=None): ''' This will retrieve the games using mlbgame arguments: args - If you want to send a different set of args in you can ''' if args == None: args = self.args if args['year'] != '' and args['month'] == '': self.games = mlbgame.games(args['year']) elif args['year'] != '' and args['month'] != '': self.games = mlbgame.games(args['year'], args['month'])
def test_games(self): games = mlbgame.games(2016, 7) self.assertIsInstance(games, list) for day in games: self.assertIsInstance(day, list) for game in day: self.assertIsInstance(game, mlbgame.game.GameScoreboard) games = mlbgame.combine_games(games) for game in games: self.assertIsInstance(game.away_team, str) self.assertIsInstance(game.away_team_errors, int) self.assertIsInstance(game.away_team_hits, int) self.assertIsInstance(game.away_team_runs, int) self.assertIsInstance(game.date, datetime) self.assertIsInstance(game.game_id, str) self.assertIsInstance(game.game_league, str) self.assertIsInstance(game.game_start_time, str) self.assertIsInstance(game.game_status, str) self.assertIsInstance(game.game_tag, str) self.assertIsInstance(game.home_team, str) self.assertIsInstance(game.home_team_errors, int) self.assertIsInstance(game.home_team_hits, int) self.assertIsInstance(game.home_team_runs, int) self.assertIsInstance(game.nice_score(), str) if game.game_tag == 'go_game': self.assertIsInstance(game.l_pitcher, str) self.assertIsInstance(game.l_pitcher_losses, int) self.assertIsInstance(game.l_pitcher_wins, int) self.assertIsInstance(game.l_team, str) self.assertIsInstance(game.sv_pitcher, str) self.assertIsInstance(game.sv_pitcher_saves, int) self.assertIsInstance(game.w_pitcher, str) self.assertIsInstance(game.w_pitcher_losses, int) self.assertIsInstance(game.w_pitcher_wins, int) self.assertIsInstance(game.w_team, str)
def mlb_edge_list(year): teams = [team.club.upper() for team in mlbgame.teams()] edge_list = [] edge_weights = {} games = mlbgame.combine_games(mlbgame.games(year)) team_dict = { team.club_common_name: team.club.upper() for team in mlbgame.teams() } for game in games: try: if str(game.w_team) not in team_dict or str( game.l_team) not in team_dict: continue w_team = team_dict[game.w_team] l_team = team_dict[game.l_team] if (str(w_team), str(l_team)) in edge_list: edge_weights[(str(w_team), str(l_team))] += 1 else: edge_weights[( str(w_team), str(l_team))] = 1 #abs(game.score_home-game.score_away) edge_list.append((str(w_team), str(l_team))) except AttributeError: pass new_edge_list = [] for winner, loser in edge_list: if (loser, winner) not in edge_weights or edge_weights[ (winner, loser)] > edge_weights[(loser, winner)]: new_edge_list.append((winner, loser)) return new_edge_list
def pitcher_response_dist(current_team, player): """ takes the player name as a string and returns a distribution of hits vs pitching difficulty :return a matrix corresponding to the hits: """ mlbteam_info = mlbgame.info.team_info() player_table = stats.br_table(current_team, player) major_years = player_table.xpath('//table/tbody/tr[@class="full"]') player_distribution = [] for year in major_years: yr = int(year.xpath('./th')[0].text) br_team_name = year.xpath('./td[@data-stat="team_ID"]/a[@title]')[0].attrib['title'] mlb_team_name = '' for team in mlbteam_info: #mlbteam_info is an alphabetical list if team['club_full_name'] == br_team_name: mlb_team_name = team['club_common_name'] #take note, mlbgame uses the common names games = mlbgame.games(yr, home=mlb_team_name, away=mlb_team_name) #now just to search through all of the mlb games to find events in which this layer participates for day in games: for game in day: print game
def game_ids_for_date(month=None, day=None, year=None): if (month is None) or (day is None) or (year is None): raise ValueError( 'Month, Day, and Year must all be provided as arguments.') return [ game.game_id for x in mlbgame.games(year, month, day) for game in x ]
def get_daily_starting_pitcher_stats(year, month, day): pitching_stats = [] for game in mlbgame.games(year, month, day)[0]: try: game_stats = mlbgame.player_stats(game.game_id) pitching_stats.append(game_stats['home_pitching'][0]) pitching_stats.append(game_stats['away_pitching'][0]) except ValueError: pass # Game doesn't exist, probably hasn't started yet return pitching_stats
def __game_data(self, team): now = datetime.datetime.now() day = now.day month = now.month year = now.year # TODO: Uncomment once the season starts # For now, let's re-live one of the Cubs' world series wins # # games = mlbgame.games(year, month, day, home=team, away=team) games = mlbgame.games(2016, 11, 1, home=team, away=team) return self.__current_game_data(games[0][0]) if len(games) else False
def retrieve_cached_gameday_report(date, long_team_name): if date in CACHED_GAMEDAY_REPORTS: return CACHED_GAMEDAY_REPORTS[date][long_team_name] else: CACHED_GAMEDAY_REPORTS[date] = {} fetched_reports_all_teams_day = mlbgame.games(date.year, date.month, date.day)[0] for game_report in fetched_reports_all_teams_day: CACHED_GAMEDAY_REPORTS[date].update( {game_report.home_team: game_report}) CACHED_GAMEDAY_REPORTS[date].update( {game_report.away_team: game_report}) return CACHED_GAMEDAY_REPORTS[date][long_team_name]
def results(numdays, inclusion, numruns): base = datetime.datetime.today() if inclusion == False: date_list = [ base - datetime.timedelta(days=x) for x in range(1, numdays) ] else: date_list = [ base - datetime.timedelta(days=x) for x in range(0, numdays) ] ### Application ### f = open('results.txt', 'a') # opens results file # deletes current contents of results file f.seek(0) f.truncate() f.close() for d in date_list: yearr = d.year monthh = d.month datee = d.day date_format = "%d" % monthh + "/%d" % datee + "/%d" % yearr f = open('results.txt', 'a') f.write(str('\n' + date_format) + '\n') f.close() results = [] game_day = mlbgame.games(yearr, monthh, datee) games = mlbgame.combine_games(game_day) for game in games: g = str(game) if "(%s)" % numruns in g: results.append(str(g)) if len(results) > 0: for x in results: f = open('results.txt', 'a') f.write(x + '\n') f.close() else: # if no game have score number, prints message to thirteen_results.txt f = open('results.txt', 'a') f.write("There were no games with %d runs" % numruns + '\n')
def getAvgRunsInFirstHome(year, month, team): month = mlbgame.games(year, month, home=team) games = mlbgame.combine_games(month) firstInningRunsOppo = 0 firstInningRunsHome = 0 num_of_games = 0 for game in games: innings = mlbgame.box_score(game.game_id).innings if innings: firstInningRunsOppo += innings[0]['away'] firstInningRunsHome += innings[0]['home'] num_of_games += 1 return { "games_played": num_of_games, "opponent": firstInningRunsOppo / num_of_games, "home": firstInningRunsHome / num_of_games }
def calculate_wins(team, year): nickname = team['team'] print("Calculating wins for {}".format(nickname)) all_games = mlb.games(year, home=nickname, away=nickname) season = mlb.combine_games(all_games) season = trim_spring_training_games(season, year) wins = 0 for game in season: try: if game.w_team == nickname: team['wins-versus'][game.l_team] += 1 wins += 1 except: pass print("Done.\n")
def main(): # acts as main method cubsPlayers = [] teams = mlbgame.teams() # Grabs list of team objects for team in teams: # just to test for now if team.club_common_name == 'Cubs': id = team.team_id # print(id, team.club_common_name, team.division) count = 0 pid = 0 # for team in teams: for i in range(4, 11): year = mlbgame.games(2015, i, home='Cubs', away='Cubs') games = mlbgame.combine_games(year) for game in games: try: cubsGameStats = mlbgame.player_stats(game.game_id).home_batting for p in cubsGameStats: temp = p.name_display_first_last f, l = p.name_display_first_last.split() if not any(x.firstName + ' ' + x.lastName == temp for x in cubsPlayers): if p.pos == 'P': # is a pitcher #print(p.name_display_first_last, 'pitcher') pid += 1 #newPlayer = Pitcher(f, l, p.s_era) else: #print(p.name_display_first_last, p.pos, p.s_hr) pid += 1 newPlayer = Batter(f, l, p.s_hr) cubsPlayers.append(newPlayer) count += 1 #print(game, count) except ValueError: print('No game found') for p in cubsPlayers: print(p, p.hr) print(len(cubsPlayers))
def getMLBEdges(start, end, gamma=0.8): """ Generates a dictionary of (team1, team2) -> wl_spread where wl_spread is the sum of discounted win-loss spreads of seasons between start and end. Win-loss spreads are calculated as the number of wins team1 has against team2 minus the number of losses Args: start (int): the first season to gather data for end (int): the last season to collect data for gamma (float): the discount factor to apply to past seasons Returns: A dictionary of edges to win/loss spreads """ edges = {} teams = { team.club_common_name: team.club.upper() for team in mlbgame.teams() } for year in range(start, end + 1): if year not in mlbGames: games = mlbgame.combine_games(mlbgame.games(year)) mlbGames[year] = games else: games = mlbGames[year] discount = gamma**(end - year) for game in games: try: # Some game data is with teams not in the MLB, some games don't have winners, so check for that if game.w_team in teams and game.l_team in teams: winner = teams[game.w_team] loser = teams[game.l_team] edges[(winner, loser)] = edges.get( (winner, loser), 0.0) + 1 * discount edges[(loser, winner)] = edges.get( (loser, winner), 0.0) - 1 * discount except AttributeError: pass return teams.values(), edges
def team_games(self,event): today = datetime.date.today() tyear = today.year tmonth = today.month tday = today.day print("Games for %s on %s %s, %s" % (self.team_select[self.teamselect.get()].club_common_name, tmonth, tday, tyear)) month = mlbgame.games(tyear, tmonth, tday, home=self.team_select[self.teamselect.get()].club_common_name, away=self.team_select[self.teamselect.get()].club_common_name) games = mlbgame.combine_games(month) #print("Games in June 2019") #for game in games: # print(game) for game_objs in month: for daygames in game_objs: print("ID:", daygames.game_id) print("Away team", daygames.away_team) print("Home team", daygames.home_team) print("Date", daygames.date) print("Score: ", daygames.home_team_runs, "to", daygames.away_team_runs)
def getMLBGames(year): teams = { team.club_common_name: team.club.upper() for team in mlbgame.teams() } if year not in mlbGames: games = mlbgame.combine_games(mlbgame.games(year)) mlbGames[year] = games else: games = mlbGames[year] processedGames = [] for game in games: try: if game.w_team in teams and game.l_team in teams: winner = teams[game.w_team] loser = teams[game.l_team] processedGames.append((winner, loser)) except: pass return processedGames
def run(): currentMonth = datetime.now().month month = mlbgame.games(2018, currentMonth) games = mlbgame.combine_games(month) for game in games: if (game.game_status == "FINAL" and hasattr(game, 'w_team')): table.put_item( Item={ 'gameID': game.game_id, "Home Team": game.home_team, "Away Team": game.away_team, "Winning Team": game.w_team, "Losing Team": game.l_team, "Home Score": game.home_team_runs, "Home Hits": game.home_team_hits, "Away Runs": game.away_team_runs, "Away Hits": game.away_team_hits, "Winning Pitcher": game.w_pitcher, "Losing Pitcher": game.l_pitcher, "Saving Pitcher": game.sv_pitcher, })
def todays_games(): today = date.today() payload = [] data = mlbgame.games(2018, 7, 4) games = mlbgame.combine_games(data) for game in games: data_obj = {} overview_data = overview(game.game_id) team_stats_data = team_stats(game.game_id) data_obj.update(overview_data) data_obj.update(team_stats_data) payload.append(data_obj) foo = GameDocument( game_id = data_obj.get('game_id'), away_team_id = data_obj.get('away_team_id'), home_team_id = data_obj.get('home_team_id'), home_code = data_obj.get('home_code'), away_code = data_obj.get('away_code'), home_pitching = jsonpickle.encode(data_obj.get('home_pitching')), away_pitching = jsonpickle.encode(data_obj.get('away_pitching')), home_additional_pitching = jsonpickle.encode(data_obj.get('home_additional_pitching')), away_additional_pitching = jsonpickle.encode(data_obj.get('away_additional_pitching')), home_batting = jsonpickle.encode(data_obj.get('home_batting')), away_batting = jsonpickle.encode(data_obj.get('away_batting')), home_additional_batting = jsonpickle.encode(data_obj.get('home_additional_batting')), away_additional_batting = jsonpickle.encode(data_obj.get('away_additional_batting')) ) foo.save() dictionary = { "payload": payload } return jsonpickle.encode(dictionary)
import mlbgame import ipdb import csv date_stats = {} for month in range(4, 11): for day in range(1, 32): if month == 4 and day >= 3 or month > 4: games = mlbgame.combine_games(mlbgame.games(2016, month, day)) day_stats = {} for game in games: try: stats = mlbgame.player_stats(game.game_id) except ValueError as e: print(game.game_id) continue for player in stats['home_batting']: name = player.name_display_first_last if player.ab + player.bb + player.sf + player.sac + player.hbp > 2: day_stats['_'.join( player.name_display_first_last.split(' '))] = { 'game_hits': player.h, 'game_ab': player.ab, 'game_bb': player.bb, 'game_sf': player.sf, 'game_sac': player.sac, 'game_hbp': player.hbp, 'opposing_pitcher': stats['away_pitching'] [0].name_display_first_last,
def didJudgeHR(self): today = datetime.datetime.today( ) #datetime.datetime(2019, 4, 8, 20, 00) game_array = mlbgame.games(today.year, today.month, today.day, home='Yankees', away='Yankees') print(game_array) if game_array != []: print('duh') print(len(game_array)) print(len(game_array[0])) if len(game_array[0]) == 1: print('huh') game = game_array[0][0] game_id = game.game_id if (today.month < 10): if (today.day < 10): url = "http://gd2.mlb.com/components/game/mlb/year_" + str( today.year ) + "/month_0" + str(today.month) + "/day_0" + str( today.day) + "/gid_" + game_id + "/boxscore.xml" else: url = "http://gd2.mlb.com/components/game/mlb/year_" + str( today.year ) + "/month_0" + str(today.month) + "/day_" + str( today.day) + "/gid_" + game_id + "/boxscore.xml" else: if (today.day < 10): url = "http://gd2.mlb.com/components/game/mlb/year_" + str( today.year ) + "/month_" + str(today.month) + "/day_0" + str( today.day) + "/gid_" + game_id + "/boxscore.xml" else: url = "http://gd2.mlb.com/components/game/mlb/year_" + str( today.year ) + "/month_" + str(today.month) + "/day_" + str( today.day) + "/gid_" + game_id + "/boxscore.xml" tree = etree.fromstring(requests.get(url).text) if (game.home_team == 'Yankees'): batting_stats = tree.findall('batting')[0] else: batting_stats = tree.findall('batting')[1] for batter in batting_stats: if (batter.get('id') == '592450'): print('here') if (int(batter.get('hr')) == 0): print('here') if game.game_status == 'FINAL': # If the game is over, treat it as such self.lastGameVal = 0 return 0 else: # If the game is not over, treat it as if there has been no game yet today return 999 else: # If he's homered, we don't care if the game is over self.lastGameVal = batter.get('hr') self.lastHRDate = today return int(batter.get('hr')) if game.game_status == 'FINAL': print('here') # If Judge isn't in batting_stats, but the game is over, treat it as such self.lastGameVal = 0 return 0 else: # If Judge isn't in batting_stats, but the game is not over, treat it as if there has been no game yet today return 999 # DOUBLE HEADER MEANS DOUBLE CODDDDDDDDDEEEEEEEEE if (len(game_array[0]) > 1): # DOUBLE HEADER GAME ONE print('here') retval = 22 game = game_array[0][0] game_id = game.game_id if (today.month < 10): if (today.day < 10): url = "http://gd2.mlb.com/components/game/mlb/year_" + str( today.year ) + "/month_0" + str(today.month) + "/day_0" + str( today.day) + "/gid_" + game_id + "/boxscore.xml" else: url = "http://gd2.mlb.com/components/game/mlb/year_" + str( today.year ) + "/month_0" + str(today.month) + "/day_" + str( today.day) + "/gid_" + game_id + "/boxscore.xml" else: if (today.day < 10): url = "http://gd2.mlb.com/components/game/mlb/year_" + str( today.year ) + "/month_" + str(today.month) + "/day_0" + str( today.day) + "/gid_" + game_id + "/boxscore.xml" else: url = "http://gd2.mlb.com/components/game/mlb/year_" + str( today.year ) + "/month_" + str(today.month) + "/day_" + str( today.day) + "/gid_" + game_id + "/boxscore.xml" tree = etree.fromstring(requests.get(url).text) if (game.home_team == 'Yankees'): batting_stats = tree.findall('batting')[0] else: batting_stats = tree.findall('batting')[1] for batter in batting_stats: if (batter.get('id') == '592450'): print('here') if (int(batter.get('hr')) == 0): print(game.game_status) if game.game_status == 'FINAL': # If the game is over, treat it as such # self.lastGameVal = 0 retval = 0 else: # If the game is not over, treat it as if there has been no game yet today retval = 999 else: # If he's homered, we don't care if the game is over # self.lastGameVal = batter.get('hr') # self.lastHRDate = today retval = int(batter.get('hr')) if game.game_status == 'FINAL': # If Judge isn't in batting_stats, but the game is over, treat it as such # self.lastGameVal = 0 retval = 0 else: # If Judge isn't in batting_stats, but the game is not over, treat it as if there has been no game yet today retval = 999 # DOUBLE HEADER GAME TWO retval2 = 22 game = game_array[0][1] game_id = game.game_id if (today.month < 10): if (today.day < 10): url = "http://gd2.mlb.com/components/game/mlb/year_" + str( today.year ) + "/month_0" + str(today.month) + "/day_0" + str( today.day) + "/gid_" + game_id + "/boxscore.xml" else: url = "http://gd2.mlb.com/components/game/mlb/year_" + str( today.year ) + "/month_0" + str(today.month) + "/day_" + str( today.day) + "/gid_" + game_id + "/boxscore.xml" else: if (today.day < 10): url = "http://gd2.mlb.com/components/game/mlb/year_" + str( today.year ) + "/month_" + str(today.month) + "/day_0" + str( today.day) + "/gid_" + game_id + "/boxscore.xml" else: url = "http://gd2.mlb.com/components/game/mlb/year_" + str( today.year ) + "/month_" + str(today.month) + "/day_" + str( today.day) + "/gid_" + game_id + "/boxscore.xml" tree = etree.fromstring(requests.get(url).text) if (game.home_team == 'Yankees'): batting_stats = tree.findall('batting')[0] else: batting_stats = tree.findall('batting')[1] print("batter", batter) for batter in batting_stats: if (batter.get('id') == '592450'): print('here') if (int(batter.get('hr')) == 0): if game.game_status == 'FINAL': # If the game is over, treat it as such # self.lastGameVal = 0 retval2 = 0 else: # If the game is not over, treat it as if there has been no game yet today retval2 = 999 else: # If he's homered, we don't care if the game is over # self.lastGameVal = batter.get('hr') # self.lastHRDate = today print('this', int(batter.get('hr'))) retval2 = int(batter.get('hr')) # Double header evaluation print('aaaa') print(retval) print(retval2) if retval > 0 and retval != 999 and retval != 22: print('hmm') self.lastGameVal = retval self.lastHRDate = today return retval if retval2 > 0 and retval2 != 999 and retval2 != 22: print('hmmmm') self.lastGameVal = retval2 self.lastHRDate = today return retval2 if retval2 == 999 or retval == 999: return 999 else: print('this1') return 0 # No game yet today else: print('this') return 999
def calendarListView_month(request, month_game=1): locations = { "Angels": "Angel Stadium", "Tigers": "Comerica Park ", "Red Sox": "Fenway Park ", "Rangers": "Globe Life Park", "White Sox": "Guaranteed Rate Field", "Royals": "Kauffman Stadium ", "Astros": "Minute Maid Park ", "Athletics": "Oakland Alameda Coliseum ", "Orioles": "Oriole Park at Camden Yards ", "Indians": "Progressive Field ", "Blue Jays": "Rogers Centre ", "Mariners": "Safeco Field ", "Twins": "Target Field ", "Rays": "Tropicana Field ", "Yankees": "Yankee Stadium ", "Giants": "AT&T Park ", "Cardinals": "Busch Stadium ", "D-backs": "Chase Field ", "Mets": "Citi Field ", "Phillies": "Citizens Bank Park ", "Rockies": "Coors Field ", "Dodgers": "Dodger Stadium ", "Reds": "Great American Ball Park ", "Marlins": "Marlins Park ", "Brewers": "Miller Park ", "Nationals": "Nationals Park ", "Padres": "Petco Park ", "Pirates": "PNC Park ", "Braves": "Turner Field ", "Cubs": "Wrigley Field " } months = { 1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October", 11: "November", 12: "December" } days = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ] """ This variables is to get the name of the month """ mymonth = int(month_game) month_title = "January" for k, v in months.items(): if int(month_game) == k: month_title = v """""" the_game_day = 0 int(month_game) if int(month_game) > 0 and int(month_game) <= 12: the_game_day = int(month_game) elif isinstance(int(month_game), str): the_game_day = 1 else: the_game_day = 1 list_of_days_in_months = [] days_d = [ calendar.MONDAY, calendar.THURSDAY, calendar.THURSDAY, calendar.SUNDAY, calendar.TUESDAY, calendar.FRIDAY, calendar.SUNDAY, calendar.WEDNESDAY, calendar.SATURDAY, calendar.MONDAY, calendar.THURSDAY, calendar.SATURDAY, ] days_month_n = [ (date(2018, 2, 1) - date(2018, 1, 1)).days, (date(2018, 3, 1) - date(2018, 2, 1)).days, (date(2018, 4, 1) - date(2018, 3, 1)).days, (date(2018, 5, 1) - date(2018, 4, 1)).days, (date(2018, 6, 1) - date(2018, 5, 1)).days, (date(2018, 7, 1) - date(2018, 6, 1)).days, (date(2018, 8, 1) - date(2018, 7, 1)).days, (date(2018, 9, 1) - date(2018, 8, 1)).days, (date(2018, 10, 1) - date(2018, 9, 1)).days, (date(2018, 11, 1) - date(2018, 10, 1)).days, (date(2018, 12, 1) - date(2018, 11, 1)).days, (date(2018, 1, 1) - date(2018, 12, 1)).days, ] a_month_games = mlbgame.games(2018, the_game_day, home="Angels", away="Angels") mlbgames = mlbgame.combine_games(a_month_games) one_month = month_days(days_d[the_game_day - 1], days_month_n[the_game_day - 1]) # one_month = zip(list_of_days_in_months, mlbgames) game_days = [] name_months = [] name_days = [] hr = [] for game in mlbgames: game_days.append(game.date.date().day) name_months.append(game.date.date().strftime("%B")) name_days.append(game.date.date().strftime("%A")) hr.append(game.date.time()) context = { 'one_month': one_month, 'months': months, 'days': days, 'mlbgames': mlbgames, 'game_days': game_days, 'locations': locations, 'the_game_day': the_game_day, 'month_title': month_title } return render(request, 'yearly/calendar_month.html', context)
def getGeneralData(day, month, year, mode, cursor): # get games year = year month = month day = day gameID = -1 # insert if haven't added to games table yet, update otherwise if mode == "insert": # Insert Into Dates Table addGame = "INSERT INTO dates (date) VALUES(%s)" gameData = (date(year, month, day), ) cursor.execute(addGame, gameData) gameID = cursor.lastrowid elif mode == "update": # Find Game ID findGame = "SELECT iddates FROM dates WHERE date = %s" findGameData = (date(year, month, day), ) cursor.execute(findGame, findGameData) for game in cursor: gameID = game[0] gamez = mlbgame.games(year, month, day) # get stats associated with each game # insert into players table batterID = [] pitcherID = [] winningPitchers = [] losingPitchers = [] for games in gamez: for game in games: if game.game_status != 'OTHER': stats = mlbgame.player_stats(game.game_id) for batter in stats['away_batting']: try: # insert into batters table, update if not there addBatter = "INSERT INTO batters (mlbID, playerName, team, lastOpp) VALUES(%s, %s, %s, %s)" batterData = (batter.id, batter.name_display_first_last, game.away_team, game.home_team) cursor.execute(addBatter, batterData) except: updateBatter = "UPDATE batters SET playerName = %s, team = %s, lastOpp = %s WHERE mlbID = %s" batterData = (batter.name_display_first_last, game.away_team, game.home_team, batter.id) cursor.execute(updateBatter, batterData) batterID.append(batter.id) for batter in stats['home_batting']: try: # insert into batters table, update if not there addBatter = "INSERT INTO batters (mlbID, playerName, team, lastOpp) VALUES(%s, %s, %s, %s)" batterData = (batter.id, batter.name_display_first_last, game.home_team, game.away_team) cursor.execute(addBatter, batterData) except: updateBatter = "UPDATE batters SET playerName = %s, team = %s, lastOpp = %s WHERE mlbID = %s" batterData = (batter.name_display_first_last, game.home_team, game.away_team, batter.id) cursor.execute(updateBatter, batterData) batterID.append(batter.id) for pitcher in stats['away_pitching']: try: # insert into batters table, update if not there addPitcher = "INSERT INTO pitchers (mlbID, playerName, pos, team, lastOpp) VALUES(%s, %s, %s, %s, %s)" pitcherData = (pitcher.id, pitcher.name_display_first_last, "P", game.away_team, game.home_team) cursor.execute(addPitcher, pitcherData) except: updatePitcher = "UPDATE pitchers SET playerName = %s, team = %s, lastOpp = %s WHERE mlbID = %s" pitcherData = (pitcher.name_display_first_last, game.away_team, game.home_team, pitcher.id) cursor.execute(updatePitcher, pitcherData) pitcherID.append(pitcher.id) if hasattr(pitcher, 'win'): winningPitchers.append(pitcher.id) if hasattr(pitcher, 'loss'): losingPitchers.append(pitcher.id) for pitcher in stats['home_pitching']: try: # insert into batters table, update if not there addPitcher = "INSERT INTO pitchers (mlbID, playerName, pos, team, lastOpp) VALUES(%s, %s, %s, %s, %s)" pitcherData = (pitcher.id, pitcher.name_display_first_last, "P", game.home_team, game.away_team) cursor.execute(addPitcher, pitcherData) except: updatePitcher = "UPDATE pitchers SET playerName = %s, team = %s, lastOpp = %s WHERE mlbID = %s" pitcherData = (pitcher.name_display_first_last, game.home_team, game.away_team, pitcher.id) cursor.execute(updatePitcher, pitcherData) pitcherID.append(pitcher.id) if hasattr(pitcher, 'win'): winningPitchers.append(pitcher.id) if hasattr(pitcher, 'loss'): losingPitchers.append(pitcher.id) alterBatter(batterID, gameID, cursor) alterPitcher(winningPitchers, losingPitchers, pitcherID, gameID, cursor) print "Updated Baseball Database for Games on %s/%s/%s" % (month, day, year)
matrixOptions = led_matrix_options(args) # Initialize the matrix matrix = RGBMatrix(options = matrixOptions) canvas = matrix.CreateFrameCanvas() # Read scoreboard options from config.json if it exists config = ScoreboardConfig("config.json") debug.set_debug_status(config) # Render the current standings or today's games depending on # the provided arguments now = datetime.datetime.now() year = now.year month = now.month day = now.day if config.display_standings: standings = mlbgame.standings(datetime.datetime(year, month, day)) division = next(division for division in standings.divisions if division.name == config.preferred_division) renderers.standings.render(matrix, matrix.CreateFrameCanvas(), division) else: while True: games = mlbgame.games(year, month, day) if not len(games): renderers.offday.render(matrix, matrix.CreateFrameCanvas()) else: # The mlbgame API returns a 2D array with the list of games as the first index, # hence the 'games[0]' GameRenderer(matrix, matrix.CreateFrameCanvas(), games[0], config).render()
def add_games(day, month): return mlbgame.games(2018, month, day)
CREATE TABLE IF NOT EXISTS TEAMS ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, NAME TEXT UNIQUE, CLUB_ID INTEGER UNIQUE , LEAGUE TEXT, PHOTOSTORE TEXT); ) CREATE TABLE IF NOT EXISTS GAMES( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, WINNER INTEGER, HOMETEAM_ID INTEGER, AWAYTEAM_ID INTEGER); ''') games = mlbgame.games(2018, 6, 1) league_info = mlbgame.info.league_info() team_info = mlbgame.info.team_info() for team in team_info: cur.execute( '''INSERT INTO TEAMS (NAME, CLUB_ID, LEAGUE, PHOTOSTORE) VALUES ( ?, ?, ? ,? )''', (team['aws_club_slug'], team['club_id'], team['league'], team['photostore_url'])) conn.commit() p = Pool(processes=10) dates = ((day, month) for day in range(1, 31) for month in range(4, 12)) all_games = p.starmap(add_games, dates) p.close()
def players_hr_total_dataframe(self): dataframes = map(lambda p : p.get_player_hr_total_dataframe(), self.players) return create_multiplayer_hr_total_dataframe(dataframes) #TODO: Take this mapping and make it read from a text file users = [User("Dave", [519317, 425902, 444432, 621043, 408234, 656941, 596748], players_dict), User("Craig", [547180, 605141, 593934, 545341, 543807, 596059, 570731], players_dict), User("Brian", [519317, 592178, 425902, 593934, 408234, 656941, 592206], players_dict), User("Jason", [519317, 430945, 592178, 593934, 475582, 656941, 608365], players_dict)] for m in months: month = mlbgame.games(year, m.id) for games in month: for game in games: #Only games in the season (pre-season games will be included without this) #Also don't try to pull games that have not been played yet as the record #will exist but the call to get the stats will fail if game.date > season_start_date: # and game.date < today_date: #Try check is here because postponed games will still come through #Need to figure out if there is a way to deal with this actively rather than passively try: stats = mlbgame.player_stats(game.game_id) game_stats_all = mlbgame.combine_stats(stats) for game_stats in game_stats_all: if hasattr(game_stats, 'hr') and game_stats.id in players_dict:
def data_storage(): print("data_storage") '''Iterate through each player's statistics from each game from each day in the 2016 regular season and add them to the db''' ## season = [mlbgame.day(2016, 4, 3, home='Pirates') + ## mlbgame.day(2016, 4, 3, home='Rays') + ## mlbgame.day(2016, 4, 3, home='Royals')] + \ ## mlbgame.games(2016, [4], list(range(4, 31))) + \ season = mlbgame.games(2018, [5, 6, 7, 8, 9], list(range(1, 32))) + \ mlbgame.games(2018, [10], [1, 2]) for day in season: print('in day') for game in day: print('in game') if game.w_team: stats = mlbgame.player_stats(game.game_id) for player in (stats['home_batting'] + stats['away_batting']): ## all players in each game player_pa = player.ab + player.bb + player.sac + player.sf + player.hbp ## check for any plate appearances if player_pa: player_in_db = players.find_one({"_id": player.id}) ## will be false if player has not yet been added to db if player_in_db: ## update player in db updated_player = players.update_one( {"_id": player.id}, { '$inc': { "pa": player_pa, "ab": player.ab, "h": player.h, "bb": player.bb, "hr": player.hr, "tb": (player.hr * 4) + (player.t * 3) + (player.d * 2) + (player.h - player.hr - player.t - player.d), "rbi": player.rbi, "r": player.r, "hbp": player.hbp, "so": player.so, "sb": player.sb, "cs": player.cs, "sac": player.sac + player.sf } }) else: ## add player to db new_player = players.insert_one({ "_id": player.id, "name": player.name_display_first_last, "position": player.pos, "pa": player.ab + player.bb + player.sac + player.sf + player.hbp, "ab": player.ab, "h": player.h, "bb": player.bb, "hr": player.hr, "tb": (player.hr * 4) + (player.t * 3) + (player.d * 2) + (player.h - player.hr - player.t - player.d), "rbi": player.rbi, "r": player.r, "hbp": player.hbp, "so": player.so, "sb": player.sb, "cs": player.cs, "sac": player.sac + player.sf })
from datetime import datetime, timedelta import mlbgame from slackclient import SlackClient from dotenv import load_dotenv from os.path import join, dirname #I want to refactor the games API calls below... games_array = [] day = #Today's MLB Games! todays_games_array = [] today = datetime.today() today_game = mlbgame.games(today.year, today.month, today.day) game = mlbgame.combine_games(today_game) for g in game: todays_games_array.append(g) #Yesterday's MLB Games! yesterdays_games_array = [] yesterday = datetime.today() - timedelta(days=1) yesterdays_games = mlbgame.games(yesterday.year, yesterday.month, yesterday.day) yesterday_boxes = mlbgame.combine_games(yesterdays_games) for g in yesterday_boxes: yesterdays_games_array.append(g) #Tomorrow's MLB Games! tomorrow_games_array = [] tomorrow = datetime.today() + timedelta(days=1)
def get_batch(year, month): games = mlbgame.games(year, month) return games
class User: def __init__(self, name, players): self.name = name self.players = players #TODO: Take this mapping and make it read from a text file users = [ User("Dave", [519317, 425902, 444432, 621043, 408234, 656941, 596748]), User("Craig", [547180, 605141, 593934, 545341, 543807, 596059, 570731]), User("Brian", [519317, 592178, 425902, 593934, 408234, 656941, 592206]), User("Jason", [519317, 430945, 592178, 593934, 475582, 656941, 608365]) ] for m in months: month = mlbgame.games(year, m.id) for games in month: for game in games: #Only games in the season (pre-season games will be included without this) #Also don't try to pull games that have not been played yet as the record #will exist but the call to get the stats will fail if game.date > season_start_date: # and game.date < today_date: #Try check is here because postponed games will still come through #Need to figure out if there is a way to deal with this actively rather than passively try: stats = mlbgame.player_stats(game.game_id) game_stats_all = mlbgame.combine_stats(stats) for game_stats in game_stats_all: if hasattr(game_stats,
#!python from __future__ import print_function import mlbgame month = mlbgame.games(2015, 6, home='Mets') games = mlbgame.combine_games(month) for game in games: print(game)
import datetime import mlbgame import time import pandas as pd import os # Define Years of Interest (2010-2018) years = [year for year in range(2010, 2018 + 1)] # Pull all games from MLBGAME API schedule = mlbgame.games(years, home='Nationals') games = mlbgame.combine_games(schedule) results = [] # Loop through games and keep regular season games played in DC for game in games: game_datetime = game.date game_date = game_datetime.date() game_overview = mlbgame.overview(game.game_id) # Game Type, should be == 'R' for regular season game_type = game_overview.game_type if (game_type != 'S'): print(game_date) game_df = pd.DataFrame({'natls_home': 1}, index=[game_date]) results.append(game_df) # Concatentate one big dataframe results_df = pd.concat(results, axis=0) # Output final dataframe TIMESTR = time.strftime("%Y%m%d_%H%M%S")