Example #1
0
def find_games(days_ahead=0):
    """
    Pull today's upcoming games

    :param days_ahead (int, optional): number of days ahead from which to pull games
    :return: DataFrame
    """
    headers = {
        'Host': 'stats.nba.com',
        'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0',
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'en-US,en;q=0.5',
        'Referer': 'https://stats.nba.com/',
        'Accept-Encoding': 'gzip, deflate, br',
        'Connection': 'keep-alive',
        'x-nba-stats-origin': 'stats',
        'x-nba-stats-token': 'true'
    }
    board = scoreboardv2.ScoreboardV2(day_offset=days_ahead,
                                      headers=headers).get_data_frames()[0]
    board.replace(id_to_abrv, inplace=True)
    return board[[
        'GAME_DATE_EST', 'GAME_ID', 'HOME_TEAM_ID', 'VISITOR_TEAM_ID'
    ]]
Example #2
0
 def getScoreBoard(self, date="2016-02-27"):
     scoreBoard = scoreboardv2.ScoreboardV2(game_date=date,
                                            league_id="00",
                                            day_offset="0").get_dict()
     with open('scoreboard.json', 'w') as fp:
         json.dump(scoreBoard, fp, indent=3)
     return scoreBoard
def getTodaysPlayers():
    """
    Returns a list of player IDs belonging to players that played today
    :return:
    """
    data = scoreboardv2.ScoreboardV2().get_data_frames()[0]

    player_ids = []

    # print(data.to_string())
    # print(list(data))
    playing_team_ids = []
    home_team_ids = data["HOME_TEAM_ID"].tolist()
    # print(home_team_ids)
    playing_team_ids += home_team_ids

    # print(data.to_string())

    away_team_ids = data["VISITOR_TEAM_ID"].tolist()

    playing_team_ids += away_team_ids

    for team_id in playing_team_ids:
        # curr_team = [team for team in getAllNbaTeams()
        #              if team['id'] == team_id]

        current_team_roster = commonteamroster.CommonTeamRoster(
            team_id=team_id).get_data_frames()[0]
        time.sleep(2)
        for index, row in current_team_roster.iterrows():
            player_id = row['PLAYER_ID']
            player_ids.append(player_id)

    print(player_ids)
    return player_ids
 def game_finder(self):
     """
     Use set_date to look for games on different date
     :return: pandas series of game ids on select day
     """
     score_board = scoreboardv2.ScoreboardV2(game_date=self.__game_date__)
     game_id = pd.DataFrame(score_board.get_data_frames()[0]).loc[:,
                                                                  "GAME_ID"]
     return game_id
Example #5
0
def get_team_id(date):
    response = scoreboardv2.ScoreboardV2(game_date=date)
    content = json.loads(response.get_json())
    team_id = []
    for k, v in content.items():
        if k == "resultSets":
            for results in v:
                team_id.append(results.get("rowSet"))

    return team_id
Example #6
0
def contender(date):
    import pandas as pd
    import time
    from datetime import datetime, timedelta
    from nba_api.stats.endpoints import scoreboardv2

    #initialize
    standings = scoreboardv2.ScoreboardV2(game_date=date)
    ec_standings = standings.get_data_frames()[4]
    wc_standings = standings.get_data_frames()[5]
    standings_df = pd.concat([ec_standings, wc_standings],
                             axis=0,
                             ignore_index=True)
    teams_list = list(standings_df['TEAM'])
    contender = {}
    new_teams_list = [i for i in teams_list]

    while len(new_teams_list) > 0:
        for team in teams_list:
            if (standings_df.loc[standings_df['TEAM'] == team]['W'] >= 40).all(
            ) and (standings_df.loc[standings_df['TEAM'] == team]['L'] <
                   20).all():
                contender[team] = True
                new_teams_list.remove(team)
            elif (standings_df.loc[standings_df['TEAM'] == team]['L'] >=
                  20).all() and (
                      standings_df.loc[standings_df['TEAM'] == team]['W'] <
                      40).all():
                contender[team] = False
                new_teams_list.remove(team)

        teams_list = [i for i in new_teams_list]
        date = datetime.strptime(date, '%Y-%m-%d') + timedelta(days=1)
        date = datetime.strftime(date, '%Y-%m-%d')
        time.sleep(3)  # Need to sleep to avoid over accessing nba_api
        standings = scoreboardv2.ScoreboardV2(game_date=date)
        ec_standings = standings.get_data_frames()[4]
        wc_standings = standings.get_data_frames()[5]
        standings_df = pd.concat([ec_standings, wc_standings],
                                 axis=0,
                                 ignore_index=True)

    return contender
Example #7
0
def scoreboard2():
	current_date = datetime.today().strftime('%Y-%m-%d')
	game_date = request.args.get('game_date')
	if game_date != 'undefined' and game_date is not None:
		current_date = game_date
	board = scoreboardv2.ScoreboardV2(game_date=current_date)
	team_leaders = board.team_leaders.get_data_frame().drop(['GAME_ID','TEAM_ID','TEAM_CITY','TEAM_NICKNAME','TEAM_ABBREVIATION'], axis=1)
	scores = board.line_score.get_data_frame().rename(columns={'PTS': 'TOTAL_PTS', 'AST': 'TOTAL_AST', 'REB': 'TOTAL_REB'})
	current_games = pd.concat([team_leaders, scores], axis=1)
	return jsonify({'date': current_date, 'prev': current_games.to_dict(orient='records')})
Example #8
0
def write_daily_schedule_and_standings():
    s = scoreboardv2.ScoreboardV2(day_offset=0, game_date=today.strftime("%m/%d/%Y"), league_id="00")
    df = s.get_data_frames()
    schedule_frame = next(frame for frame in df if "NATL_TV_BROADCASTER_ABBREVIATION" in frame.columns)
    games_f = schedule_frame[['GAME_ID', 'GAME_STATUS_TEXT', 'HOME_TEAM_ID', 'VISITOR_TEAM_ID', 'NATL_TV_BROADCASTER_ABBREVIATION']]
    games_f.columns = ['GAME_ID', 'START_TIME', 'HOME_ID', 'AWAY_ID', 'NATL_TV']
    write_dataframe_to_csv_on_s3(games_f, "{}/schedule/{}".format(data_path_prefix, today.strftime('%Y-%m-%d.csv')), bucket_path)

    teams_f = pd.concat([frame for frame in df if "STANDINGSDATE" in frame.columns])
    teams_f = teams_f[['TEAM_ID', 'CONFERENCE', 'TEAM', 'G', 'W', 'L', 'W_PCT']]
    teams_f.sort_values(by=['CONFERENCE', 'W_PCT'])
    write_dataframe_to_csv_on_s3(teams_f, "{}/standings/{}".format(data_path_prefix, today.strftime('%Y-%m-%d.csv')), bucket_path)
def get_games_on_this_date():
    # This iterates over every year in the league's history and pulls every game on the current date.
    # The game data is written to a file
    
    years = range(1949, 2022)
    all_games = []

    for year in years:
        date = str(year) + '-' + str(month) + '-' + str(day)
        games = scoreboardv2.ScoreboardV2(game_date = date)
        game_dict = games.game_header.get_dict()
        print("good")
        all_games.append(game_dict)
        time.sleep(1.1)

    f = open("AllGamesOnThisDate.txt", "w")
    for game in all_games:
        f.write(str(game) + "\n")
    f.close()
Example #10
0
    def update_live_games(self):
        """Grab the latest live information based on current date.
        This method is to attempt to collect live information every 30 seconds
        to update the game information in the main window. If the data has not
        changed, do not send signal to update.
        """
        game_info = []

        # exceptions = (ConnectionError, ConnectionRefusedError, TimeoutError, )
        date = str(datetime.now().date())
        id = '00'
        try:
            current_scoreboard_info = scoreboardv2.ScoreboardV2(day_offset=0,
                                                                game_date=date,
                                                                league_id=id)

        except requests.exceptions.ConnectionError:
            print("Request failed.")

        else:
            game_info.append(current_scoreboard_info.line_score.data['data'])
            game_info.append(current_scoreboard_info.data_sets[0].data['data'])
            self.list_signal.emit(game_info)
Example #11
0
def predict_todays_games():
    """
    Creates a model for all the games happening today and tries to predict the outcomes
    :return:
    """
    # get todays date
    now = datetime.datetime.now()
    date = now.strftime("%Y-%m-%d")

    # call the scoreboard endpoint to get the games happening today
    scoreboard_data = scoreboardv2.ScoreboardV2().get_data_frames()[0]
    time.sleep(2)

    winners = []
    team_info = {}

    nba_teams = boxScoreScraper.getAllNbaTeams() # get a list containing information for all the teams
    print(nba_teams)


    for index, row in scoreboard_data.iterrows():

        # can get the teams playing by getting the GAMECODE of the row
        gamecode = row["GAMECODE"]
        tokens = gamecode.split("/")

        teams_playing_str = tokens[1]

        # slice the string to get the abbreviations of the teams playing
        away_team_abbreviation = teams_playing_str[:3]
        home_team_abbreviation = teams_playing_str[-3:]

        # format a matchup string using the abbreviations
        matchup = "{} @ {}".format(away_team_abbreviation, home_team_abbreviation)

        # get the dataframe for the away team
        filename = "{}datasets/{}_2015_to_2018.csv".format(filepath, away_team_abbreviation)
        df = load_dataset(filename) # load a dataframe for the teams data

        # create a model for the current team
        model = create_model(df)

        prediction = make_prediction(model, matchup, df)





        if 1 in prediction:
            # this means that the away team won the game
            winners.append(away_team_abbreviation)

            away_team_info = {} # create a dictionary of information for the winning team
            # need to store their prediction, their team id, and the team they played
            away_team_info["winPrediction"] = True # away team was predicted to win
            away_team_info["homeGame"] = False # were they the home team
            # iterate over nba_teams to find some information to store
            away_full_name = ""
            away_id = None

            home_full_name = ""
            home_id = None
            for team in nba_teams:
                if team["abbreviation"] == away_team_abbreviation:
                    away_full_name = team["full_name"]
                    away_id = team["id"]
                if team["abbreviation"] == home_team_abbreviation:
                    home_id = team["id"]
                    home_full_name = team["full_name"]
            away_team_info["full_name"] = away_full_name
            away_team_info["id"] = away_id
            away_team_info["date"] = date
            away_team_info["opponentId"] = home_id
            # team_info[away_team_abbreviation] = away_team_info

            # now store the required information for the home team
            home_team_info = {}
            home_team_info["winPrediction"] = False
            home_team_info["homeGame"] = True
            # for team in nba_teams:
            #     if team["abbreviation"] == home_team_abbreviation:
            #         home_full_name = team["full_name"]
            #         home_id = team["id"]
            #         break
            home_team_info["full_name"] = home_full_name
            home_team_info["id"] = home_id
            home_team_info["opponentId"] = away_id
            home_team_info["date"] = date
            home_team_info["opponentFullName"] = away_full_name
            team_info[home_team_abbreviation] = home_team_info

            away_team_info["opponentFullName"] = home_full_name
            team_info[away_team_abbreviation] = away_team_info


        else:
            # this means the home team won the game
            winners.append(home_team_abbreviation)

            away_team_info = {}  # create a dictionary of information for the winning team
            # need to store their prediction, their team id, and the team they played
            away_team_info["winPrediction"] = False  # away team was predicted to win
            away_team_info["homeGame"] = False  # were they the home team
            # iterate over nba_teams to find some information to store
            away_full_name = ""
            away_id = None
            home_full_name = ""
            home_id = None
            for team in nba_teams:
                if team["abbreviation"] == away_team_abbreviation:
                    away_full_name = team["full_name"]
                    away_id = team["id"]
                if team["abbreviation"] == home_team_abbreviation:
                    home_full_name = team["full_name"]
                    home_id = team["id"]
            away_team_info["full_name"] = away_full_name
            away_team_info["id"] = away_id
            away_team_info["opponentId"] = home_id
            away_team_info["date"] = date

            # now store the required information for the home team
            home_team_info = {}
            home_team_info["winPrediction"] = True
            home_team_info["homeGame"] = True
            # for team in nba_teams:
            #     if team["abbreviation"] == home_team_abbreviation:
            #         home_full_name = team["full_name"]
            #         home_id = team["id"]
            #         break
            home_team_info["full_name"] = home_full_name
            home_team_info["id"] = home_id
            home_team_info["opponentId"] = away_id
            home_team_info["opponentFullName"] = away_full_name
            home_team_info["date"] = date
            team_info[home_team_abbreviation] = home_team_info

            away_team_info["opponentFullName"] = home_full_name
            team_info[away_team_abbreviation] = away_team_info





    return team_info
Example #12
0
    today = {}

    #today games
    st.header('Todays Games:')
    games = json.loads(
        leaguegamefinder.LeagueGameFinder(league_id_nullable='00',
                                          player_or_team_abbreviation="",
                                          date_to_nullable=day,
                                          date_from_nullable=day).
        league_game_finder_results.get_json())['data']
    for game in games:
        if not game[4] in gamefinder:
            gamefinder.append(game[4])

    today_score = json.loads(
        scoreboardv2.ScoreboardV2(
            day_offset=0).get_json())['resultSets'][0]['rowSet']
    for row in today_score:
        today[row[2]] = {
            'Matchup': row[5][-6:-3] + " @ " + row[5][12:15],
            'Time': row[4],
            'Score': '',
            'National TV': row[11],
            'Home Feed': row[12],
            'Away Feed': row[13],
            'Arena': row[15]
        }

    for game in gamefinder:
        box_score = json.loads(
            winprobabilitypbp.WinProbabilityPBP(
                game_id=game).game_info.get_json())['data'][0]
Example #13
0
        path.join(data_path, 'game_logs',
                  date_in_question.strftime('%Y-%m-%d.csv'))):
    date_in_question = date_in_question + timedelta(1)

# I now have the first date that does not exist; I want to go back and update the last one that *does* in case it's incomplete
if date_in_question is not first_day:  # unless we're rebuilding the whole season, naturally
    date_in_question = date_in_question - timedelta(1)

while date_in_question <= today:
    write_data_file_for_date(date_in_question)
    date_in_question = date_in_question + timedelta(1)

# now, let's fetch up-to-date standings and schedule (for today) data
print("getting today's schedule and league standings")
s = scoreboardv2.ScoreboardV2(day_offset=0,
                              game_date=today.strftime("%m/%d/%Y"),
                              league_id="00")
df = s.get_data_frames()
games_f = df[0][[
    'GAME_ID', 'GAME_STATUS_TEXT', 'HOME_TEAM_ID', 'VISITOR_TEAM_ID',
    'NATL_TV_BROADCASTER_ABBREVIATION'
]]
games_f.columns = ['GAME_ID', 'START_TIME', 'HOME_ID', 'AWAY_ID', 'NATL_TV']
games_f.to_csv(path.join(data_path, 'schedule',
                         today.strftime('%Y-%m-%d.csv')),
               index=False)

teams_f = pd.concat([df[4], df[5]])
teams_f = teams_f[['TEAM_ID', 'CONFERENCE', 'TEAM', 'G', 'W', 'L', 'W_PCT']]
teams_f.sort_values(by=['CONFERENCE', 'W_PCT'])
teams_f.to_csv(path.join(data_path, 'standings',