def test(): team_id = TEAMS['ATL']['id'] player_id = get_player('Lebron', 'James') assert team.TeamList() assert team.TeamSummary(team_id) team_details = team.TeamDetails(team_id) assert team_details assert team_details.background() assert team_details.history() assert team.TeamCommonRoster(team_id) assert team.TeamGeneralSplits(team_id) assert team.TeamOpponentSplits(team_id) assert team.TeamLastNGamesSplits(team_id) assert team.TeamInGameSplits(team_id) assert team.TeamClutchSplits(team_id) assert team.TeamShootingSplits(team_id) assert team.TeamPerformanceSplits(team_id) assert team.TeamLineups(team_id) assert team.TeamPlayers(team_id) assert team.TeamPlayerOnOffDetail(team_id) assert team.TeamPlayerOnOffSummary(team_id) assert team.TeamGameLogs(team_id) assert team.TeamShotTracking(team_id) assert team.TeamReboundTracking(team_id) assert team.TeamPassTracking(team_id) assert team.TeamVsPlayer(team_id, player_id)
def getPaceFromId(self, teamId): if (teamId in self.teamIdDict): (city, name) = self.teamIdDict[teamId] else: tsum = team.TeamSummary(teamId).info()[0] city = tsum['TEAM_CITY'] name = tsum['TEAM_NAME'] self.teamIdDict[teamId] = (city, name) return self.getPace(city, name)
def search(): """Search post request when searching for a specific player or team. """ name = request.form["searchname"] if name.upper() == "YAO MING": return redirect(url_for("players", playerid="2397")) team_id = "" split_name = name.split(" ", 1) if (len(split_name) == 1): try: get_player = player.get_player(split_name[0], just_id=False) get_team = False except: get_player = False if (split_name[0].upper() in TEAMS): team_id = TEAMS[split_name[0].upper()]["id"] team_summary = team.TeamSummary(team_id) get_team = team_summary.info() else: get_team = False else: try: get_player = player.get_player(split_name[0], last_name=split_name[1], just_id=False) get_team = False except: get_player = False if (name.lower() in TEAM_NAME_TO_ID): team_id = TEAM_NAME_TO_ID[name.lower()]["id"] team_summary = team.TeamSummary(team_id) get_team = team_summary.info() else: get_team = False if get_player: return redirect(url_for("players", playerid=get_player["PERSON_ID"])) elif get_team: return redirect(url_for("teams", teamid=team_id)) else: return render_template("search.html")
def get_team_summary(self) -> pd.DataFrame: """Retrieve individual team summary data using API. """ team_summary = pd.DataFrame() for team_data in self.team_list.itertuples(index=False): self.logger.info(f'Retrieving team summary data for {team_data.TEAM_ID}') data = team.TeamSummary(team_data.TEAM_ID, season=self.season).info() team_summary = team_summary.append(data, ignore_index=True) time.sleep(1) return team_summary
def get_team_info(_team_id): # get team info from team_id info = nba_team.TeamSummary(_team_id, season='2017-18').info() # fetch data abbr = info['TEAM_ABBREVIATION'].values[0] conf = info['TEAM_CONFERENCE'].values[0] rank = info['CONF_RANK'].values[0] # return data return (abbr, conf, rank)
def populate_teams(): conn = sqlite3.connect('../data/data_team.db') c = conn.cursor() for team_id in team_ids: tid = TEAMS[team_id]['id'] team_stats = dict(team.TeamSummary(tid, season).json) team_name = team_id team_wins = team_stats['resultSets'][0]['rowSet'][0][8] team_loss = team_stats['resultSets'][0]['rowSet'][0][9] team_pct = team_stats['resultSets'][0]['rowSet'][0][10] row = (team_name, team_wins, team_loss, team_pct) c.execute('INSERT INTO teams VALUES (?,?,?,?)', row) conn.commit() conn.close()
def __init__(self, teamId, players, paceAdjust): self.teamId = teamId self.paceAdjust = paceAdjust # team pace adjustment factor for PER teamSum = team.TeamSummary(teamId, season=constants.SEASON).info()[0] self.name = str(teamSum['TEAM_NAME']) self.winPercentage = teamSum['PCT'] self.players = players T = team.TeamYearOverYearSplits(teamId).by_year()[ constants.SEASON_INDEX] self.ast = T['AST'] * 1.0 self.fg = T['FGM'] * 1.0 self.ft = T['FTM'] * 1.0 self.pts = T['PTS'] * 1.0 self.fga = T['FGA'] * 1.0 self.orb = T['OREB'] * 1.0 self.tov = T['TOV'] * 1.0 self.fta = T['FTA'] * 1.0 self.pf = T['PF'] * 1.0 self.trb = T['REB'] * 1.0
def teams(teamid): """Specific team pages. """ team_summary = team.TeamSummary(teamid) team_summary_info = team_summary.info() team_season_ranks = team_summary.season_ranks() team_common_roster = team.TeamCommonRoster(teamid) roster = team_common_roster.roster() coaches = team_common_roster.coaches() season = team_summary_info[0]["SEASON_YEAR"] team_game_log = team.TeamGameLogs(teamid, season=season) team_games = team_game_log.info() playoffs_teamgamelogs = team.TeamGameLogs(teamid, season=season, season_type="Playoffs") playoffs_team_games = playoffs_teamgamelogs.info() team_season = team.TeamSeasons(teamid) team_season_info = team_season.info() for i in team_season_info: if (i["YEAR"] == season): current_season_info = i return render_template("teams.html", title=team_summary_info[0]["TEAM_CITY"] + " " + team_summary_info[0]["TEAM_NAME"], teamid=teamid, team_summary_info=team_summary_info, team_season_ranks=team_season_ranks, season=season, team_games=team_games, playoffs_team_games=playoffs_team_games, team_season=team_season_info, roster=roster, coaches=coaches, current_season_info=current_season_info, team_img=TEAM_ID_DATA)
def save_teams(): # teams = Team.objects.all().delete() teams = Team.objects.all() if not teams: teamList = team.TeamList() for x in range(0, 29): val = teamList.info().__getitem__(x) team_summary = team.TeamSummary(val['TEAM_ID']) teamApp = Team() # print(team.TeamSummary(val['TEAM_ID']).info()[0]) # teamApp.name = val['DISPLAY_FIRST_LAST'] teamApp.name = team_summary.info()[0]['TEAM_NAME'] teamApp.id_nba = val['TEAM_ID'] division = Division.objects.get( name=team_summary.info()[0]['TEAM_DIVISION']) teamApp.division = division teamApp.fundation_date = team_summary.info()[0]['MIN_YEAR'] teamApp.owner = team_summary.info()[0]['MIN_YEAR'] teamApp.city = team_summary.info()[0]['TEAM_CITY'] teamApp.save() update_team_stats(True)
def teams_and_season(teamid, season): # season example: "2016-17" # type example: "Regular Season" or "Playoffs" team_game_log = team.TeamGameLogs(teamid, season=season) team_games = team_game_log.info() playoffs_teamgamelogs = team.TeamGameLogs(teamid, season=season, season_type="Playoffs") playoffs_team_games = playoffs_teamgamelogs.info() team_summary = team.TeamSummary(teamid, season=season) team_summary_info = team_summary.info() team_season_ranks = team_summary.season_ranks() team_common_roster = team.TeamCommonRoster(teamid) roster = team_common_roster.roster() coaches = team_common_roster.coaches() team_season = team.TeamSeasons(teamid) team_season_info = team_season.info() for i in team_season_info: if (i["YEAR"] == season): current_season_info = i return render_template("teams.html", title=team_summary_info[0]["TEAM_CITY"] + " " + team_summary_info[0]["TEAM_NAME"], teamid=teamid, team_summary_info=team_summary_info, team_season_ranks=team_season_ranks, season=season, team_games=team_games, playoffs_team_games=playoffs_team_games, current_season_info=current_season_info, team_img=TEAM_ID_DATA)
def populate_teams(): print('Retrieving team stats') conn = sqlite3.connect('../data/data_team.db') c = conn.cursor() c.execute('DELETE FROM teams') # remove old entries conn.commit() for team_id in team_ids: tid = TEAMS[team_id]['id'] team_stats = dict(team.TeamSummary(tid, season).json) team_name = team_id team_conf = team_stats['resultSets'][0]['rowSet'][0][5] team_wins = team_stats['resultSets'][0]['rowSet'][0][8] team_loss = team_stats['resultSets'][0]['rowSet'][0][9] team_pct = team_stats['resultSets'][0]['rowSet'][0][10] row = (team_name, team_conf, team_wins, team_loss, team_pct) c.execute('INSERT INTO teams VALUES (?,?,?,?,?)', row) conn.commit() conn.close() print('Done')
def testAll(self): assert team.TeamList() assert team.TeamSummary(self.teamId) team_details = team.TeamDetails(self.teamId) assert team_details # assert team_details.background() # assert team_details.history() assert team.TeamCommonRoster(self.teamId) assert team.TeamGeneralSplits(self.teamId) assert team.TeamOpponentSplits(self.teamId) assert team.TeamLastNGamesSplits(self.teamId) assert team.TeamInGameSplits(self.teamId) assert team.TeamClutchSplits(self.teamId) assert team.TeamShootingSplits(self.teamId) assert team.TeamPerformanceSplits(self.teamId) assert team.TeamLineups(self.teamId) assert team.TeamPlayers(self.teamId) assert team.TeamPlayerOnOffDetail(self.teamId) assert team.TeamPlayerOnOffSummary(self.teamId) assert team.TeamGameLogs(self.teamId) assert team.TeamShotTracking(self.teamId) assert team.TeamReboundTracking(self.teamId) assert team.TeamPassTracking(self.teamId) assert team.TeamVsPlayer(self.teamId, self.playerId)
from datetime import date pd.set_option('display.max_columns', None) # Get todays date for input to nba_py module today = str(date.today()) year, month, day = today.split("-") year, month, day = int(year), int(month), int(day) # Returns dataframe about todays NBA games, contains the ID's of the teams that are playing games_df = Scoreboard(month=month, day=day, year=year) games_df = games_df.game_header() games = [] # Process dataframe and returns games which is a list of games being played for index, row in games_df.iterrows(): game = [] # Get team ID and convert to team name road_team = row['VISITOR_TEAM_ID'] road_team = team.TeamSummary(road_team) road_team = road_team.info() road_team = road_team['TEAM_NAME'].values[0] game.append(road_team) home_team = row['HOME_TEAM_ID'] home_team = team.TeamSummary(home_team) home_team = home_team.info() home_team = home_team['TEAM_NAME'].values[0] game.append(home_team) games.append(game) num_of_games = len(games)
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)
def get_summary(team_name, season): team_id = team_dict[team_name] team_info = team.TeamSummary(team_id, season).info() return team_info
def print_team_information(team_choice): # print(team_choice) try: team_id = team_ids[team_choice] except: print("Invalid team.") print() print() return # print(team_id) print('1. View Team Roster') print('2. View Team Coaches') print('3. View Championship History') print('4. View Hall of Fame History') print('5. View Retired Jerseys') print('6. View Season Totals for Team\'s Players') print('7. View Shooting Splits by Area') print('8. View Season Totals for 2017-18') print('9. Go back to main menu') team_info_choice = input("What information about " + team_choice + " would you like to view?\n") teamdetails = team.TeamDetails(team_id) if int(team_info_choice) == 1: teamcommonroster = team.TeamCommonRoster(team_id, season='2017-18') printer.pprint(teamcommonroster.roster()) elif int(team_info_choice) == 2: teamcommonroster = team.TeamCommonRoster(team_id, season='2017-18') printer.pprint(teamcommonroster.coaches()) elif int(team_info_choice) == 3: # teamdetails = team.TeamDetails(team_id) printer.pprint(teamdetails.awards_championships()) elif int(team_info_choice) == 4: # teamdetails = team.TeamDetails(team_id) printer.pprint(teamdetails.hof()) elif int(team_info_choice) == 5: # teamdetails == team.TeamDetails(team_id) printer.pprint(teamdetails.retired()) elif int(team_info_choice) == 6: teamplayers = team.TeamPlayers(team_id, season='2017-18') printer.pprint(teamplayers.season_totals()) # printer.pprint(teamdetails.social_sites()) elif int(team_info_choice) == 7: shooting = team.TeamShootingSplits(team_id) printer.pprint(shooting.shot_areas()) elif int(team_info_choice) == 8: sum = team.TeamSummary(team_id, season='2017-18') printer.pprint(sum.season_ranks()) elif int(team_info_choice) == 9: return else: print("Invalid menu choice")
import sys import webbrowser import os from nba_py import team as team from nba_py import constants as constants teams = constants.TEAMS teamAbbrev = sys.argv[1] singleTeam = teams[teamAbbrev] teamID = singleTeam["id"] teamShootingSplits = team.TeamShootingSplits(teamID).shot_areas() print json.dumps(singleTeam, indent=4) print(teamID) print json.dumps(teamShootingSplits, indent=4) teamInfo = team.TeamSummary(teamID).info() print json.dumps(teamInfo, indent=4) with open('teamShots.json', 'w') as f: f.write("teamShots='" + json.dumps(teamShootingSplits) + "'") with open('teamInfo.json', 'w') as f: f.write("teamInfo='" + json.dumps(teamInfo) + "'") webbrowser.open("file://" + os.path.realpath("team.html"))
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)