示例#1
0
def GetAllBoxScores(next_n_days, start_month, start_day, start_year):
    print("GETTING ALL BOXSCORES")

    for i in range(next_n_days, 0, -1):
        # Request Scoreboard
        scoreboard = nba_py.Scoreboard(month=start_month,
                                       day=start_day,
                                       year=start_year,
                                       league_id='00',
                                       offset=i)
        box_scores_summaries.append(scoreboard.game_header())
        time.sleep(1)

        print("SCOREBOARD REQUEST COMPLETE: " + str(i))

        for game_id in scoreboard.available()['GAME_ID']:
            # Request Boxscore
            player_stats = game.Boxscore(game_id).player_stats()
            box_scores_player_stats.append(player_stats)
            time.sleep(1)

            team_stats = game.Boxscore(game_id).team_stats()
            box_scores_team_stats.append(team_stats)
            time.sleep(1)

            print("BOXSCORE REQUEST COMPLETE")
示例#2
0
def most_recent(id):
    foo = game.Boxscore(id)
    foo = foo.team_stats()
    recent_id = id
    while not foo.empty:
        recent_id = int(recent_id)
        recent_id += 1
        recent_id = '00' + str(recent_id)
        foo = game.Boxscore(recent_id)
        foo = foo.team_stats()
    return '00' + str(
        int(recent_id) - 15
    )  # Need to subtract 15 games because todays games are incomplete and will raise an error if included
示例#3
0
def combineTeam(name, season=current_year):
    df = getData(name, 'gamelog', season)
    sleep(1)
    df.columns = [x.upper() for x in df.columns]
    pid = df['PLAYER_ID'].unique()[0]
    df['TEAM_ID'] = playerInfo['TEAM_ID'].loc[playerInfo['PERSON_ID'] == pid].item()
    total = df['GAME_ID'].count()
    counter = 0
    ts = pd.DataFrame()
    for i in df['GAME_ID']:
        teamstats = pd.DataFrame(game.Boxscore(str(i), str(season) + '-' + str(int(season)+1)[-2:]).team_stats())
        teamstats.columns = ['TEAM_'+str(x) for x in teamstats.columns]
        ts = ts.append(teamstats)
        sleep(randint(1,3))
        counter += 1
        print('Finished {0} %'.format(round((counter/total)*100,0)))
    
    df = pd.merge(df, ts, how='left', left_on=['GAME_ID'], right_on = ['TEAM_GAME_ID'])
    # Player Stats and Team Stats
    df1 = df.loc[df['TEAM_ID'] == df['TEAM_TEAM_ID']] 
    df1 = df1.drop(['VIDEO_AVAILABLE', 'TEAM_GAME_ID', 'TEAM_TEAM_ID'], axis=1)
    df1 = df1.rename(columns = {'TEAM_TEAM_NAME' : 'TEAM_NAME', 'TEAM_TEAM_ABBREVIATION' : 'TEAM_ABBREVIATION', 'TEAM_TEAM_CITY' : 'TEAM_CITY'})
    # Opposing Team Stats
    df2 = df.loc[df['TEAM_ID'] != df['TEAM_TEAM_ID']].iloc[:,27:]
    df2 = df2.rename(columns = {'TEAM_TEAM_NAME' : 'TEAM_NAME', 'TEAM_TEAM_ABBREVIATION' : 'TEAM_ABBREVIATION', 'TEAM_TEAM_CITY' : 'TEAM_CITY'})
    df2.columns = ['OPP_'+x for x in df2.columns]
    df2 =  df2.drop('OPP_TEAM_ID', axis = 1)
    
    df = pd.merge(df1, df2, 'left', left_on='GAME_ID', right_on='OPP_TEAM_GAME_ID')
    df = df.drop('OPP_TEAM_GAME_ID', axis=1)
    return df
示例#4
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
def worker():
    global count
    while True:
        count += 1
        print count
        game_id = q.get()
        team_logs = game.Boxscore(str(game_id)).line_score()

        def add_opp_stats(dct, a, b):
            dct[a]['OPP_TEAM_ID'] = dct[b]['TEAM_ID']
            dct[a]['OPP_TEAM_NAME'] = dct[b]['TEAM_NAME']
            dct[a]['OPP_PTS'] = dct[b]['PTS']
            dct[a]['OPP_FGM'] = dct[b]['FGM']
            dct[a]['OPP_FGA'] = dct[b]['FGA']
            dct[a]['OPP_FG3M'] = dct[b]['FG3M']
            dct[a]['OPP_FG3A'] = dct[b]['FG3A']
            dct[a]['OPP_FTM'] = dct[b]['FTM']
            dct[a]['OPP_FTA'] = dct[b]['FTA']
            dct[a]['OPP_REB'] = dct[b]['REB']
            dct[a]['OPP_OREB'] = dct[b]['OREB']
            dct[a]['OPP_DREB'] = dct[b]['DREB']
            dct[a]['OPP_AST'] = dct[b]['AST']
            dct[a]['OPP_STL'] = dct[b]['STL']
            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()
示例#6
0
def getGameStatsArray(gameIDToken):

    #using the python client nba_py for gathering statistics
    boxscore = game.Boxscore(gameIDToken)
    #you can find the values returned by Boxscore in the nba_py documentation or editing this code to use the stats object's property: get_feature_names
    stats = boxscore.team_stats()

    team_1_stats_dict = stats[0]
    team_2_stats_dict = stats[1]
    #remove features from the python stats dictionary
    team_1_stats_dict.pop('GAME_ID')
    team_1_stats_dict.pop('TEAM_ID')
    team_1_stats_dict.pop('TEAM_NAME')
    team_1_stats_dict.pop('TEAM_ABBREVIATION')
    team_1_stats_dict.pop('TEAM_CITY')
    team_1_stats_dict.pop('MIN')
    team_2_stats_dict.pop('GAME_ID')
    team_2_stats_dict.pop('TEAM_ID')
    team_2_stats_dict.pop('TEAM_NAME')
    team_2_stats_dict.pop('TEAM_ABBREVIATION')
    team_2_stats_dict.pop('TEAM_CITY')
    team_2_stats_dict.pop('MIN')

    #transform the python dictionary->array using DictVectorzier from sklearn
    vec = DictVectorizer()
    array = vec.fit_transform([team_1_stats_dict, team_2_stats_dict]).toarray()

    sample = np.append(array[0], array[1])

    return sample
示例#7
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
示例#8
0
def test():
    gid = '0041400122'
    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)
示例#10
0
 def sync_detail_all(self):
     for item in self.schedule_list:
         gdate = item.get('gdte')
         t1 = time.strptime(gdate, '%Y-%m-%d')  # east time
         t2 = time.localtime()  # current time
         if t1 > t2:  # avoid overwhelming
             break
         gid = '{0:010d}'.format(int(item.get('gid')))
         game.Boxscore(gid).team_stats().to_sql('match_detail',
                                                self.conn,
                                                if_exists='append')
示例#11
0
def test():
    gid = '0041400122'
    print(game.BoxscoreSummary(gid).line_score())
    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)
    assert game.HustleStats(gid)
示例#12
0
 def sync_detail_incremental(self):
     gids = []
     for item in self.schedule_list:
         gdate = item.get('gdte')
         t1 = datetime.datetime.now() - datetime.timedelta(7)  # 增加备份时间
         t2 = datetime.datetime.strptime(gdate, '%Y-%m-%d')
         t3 = datetime.datetime.now() + datetime.timedelta(1)  # 北京时间比西方时间早
         if t1 < t2 and t2 < t3:
             gid = '{0:010d}'.format(int(item.get('gid')))
             gids.append(gid)
     for gid in gids:
         game.Boxscore(gid).team_stats().to_sql('match_detail',
                                                self.conn,
                                                if_exists='append')
示例#13
0
def get_gameDataWithTeamsAndPoints(teamName, season):
    teamsPlayingArray = []
    teamPointsArray = []

    team_id = TEAMS[teamName]['id']
    df = team.TeamGameLogs(team_id, season).info()

    gameIds = df["Game_ID"].values
    #   For each game get the teams who played and the points and add them to the dataframe line
    i = 0
    percentDone = 0
    for matchup in df["MATCHUP"]:
        print("%s %f " % (teamName, i / len(gameIds)))
        teamsVector = np.zeros(2 * len(teamToIndex))
        pointsVector = np.zeros(2 * len(teamToIndex))
        team_stats = game.Boxscore(gameIds[i]).team_stats()
        home = 0
        if '@' in matchup:
            home = 0
        else:
            home = 1
        teams = matchup.split(" ")
        ##        if(teams[0] not in teamToIndex.keys() or )
        t1Index = teamToIndex[teams[0]]
        t2Index = teamToIndex[teams[2]]
        if (team_stats["TEAM_ID"].values[0] == teamName):
            teamNamePoints = team_stats["PTS"].values[0]
            otherPoints = team_stats["PTS"].values[1]
        else:
            teamNamePoints = team_stats["PTS"].values[1]
            otherPoints = team_stats["PTS"].values[0]
        if home:
            teamsVector[t1Index] = 1
            teamsVector[t2Index + len(teamToIndex)] = 1

            pointsVector[t1Index] = teamNamePoints
            pointsVector[t2Index + len(teamToIndex)] = otherPoints
        else:
            teamsVector[t2Index] = 1
            teamsVector[t1Index + len(teamToIndex)] = 1
            pointsVector[t2Index] = otherPoints
            pointsVector[t1Index + len(teamToIndex)] = teamNamePoints

        teamsPlayingArray.append(teamsVector)
        teamPointsArray.append(pointsVector)
        i += 1
    df = df.assign(teams=pd.Series(teamsPlayingArray).values)
    df = df.assign(points=pd.Series(teamPointsArray).values)
    return df
    def testBoxScore(self):
        boxscore = game.Boxscore(self.gameId)

        playerstats = boxscore.player_stats()
        self.assertTrue((26, 28), playerstats.shape)
        self.assertTrue(('Aaron Gordon' == playerstats[1:2].PLAYER_NAME).all())

        teamstats = boxscore.team_starter_bench_stats()
        self.assertTrue((4, 25), teamstats.shape)
        self.assertTrue(('Magic' == teamstats[1:2].TEAM_NAME).all())

        teamstarterbenchstats = boxscore.team_starter_bench_stats()
        self.assertTrue((4, 25), teamstarterbenchstats.shape)
        self.assertTrue(
            ('Magic' == teamstarterbenchstats[1:2].TEAM_NAME).all())
示例#15
0
 def process_boxscore_summary(self):
     while True:
         log = self.q.get()
         ap = game.Boxscore(game_id=log['GAME_ID'])
         summary = ap.game_summary().to_dict('records')
         self.collection.update_many(
             {
                 "GAME_ID": log['GAME_ID'],
                 "TEAM_ABBREVIATION": log['TEAM_ABBREVIATION']
             }, {
                 "$set": {
                     "TEAM_ID": log['TEAM_ID'],
                     "HOME_TEAM_ID": summary[0]['HOME_TEAM_ID'],
                     "VISITOR_TEAM_ID": summary[0]['VISITOR_TEAM_ID']
                 }
             })
         self.q.task_done()
示例#16
0
def create_box_score_files():
    """Creates a file storing box score data of a game given the ID
    """
    # create a list of game IDs using the team game log files
    game_id_list = []
    for team in TEAM_DICT.values():
        team_path = os.path.join(TEAM_BASE_PATH, team + '.json')
        with open(team_path, 'r') as game_log_path:
            data = json.load(game_log_path)

        for single_game in data['resultSets'][0]['rowSet']:
            game_id_list.append(single_game[1])

    # output a message to let the user know that the program is running
    print("Retrieving box score data and creating files ...")

    # retrieve data using game IDs from the list and store them in a file
    for game_id in game_id_list:
        path = os.path.join(GAME_BASE_PATH, game_id + '.json')
        if not os.path.exists(path):
            print("Retrieving " + game_id + " data")
            box_score_data = game.Boxscore(game_id).json
            with open(path, 'w') as box_score_file:
                json.dump(box_score_data, box_score_file)
示例#17
0
def load_player_game_data_at_year(teamName, year):
  teamId = TEAMS[teamName]['id']
  season = get_season(year)
  gameData = team.TeamGameLogs(teamId, season).info()
  playerData = pd.DataFrame()
  header = ['GAME_ID', 'TEAM_ID', 'PLAYER_ID', 'START_POSITION',
            'MIN', 'FGM', 'FGA', 'FG_PCT', 'FG3M', 'FG3A', 'FG3_PCT',
            'FTM', 'FTA', 'FT_PCT', 'OREB', 'DREB', 'REB', 'AST', 'STL',
            'BLK', 'TO', 'PF', 'PTS', 'PLUS_MINUS']
  visited = set()
  i = 1
  for g in gameData["Game_ID"]:
    print(i)
    i += 1
    if (g in visited):
      continue
    visited.add(g)
    temp = game.Boxscore(g).player_stats()
    temp = temp[header]
    playerData = playerData.append(temp)

    time.sleep(5)

  return playerData
示例#18
0
def get_player_stats_from_game(game_id):
    boxscore = game.Boxscore(game_id)
    return boxscore.player_stats()
示例#19
0
from nba_py import game

pbp = game.PlayByPlay('0041400122')
print pbp.info()
bs = game.Boxscore('0041400122')
print bs.game_summary()
示例#20
0
infile = open("gameids.csv",'r')
outfile = open("gamelineup.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.Boxscore(gameid)
        players = bs.player_stats()
        playerTouples = list() 
        for player in players:
            playerTouples.append([player["TEAM_ID"], player["PLAYER_ID"]])
        playerTeamOne = list()
        playerTeamTwo = list()
        tid = "-1"
        for touple in playerTouples:
            if tid == "-1":
                tid = touple[0]
            if(touple[0]==tid):
                playerTeamOne.append(touple)
            else:
                playerTeamTwo.append(touple)
        for i in range(0,2):
示例#21
0
def getBoxscore(id):
    nbaGame = game.Boxscore(str(id))
    boxscore = nbaGame.player_stats()
    teamStats = json.dumps(nbaGame.team_stats()).split()
    #homeTeamId = int(teamStats[5][:-1])
    homeTeamId = nbaGame.json['resultSets'][0]['rowSet'][0][1]
    #awayTeamId = int(teamStats[55][:-1])
    awayTeamId = nbaGame.json['resultSets'][1]['rowSet'][0][1]
    print(nbaGame)
    # print(len(team.TeamCommonRoster(homeTeamId,'2016-17').roster()))

    for dictionary in boxscore:
        for key in dictionary.keys():
            if dictionary[key] is None:
                dictionary[key] = 0

    boxscoreJson = {'data': boxscore}
    boxscoreHTML = json2html.convert(json=boxscoreJson)

    soup = BeautifulSoup(boxscoreHTML, 'html5lib')
    [s.extract() for s in soup('th', text='data')]
    soup.findAll('table')[1]['border'] = 0

    for row in soup.find_all('table')[0].tbody.findAll('tr'):
        rows = row.contents[0].contents[0].contents[0].contents
        for col in rows:
            col.contents[27].extract()
            col.contents[26].extract()
            col.contents[25].extract()
            col.contents[24].extract()
            col.contents[21].extract()
            col.contents[9].extract()
            col.contents[4].extract()
            col.contents[2].extract()

            col.contents[5], col.contents[0] = col.contents[0], col.contents[5]
            col.contents[10], col.contents[1] = col.contents[1], col.contents[
                10]
            col.contents[3], col.contents[3]
            # col.contents[0], col.contents[2] = col.contents[2], col.contents[0]
            col.contents[5], col.contents[2] = col.contents[2], col.contents[5]
            col.contents[4], col.contents[12] = col.contents[12], col.contents[
                4]
            col.contents[5], col.contents[14] = col.contents[14], col.contents[
                5]
            col.contents[6], col.contents[14] = col.contents[14], col.contents[
                6]
            col.contents[7], col.contents[13] = col.contents[13], col.contents[
                7]
            col.contents[8], col.contents[13] = col.contents[13], col.contents[
                8]
            col.contents[9], col.contents[12] = col.contents[12], col.contents[
                9]
            col.contents[10], col.contents[19] = col.contents[
                19], col.contents[10]
            col.contents[11], col.contents[16] = col.contents[
                16], col.contents[11]
            col.contents[12], col.contents[14] = col.contents[
                14], col.contents[12]
            col.contents[13], col.contents[19] = col.contents[
                19], col.contents[13]
            col.contents[14], col.contents[19] = col.contents[
                19], col.contents[14]
            col.contents[15], col.contents[18] = col.contents[
                18], col.contents[15]
            col.contents[16], col.contents[18] = col.contents[
                18], col.contents[16]
            col.contents[17], col.contents[17]
            col.contents[18], col.contents[19] = col.contents[
                19], col.contents[18]
        break

    [
        s.extract()
        for s in soup('th',
                      text=[
                          'TEAM_ID', 'PLAYER_ID', 'TEAM_ABBREVIATION',
                          'GAME_ID', 'TEAM_CITY'
                      ])
    ]

    homeTag = soup.new_tag('tr')
    homeTag.contents.append(soup.new_tag('th'))
    homeTag.find('th').insert(0, teamsById[homeTeamId].upper())

    awayTag = soup.new_tag('tr')
    awayTag.contents.append(soup.new_tag('th'))
    awayTag.find('th').insert(0, teamsById[awayTeamId].upper())

    a = soup.findAll('table')[1].find('tbody').contents[0]
    soup.findAll('table')[1].contents[0].contents[0].contents[0].contents[
        0].replaceWith('NAME')
    soup.findAll('table')[1].contents[0].contents[0].contents[1].contents[
        0].replaceWith('POS')
    soup.findAll('table')[1].contents[0].contents[0].contents[5].contents[
        0].replaceWith('+/-')
    a.append(homeTag)

    b = soup.find('table').contents[0].find('tbody').contents
    index = 0
    bench = False
    for thead in b:
        if bench == False:
            index += 1
            if thead.contents[2].contents[0] == '0':
                bench = True
                index -= 1
        else:
            index += 1
            if thead.contents[2].contents[0] != '0':
                index -= 1
                break
        #print(thead.contents[2].contents[0])
        #print(index)
    # print(b)
    res = b[index]
    res.append(awayTag)
    #print(awayTag)

    return soup
示例#22
0
import matplotlib.pyplot as plt
from multiprocessing import Pool
import numpy as np
for i in range(1, 1231):
    # Generate games, they are 0001 to 1230
    print("ITERS", i)
    path = '/Users/tynanseltzer/ap216/project/pics/3/'
    gamestr = '002160'
    gamestr += str(i).zfill(4)
    # Home players
    print("got here")
    summary = game.BoxscoreSummary(game_id=gamestr).game_summary()
    homeTeam = summary['HOME_TEAM_ID']
    awayTeam = summary['VISITOR_TEAM_ID']
    print("here")
    ids = game.Boxscore(game_id=gamestr).player_stats()['PLAYER_ID']
    homeIds = ids.where(
        game.Boxscore(
            game_id=gamestr).player_stats()['TEAM_ID'] == int(homeTeam))
    homeIds = homeIds.dropna().astype('int')
    # Go through players
    appended_data = []
    for an_id in homeIds:
        print("here actually")
        shot_df = ShotChart(player_id=an_id, game_id=gamestr, season='2016-17')
        shot_df = shot_df.shot_chart()
        appended_data.append(shot_df)
        print("alive")
    shot_df = pd.concat(appended_data, axis=0)
    plt.scatter(shot_df.LOC_X, shot_df.LOC_Y)
    homePath = path + gamestr + ".jpg"
示例#23
0
for i in seasons:
    GameIDfile = pd.read_csv('FileGenerate/TimeSeries/' + 'nba_gamelog' + i +
                             '.csv')
    Date = []
    HomeTeam = []
    VisitTeam = []
    HomeTeamPTS = []
    VisitTeamPTS = []
    Winning = []
    count = 0
    for index, row in GameIDfile.iterrows():
        count += 1
        #print(row['Game_ID']
        print(count)
        gameid = str(row['Game_ID'])
        games = game.Boxscore('00' + gameid).team_stats()
        if (len(games) == 2):
            Date.append(row['GAME_DATE'])
            HomeTeam.append(row['HomeTeam'])
            VisitTeam.append(row['VisitTeam'])

            if (row['HomeTeam'] == games.TEAM_ABBREVIATION[0]):
                HomeTeamPTS.append(games.PTS[0])
                VisitTeamPTS.append(games.PTS[1])
                Winning.append(games.PTS[0] / games.PTS[1])
            else:
                HomeTeamPTS.append(games.PTS[1])
                VisitTeamPTS.append(games.PTS[0])
                Winning.append(games.PTS[1] / games.PTS[0])
    dic = {
        'Date': Date,
示例#24
0
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',
                aspect='normal',
                bbox_inches='tight',
                pad_inches=0)
示例#25
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('-')
示例#26
0
        recent_id = int(recent_id)
        recent_id += 1
        recent_id = '00' + str(recent_id)
        foo = game.Boxscore(recent_id)
        foo = foo.team_stats()
    return '00' + str(
        int(recent_id) - 15
    )  # Need to subtract 15 games because todays games are incomplete and will raise an error if included


recent_id = most_recent(dataset_id)

#%%
# Collect and process data of the latest games played currently not used in the model
g_id = '00' + str(int(dataset_id) + 1)
trad = game.Boxscore(g_id)
trad = trad.team_stats()
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
示例#27
0
from nba_py import game, team
import pandas as pd
import numpy as np

# Constants
game_id = '0021600849'
tID = '1610612738'

bs = game.Boxscore(game_id=game_id,
                   season='2016-17',
                   season_type='Regular Season',
                   range_type='0',
                   start_period='0',
                   end_period='0',
                   start_range='0',
                   end_range='0')
df_total = bs.player_stats()
df_total = df_total[df_total['TEAM_CITY'] == 'Boston'.encode('utf-8')]
df_total.fillna(value=0)
# bsA = game.BoxscoreAdvanced(game_id=game_id, season='2016-17', season_type='Regular Season', range_type='0', start_period='0', end_period='0', start_range='0', end_range='0')
# print bsA.sql_players_advanced()

noGames = 5
for x in range(0, noGames + 1):
    bs = game.Boxscore(game_id=game_id,
                       season='2016-17',
                       season_type='Regular Season',
                       range_type='0',
                       start_period='0',
                       end_period='0',
                       start_range='0',
示例#28
0
matplotlib.use('agg')
import matplotlib.pyplot as plt
from multiprocessing import Pool
import numpy as np
top = [1610612744, 1610612745, 1610612739, 1610612746, 1610612743, 1610612761, 1610612759, 1610612738, 1610612764,
    1610612750, 1610612757, 1610612762, 1610612749, 1610612766]
for i in range(1,1231):
    # Generate games, they are 0001 to 1230
    path = '/home/tynan/am216/picseff/'
    gamestr = '002160'
    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']
    homeIds = ids.where(game.Boxscore(game_id=gamestr).player_stats()['TEAM_ID'] == int(homeTeam))
    homeIds = homeIds.dropna().astype('int')
    # Go through players
    appended_data = []
    for an_id in homeIds:
        shot_df = ShotChart(player_id=an_id, game_id = gamestr, season='2016-17')
        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)
    if int(homeTeam) in top:
        homePath = path + 'top/'
    else:
        homePath = path + 'bot/'
    homePath += gamestr + ".jpg"
示例#29
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)
示例#30
0
def boxscore_traditional(game_id, start_period, end_period, start_range,
                         end_range, range_type):
    return game.Boxscore(game_id, start_period=start_period,
                         end_period=end_period, start_range=start_range,
                         end_range=end_range, range_type=range_type)