Beispiel #1
0
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
Beispiel #2
0
 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)
Beispiel #3
0
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
Beispiel #4
0
    def crawl_xmls(self, browser):

        xmls_to_fetch = [
            "boxscore.xml", "rawboxscore.xml", "game_events.xml",
            "linescore.xml", "players.xml", "inning/inning_all.xml", "game.xml"
        ]

        event_dates = mlbgame.important_dates(year=self.year)
        last_date = event_dates.last_date_seas
        first_date = event_dates.first_date_seas if self.start_date is None else self.start_date
        dates = date_range(first_date, last_date)

        for date in dates:
            game_scoreboards = mlbgame.day(date.year, date.month, date.day)
            game_scoreboards = [[match] for match in game_scoreboards]
            games = mlbgame.combine_games(game_scoreboards)

            year = date.year
            month = "{0:02d}".format(date.month)
            day = "{0:02d}".format(date.day)

            for game in games:
                gameid = game.game_id

                if not os.path.exists("xml/" + gameid):
                    os.makedirs("xml/" + gameid)

                dir_path = "http://gd2.mlb.com/components/game/mlb/year_%s/month_%s/day_%s/gid_%s/" % \
                          (year, month, day, gameid)

                for xml in xmls_to_fetch:
                    url_fetch = dir_path + xml
                    path_write = "xml/" + gameid + "/" + xml
                    self.fetch_xml(url_fetch, path_write)
Beispiel #5
0
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')
Beispiel #6
0
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
    }
Beispiel #7
0
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")
Beispiel #8
0
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))
Beispiel #9
0
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
Beispiel #10
0
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
Beispiel #11
0
    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)
Beispiel #12
0
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,
                })
Beispiel #13
0
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)
Beispiel #14
0
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)
Beispiel #15
0
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)
tomorrow_games = mlbgame.games(tomorrow.year, tomorrow.month, tomorrow.day)
Beispiel #16
0
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")
Beispiel #17
0
import datetime
import mlbgame

base = datetime.datetime.today()

### Setup Questions ###
numdays = int(raw_input("How many days back to you want to see?  "))

inclusion = str(raw_input("Include today? y/n  "))
if inclusion == 'n':
    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)]

num_runs = str(raw_input("How many runs?  "))

### Application ###
for d in date_list:
    yearr = d.year
    monthh = d.month
    datee = d.day

    print(str(d))
    game_day = mlbgame.games(yearr, monthh, datee)
    games = mlbgame.combine_games(game_day)
    for game in games:
        g = str(game)
        if "(%s)" % num_runs in g:
            print(g)
Beispiel #18
0
#!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)
Beispiel #19
0
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,