def generate_players_list():
    player_dict = players.get_players()
    playerz = len(player_dict)

    ballers = []
    for i in range(playerz):
        try:
            doc = {}
            baller = commonplayerinfo.CommonPlayerInfo(
                player_id=i).get_dict()['resultSets'][0]['rowSet'][0]
            doc['name'] = '{} {}'.format(baller[1], baller[2])
            doc['birth_date'] = datetime.strptime(baller[7].split('T')[0],
                                                  "%Y-%m-%d")
            doc['nationality'] = baller[9]
            doc['height'] = baller[11]
            doc['weight'] = int(baller[12])
            doc['jersey'] = int(baller[14])
            doc['position'] = baller[15]
            doc['team'] = '{} {}'.format(baller[22], baller[19])
            doc['school'] = baller[8]
            doc['draft'] = {}
            doc['draft']['draft_year'] = int(baller[29])
            doc['draft']['draft_round'] = int(baller[30])
            doc['draft']['draft_number'] = int(baller[31])
            ballers.append(doc)
        except (json.decoder.JSONDecodeError, ValueError, TypeError):
            pass

    return ballers
Example #2
0
def get_player_shot_chart_info(player_name, season_id, season_type):

    # Searching for requested player
    all_nba_players = players.get_players()
    player_dict = [
        player for player in all_nba_players
        if player['full_name'] == player_name
    ][0]

    # Creating the dataframe for the player's career
    career = playercareerstats.PlayerCareerStats(player_id=player_dict['id'])
    career_df = career.get_data_frames()[0]

    # Finding the team that the player played for during the season
    team_id = career_df[career_df['SEASON_ID'] == season_id]['TEAM_ID']

    # Endpoints to acquire the shot chart detail
    shot_chart = shotchartdetail.ShotChartDetail(
        team_id=int(team_id),
        player_id=int(player_dict['id']),
        season_type_all_star=season_type,
        season_nullable=season_id,
        context_measure_simple="FGA").get_data_frames()

    return shot_chart[0]
Example #3
0
    def get_player_id(self, player_lastname, player_firstname):
        """Match user input to legal nba player.

        :param basestring player_lastname:
            Last name of an NBA Player provided by user.

        :param basestring player_firstname:
            First name of an NBA Player provided by user.

        :returns Legal player ID
        :rtype int
        """
        player_dict = player_ref.get_players()
        player_id = None

        for i in range(len(player_dict)):
            if re.search((player_dict[i].get('last_name')).lower(),
                         player_lastname.lower()):
                if re.search((player_dict[i].get('first_name')).lower(),
                             player_firstname.lower()):
                    player_id = player_dict[i].get('id')

        if player_id is None:
            print(
                "Player not found, check your spelling of {} or please choose another player."
                .format(player_lastname + player_firstname))
        return player_id
Example #4
0
def nbamultiapp():
    st.write("""
    # player career stats 
    ### type a player (accurately and completely)

    """)

    player_name = st.text_input("Player", 'Michael Jordan')

    nba_players = players.get_players()
    player_dict = [
        player for player in nba_players if player['full_name'] == player_name
    ][0]
    print(player_dict)

    career_stats = playercareerstats.PlayerCareerStats(
        player_id=player_dict['id'])
    playerdf = career_stats.get_data_frames()[0]
    df = pd.DataFrame(playerdf)
    df['NAME'] = player_dict['full_name']
    df = df[[
        'NAME', 'SEASON_ID', 'TEAM_ABBREVIATION', 'PLAYER_AGE', 'PTS',
        'FG_PCT', 'FG3_PCT', 'REB', 'AST', 'BLK'
    ]]

    st.table(df)
Example #5
0
    def get_player_shotchartdetail(player_name, season_id, season_type):

        #player dictionary
        nba_players = players.get_players()
        player_dict = [
            player for player in nba_players
            if player['full_name'] == player_name
        ]

        if len(player_dict) == 0:
            return None, None

        #career dataframe
        career = playercareerstats.PlayerCareerStats(
            player_id=player_dict[0]['id'])
        career_df = json.loads(career.get_json())['resultSets'][0]['rowSet']

        #team id during the season
        team_ids = [
            season[3] for season in career_df if season[1] == season_id
        ]

        #st.write(career_df[0])
        shots = []
        for team_id in team_ids:
            shotchartlist = shotchartdetail.ShotChartDetail(
                team_id=int(team_id),
                player_id=int(player_dict[0]['id']),
                season_type_all_star=season_type,
                season_nullable=season_id,
                context_measure_simple="FGA").get_data_frames()
            shots.extend(shotchartlist)

        return shotchartlist[0], shotchartlist[1]
def getAllNbaPlayers():
    """
    IMPORTANT: the list contains all players ever, not just current players
    :return: list of dictionaries, each representing an NBA player
    """
    nba_players = players.get_players()
    return nba_players
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))
Example #8
0
def nbamultiapp():
    st.write("""
    # player game log by year
    ### type a player, pick a year
    
    """)
    years = [
        '2020-21', '2019-20', '2018-19', '2017-18', '2016-17', '2015-16',
        '2014-15', '2013-14', '2012-13'
    ]
    player_name = st.text_input("Player (name must be spelled correctly)",
                                'LeBron James')
    years_input = st.selectbox("Year", years)

    nba_players = players.get_players()
    player_dict = [
        player for player in nba_players if player['full_name'] == player_name
    ][0]
    #print(player_dict)

    allGameLogs = playergamelogs.PlayerGameLogs(
        player_id_nullable=player_dict['id'], season_nullable=years_input)
    playerdf = allGameLogs.get_data_frames()[0]
    df = pd.DataFrame(playerdf)
    #print(df)
    df = df[[
        'SEASON_YEAR', 'PLAYER_NAME', 'TEAM_ABBREVIATION', 'GAME_DATE',
        'MATCHUP', 'WL', 'PTS', 'REB', 'AST', 'STL', 'TOV'
    ]]
    st.table(df)
Example #9
0
def get_player_info(player_name, season_id, season_progress):

    # player dictionary
    nba_players = players.get_players()
    player_dict = [
        player for player in nba_players if player['full_name'] == player_name
    ][0]

    player_regular_info = playercareerstats.PlayerCareerStats(
        player_id=int(player_dict['id']), per_mode36='PerGame')
    player_regular_info_df = player_regular_info.get_data_frames()[0]

    season = player_regular_info_df[player_regular_info_df['SEASON_ID'] ==
                                    season_id]
    PTS = float(season['PTS'])
    REB = float(season['REB'])
    AST = float(season['AST'])
    FG_PCT = round(float(season['FG_PCT'] * 100), 2)
    FG3_PCT = round(float(season['FG3_PCT'] * 100), 2)
    FT_PCT = round(float(season['FT_PCT'] * 100), 2)
    STL = float(season['STL'])
    BLK = float(season['BLK'])
    TOV = float(season['TOV'])

    stats = 'PTS: ' + str(PTS) + '\nREB: ' + str(REB) + '\nAST: ' + str(
        AST) + '\nFG%: ' + str(FG_PCT) + '%\n3PT%: ' + str(
            FG3_PCT) + '%\nFT%: ' + str(FT_PCT) + '%\nSTL: ' + str(
                STL) + '\nBLK: ' + str(BLK) + '\nTOV: ' + str(TOV)

    return stats
def main(season):
    #All NBA Players Information in DataFrame
    nba_players_info = pd.concat([pd.DataFrame.from_dict(players.get_players()[i], orient='index').transpose() for i in range(len(players.get_players()))],ignore_index=True)
    
    #All NBA Teams Information in DataFrame
    nba_teams_info = pd.concat([pd.DataFrame.from_dict(teams.get_teams()[i], orient='index').transpose() for i in range(30)],ignore_index=True)
    
    #Players that are active right now
    players_active = nba_players_info[nba_players_info['is_active'] == True].reset_index(drop=True)
    
    #Players Active in Array
    players_active_array = players_active['full_name'].values
    
    #Teams in Array 
    teams_array = nba_teams_info['full_name'].values
    
    #Seasons in Array
    seasons = ['2018-19','2017-18','2016-17','2015-16','2014-15','2013-14','2012-13','2011-12','2010-11','2009-10']
    
    #Stephs ID
    steph_id = players.find_players_by_full_name('Steph')[1]['id']
    
    
    input_season_df = season_player(season, steph_id, players_active)
    input_season_df.to_csv("Steph_" + season + "_matchup.csv")
Example #11
0
def get_player_shots_data(player_full_name):
    pd.set_option("display.max_rows", None)
    nba_players = players.get_players()
    try:
        current_player = [
            player for player in nba_players
            if player["full_name"] == player_full_name
        ][0]
    except:
        return "Player not found."
    if not os.path.isdir(
            str(os.path.dirname(os.path.abspath(__file__))) + "/../data/" +
            str(current_player["id"]) + "/"):
        try:
            os.makedirs(str(os.path.dirname(os.path.abspath(__file__))) +
                        "/../data/" + str(current_player["id"]) + "/",
                        mode=0o777,
                        exist_ok=True)
        except OSError as error:
            print(error)
        player = commonplayerinfo.CommonPlayerInfo(
            player_id=str(current_player["id"]))
        player_df = player.get_data_frames()[0]
        player_df = player_df.loc[:, [
            "FIRST_NAME", "LAST_NAME", "COUNTRY", "HEIGHT", "WEIGHT", "JERSEY",
            "POSITION", "TEAM_ABBREVIATION", "FROM_YEAR", "TO_YEAR"
        ]]
        player_df.to_json(str(os.path.dirname(os.path.abspath(__file__))) +
                          '/../data/' + str(current_player["id"]) +
                          '/player_data.json',
                          orient='records')
        shots = shotchartdetail.ShotChartDetail(team_id=0,
                                                player_id=str(
                                                    current_player["id"]),
                                                context_measure_simple='FGA')
        shots_df = shots.get_data_frames()[0]
        shots_df = shots_df.loc[:, [
            "TEAM_NAME", "PERIOD", "MINUTES_REMAINING", "SECONDS_REMAINING",
            "ACTION_TYPE", "SHOT_TYPE", "SHOT_DISTANCE", "LOC_X", "LOC_Y",
            "SHOT_MADE_FLAG", "GAME_DATE", "HTM", "VTM"
        ]]
        shots_distances = []
        for i in range(shots_df.shape[0]):
            shots_distances += [
                (shots_df.at[i, "LOC_X"]**2 + shots_df.at[i, "LOC_Y"]**2)**0.5
                / 10
            ]
        shots_df.drop(["SHOT_DISTANCE"], axis=1, inplace=True)
        shots_df.insert(5, "SHOT_DISTANCE", shots_distances, True)
        shots_angles = []
        for i in range(shots_df.shape[0]):
            shots_angles += [shots_df.at[i, "LOC_Y"] / shots_df.at[i, "LOC_X"]]
        shots_df.insert(5, "SHOT_ANGLE", shots_angles, True)
        shots_df.drop(["LOC_X", "LOC_Y"], axis=1, inplace=True)
        shots_df.to_json(str(os.path.dirname(os.path.abspath(__file__))) +
                         '/../data/' + str(current_player["id"]) +
                         '/shots_data.json',
                         orient='records')
    return "Player found and data added to database."
def __getPlayerID(fullName: str) -> str:
    player_dict = players.get_players()
    player = None
    for person in player_dict:
        if person['full_name'] == fullName:
            player = person
    assert (player is not None), 'Player name does not exist!'
    return player['id']
def get_players_list():
    player_dict_lst = players.get_players()
    player_lst = [{
        'label': player_dict['full_name'],
        'value': player_dict['id']
    } for player_dict in player_dict_lst]

    return player_lst
def fill_player_dict(all_games):
    player_dict = {}
    for player in players.get_players():
        player_dict[player["id"]] = dict.fromkeys(
            [game[1] for game in all_games])
        for game in all_games:
            player_dict[player["id"]][game[1]] = None

    return player_dict
def download_all_players(database=None):
    # call nba_api and get all the players
    all_players = players.get_players()

    # initialize response with the specified database
    r = Response(all_players, database=database)

    # extract the response for only active players
    r.extract_active_players()
Example #16
0
    def details(self):
        try:
            players_dict = players.get_players()
            player_details = \
                [player for player in players_dict if player[FULL_NAME].lower()
                 == self.fullname.strip().lower()][0]

            return player_details
        except:
            return NA
Example #17
0
def update_players(conn):
    '''
    Get list of all players from nba-api and store as table
    '''
    df_players = pd.DataFrame(players.get_players()).astype({'id': 'str'})

    try:
        df_players.to_sql('Player', conn, index=False)
    except:
        pass
Example #18
0
 def __init__(self):
     self.nba_players = players.get_players()
     self.players_id_dict = {
         self.nba_players[i]["full_name"]: self.nba_players[i]["id"]
         for i in range(len(self.nba_players))
     }
     self.nba_players_list = [
         self.nba_players[i]["full_name"]
         for i in range(len(self.nba_players))
     ]
Example #19
0
def basePlayers():
    player_dict = players.get_players()

    nbaCollection = db.get_collection("Players")

    for player in player_dict:
        player1 = db.get_document(nbaCollection,
                                  player['full_name'].replace(" ", ""))
        player1["value"] = player
        player1.save()
Example #20
0
    def find_player_id(self):
        """A method to find player's id

            Args:
                self: self

            Returns:
                if (int): player's id, found in nba_api
        """
        for player in players.get_players():
            if player['full_name'].lower() == self.player_name.lower():
                return player['id']
Example #21
0
def get_player_stats(name, season):
    nba_players = players.get_players()
    try:
        player = [
            player for player in nba_players if player['last_name'] == name
            or player['first_name'] == name or player['full_name'] == name
        ][0]
    except:
        print('Invalid name')
        return
    career = playercareerstats.PlayerCareerStats(player_id=player['id'])
    career_df = career.get_data_frames()[0]
    print(career_df[career_df['SEASON_ID'] == season].iloc[:, 4:])
Example #22
0
    def full_player_list(self):
        """Get a complete list of all players and their associated player ID."""

        for player in players.get_players():
            if player['first_name']:
                abv_name = ("{}. {}".format(player['first_name'][0],
                                            player['last_name']))
                last_name_first_name = ("{}, {}".format(
                    player['last_name'], player['first_name']))
                player_id = ("{}".format(player['id']))
                self.abv_player_list.append(abv_name)
                self.last_names.append(last_name_first_name)
                self.player_id.append(player_id)
Example #23
0
def show_graph(player_name):
    player_dict = players.get_players()

    player_df = [player for player in player_dict if player['full_name'] == player_name][0]
    player_id = player_df['id']

    gamelog_player_all = playergamelog.PlayerGameLog(player_id=player_id, season = SeasonAll.all)
    gamelog_player_all_df = gamelog_player_all.get_data_frames()[0]

    fig, ax = plt.subplots()
    ax.scatter(gamelog_player_all_df['FG3A'], gamelog_player_all_df['FG3M'], c='blue', alpha=0.5)
    
    return fig
def get_common_player_info():
    all_players = get_players()
    id_list = [player['id'] for player in all_players]

    info_list = []
    for index, id in enumerate(id_list):
        print('Fetching player {} of {}'.format(index + 1, len(id_list)),
              end='\r')
        info_list.append(
            CommonPlayerInfo(
                player_id=id).get_normalized_dict()['CommonPlayerInfo'][0])
        sleep(3)

    return pd.DataFrame(info_list)
Example #25
0
def get_player_stats(player_name, fundamental, season_all):
        
    player_dict = players.get_players()

    player_df = [player for player in player_dict if player['full_name'] == player_name][0]
    player_id = player_df['id']

    if season_all == True:
        gamelog_player_all = playergamelog.PlayerGameLog(player_id=player_id, season = SeasonAll.all)
    else:
        gamelog_player_all = playergamelog.PlayerGameLog(player_id=player_id, season = SeasonAll.current_season)

    gamelog_player_all_df = gamelog_player_all.get_data_frames()[0]

    return gamelog_player_all_df[fundamental].mean().round(decimals=1)
Example #26
0
def get_player_stats_detail(player_name):
        
    player_dict = players.get_players()

    player_df = [player for player in player_dict if player['full_name'] == player_name][0]
    player_id = player_df['id']

    gamelog_player_all = playergamelog.PlayerGameLog(player_id=player_id, season = SeasonAll.all)
    gamelog_player_all_df = gamelog_player_all.get_data_frames()[0]

    gamelog_player_all_df = gamelog_player_all_df[['GAME_DATE', 'MATCHUP', 'WL', 'MIN', 'FGM', 'FGA', 'FG_PCT', 'FG3M', 'FG3A', 'FG3_PCT', 'FTM', 'FTA', 'FT_PCT', 'OREB', 'DREB', 'REB', 'AST', 'STL', 'BLK', 'TOV', 'PTS']]
    gamelog_player_all_df = gamelog_player_all_df.rename(columns = {'GAME_DATE':'Game Date', 'FG_PCT' : 'FG %', 'FG3_PCT':'FG3 %', 'FT_PCT':'FT %'})
    gamelog_player_all_df['FG %'] = pd.Series(["{0:.2f}%".format(val * 100) for val in gamelog_player_all_df['FG %']], index = gamelog_player_all_df.index)
    gamelog_player_all_df['FG3 %'] = pd.Series(["{0:.2f}%".format(val * 100) for val in gamelog_player_all_df['FG3 %']], index = gamelog_player_all_df.index)
    gamelog_player_all_df['FT %'] = pd.Series(["{0:.2f}%".format(val * 100) for val in gamelog_player_all_df['FT %']], index = gamelog_player_all_df.index)

    return gamelog_player_all_df
Example #27
0
def stats_by_speech():
    speak("Give me an NBA player's last name or first name")
    name = get_audio()
    nba_players = players.get_players()
    try:
        player = [
            player for player in nba_players if player['last_name'] == name
            or player['first_name'] == name or player['full_name'] == name
        ][0]
    except:
        print('Invalid name')
        return
    speak("Now give me the year in question")
    try:
        year = get_audio()
        season = f"{int(year)}-{str(int(year)+1)[-2:]}"
    except:
        print('Invalid year')
        return
    get_player_stats(name, season)
Example #28
0
def get_player_shotchartdetail(player_name, season_id, season_progress):

    # player dictionary
    nba_players = players.get_players()
    player_dict = [player for player in nba_players if player['full_name'] == player_name][0]

    # career dataframe
    career = playercareerstats.PlayerCareerStats(player_id=player_dict['id'])
    career_df = career.get_data_frames()[0]

    # team id during the season
    team_id = career_df[career_df['SEASON_ID'] == season_id]['TEAM_ID']

    # shotchartdetail endpoints
    shotchartlist = shotchartdetail.ShotChartDetail(team_id=int(team_id),
                                                    player_id=int(player_dict['id']),
                                                    season_type_all_star=season_progress,
                                                    season_nullable=season_id,
                                                    context_measure_simple='FGA').get_data_frames()

    return shotchartlist[0], shotchartlist[1]
Example #29
0
    async def get_player_info(self, ctx, player_name):
        from nba_api.stats.static import players

        player_dict = players.get_players()
        player_name = player_name.lower()
        player_info = [
            player for player in player_dict
            if (player['full_name'].lower() == player_name
                or player['first_name'].lower() == player_name
                or player['last_name'].lower() == player_name)
        ]
        if len(player_name) == 0:
            await ctx.send('Please provide a player\'s name')
        elif len(player_info) == 1:
            return player_info[0]
        elif len(player_info) > 1:
            msg = f"Results for {player_name}:\n"
            for player in player_info:
                msg += f"{player['full_name']}\n"
            await ctx.send(msg)
        else:
            await ctx.send('Couldn\'t find the player.')
        return None
Example #30
0
from nba_api.stats.endpoints import playercareerstats

career = playercareerstats.PlayerCareerStats(player_id='203076')
#print(career.get_data_frames()[0])

from nba_api.stats.static import teams
# get_teams returns a list of 30 dictionaries, each an NBA team.
nba_teams = teams.get_teams()
#print('Number of teams fetched: {}'.format(len(nba_teams)))
for team in nba_teams:
    print(team['abbreviation'])
#dict_keys(['id', 'full_name', 'abbreviation', 'nickname', 'city', 'state', 'year_founded'])

from nba_api.stats.static import players
# get_players returns a list of dictionaries, each representing a player.
nba_players = players.get_players()
#print('Number of players fetched: {}'.format(len(nba_players)))
nba_players[:5]
#print(nba_players)

spurs = [
    team for team in nba_teams if team['full_name'] == 'San Antonio Spurs'
][0]

#print(type(spurs))

big_fundamental = [
    player for player in nba_players if player['full_name'] == 'Tim Duncan'
][0]

#print(big_fundamental['id'])