Exemplo n.º 1
0
def getADVStats(gameList):
    df1 = pd.DataFrame()
    for a in gameList:
        print(a)
        boxscore_summary = game.BoxscoreSummary(a)
        sql_team_basic = boxscore_summary.game_summary()
        sql_team_basic = sql_team_basic[['GAME_DATE_EST', 'GAMECODE']]

        boxscore_advanced = game.BoxscoreAdvanced(a)
        sql_team_advanced = boxscore_advanced.sql_team_advanced()

        team_four_factors = game.BoxscoreFourFactors(a)
        sql_team_four_factors = team_four_factors.sql_team_four_factors()

        boxscore = game.Boxscore(a)
        sql_team_scoring = boxscore.team_stats()

        df = pd.concat([
            sql_team_basic, sql_team_advanced, sql_team_four_factors,
            sql_team_scoring
        ],
                       axis=1)
        df1 = pd.concat([df1, df], axis=0)
    df1.fillna(method='ffill', inplace=True)
    # print(df1.head())
    print('Stats Compiled')
    return df1
Exemplo n.º 2
0
    def get_boxscore_data(self) -> Dict[str, Dict[str, pd.DataFrame]]:
        """Retrieve individual game boxscore data using API.
        """
        boxscore_data = {}
        for game_id in [f'002180{"%04d" % index}' for index in range(1, 1231)]:
            self.logger.info(f'Retrieving boxscore data for {game_id}')

            boxscore = game.Boxscore(game_id, season=self.season)
            boxscore_summary = game.BoxscoreSummary(game_id, season=self.season)

            boxscore_data[game_id] = {
                'player_data': boxscore.player_stats(),
                'game_summary': boxscore_summary.game_summary(),
                'inactive_players': boxscore_summary.inactive_players(),
                'line_score': boxscore_summary.line_score()
            }
            time.sleep(0.5)

        # boxscore_data = {}
        # for game_id in [f'002180{"%04d" % index}' for index in range(1, 1231)]:
        #     self.logger.info(f'Retrieving boxscore data for {game_id}')
        #
        #     with open(f'data/{self.season}/boxscore/{game_id}.json') as f:
        #         data = json.load(f)
        #
        #     boxscore_data[game_id] = {
        #         'player_data': pd.read_json(data['PLAYER_DATA']),
        #         'game_summary': pd.read_json(data['GAME_SUMMARY']),
        #         'inactive_players': pd.read_json(data['INACTIVE_PLAYER']),
        #         'line_score': pd.read_json(data['LINE_SCORE'])
        #     }

        return boxscore_data
Exemplo n.º 3
0
def test():
    gid = '0041400122'
    assert game.BoxscoreSummary(gid)
    assert game.Boxscore(gid)
    assert game.BoxscoreScoring(gid)
    assert game.BoxscoreUsage(gid)
    assert game.BoxscoreMisc(gid)
    assert game.BoxscoreAdvanced(gid)
    assert game.BoxscoreFourFactors(gid)
    assert game.PlayByPlay(gid)
 def testAll(self):
     assert game.BoxscoreSummary(self.gameId)
     assert game.Boxscore(self.gameId)
     assert game.BoxscoreScoring(self.gameId)
     assert game.BoxscoreUsage(self.gameId)
     assert game.BoxscoreMisc(self.gameId)
     assert game.BoxscoreAdvanced(self.gameId)
     assert game.BoxscoreFourFactors(self.gameId)
     assert game.PlayByPlay(self.gameId)
     assert game.HustleStats(self.gameId)
Exemplo n.º 5
0
 def worker(self, q):
     while True:
         game_id = q.get()
         game_summary = game.BoxscoreSummary(str(game_id)).game_summary()
         # for some reason there's duplicate records of some games,
         # so we just store the first result
         if isinstance(game_summary, pandas.DataFrame):
             game_summary = game_summary.to_dict("records")
         self.db.all_games_summaries.insert_one(game_summary[0])
         print("%d game summaries processed" %
               self.db.all_games_summaries.count())
         q.task_done()
Exemplo n.º 6
0
def update_refs(db=os.path.join("..", "data", "l2m.db")):
    """Get referees for each l2m.
    Args:
        db (str) - path to l2m.db.
    """

    tstart = time.time()
    print("L2M: Updating referee table.                                       ")
    sys.stdout.flush()

    # -- Load existing data.
    try:
        with sqlite3.connect(db) as conn:
            refs = pd.read_sql("SELECT * FROM refs", conn)
    except:
        refs = []

    with sqlite3.connect(db) as conn:
        urls = pd.read_sql("SELECT * FROM urls", conn)

    # -- Get list of gameids that do not have corresponding ref data.
    if len(refs) > 0:
        gameids = list(set(urls.gameid.values) - set(refs.gameid.values))
    else:
        gameids = list(set(urls.gameid.values))

    data = []
    ngames = len(urls)
    # -- For each gameid get referees.
    for idx, gameid in enumerate(gameids):
        refs = game.BoxscoreSummary(gameid).json["resultSets"][2]["rowSet"]
        refs = [[gameid] + ref for ref in refs]
        data = data + refs
        print("L2M: Finding refs for game {} ({}/{})                         " \
            .format(gameid, idx, ngames))
        sys.stdout.flush()

    # -- Put data in dataframe.
    cols = ["gameid", "refid", "first_name", "last_name", "jersey_num"]
    df = pd.DataFrame(data, columns=cols)

    # -- Write dataframe to db.
    with sqlite3.connect(db) as conn:
        df.to_sql("refs", conn, if_exists="append")

    print("L2M: Complete ({:.2f}s elapsed)                                   " \
        .format(time.time() - tstart))
    sys.stdout.flush()
Exemplo n.º 7
0
def load_custom_data(teamName, season, opponentTeam):
    #df = team.TeamOpponentSplits(TEAMS[teamName]['id'],location='Home',season=get_season(season),
    #                               opponent_team_id =TEAMS[opponentTeam]['id']).by_opponent()
    df = game.BoxscoreSummary(game_id='0041400122').line_score()
    #df = team.TeamGameLogs(TEAMS[teamName]['id'], get_season(season)).info()
    lf = Scoreboard().east_conf_standings_by_day()
    #df = team.TeamYearOverYearSplits(TEAMS[teamName]['id'], measure_type='Advanced',season=get_season(season), opponent_team_id =TEAMS[opponentTeam]['id']).by_year()
    #df = team.TeamOpponentSplits(TEAMS[teamName]['id'], measure_type='Advanced', season=get_season(season),                                 opponent_team_id=TEAMS[opponentTeam]['id']).by_opponent()
    print(list(lf))
    print(lf)
    print(list(df))
    print(df)
    #print(list(df))
    #return df
    df1 = team.TeamGameLogs(TEAMS[teamName]['id'], get_season(season)).info()
    #df1 = team.TeamLineups(TEAMS['MIL']['id']).overall()
    print(list(df1))
    return df1
Exemplo n.º 8
0
def get_refs(score_home, score_away, home, guest):

    connect = sqlite3.connect("nbadb.db")
    cursor = connect.cursor()
    officials_dict = game.BoxscoreSummary('0041700151').officials().to_dict()
    off_params = []
    for i in range(len(officials_dict['FIRST_NAME'])):
        cursor.execute(
            """SELECT FirstName, LastName, "FGA Home Teams","FGA Visitor Teams", "FTA Home Teams","FTA Visitor Teams" FROM officials
                                                      WHERE FirstName = (?) AND LastName = (?)
                                                  """, (
                officials_dict['FIRST_NAME'][i],
                officials_dict['LAST_NAME'][i],
            ))
        off_params.append(cursor.fetchall()[0])
    cursor.execute(
        """SELECT FTA,FGA,FT_PCT,FG_PCT FROM team_stats_home
                                                      WHERE TEAM_ID = (?)
                                                  """, (home, ))
    fta_home, fga_home, ft_pct_home, fg_pct_home = cursor.fetchall()[0]
    cursor.execute(
        """SELECT FTA,FGA,FT_PCT,FG_PCT FROM team_stats_away
                                                          WHERE TEAM_ID = (?)
                                                      """, (guest, ))

    fta_away, fga_away, ft_pct_away, fg_pct_away = cursor.fetchall()[0]
    home_pts = fg_pct_home * (
        ((off_params[0][2] + off_params[1][2] + off_params[2][2]) / 3 +
         fga_home) / 2 - fga_home)
    away_pts = fg_pct_away * (
        ((off_params[0][3] + off_params[1][3] + off_params[2][3]) / 3 +
         fga_away) / 2 - fga_away)
    home_fts = ft_pct_home * (
        ((off_params[0][4] + off_params[1][4] + off_params[2][4]) / 3 +
         fta_home) / 2 - fta_home)
    away_fts = ft_pct_away * (
        ((off_params[0][5] + off_params[1][5] + off_params[2][5]) / 3 +
         fta_away) / 2 - fta_away)
    score_home = score_home + home_pts + home_fts
    score_away = score_away + away_pts + away_fts

    return score_home, score_away, home, guest
    def testBoxScoreSummary(self):
        boxscoresummary = game.BoxscoreSummary(self.gameId)

        availablevideo = boxscoresummary.available_video()
        self.assertTrue((1, 7), availablevideo.shape)
        self.assertTrue((2 == availablevideo[0:2].VIDEO_AVAILABLE_FLAG).all())

        gameinfo = boxscoresummary.game_info()
        self.assertTrue((1, 3), gameinfo.shape)
        self.assertTrue((18624 == gameinfo[1:2].ATTENDANCE).all())

        gamesummary = boxscoresummary.game_summary()
        self.assertTrue((1, 14), gamesummary.shape)
        self.assertTrue(('20181022/ORLBOS' == gamesummary[1:2].GAMECODE).all())

        inactiveplayers = boxscoresummary.inactive_players()
        self.assertTrue((8, 8), inactiveplayers.shape)
        self.assertTrue(('Dozier' == inactiveplayers[1:2].LAST_NAME).all())

        lastmeeting = boxscoresummary.last_meeting()
        self.assertTrue((1, 13), lastmeeting.shape)
        self.assertTrue(
            ('Orlando' == lastmeeting[1:2].LAST_GAME_VISITOR_TEAM_CITY).all())

        linescore = boxscoresummary.line_score()
        self.assertTrue((2, 23), linescore.shape)
        self.assertTrue((93 == linescore[1:2].PTS).all())

        officials = boxscoresummary.officials()
        self.assertTrue((3, 4), officials.shape)
        self.assertTrue(('Orr' == officials[1:2].LAST_NAME).all())

        otherstats = boxscoresummary.other_stats()
        self.assertTrue((2, 14), otherstats.shape)
        self.assertTrue(('Orlando' == otherstats[1:2].TEAM_CITY).all())

        seasonseries = boxscoresummary.season_series()
        self.assertTrue((1, 7), seasonseries.shape)
        self.assertTrue(('Orlando' == seasonseries[1:2].SERIES_LEADER).all())
Exemplo n.º 10
0
            dct[a]['OPP_BLK'] = dct[b]['BLK']
            dct[a]['OPP_TO'] = dct[b]['TO']
            dct[a]['OPP_PF'] = dct[b]['PF']
            dct[a]['OPP_PLUS_MINUS'] = dct[b]['PLUS_MINUS']

        add_opp_stats(team_logs, 0, 1)
        add_opp_stats(team_logs, 1, 0)
        db.team_game_logs.insert_many(team_logs)
        q.task_done()


for i in range(num_worker_threads):
    t = Thread(target=worker)
    t.daemon = True
    t.start()

q.join()

game_ids = db.team_game_logs.distinct("GAME_ID")
count = 0
for game_id in game_ids:
    count += 1
    print count
    ap = game.BoxscoreSummary(game_id=game_id)
    game_date = ap.game_info()[0]['GAME_DATE']
    db.team_game_logs.update_many({"GAME_ID": game_id},
                                  {"$set": {
                                      "GAME_DATE": game_date
                                  }},
                                  upsert=False)
Exemplo n.º 11
0
def load_customized_data(teamName, startYear, endYear):
    home_team = []
    away_team = []
    home_team_home_record_pct = []
    away_team_away_record_pct = []
    home_team_current_win_percentage = []
    away_team_current_win_percentage = []
    home_team_current_standing = []
    away_team_current_standing = []
    home_team_win_percentage_streak_over_last_n_games = []
    away_team_win_percentage_streak_over_last_n_games = []
    home_team_current_streak = []
    away_team_current_streak = []
    recent_head_to_head_wrt_home_team = []

    df = get_teamBoxScore(teamName, get_season(startYear))
    time.sleep(0.5)
    for index, row in df.iterrows():
        game_id = row["Game_ID"]
        print("game_id", game_id)
        game_summary = game.BoxscoreSummary(game_id=game_id).game_summary()
        time.sleep(0.5)
        game_summary = game_summary.iloc[0]

        home_team_id = game_summary["HOME_TEAM_ID"]

        away_team_id = game_summary["VISITOR_TEAM_ID"]
        home_team.append(home_team_id)
        away_team.append(away_team_id)
        date = datetime.datetime.strptime(row['GAME_DATE'], "%b %d, %Y")
        year, month, day = date.year, date.month, date.day
        scoreboard = Scoreboard(month=month, day=day, year=year)
        time.sleep(0.5)
        if IdToConference[str(home_team_id)] == 'Eastern':
            day_home_stats = scoreboard.east_conf_standings_by_day()
        else:
            day_home_stats = scoreboard.west_conf_standings_by_day()

        if IdToConference[str(away_team_id)] == 'Eastern':
            day_away_stats = scoreboard.east_conf_standings_by_day()
        else:
            day_away_stats = scoreboard.west_conf_standings_by_day()

        home_index = np.flatnonzero(
            day_home_stats['TEAM_ID'] == home_team_id)[0]
        away_index = np.flatnonzero(
            day_away_stats['TEAM_ID'] == away_team_id)[0]
        day_home_team_stats = day_home_stats.iloc[home_index]
        day_away_team_stats = day_away_stats.iloc[away_index]
        #print("idx::",day_home_team_stats)
        home_team_current_win_percentage.append(day_home_team_stats["W_PCT"])
        away_team_current_win_percentage.append(day_away_team_stats["W_PCT"])
        home_team_current_standing.append(home_index + 1)
        away_team_current_standing.append(away_index + 1)
        #print ("hhghg:",day_home_team_stats["HOME_RECORD"])
        home_wins, home_losses = map(
            int, day_home_team_stats["HOME_RECORD"].split('-'))
        away_wins, away_losses = map(
            int, day_away_team_stats["ROAD_RECORD"].split('-'))
        home_team_home_w_pct = 0
        away_team_away_w_pct = 0
        if home_wins + home_losses:
            home_team_home_w_pct = home_wins / (home_wins + home_losses)
        if away_wins + away_losses:
            away_team_away_w_pct = away_wins / (away_wins + away_losses)

        home_team_home_record_pct.append(home_team_home_w_pct)
        away_team_away_record_pct.append(away_team_away_w_pct)

    for i in range(endYear - startYear):
        season = get_season(startYear + 1 + i)
        print("season:::", season)
        additional_data = get_teamBoxScore(teamName, season)
        time.sleep(0.5)
        for index, row in additional_data.iterrows():
            game_id = row["Game_ID"]
            print("game_id::", game_id)
            game_summary = game.BoxscoreSummary(game_id=game_id).game_summary()
            time.sleep(0.5)
            game_summary = game_summary.iloc[0]
            home_team_id = game_summary["HOME_TEAM_ID"]
            away_team_id = game_summary["VISITOR_TEAM_ID"]
            home_team.append(home_team_id)
            away_team.append(away_team_id)
            date = datetime.datetime.strptime(row['GAME_DATE'], "%b %d, %Y")
            year, month, day = date.year, date.month, date.day
            scoreboard = Scoreboard(month=month, day=day, year=year)
            time.sleep(0.5)
            day_stats = None
            if IdToConference[str(home_team_id)] == 'Eastern':
                day_home_stats = scoreboard.east_conf_standings_by_day()
            else:
                day_home_stats = scoreboard.west_conf_standings_by_day()

            if IdToConference[str(away_team_id)] == 'Eastern':
                day_away_stats = scoreboard.east_conf_standings_by_day()
            else:
                day_away_stats = scoreboard.west_conf_standings_by_day()

            try:
                home_index = np.flatnonzero(
                    day_home_stats['TEAM_ID'] == home_team_id)[0]
            except:
                print("home_team_id::", home_team_id)
                print("stats::", day_home_stats)
                print("game_id:::", game_id, game_summary)
                raise Exception("sha")
            away_index = np.flatnonzero(
                day_away_stats['TEAM_ID'] == away_team_id)[0]
            day_home_team_stats = day_home_stats.iloc[home_index]
            day_away_team_stats = day_home_stats.iloc[away_index]
            home_team_current_win_percentage.append(
                day_home_team_stats["W_PCT"])
            away_team_current_win_percentage.append(
                day_away_team_stats["W_PCT"])
            home_team_current_standing.append(home_index + 1)
            away_team_current_standing.append(away_index + 1)
            home_wins, home_losses = map(
                int, day_home_team_stats["HOME_RECORD"].split('-'))
            away_wins, away_losses = map(
                int, day_away_team_stats["ROAD_RECORD"].split('-'))
            home_team_home_w_pct = 0
            away_team_away_w_pct = 0
            if home_wins + home_losses:
                home_team_home_w_pct = home_wins / (home_wins + home_losses)
            if away_wins + away_losses:
                away_team_away_w_pct = away_wins / (away_wins + away_losses)

            home_team_home_record_pct.append(home_team_home_w_pct)
            away_team_away_record_pct.append(away_team_away_w_pct)

        df = df.append(additional_data, ignore_index=True)

    home_team_series = pd.Series(home_team)
    away_team_series = pd.Series(away_team)
    home_team_home_record_pct_series = pd.Series(home_team_home_record_pct)
    away_team_away_record_pct_series = pd.Series(away_team_away_record_pct)
    home_team_current_win_percentage_series = pd.Series(
        home_team_current_win_percentage)
    away_team_current_win_percentage_series = pd.Series(
        away_team_current_win_percentage)
    home_team_current_standing_series = pd.Series(home_team_current_standing)
    away_team_current_standing_series = pd.Series(away_team_current_standing)

    print("length:::", len(home_team_series.values))
    print("df_length:::", df.index)
    df = df.assign(home_team=home_team_series.values)
    df = df.assign(away_team=away_team_series.values)
    df = df.assign(
        home_team_home_record_pct=home_team_home_record_pct_series.values)
    df = df.assign(
        away_team_home_record_pct=away_team_away_record_pct_series.values)
    df = df.assign(
        home_team_current_win_percentage=home_team_current_win_percentage_series
        .values)
    df = df.assign(
        away_team_current_win_percentage=away_team_current_win_percentage_series
        .values)
    df = df.assign(
        home_team_current_standing_series=home_team_current_standing_series.
        values)
    df = df.assign(
        away_team_current_standing_series=away_team_current_standing_series.
        values)

    print("headers:::", list(df))
    return df
Exemplo n.º 12
0
    game_id_count = 1

    #Loop through the game_id's until the last game is reached, upon which a break is triggered
    while True:

        #Replace the game_id_temple with the proper variables
        game_id = template_game_id.replace(
            '@',
            str(year)[2:4]).replace('!',
                                    str(game_id_count).rjust(5, '0'))
        print(game_id)

        #Call the API, if it fails, it means you hit the last game, move onto the next year
        try:
            boxscore_summary = game.Boxscore(game_id)
            game_summary = game.BoxscoreSummary(game_id)
        except:
            break

        #Get stats
        player_stats = boxscore_summary.player_stats()
        game_stats = game_summary.line_score()
        game_info = game_summary.game_summary()

        if player_stats.empty or game_stats.empty or game_info.empty:
            break

        #Wins and lossess are stored in the format: Wins-Losses, parse it and get the numeric values
        win_loss = game_summary.line_score()['TEAM_WINS_LOSSES']
        win_loss = win_loss.str.split('-')
        try:
Exemplo n.º 13
0
from nba_py import game
from time import sleep

infile = open("gameids.csv", 'r')
outfile = open("nbagames.csv", 'a')
failfile = open("failgid.csv", 'a')

for line in infile:
    gameid = line.rstrip()
    try:
        bs = game.BoxscoreSummary("00" + str(gameid))
        for gamesum in bs.game_summary():
            outfile.write(str(gamesum['GAME_ID']) + ', ')
            outfile.write(str(gamesum['GAME_SEQUENCE']) + ', ')
            outfile.write(str(gamesum['GAME_STATUS_TEXT']) + ', ')
            outfile.write(str(gamesum['HOME_TEAM_ID']) + ', ')
            outfile.write(str(gamesum['VISITOR_TEAM_ID']) + ', ')
            outfile.write(str(gamesum['SEASON']) + ', ')
            outfile.write(
                str(gamesum['NATL_TV_BROADCASTER_ABBREVIATION']) + ', ')
        for gameinf in bs.game_info():
            outfile.write(str(gameinf['GAME_DATE']) + ', ')
            outfile.write(str(gameinf['GAME_TIME']) + ', ')
            outfile.write(str(gameinf['ATTENDANCE']) + '\n')
        print(gameid + " successful")
        sleep(2)
    except Exception as exception:
        failfile.write(gameid + '\n')
        print(exception)
        sleep(2)
Exemplo n.º 14
0
def boxscore_summary(game_id, start_period, end_period, start_range,
                     end_range, range_type):
    return game.BoxscoreSummary(game_id, start_period=start_period,
                                end_period=end_period, start_range=start_range,
                                end_range=end_range, range_type=range_type)
Exemplo n.º 15
0
from nba_py.shotchart import ShotChart
from nba_py import game
import requests_cache
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from multiprocessing import Pool
import numpy as np
for i in range(1100, 1231):
    # Generate games, they are 0001 to 1230
    print("ITERS", i)
    path = '/Users/tynanseltzer/ap216/project/pics/10/'
    gamestr = '002100'
    gamestr += str(i).zfill(4)
    # Home players
    summary = game.BoxscoreSummary(game_id=gamestr).game_summary()
    homeTeam = summary['HOME_TEAM_ID']
    awayTeam = summary['VISITOR_TEAM_ID']
    ids = game.Boxscore(game_id=gamestr).player_stats()['PLAYER_ID']
    # Go through players
    appended_data = []
    for an_id in ids:
        shot_df = ShotChart(player_id=an_id, game_id=gamestr, season='2010-11')
        shot_df = shot_df.shot_chart()
        appended_data.append(shot_df)
    shot_df = pd.concat(appended_data, axis=0)
    plt.scatter(shot_df.LOC_X, shot_df.LOC_Y)
    homePath = path + gamestr + ".jpg"
    plt.savefig(homePath,
                dpi=100,
                frameon='false',
Exemplo n.º 16
0
def boxscores(gameid, season=CURRENT_SEASON):
    boxscore = game.Boxscore(gameid)

    player_stats = boxscore.player_stats()
    team_stats = boxscore.team_stats()

    len_player_stats = len(player_stats)
    len_team_stats = len(team_stats)
    num_starters = 5
    starters_title = True

    # Used to calculate the current season
    try:
        boxscore_summary = game.BoxscoreSummary(gameid)
    except:
        return render_template("boxscores.html",
                               title="boxscore",
                               len_team_stats=0)

    boxscore_game_summary = boxscore_summary.game_summary()
    home_team = boxscore_game_summary[0]["GAMECODE"][9:12]
    away_team = boxscore_game_summary[0]["GAMECODE"][12:16]

    if home_team in TEAM_ID_DATA:
        home_team_city = TEAM_ID_DATA[home_team]["city"]
        home_team_name = TEAM_ID_DATA[home_team]["name"]
        home_team_logo = TEAM_ID_DATA[home_team]["img"]
    else:
        home_team_logo = False

    if away_team in TEAM_ID_DATA:
        away_team_city = TEAM_ID_DATA[away_team]["city"]
        away_team_logo = TEAM_ID_DATA[away_team]["img"]
        away_team_name = TEAM_ID_DATA[away_team]["name"]
    else:
        away_team_logo = False

    boxscore_game_date = boxscore_game_summary[0]["GAME_DATE_EST"]
    datetime_boxscore = datetime.datetime.strptime(boxscore_game_date[:10],
                                                   "%Y-%m-%d")
    pretty_date = datetime_boxscore.strftime("%b %d, %Y")

    # Get current season like "2016-17".
    to_year = int(boxscore_game_summary[0]["SEASON"])
    next_year = to_year + 1

    season = str(to_year) + "-" + str(next_year)[2:4]

    # Create NBA recap link.
    recap_date = datetime_boxscore.strftime("%Y/%m/%d")

    # Get nba recap video links for previous years like 2016 or before.
    # It takes 2 extra seconds. Commenting for now.
    # nba_recap = False
    """
    if (to_year < 2016):
        nba_recap = "http://www.nba.com/video/games/" + TEAM_ID_DATA[away_team]["name"] + "/" + recap_date + "/" + gameid + "-" + home_team + "-" + away_team + "-recap.nba"
        if not test_link(nba_recap):
            nba_recap = "http://www.nba.com/video/channels/playoffs/" + recap_date + "/" + gameid + "-" + home_team + "-" + away_team + "-recap.nba"

            if not test_link(nba_recap):
              nba_recap = False
    """
    if (to_year >= 2016):
        nba_recap = "http://www.nba.com/video/" + recap_date + "/" + gameid + "-" + home_team + "-" + away_team + "-recap"
        if not test_link(nba_recap):
            yesterday = datetime_boxscore - datetime.timedelta(1)
            recap_date = yesterday.strftime("%Y/%m/%d")
            nba_recap = "http://www.nba.com/video/" + recap_date + "/" + gameid + "-" + home_team + "-" + away_team + "-recap"
            if not test_link(nba_recap):
                nba_recap = False
    else:
        nba_recap = False

    # Figure out which team won or is winning.
    leading_points = 0
    winning = ""
    for i in team_stats:
        if i["PTS"] > leading_points:
            leading_points = i["PTS"]
            winning = i["TEAM_ABBREVIATION"]
        elif i["PTS"] < leading_points:
            continue
        else:
            winning = False

    # Add a 0 to a single digit minute like 4:20 to 04:20
    # Because bootstrap-datatable requires consistency.
    for i in player_stats:
        if (i["MIN"] and not isinstance(i["MIN"], int)):
            if (len(i["MIN"]) == 4):
                i["MIN"] = "0" + i["MIN"]

    if (len_team_stats != 0):
        team_summary_info = [
            team.TeamSummary(team_stats[0]["TEAM_ID"], season=season).info(),
            team.TeamSummary(team_stats[1]["TEAM_ID"], season=season).info()
        ]
    else:
        team_summary_info = False

    # Search for relevant reddit Post Game Thread.
    boxscore_line_score = boxscore_summary.line_score()
    """
    startTime = time.time()
    elapsedTime = time.time() - startTime
    elapsedTime = elapsedTime * 1000
    print(elapsedTime)
    """
    # post_game_thread = False
    post_game_thread = get_post_game_thread(
        next_year, boxscore_game_summary[0]["GAME_STATUS_TEXT"],
        boxscore_line_score, team_stats)

    # Get link for fullmatchtv (full broadcast video link). It takes 2 extra seconds. Commenting for now.
    full_match_url = False
    """
    if (next_year > 2016 and boxscore_game_summary[0]["GAME_STATUS_TEXT"] == "Final"):
        match_date = datetime_boxscore.strftime("%b-%-d-%Y")
        full_match_url = search_nba_full_match(away_team_city,
                                               away_team_name,
                                               home_team_city,
                                               home_team_name,
                                               match_date)
    else:
        full_match_url = False
    """

    if (team_stats
            and boxscore_game_summary[0]["GAME_STATUS_TEXT"] == "Final"):
        youtube_search_query = team_stats[0]["TEAM_CITY"] + " " + \
                               team_stats[0]["TEAM_NAME"] + " vs " + \
                               team_stats[1]["TEAM_CITY"] + " " + \
                               team_stats[1]["TEAM_NAME"] + " " + \
                               pretty_date
        youtube_url = youtube_search(youtube_search_query, 1)
    else:
        youtube_url = False

    inactive_players = boxscore_summary.inactive_players()
    officials = boxscore_summary.officials()

    return render_template("boxscores.html",
                           title="boxscore",
                           player_stats=player_stats,
                           len_player_stats=len_player_stats,
                           len_team_stats=len_team_stats,
                           starters_title=starters_title,
                           num_starters=num_starters,
                           team_stats=team_stats,
                           winning=winning,
                           team_summary_info=team_summary_info,
                           pretty_date=pretty_date,
                           boxscore_line_score=boxscore_line_score,
                           post_game_thread=post_game_thread,
                           home_team=home_team,
                           away_team=away_team,
                           home_team_logo=home_team_logo,
                           away_team_logo=away_team_logo,
                           nba_recap=nba_recap,
                           full_match_url=full_match_url,
                           youtube_url=youtube_url,
                           inactive_players=inactive_players,
                           officials=officials)
Exemplo n.º 17
0
adv = game.BoxscoreAdvanced(g_id)
adv = adv.sql_team_advanced()
ff = game.BoxscoreFourFactors(g_id)
ff = ff.sql_team_four_factors()
df = []
df.append(trad)
df.append(adv)
df.append(ff)
merge0 = pd.concat(df, axis=1)
df1, df2 = np.split(merge0, [1], axis=0)
cols_A = [col + 'A' for col in df1.columns]
cols_B = [col + 'B' for col in df2.columns]
df1.columns = cols_A
df2.columns = cols_B
df2 = df2.reset_index(drop=True)
summ = game.BoxscoreSummary(g_id)
hc_df = summ.game_summary()
hc_df = hc_df[['HOME_TEAM_ID']]
raw_data = pd.concat([df1, df2, hc_df], axis=1)
for i in range((int(g_id) + 1), int(recent_id), 1):
    game_id = '00' + str(i)
    trad = game.Boxscore(game_id)
    trad = trad.team_stats()
    adv = game.BoxscoreAdvanced(game_id)
    adv = adv.sql_team_advanced()
    ff = game.BoxscoreFourFactors(game_id)
    ff = ff.sql_team_four_factors()
    df = []
    df.append(trad)
    df.append(adv)
    df.append(ff)
infile = open("gameids.csv", 'r')
outfile = open("nbascores.csv", 'a')
failfile = open("failgid.csv", 'a')

sent = True

for line in infile:
    gameid = line.rstrip()

    if gameid != "0021500841" and sent:
        print("not yet")
        continue
    else:
        sent = False
    try:
        bs = game.BoxscoreSummary(gameid)
        for i in range(0, 2):
            teamscore = bs.line_score()[i]
            outfile.write(str(gameid) + ", ")
            outfile.write(str(teamscore["TEAM_ID"]) + ", ")
            outfile.write(str(teamscore["PTS"]) + "\n")
        print(gameid + " successful")
        sleep(2)
    except Exception as exception:
        failfile.write(gameid + '\n')
        print(exception)
        sleep(2)

infile.close()
outfile.close()
failfile.close()
Exemplo n.º 19
0
def boxscores(gameid, season=CURRENT_SEASON):
    boxscore = game.Boxscore(gameid)

    player_stats = boxscore.player_stats()
    team_stats = boxscore.team_stats()

    len_player_stats = len(player_stats)
    len_team_stats = len(team_stats)
    num_starters = 5
    starters_title = True

    # Used to calculate the current season
    try:
        boxscore_summary = game.BoxscoreSummary(gameid)
    except:
        return render_template("boxscores.html",
                               title="boxscore",
                               len_team_stats=0)

    boxscore_game_summary = boxscore_summary.game_summary()
    home_team = boxscore_game_summary[0]["GAMECODE"][9:12]
    away_team = boxscore_game_summary[0]["GAMECODE"][12:16]

    if home_team in TEAM_ID_DATA:
        home_team_city = TEAM_ID_DATA[home_team]["city"]
        home_team_name = TEAM_ID_DATA[home_team]["name"]
        home_team_logo = TEAM_ID_DATA[home_team]["img"]
    else:
        home_team_logo = False

    if away_team in TEAM_ID_DATA:
        away_team_city = TEAM_ID_DATA[away_team]["city"]
        away_team_logo = TEAM_ID_DATA[away_team]["img"]
        away_team_name = TEAM_ID_DATA[away_team]["name"]
    else:
        away_team_logo = False

    boxscore_game_date = boxscore_game_summary[0]["GAME_DATE_EST"]
    datetime_boxscore = datetime.datetime.strptime(boxscore_game_date[:10],
                                                   "%Y-%m-%d")
    pretty_date = datetime_boxscore.strftime("%b %d, %Y")

    # Get current season like "2017-18".
    to_year = int(boxscore_game_summary[0]["SEASON"])
    next_year = to_year + 1

    season = str(to_year) + "-" + str(next_year)[2:4]

    # Create NBA recap link.
    recap_date = datetime_boxscore.strftime("%Y/%m/%d")

    # Figure out which team won or is winning.
    leading_points = 0
    winning = ""
    for i in team_stats:
        if i["PTS"] > leading_points:
            leading_points = i["PTS"]
            winning = i["TEAM_ABBREVIATION"]
        elif i["PTS"] < leading_points:
            continue
        else:
            winning = False

    # Add a 0 to a single digit minute like 4:20 to 04:20
    # Because bootstrap-datatable requires consistency.
    for i in player_stats:
        if (i["MIN"] and not isinstance(i["MIN"], int)):
            if (len(i["MIN"]) == 4):
                i["MIN"] = "0" + i["MIN"]

    if (len_team_stats != 0):
        team_summary_info = [
            team.TeamSummary(team_stats[0]["TEAM_ID"], season=season).info(),
            team.TeamSummary(team_stats[1]["TEAM_ID"], season=season).info()
        ]
    else:
        team_summary_info = False

    post_game_thread = get_post_game_thread(
        next_year, boxscore_game_summary[0]["GAME_STATUS_TEXT"],
        boxscore_line_score, team_stats)

    # Get link for fullmatchtv (full broadcast video link). It takes 2 extra seconds. Commenting for now.
    full_match_url = False

    inactive_players = boxscore_summary.inactive_players()
    officials = boxscore_summary.officials()

    return render_template(
        "boxscores.html",
        title="boxscore",
        player_stats=player_stats,
        len_player_stats=len_player_stats,
        len_team_stats=len_team_stats,
        starters_title=starters_title,
        num_starters=num_starters,
        team_stats=team_stats,
        winning=winning,
        team_summary_info=team_summary_info,
        pretty_date=pretty_date,
        boxscore_line_score=boxscore_line_score,
        post_game_thread=post_game_thread,
        home_team=home_team,
        away_team=away_team,
        home_team_logo=home_team_logo,
        away_team_logo=away_team_logo,
        nba_recap=nba_recap,
        full_match_url=full_match_url,
        #youtube_url=youtube_url,
        inactive_players=inactive_players,
        officials=officials)
Exemplo n.º 20
0
from nba_py import game

boxscore_summary = game.BoxscoreSummary("0021800526")
print(boxscore_summary.game_summary())
print(boxscore_summary.other_stats())
print(boxscore_summary.officials())