async def get_scores(self, score): result = '```' line_score = score.line_score ls_df = line_score.get_data_frame() ls_df['PTS'] = ls_df['PTS'].fillna(0).astype(numpy.int64) game_header = score.game_header gh_df = game_header.get_data_frame() if not ls_df.empty: team_points = ls_df[['TEAM_ID', 'PTS']] for x in range(0, len(team_points), 2): try: away_team = teams.find_team_name_by_id( ls_df['TEAM_ID'][x])['nickname'] home_team = teams.find_team_name_by_id( ls_df['TEAM_ID'][x + 1])['nickname'] # handles case where teams are not in the list of current teams i.e. Team LeBron, West All-Stars except: away_team = ls_df['TEAM_CITY_NAME'][x] + ' ' + ls_df[ 'TEAM_ABBREVIATION'][x] home_team = ls_df['TEAM_CITY_NAME'][ x + 1] + ' ' + ls_df['TEAM_ABBREVIATION'][x + 1] away_points = ls_df['PTS'][x] home_points = ls_df['PTS'][x + 1] away_win = '' home_win = '' if home_points > away_points: home_win = '**' else: away_win = '**' # result += f"{away_win}{away_team} {away_points}{away_win} - {home_win}{home_points} {home_team}{home_win} {gh_df['GAME_STATUS_TEXT'][x // 2]}\n" result += f"{away_team:<14} {int(away_points):>3}-{int(home_points):<3} {home_team:>14} {gh_df['GAME_STATUS_TEXT'][x // 2]}\n" result += '```' return result
def add_one_team_to_league_df(team_id, season_end): team_info = teams.find_team_name_by_id(team_id) team_name = team_info.get('full_name') print(team_name + '' + str(team_id)) team_roster = commonteamroster.CommonTeamRoster( team_id=team_id, season=season_end).common_team_roster.get_data_frame() team_df = team_roster[[ 'PLAYER_ID', 'TeamID', 'SEASON', 'PLAYER', 'AGE', 'EXP' ]] team_df = team_df.rename( columns={ 'PLAYER_ID': 'player_id', 'TeamID': 'team_id', 'SEASON': 'season_end', 'PLAYER': 'player_name', 'AGE': 'age', 'EXP': 'exp' }) team_df['team_name'] = team_name #league_df = league_df.append(team_df) conn = pg2.connect(dbname='postgres', host="localhost") conn.autocommit = True engine = create_engine( 'postgresql+psycopg2://jacobpress:bocaj29@localhost/wins_contr') team_df.to_sql('league_rosters', con=engine, if_exists='append', index=False) conn.close()
def get_boxscores_api(team_ids): # dictionary with every player id team_games, all_games = get_games_api(team_ids) players_dict = fill_player_dict(all_games) player_game_count_dict = dict.fromkeys( [player["id"] for player in players.get_players()]) for key in player_game_count_dict: player_game_count_dict[key] = 0 print("-------------------------------------------------") print("All games loaded. Beginning game by game calculations...") print("-------------------------------------------------") for game_info in team_games: team_id = game_info[0] print("Running calculations for " + str({teams.find_team_name_by_id(team_id)["full_name"]}) + "...") game_set = game_info[1] i = 0 for game_id in game_set: print(str(i) + " games done") i += 1 boxscore = boxscoreadvancedv2.BoxScoreAdvancedV2( game_id=game_id).get_dict()["resultSets"][0]["rowSet"] print("writing temp file for game: " + str(game_id)) with open(f"games{SEASON.split('-')[0]}/{game_id}", "w") as file: file.write(json.dumps(boxscore))
def get_games_api(team_ids): print("Loading game lists...") team_games = [] all_games = [] for tid in team_ids: team_log = teamgamelog.TeamGameLog(season=SEASON, season_type_all_star=SEASON_TYPE, team_id=tid).get_dict() results = team_log["resultSets"][0]["rowSet"] game_ids = [res[GAMELOG_GAME_ID_INDEX] for res in results] dates = [ datetime.strptime(res[GAMELOG_DATE_INDEX].replace(",", ""), "%b %d %Y") for res in results ] for pair in zip(dates, game_ids): bisect.insort_left(all_games, pair) # Reverse the game id list! team_games.append((tid, game_ids[::-1])) name = teams.find_team_name_by_id(tid)["full_name"] print(name + " done...") # deduplicate games all_games = OrderedDict((x, True) for x in all_games).keys() return team_games, list(all_games)
def getTeamLogoURL(team_id: int) -> Optional[str]: static_info = teams.find_team_name_by_id(team_id) if static_info is None or len(static_info) < 1: return None teamThreeLetter = (TeamInfoCommon( team_id=team_id, season_nullable=Season.current_season).get_normalized_dict().get( 'TeamInfoCommon')[0]).get("TEAM_ABBREVIATION").lower() return f"https://a.espncdn.com/i/teamlogos/nba/500/{teamThreeLetter}.png"
def create_league_team_df(): team_ids = [ 1610612737, 1610612738, 1610612751, 1610612766, 1610612741, 1610612739, 1610612742, 1610612743, 1610612765, 1610612744, 1610612745, 1610612754, 1610612746, 1610612747, 1610612763, 1610612748, 1610612749, 1610612750, 1610612740, 1610612752, 1610612760, 1610612753, 1610612755, 1610612756, 1610612757, 1610612758, 1610612759, 1610612761, 1610612762, 1610612764 ] season_end_list = [2019, 2018, 2017, 2016, 2015, 2014] for season_end in season_end_list: for team_id in team_ids: team_info = teams.find_team_name_by_id(team_id) team_name = team_info.get('full_name') print(team_name + '' + str(team_id)) team_roster = commonteamroster.CommonTeamRoster( team_id=team_id, season=season_end).common_team_roster.get_data_frame() team_df = team_roster[[ 'PLAYER_ID', 'TeamID', 'SEASON', 'PLAYER', 'AGE', 'EXP' ]] team_df = team_df.rename( columns={ 'PLAYER_ID': 'player_id', 'TeamID': 'team_id', 'SEASON': 'season_end', 'PLAYER': 'player_name', 'AGE': 'age', 'EXP': 'exp' }) team_df['team_name'] = team_name #league_df = league_df.append(team_df) conn = pg2.connect(dbname='postgres', host="localhost") conn.autocommit = True engine = create_engine( 'postgresql+psycopg2://jacobpress:bocaj29@localhost/wins_contr' ) team_df.to_sql('league_rosters', con=engine, if_exists='append', index=False) conn.close() sleep(15)
async def getTeamCareerStatsByID( team_id: int, use_proxy: Optional[bool] = None) -> Optional[Dict[str, Any]]: static_info = teams.find_team_name_by_id(team_id) if static_info is None or len(static_info) < 1: return None stats_dict = {} all_seasons_response = await ProxiedEndpoint(TeamYearByYearStats, team_id=team_id, use_proxy=use_proxy) all_seasons = all_seasons_response.get_normalized_dict().get('TeamStats') stats_dict['W'] = 0 stats_dict['L'] = 0 stats_dict['PCT'] = 0 stats_dict['MAX_CONF_RANK'] = all_seasons[0].get('CONF_RANK') stats_dict['MIN_CONF_RANK'] = all_seasons[0].get('CONF_RANK') stats_dict['MAX_DIV_RANK'] = all_seasons[0].get('DIV_RANK') stats_dict['MIN_DIV_RANK'] = all_seasons[0].get('DIV_RANK') # Add up all the stats for all seasons for season in all_seasons: stats_dict['W'] += season.get('WINS') stats_dict['L'] += season.get('LOSSES') if stats_dict['MAX_CONF_RANK'] > season.get( 'CONF_RANK') or stats_dict['MAX_CONF_RANK'] < 1: stats_dict['MAX_CONF_RANK'] = season.get('CONF_RANK') elif stats_dict['MIN_CONF_RANK'] < season.get('CONF_RANK'): stats_dict['MIN_CONF_RANK'] = season.get('CONF_RANK') if stats_dict['MAX_DIV_RANK'] > season.get('DIV_RANK'): stats_dict['MAX_DIV_RANK'] = season.get('DIV_RANK') elif stats_dict['MIN_DIV_RANK'] < season.get('DIV_RANK'): stats_dict['MIN_DIV_RANK'] = season.get('DIV_RANK') stats_dict['PCT'] = (stats_dict['W'] + stats_dict['L']) / float( stats_dict['W']) return stats_dict
def display_team_shot_charts(team, season, season_type): shots_df,league_avg = get_team_shotchartdetail(team, season, season_type) name = teams.find_team_name_by_id(team)['full_name'] shot_fig = go.Figure() heat_fig = go.Figure() hex_fig = go.Figure() if int(season[:4]) >= 1996 : make_shot_chart(shot_fig,shots_df, name, season) draw_plotly_court(shot_fig) make_heatmap(heat_fig,shots_df,name,season) draw_plotly_court(heat_fig, layer='above') make_team_hexbin(hex_fig,shots_df,league_avg,name,season) draw_plotly_court(hex_fig) else: draw_plotly_court(shot_fig) shot_fig.update_layout( title={ 'text': 'No Shot Chart Data', 'y':0.98, 'x':0.5, 'xanchor': 'center', 'yanchor': 'top'}) draw_plotly_court(heat_fig) heat_fig.update_layout( title={ 'text': 'No Shot Chart Data', 'y':0.98, 'x':0.5, 'xanchor': 'center', 'yanchor': 'top'}) draw_plotly_court(hex_fig) hex_fig.update_layout( title={ 'text': 'No Shot Chart Data', 'y':0.98, 'x':0.5, 'xanchor': 'center', 'yanchor': 'top'}) return shot_fig, heat_fig, hex_fig
async def getTeamSeasonStatsByID( team_id: int, season_id: str = Season.current_season, use_proxy: Optional[bool] = None) -> Optional[Dict[str, Any]]: static_info = teams.find_team_name_by_id(team_id) if static_info is None or len(static_info) < 1: return None stats_dict = {} season_info_response = await ProxiedEndpoint(TeamInfoCommon, team_id=team_id, season_nullable=season_id, use_proxy=use_proxy) season_dict = season_info_response.get_normalized_dict() season_info = season_dict.get('TeamInfoCommon')[0] season_stats = season_dict.get('TeamSeasonRanks')[0] stats_dict['TEAM_CONFERENCE'] = season_info.get('TEAM_CONFERENCE') stats_dict['CONF_RANK'] = season_info.get('CONF_RANK') stats_dict['TEAM_DIVISION'] = season_info.get('TEAM_DIVISION') stats_dict['DIV_RANK'] = season_info.get('DIV_RANK') stats_dict['W'] = season_info.get('W') stats_dict['L'] = season_info.get('L') stats_dict['PCT'] = season_info.get('PCT') stats_dict['TEAM_COLOR'] = getTeamColor(team_id) stats_dict['SEASON_ID'] = season_id stats_dict['PPG'] = season_stats['PTS_PG'] stats_dict['PTS_RANK'] = season_stats['PTS_RANK'] stats_dict['RPG'] = season_stats['REB_PG'] stats_dict['REB_RANK'] = season_stats['REB_RANK'] stats_dict['APG'] = season_stats['AST_PG'] stats_dict['AST_RANK'] = season_stats['AST_RANK'] stats_dict['OPPG'] = season_stats['OPP_PTS_PG'] stats_dict['OPPG_RANK'] = season_stats['OPP_PTS_RANK'] return stats_dict
def get_team_id(last_message): team_id = '' team_name = '' unicode_input = u'{}'.format(last_message) with open('data/teams.json') as f: data = json.load(f) for entry in data: if entry['teamName'] in unicode_input: team_id = json.dumps(entry['teamId']) elif entry['teamName'] in unicode_input: team_id = json.dumps(entry['teamId']) elif entry['location'] in unicode_input: team_id = json.dumps(entry['teamId']) elif entry['simpleName'] in unicode_input: team_id = json.dumps(entry['teamId']) if team_id != '': team_name = json.dumps(teams.find_team_name_by_id(team_id)['nickname']) return team_id, team_name
async def make_season_embed(self, player_info, season, toggle_per_game, index, img_link): player_id = player_info['id'] player_career_stats = playercareerstats.PlayerCareerStats( player_id=player_id, per_mode36='PerGame' if toggle_per_game else 'Totals') season_tot = player_career_stats.season_totals_regular_season.get_data_frame( ) season_info = season_tot[season_tot['SEASON_ID'] == season] categories = season_info.columns stats = season_info.values embed = discord.Embed( title=f"{season} Season Stats for {player_info['full_name']}:\n") team_id = stats[index][categories.get_loc( 'TEAM_ID')] # gets the player's team for the given season player_team = teams.find_team_name_by_id(team_id) result = f"```TEAM: {player_team['full_name']}\n" for cat in range(5, len( categories)): # filters out the player, league, and team ID result += f"{categories[cat]}: {stats[index][cat]}\n" result += '```' embed.description = result embed.set_thumbnail(url=img_link) return embed
def get_todays_high_player_stats(sixers_scores): # Each player in the box score is iterated over and checked to see if they had the highest # of any stat for that day. high_default = [0, "No Games", 0, 0, 0, 0, 0, "Nobody", "H", "0000", "https://www.basketball-reference.com"] points_high = high_default assists_high = high_default rebounds_high = high_default steals_high = high_default blocks_high = high_default for game_list in sixers_scores: box_score = game_list[0] for player in box_score['data']: #if they're not a sixers player, continue if player[1] != sixers_id: continue else: #build a list of all important data about the player #game_id, player name, points, assists, rebounds, steals, blocks, opponent, home/away, year player_info = [player[0], player[5], player[26],player[21],player[20],player[22],player[23], teams.find_team_name_by_id(game_list[1])['nickname'], game_list[2], game_list[3]] #append basketball reference URL if player_info[8] == "H": player_info.append("https://www.basketball-reference.com/boxscores/" + player_info[9] + "0" + str(month) + url_day_format(day) + "0" + "PHI.html") else: player_info.append("https://www.basketball-reference.com/boxscores/" + player_info[9] + "0" + str(month) + url_day_format(day) + "0" + (teams.find_teams_by_nickname(player_info[7])[0]["abbreviation"]) +".html") #check if player has highest points. If None type replace with 0 if player_info[2] != None: if player_info[2] > points_high[2]: points_high = player_info #check for ties elif player_info[2] == points_high[2]: points_high.append(player_info) else: player_info[2] = 0; #check for highest assists if player_info[3] != None: if player_info[3] > assists_high[3]: assists_high = player_info elif player_info[3] == assists_high[3]: assists_high.append(player_info) else: player_info[3] = 0; #check for highest rebounds if player_info[4] != None: if player_info[4] > rebounds_high[4]: rebounds_high = player_info elif player_info[4] == rebounds_high[4]: rebounds_high.append(player_info) else: player_info[4] = 0; #check for highest steals if player_info[5] != None: if player_info[5] > steals_high[5]: steals_high = player_info elif player_info[5] == steals_high[5]: steals_high.append(player_info) else: player_info[5] = 0; #check for highest blocks if player_info[6] != None: if player_info[6] > blocks_high[6]: blocks_high = player_info elif player_info[6] == blocks_high[6]: blocks_high.append(player_info) else: player_info[6] = 0; # f.close() write_javascript_file(date, points_high, assists_high, rebounds_high, steals_high, blocks_high) print("Points High:", points_high) print("Assists High:", assists_high) print("Rebounds High:", rebounds_high) print("Steals High:", steals_high) print("Blocks High:", blocks_high)
def getTeamname(self): return teams.find_team_name_by_id(self.team_id)["nickname"]
def __init__(self, id, per_mode): self.dict = teams.find_team_name_by_id(id) self.name = self.dict['nickname'] self.teamstats = teamyearbyyearstats.TeamYearByYearStats( id, per_mode_simple=per_mode).get_data_frames()[0]
def create_player_matrix_from_local(filename, season): path = "" if season == "2017": path = "games2017" elif season == "2018": path = "games2018" else: print(season) print(season == "2017") print(season == "2018") print("SEASON NOT AVAILABLE") sys.exit(0) team_games, all_games = get_games_local(season) players_dict = fill_player_dict(all_games) player_game_count_dict = dict.fromkeys( [player["id"] for player in players.get_players()]) for key in player_game_count_dict: player_game_count_dict[key] = 0 print("-------------------------------------------------") print("All games loaded. Beginning game by game calculations...") print("-------------------------------------------------") for game_info in team_games: team_id = game_info[0] print("Running calculations for " + str({teams.find_team_name_by_id(team_id)["full_name"]}) + "...") game_set = game_info[1] i = 0 for game_id in game_set: i += 1 boxscore = file_dumps.read_json(f"{path}/{game_id}") for player_line in boxscore: if player_line[BOXSCORE_TEAM_ID] == team_id: # update player matrix if player_line[BOXSCORE_STAT_START] is None: # DNP (coach's decision) case continue player_line[BOXSCORE_STAT_START] = int(player_line[ BOXSCORE_STAT_START].split(":")[0]) * 60 + int( player_line[BOXSCORE_STAT_START].split(":")[1]) players_dict[ player_line[BOXSCORE_PLAYER_ID]][game_id] = np.array( player_line[BOXSCORE_STAT_START:], dtype="float32") print("-------------------------------------------") print("Filling in time step blanks...") # In the above code, we simply filled in every night with # each players stats from that night. Now we sweep through # and calculate the average after that night. prev_game_id = all_games[0][1] for chron_game in all_games: chron_game_id = chron_game[1] for p_id in players_dict: if players_dict[p_id][chron_game_id] is not None: if chron_game_id != prev_game_id: if players_dict[p_id][prev_game_id] is not None: players_dict[p_id][chron_game_id] = ( (player_game_count_dict[p_id] - 1) * players_dict[p_id][chron_game_id] ) + players_dict[p_id][prev_game_id] player_game_count_dict[p_id] += 1 players_dict[p_id][chron_game_id] = ( players_dict[p_id][chron_game_id] / player_game_count_dict[p_id]) else: player_game_count_dict[p_id] = 1 else: players_dict[p_id][chron_game_id] = players_dict[p_id][ prev_game_id] prev_game_id = chron_game_id for player in players_dict: for game in players_dict[player]: if players_dict[player][game] is None: players_dict[player][game] = np.zeros(23, dtype="float32") # The final dictionary is: (num_players, num_games, num_stats) # each player id and game id is a key. The stats are stored in a numpy array print("-------------------------------------------") file_dumps.write_player_dict(players_dict, filename)
'max_incorrect_ratio': 0, 'min_incorrect_ratio': 1} for row in reader: #First check if field has an ID instead of a name team_id = None try: team_id = int(row[CORRECT_INDEX]) except ValueError: pass # If it's not an ID, get the team by their name if team_id is None: teams_dict = teams.find_teams_by_full_name(row[CORRECT_INDEX]) else: teams_dict = [teams.find_team_name_by_id(team_id)] # Don't run the test if we don't know what the solution should be if not len(teams_dict) == 1: print(f"Couldn't find team matching {row[CORRECT_INDEX]}") else: print(f"\"{row[MISSPELLED_INDEX]}\" ", end='') # Figure out which mode the fuzzy code is going to run in team_names = row[MISSPELLED_INDEX].split() if len(team_names) == 1: stats_dict = one_stats_dict print('(First or last name mode)') else: stats_dict = full_stats_dict print('(Full name mode)')