def getTodaysPlayers(): """ Returns a list of player IDs belonging to players that played today :return: """ data = scoreboardv2.ScoreboardV2().get_data_frames()[0] player_ids = [] # print(data.to_string()) # print(list(data)) playing_team_ids = [] home_team_ids = data["HOME_TEAM_ID"].tolist() # print(home_team_ids) playing_team_ids += home_team_ids # print(data.to_string()) away_team_ids = data["VISITOR_TEAM_ID"].tolist() playing_team_ids += away_team_ids for team_id in playing_team_ids: # curr_team = [team for team in getAllNbaTeams() # if team['id'] == team_id] current_team_roster = commonteamroster.CommonTeamRoster( team_id=team_id).get_data_frames()[0] time.sleep(2) for index, row in current_team_roster.iterrows(): player_id = row['PLAYER_ID'] player_ids.append(player_id) print(player_ids) return player_ids
def 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 create_roster(season, team, struc): response = ctr.CommonTeamRoster(season=season, team_id=team) content = json.loads(response.get_json()) # transform contents into dataframe results = content['resultSets'][0] headers = results['headers'] rows = results['rowSet'] team_roster = pd.DataFrame(rows) team_roster.columns = headers if struc == 'df': roster = team_roster elif struc == 'list': roster = team_roster['PLAYER'].tolist() else: print('\nIncorrect data structure input. Use either "list" or "df".\n') return roster
def roster(team, season): team = teams.find_teams_by_full_name(team) team = team[0] team = commonteamroster.CommonTeamRoster(team_id=team.get("id"), season=season) team = (team.get_data_frames())[0] return team['PLAYER']
def get_roster_stats(): try: roster = commonteamroster.CommonTeamRoster(season='2018-19', team_id=miami_heat_team_id) roster_stats = roster.get_dict() return processnbadict(roster_stats['resultSets'][0]) #array [] except Exception as e: return str(e)
def insert_players(cur, conn, id): roster = commonteamroster.CommonTeamRoster(team_id=id).get_dict() player_ids = [] names = [] for player in roster['resultSets'][0]['rowSet']: if (player[-3] != 'R' and int(player[11]) >= 4): player_ids.append(player[-1]) names.append(player[3]) for i in range(len(player_ids)): cur.execute( 'INSERT INTO players (player_id, name, team_id) VALUES (?,?,?)', (player_ids[i], names[i], id)) conn.commit()
def getRosterFromId(self, my_team_id="1610612744", my_season="2018-19"): try: roster_info = commonteamroster.CommonTeamRoster(season=my_season, team_id=my_team_id) roster = roster_info.get_dict() a = roster['resultSets'] b = a[0] c = b['rowSet'] my_players = [] for player in c: my_players.append(player[3]) return my_players except: raise Exception("Team ID not valid")
async def roster(self, ctx, season_year, *, object_search): try: object_row = (sheet.find(object_search).row) object_column = (sheet.find(object_search).col) object_id = sheet.cell(object_row, object_column - 1).value object_id = str(object_id) team_roster = commonteamroster.CommonTeamRoster(season=season_year, team_id=object_id) df_team_roster = team_roster.get_data_frames() # ID found and roster data found roster_player_name = df_team_roster[0]['PLAYER'].to_string( index=False) jersey_number = df_team_roster[0]['NUM'].to_string(index=False) player_position = df_team_roster[0]['POSITION'].to_string( index=False) # columns converted to strings so that they display in one large column in embedd message # embedd message limited in that they don't have table functionality and can only take 3 columns before formatting poorly roster_embed = discord.Embed( title=(f'{season_year} Roster for the {object_search}'), colour=discord.Colour(0x0e1cf5)) roster_embed.set_footer(text='gimme help | RIP Kobe') roster_embed.set_image( url= 'https://cdn.vox-cdn.com/thumbor/v1jR5XEgcDrnwTq_uSZt4ApiIqg=/1400x1400/filters:format(jpeg)/cdn.vox-cdn.com/uploads/chorus_asset/file/20025173/nba_covid_3_ringer_illo.jpg' ) roster_embed.set_author( name=f'Roster for the {season_year} {object_search}') roster_embed.add_field(name='Players', value=roster_player_name) roster_embed.add_field(name='Jersey #', value=jersey_number) roster_embed.add_field(name='Position', value=player_position) await ctx.send(embed=roster_embed) # once again, value of variables added to embedded message and sent to chat except (UnboundLocalError, gspread.exceptions.CellNotFound): await ctx.send(""" I think you spelled it wrong hombre, make sure you're using this format: `gimme roster Toronto Raptors`. Also, make sure you're not using shortened versions of names like `Raptors`, `Toronto`, or `TOR`. """)
def scrapeTeamRosters(): teams = getAllNbaTeams() # print(teams) for team in teams: # print(team) team_id = team['id'] team_abbrev = team['abbreviation'] time.sleep(5) current_team_roster = commonteamroster.CommonTeamRoster( team_id=team_id).get_data_frames()[0] print(current_team_roster) filename = '{}datasets/rosters/{}_Roster.csv'.format( filepath, team_abbrev) current_team_roster.to_csv(filename, index=None, header=True) print("finished {}'s roster".format(team_abbrev))
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)
def get_team_common_info(team): team_info = teaminfocommon.TeamInfoCommon(team).get_data_frames()[0] team_info2 = teamdetails.TeamDetails(team).get_data_frames()[0] team_stats = teaminfocommon.TeamInfoCommon(team).get_data_frames()[1] team_players = teamdetails.TeamDetails(team).get_data_frames()[6] team_roster_df = commonteamroster.CommonTeamRoster(1610612737).get_data_frames()[0] player_columns=[{"name": i, "id": i} for i in team_roster_df.columns], team_roster_df = team_roster_df.loc[team_roster_df['EXP']!="R"] team_roster = team_roster_df.to_dict(orient='records') name = team_info['TEAM_NAME'][0] city = team_info['TEAM_CITY'][0] team_conf = rank_name(team_info['CONF_RANK'][0]) + ' in ' + team_info['TEAM_CONFERENCE'][0] + " Conference" team_div = rank_name(team_info['DIV_RANK'][0]) + ' in ' + team_info['TEAM_DIVISION'][0] + ' Division' firstactive = 'Year Founded: ' + team_info['MIN_YEAR'][0] lastactive = 'Last Active: ' + team_info['MAX_YEAR'][0] # manager = 'Manager: ' + team_info2['GENERALMANAGER'][0] head_coach = 'Head Coach: ' + team_info2['HEADCOACH'][0] abrv = team_info['TEAM_ABBREVIATION'][0] team_logo = f'https://stats.nba.com/media/img/teams/logos/{abrv}_logo.svg' team_pts = str(team_stats['PTS_PG'][0]) team_ast = str(team_stats['AST_PG'][0]) # team_oreb = str(team_info['OREB'][0]) # team_dreb = str(team_info['DREB'][0]) team_reb = str(team_stats['REB_PG'][0]) team_opp_pts = str(team_stats['OPP_PTS_PG'][0]) team_pts_rank = rank_name(team_stats['PTS_RANK'][0]) team_ast_rank = rank_name(team_stats['AST_RANK'][0]) # team_oreb_rank = rank_name(team_info['OREB_RANK'][0]) # team_dreb_rank = rank_name(team_info['DREB_RANK'][0]) team_reb_rank = rank_name(team_stats['REB_RANK'][0]) team_opp_pts_rank = rank_name(team_stats['OPP_PTS_RANK'][0]) # ppg = team_info['PTS_PG'][0] # rpg = team_info['REB_PG'][0] # apg = team_info['AST_PG'][0] return name, city, team_conf, team_div, firstactive, lastactive, head_coach, team_logo, \ team_pts, team_reb, team_ast, team_opp_pts,\ team_pts_rank, team_reb_rank, team_ast_rank,team_opp_pts_rank, team_roster
def run(self, dispatcher, tracker, domain): last_message = tracker.current_state()['latest_message']['text'] try: team_id, team_name = get_team_id(last_message) except Exception as e: print('Failed to get team information from your input. Error: {}'. format(e)) try: team_roster = commonteamroster.CommonTeamRoster( team_id=team_id).coaches.get_dict() team_name = team_name.replace('"', '') dispatcher.utter_message('The coach of the {} is {}'.format( team_name, json.dumps(team_roster['data'][0][5], indent=4))) except Exception as e: print( 'Failed to get roster information with the processed team id. E: {}' .format(e)) return []
o += 1 p += 1 #getting team IDs given the names seen above Team1 = [x for x in teams if x['full_name'] == a][0] Team1_id = Team1['id'] Team2 = [x for x in teams if x['full_name'] == b][0] Team2_id = Team2['id'] #find games played by a team, to see stats for the team for a given season Team1_Current = teamgamelog.TeamGameLog(Team1_id).get_data_frames()[0] Team2_Current = teamgamelog.TeamGameLog(Team2_id).get_data_frames()[0] #find current roster for each team Team1_Roster = commonteamroster.CommonTeamRoster(Team1_id).get_data_frames()[0] Team2_Roster = commonteamroster.CommonTeamRoster(Team2_id).get_data_frames()[0] #find player ids for everyone on both teams Team1_PlayerIds = Team1_Roster[['PLAYER_ID']] Team1_PlayerIds = convert(Team1_PlayerIds, 'PLAYER_ID') Team2_PlayerIds = Team2_Roster[['PLAYER_ID']] Team2_PlayerIds = convert(Team2_PlayerIds, 'PLAYER_ID') #determining the lenght of each team Team1_length = len(Team1_PlayerIds) Team2_length = len(Team2_PlayerIds) #getting info on all the players on each team for how succesfull each player is Team1_PlayerInfo = []
def get_szn_teammates(tid, szn): teammates = commonteamroster.CommonTeamRoster(team_id=tid, season=szn) return [ d['PLAYER_ID'] for d in teammates.get_normalized_dict()['CommonTeamRoster'] ]
for player in allPlayers: if player["full_name"] == "LeBron James": lebronsID = player["id"] career = playercareerstats.PlayerCareerStats(player_id='{}'.format(lebronsID)) lebronCareer = career.season_totals_regular_season.get_data_frame() lebronPlayoffs = career.season_totals_post_season.get_data_frame() lebron_info = commonplayerinfo.CommonPlayerInfo(player_id="{}".format(lebronsID)) lebron_bio = lebron_info.common_player_info.get_data_frame() #Draft position, hometown, height, weight, etc allTeams = teams.get_teams() #Team names and IDs for l in allTeams: if l["full_name"] == "Los Angeles Lakers": lakersID = l["id"] lakersRoster = commonteamroster.CommonTeamRoster(lakersID, season="2019-20") lakersRosterData = lakersRoster.common_team_roster.get_data_frame() standings19_20 = leaguestandingsv3.LeagueStandingsV3(season="2019-20") standings19_20data = standings19_20.get_data_frames()[0] #Can get regular season team stats (WL Record) from this #%% Basketball-Reference Examples stevosAdvanced = pd.DataFrame() for year in range(2000,2020): #Search for the big kiwi in all data temp = pd.read_excel("./Basketball-Reference/advanced{}.xlsx".format(yearConvert(year))) for index, row in temp.iterrows(): if "Steven Adams" in row["Player"]: stevo = row stevo["Year"] = yearConvert(year) stevosAdvanced = stevosAdvanced.append(stevo, ignore_index=True) print("Steven Adams' Advanced Stats:")
with open(path, 'w') as outFile: outFile.write(",".join(headers) + "\n") for row in rows: rowStr = [str(r) for r in row] outFile.write(",".join(rowStr) + "\n") # Simple Team info such as location and name teamDataPath = './data/teams.csv' if not os.path.exists(teamDataPath): listOfDicToFile(teams.get_teams(), teamDataPath) teamsInfo = csvToArrayDic(teamDataPath) for team in teamsInfo: rosterPath = './data/' + team['abbreviation'] + '_roster.csv' print(rosterPath) if not os.path.exists(rosterPath): time.sleep(1) resp = commonteamroster.CommonTeamRoster(team['id'], proxy=False) rosterDict = resp.common_team_roster.get_dict() headers = rosterDict['headers'] data = rosterDict['data'] headersAndRowsToCSV(headers, data, rosterPath) rosterInfo = csvToArrayDic(rosterPath) gameLogPath = './data/gameLogs.csv' gameLog = leaguegamelog.LeagueGameLog(proxy=False) gameLogDict = gameLog.league_game_log.get_dict() headers = gameLogDict['headers'] data = gameLogDict['data'] headersAndRowsToCSV(headers, data, gameLogPath)
stephen_curry = players.find_player_by_id(201939) print(stephen_curry['full_name']) from nba_api.stats.endpoints import commonplayerinfo # Basic Request player_info = commonplayerinfo.CommonPlayerInfo(player_id=2544) lebron_stats = player_info.player_headline_stats.get_dict() print(lebron_stats['data']) from nba_api.stats.endpoints import commonteamroster import json roster_info = commonteamroster.CommonTeamRoster(season=2017, team_id=1610612739) roster_cavs = roster_info.get_dict() with open('nba.json', 'w') as fp: json.dump(roster_cavs, fp, indent=3) a = roster_cavs['resultSets'] b = a[0] c = b['rowSet'] for player in c: print(player[3]) from nba_api.stats.endpoints import leagueleaders league_info = leagueleaders.LeagueLeaders(
from nba_api.stats.static import teams from nba_api.stats.endpoints import commonteamroster import os, time nba_teams = teams.get_teams() dirtowrite = 'C://Users//mpollard//Documents//GitHub//nba_api//output//' for team in nba_teams: roster = commonteamroster.CommonTeamRoster(team_id=team['id']) roster = roster.get_data_frames()[0] filename = team['full_name'] + '-roster.csv' roster.to_csv(os.path.join(dirtowrite, filename)) time.sleep(10)
from nba_api.stats.endpoints import commonplayerinfo, commonteamroster from nba_api.stats.static import players, teams import time import pandas as pd df = pd.DataFrame(columns=["realname","team"]) year = '1946' for team in teams.get_teams(): print(team) for i in range(1945,2018): team_roster = commonteamroster.CommonTeamRoster(season=str(i)+'-'+str(i+1)[2:],team_id=team['id']) print(team_roster.common_team_roster.get_dict()['data']) for player in team_roster.common_team_roster.get_dict()['data']: df = df.append({'realname':player[3], 'team':team['abbreviation']}, ignore_index=True) print({'realname':player[3], 'team':team['abbreviation']}) time.sleep(2) df.drop_duplicates(inplace=True) df.to_csv('players.csv')
def get_roster(team_abbr): roster = commonteamroster.CommonTeamRoster( teams.find_team_by_abbreviation(team_abbr.lower())["id"]) return roster.get_data_frames()[0]
num_to_team = {1610612737:"Atlanta_Hawks",1610612738:"Boston_Celtics", 1610612739:"Cleveland_Cavaliers", 1610612740:"New_Orleans_Pelicans", 1610612741:"Chicago_Bulls", 1610612742: "Dallas_Mavericks",1610612743:"Denver_Nuggets", 1610612744:"Golden_State_Warriors",1610612745:"Houston_Rockets", 1610612746:"Los_Angeles_Clippers", 1610612747: "Los_Angeles_Lakers", 1610612748: "Miami_Heat",1610612750:"Minnesota_Timberwolves", 1610612751:"Brooklyn_Nets", 1610612752:"New_York_Knicks", 1610612753:"Orlando_Magic", 1610612754: "Indiana_Pacers", 1610612755: "Philadelphia_76ers", 1610612756:"Phoenix_Suns", 1610612757:"Portland_Trail_Blazers", 1610612758:"Sacramento_Kings",1610612759:"San_Antonio_Spurs", 1610612760:"Oklahoma_City_Thunder", 1610612749:"Milwaukee_Bucks", 1610612762:"Utah_Jazz", 1610612763:"Menphis_Grizzlies",1610612764:"Washington_Wizards", 1610612765:"Detroit_Pistons", 1610612766:"Charlotte_Hornets", 1610612761:"Toronto_Raptors"} #get teams teams_dict = commonteamyears.CommonTeamYears() teams_dict = teams_dict.team_years.get_dict() teams = [] for teamNum in range(30): teams.append(teams_dict["data"][teamNum]) #get rosters rosters = [] for team in teams: time.sleep(1) rosters_dict = commonteamroster.CommonTeamRoster(season="2018-19",team_id=team[1]) rosters_dict = rosters_dict.common_team_roster.get_dict() rosters.append(rosters_dict["data"]) db = mysql.connector.connect( host = database.databaseInfo["host"], user = database.databaseInfo["user"], passwd = database.databaseInfo["passwd"], database = database.databaseInfo["database"] ) cursor = db.cursor() for team in teams: sql = "CREATE TABLE IF NOT EXISTS " sql += str(num_to_team[team[1]]) + "_Roster (teamid INT, playerid INT, playername VARCHAR(255), num INT, position VARCHAR(255), height VARCHAR(255), weight INT, age INT, PRIMARY KEY (playerid))" cursor.execute(sql)
teamRegularSeasonStandings = {} for year, standingsData in allRegularSeasonStandings.items(): for index, row in standingsData.iterrows(): if teamInput in row[ "TeamName"]: #Change to teamID == row["TeamID"] to see technical team data (Ex Seattle+OKC has same ID) teamRegularSeasonStandings[year] = row teamRegularSeasonWinPercentages = {} for year, seasonSeries in teamRegularSeasonStandings.items(): teamRegularSeasonWinPercentages[year] = seasonSeries["WinPCT"] #%% Get the team's roster for every year teamAllRosters = {} for year in range(2000, 2020): time.sleep(2) #Needed to avoid timeouts teamRoster = commonteamroster.CommonTeamRoster( teamID, season=yearConvert(year)) teamRosterData = teamRoster.common_team_roster.get_data_frame() teamAllRosters[yearConvert(year)] = teamRosterData #%% Get advanced stats for each player on the roster every year teamAdvancedStats = {} for year, rosterDF in teamAllRosters.items(): #For that year, make a DataFrame with all Advanced Stats for each player currentYearDF = pd.DataFrame() advanced = pd.read_excel( "./Basketball-Reference/advanced{}.xlsx".format(year)) for advancedIndex, advancedRow in advanced.iterrows(): for rosterIndex, rosterRow in rosterDF.iterrows(): if rosterRow["PLAYER"] in advancedRow["Player"]: if advancedRow["Tm"] == teamAbbreviation: # ^^ Removes stats from players not recorded on that team