Example #1
0
def create_figure(graph_type, playerid, playerid2):
    axis = fig.add_subplot(1, 1, 1)
    career = playercareerstats.PlayerCareerStats(player_id=playerid)
    player_career_regular_season_totals = career.get_data_frames()[0].to_dict(
        'records')
    player_career_post_season_totals = career.get_data_frames()[2].to_dict(
        'records')

    player_career_regular_season_totals = get_average_stats(
        player_career_regular_season_totals)
    #player_career_post_season_totals  = get_average_stats(player_career_post_season_totals)

    i = 0
    xs = []
    ys = []
    for state in player_career_regular_season_totals:
        xs.append(i)
        ys.append(state[graph_type])
        i = i + 1
    axis.title.set_text(graph_type)
    axis.set_xlabel('nth seasons in the nba')
    axis.set_ylabel(graph_type)

    axis.plot(xs, ys, 'r', label=playerid)
    if playerid2:
        career = playercareerstats.PlayerCareerStats(player_id=playerid2)
        player_career_regular_season_totals = career.get_data_frames(
        )[0].to_dict('records')
        player_career_post_season_totals = career.get_data_frames()[2].to_dict(
            'records')

        player_career_regular_season_totals = get_average_stats(
            player_career_regular_season_totals)
        player_career_post_season_totals = get_average_stats(
            player_career_post_season_totals)
        i = 1
        xs2 = []
        ys2 = []
        for state in player_career_regular_season_totals:
            xs2.append(i)
            ys2.append(state[graph_type])
            i = i + 1
        axis.plot(xs2, ys2, 'b', label=playerid2)

    axis.legend()
    axis.savefig(output, format='png')
    output.seek(0)
    plot_data = base64.b64encode(output.getvalue()).decode()
    return plot_data
Example #2
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
Example #3
0
def queryTableInfo(pid):
    career = playercareerstats.PlayerCareerStats(player_id=pid, timeout= 60, headers=header)
    d = career.get_dict()
    jData = {}
    for item in sorted(d['resultSets'][0]['rowSet']):
        if item[1] in jData:
            item[1] = item[1] + "-" + str(i)
            i+=1
        else:
            i=1

        if item[6] is None: item[6] = 1

        jData[item[1]] = {}
        jData[item[1]]["team"] = item[4]
        jData[item[1]]["pointPerGame"] = truncate(item[26]/item[6], 1) if item[26] is not None else None
        jData[item[1]]["fieldGoalPercentage"] = truncate(item[11]*100,1) if item[11] is not None else None
        jData[item[1]]["fieldGoal3Percentage"] = truncate(item[14]*100,1) if item[14] is not None else None
        jData[item[1]]["assistsPerGame"] = item[21]//item[6] if item[21] is not None else None
        jData[item[1]]["reboundsPerGame"] = item[20]//item[6] if item[20] is not None else None
        jData[item[1]]["personalFouls"] = item[25] if item[25] is not None else None
        
    pprint(jData, indent=2)
    Data = dict()
    for key in sorted(jData.keys(),reverse = True):
        Data[key] = jData[key]
    return Data
Example #4
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 make_csv(id):
    player_info = playercareerstats.PlayerCareerStats(player_id=id)
    df = player_info.get_data_frames()[0]
    df.to_csv('Stats.csv')
    read_df = pandas.read_csv('Stats.csv')
    raw_values = read_df.sum(axis=0, skipna=True)
    return raw_values
Example #6
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 #7
0
 def __init__(self, name):
     self.search_name = name
     self.player = players.find_players_by_full_name(self.search_name)[0]
     self.playerid = self.player['id']
     self.playername = self.player['full_name']
     self.playerstats = playercareerstats.PlayerCareerStats(
         self.playerid).get_data_frames()[0]
Example #8
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 #9
0
def get_common_teammates(p1name, p2name):
    '''
	Get all common teammates of the players listed
	'''

    print 'Getting players ...'
    p1name, p1id = get_player_id(p1name)
    p2name, p2id = get_player_id(p2name)

    print 'Getting careers ...'
    p1career = playercareerstats.PlayerCareerStats(p1id)
    sleep(0.2)
    p2career = playercareerstats.PlayerCareerStats(p2id)
    sleep(0.2)

    p1teamsszns = [
        (d['TEAM_ID'], d['SEASON_ID'])
        for d in p1career.get_normalized_dict()['SeasonTotalsRegularSeason']
        if d['TEAM_ID'] != 0
    ]
    p2teamsszns = [
        (d['TEAM_ID'], d['SEASON_ID'])
        for d in p2career.get_normalized_dict()['SeasonTotalsRegularSeason']
        if d['TEAM_ID'] != 0
    ]

    print 'Getting teammates ...'
    p1teammates = set()
    for tid, szn in tqdm(p1teamsszns, desc=p1name):
        p1teammates.update(get_szn_teammates(tid, szn))
        sleep(0.2)
    p1teammates.remove(p1id)

    p2teammates = set()
    for tid, szn in tqdm(p2teamsszns, desc=p2name):
        p2teammates.update(get_szn_teammates(tid, szn))
        sleep(0.2)
    p2teammates.remove(p2id)

    common = p1teammates.intersection(p2teammates)

    commoninfo = [players.find_player_by_id(i) for i in common]
    for p in commoninfo:
        print p['full_name']


# get_common_teammates('rajon rondo', 'chris paul')
Example #10
0
def getSeasonTotalForPlayer(name, season):
    Id = players.find_players_by_full_name(name)[0]["id"]
    career = playercareerstats.PlayerCareerStats(player_id=Id)
    seasonTotalsDf = career.season_totals_regular_season.get_data_frame()
    seasonStatsDf = seasonTotalsDf.loc[seasonTotalsDf["SEASON_ID"] == season]
    #add name for convience
    seasonStatsDf.insert(0, 'Name', name)
    return seasonStatsDf
Example #11
0
def queryPlayerPPGScrollGraph(pid):
    career = playercareerstats.PlayerCareerStats(player_id=pid, timeout= 60, headers=header)
    d = career.get_dict()

    jujaData = dict()
    jujaData["chart"] = dict()
    jujaData["chart"]["theme"] = "candy"
    jujaData["chart"]["caption"] = "Points per season"
    jujaData["chart"]["numbersuffix"] = "pts"
    jujaData["chart"]["xAxisName"] = "Season"
    jujaData["chart"]["yAxisName"] = "Points Per Game"
    jujaData["chart"]["exportenabled"]= "1"
    jujaData["chart"]["exportmode"] = "client"
    jujaData["chart"]["exportfilename"] = "{}PPG".format(pid)
    
    jujaData["categories"] = list()
    cata = dict()
    cata["category"] = list()
    jujaData["categories"].append(cata)
    jujaData["dataSet"] = list()
    datem = dict()
    datem["data"] = list()
    jujaData["dataSet"].append(datem)
    jujaData["trendlines"] = list()
    trendLine = dict()
    trendLine["line"] = list()
    jujaData["trendlines"].append(trendLine)
    lineInfo = dict()
    total = 0
    i = len(d['resultSets'][0]['rowSet'])
    for item in d['resultSets'][0]['rowSet']:
        season = item[1]
        gp =item[6]
        pts = item[26]
        ppg =dict()
        
        ppg["value"] = truncate(pts/gp, 1)
        total += int(ppg["value"])
        jujaData["dataSet"][0]["data"].append(ppg)
        kvPair = {"label" : season}
        jujaData["categories"][0]["category"].append(kvPair)
    
    avg = (total/i)
    lineInfo["startvalue"] = avg
    lineInfo["endvalue"] = ""
    lineInfo["color"] = "#29C3BE"
    lineInfo["displayvalue"] = "Career average PPG"
    lineInfo["valueonright"] = "1"
    lineInfo["dashed"] = "1"
    lineInfo["thickness"] = "2"
    lineInfo["tooltext"] = "Career avg PPG: " + str(truncate(avg, 1))
    jujaData["trendlines"][0]["line"].append(lineInfo)
    pprint(jujaData, indent=2)
    
    return json.dumps(jujaData)
Example #12
0
def get_player_stats(player_id):
    """
    Args:
        player_id (str): String of a player id.

    Returns:
        dict: Data frames containing a player's career stats.
    """
    Career = playercareerstats.PlayerCareerStats(player_id)
    career_dict = Career.get_dict()
    return {i["name"]:pd.DataFrame(i["rowSet"],columns=i["headers"]) for i in career_dict["resultSets"]}
def get_active_seasons(selected_player):
    # career df
    career_df = playercareerstats.PlayerCareerStats(
        player_id=selected_player).get_data_frames()[0]
    #List of active seasons
    season_lst = [{
        'label': season,
        'value': season
    } for season in career_df['SEASON_ID']]

    return season_lst
def getPlayerRegularSeasonStats(player_id):
    """
    Given a player id, gets their career regular season stats from the NBA.com API and returns that dataframe
    :param player_id: NBA.com player id (ex. 1495)
    :return: pandas DataFrame containing the stats
    """
    # given a player_id
    stats = playercareerstats.PlayerCareerStats(
        player_id=player_id).get_data_frames()[0]
    # print(type(stats))
    return stats
Example #15
0
 def get_season(self, player_id, dictionary):
     # get the seasons that player_id played
     career = playercareerstats.PlayerCareerStats(player_id=player_id)
     # get all of the seasons a player played in
     arr = list(career.get_data_frames()[0]['SEASON_ID'].values)
     name = players.find_player_by_id(player_id)['full_name']
     # print the name for a measure of the speed of this program.
     print(f'{name} processed.')
     player_dict = {player_id: arr}
     # update the dictionary in shared memory
     dictionary.update(player_dict)
Example #16
0
def get_player_information(playerid):
    playerinfo = {}

    # Retrieve player 1 information and stats
    ##player_summary = commonplayerinfo.CommonPlayerInfo(player_id=playerid, proxy=proxy, timeout=100)
    player_summary = commonplayerinfo.CommonPlayerInfo(player_id=playerid,
                                                       timeout=500)
    player_summary_info = player_summary.get_data_frames()[0]
    headline_stats = player_summary.get_data_frames()[1]
    playerinfo['headline_stats'] = headline_stats
    playerinfo['player_summary_info'] = player_summary_info
    # Get last year that he played in
    to_year = int(player_summary_info.iloc[0]["TO_YEAR"])
    next_year = to_year + 1
    season = str(to_year) + "-" + str(next_year)[2:4]
    playerinfo['season'] = season

    time.sleep(5)
    # Get birth date for the player 1
    birth_datestring = player_summary_info.iloc[0]["BIRTHDATE"][:10]
    birth_date = datetime.datetime.strptime(birth_datestring, "%Y-%m-%d")
    playerinfo['pretty_birth_date'] = birth_date.strftime("%m-%d-%Y")
    playerinfo['age'] = calculate_age(birth_date)

    #career = playercareerstats.PlayerCareerStats(player_id=playerid, proxy=proxy, timeout=100)
    career = playercareerstats.PlayerCareerStats(player_id=playerid,
                                                 timeout=100)
    player_career_regular_season_totals = career.get_data_frames()[1].to_dict(
        'records')
    player_career_post_season_totals = career.get_data_frames()[3].to_dict(
        'records')
    player_career_regular_season = career.get_data_frames()[0].to_dict(
        'records')
    player_career_post_season = career.get_data_frames()[2].to_dict('records')
    playerinfo['player_career_regular_season_averages'] = get_average_stats(
        player_career_regular_season)
    playerinfo['player_career_post_season_averages'] = get_average_stats(
        player_career_post_season)
    playerinfo['player_career_regular_season'] = player_career_regular_season
    playerinfo['player_career_post_season'] = player_career_post_season
    playerinfo[
        'player_career_regular_season_totals'] = get_shooting_percentage(
            player_career_regular_season_totals)
    playerinfo['player_career_post_season_totals'] = get_shooting_percentage(
        player_career_post_season_totals)

    player_headshot = "https://ak-static.cms.nba.com/wp-content/uploads/headshots/nba/latest/260x190/" + playerid + ".png"
    if (not test_link(player_headshot)):
        player_headshot = False

    playerinfo['player_headshot'] = player_headshot
    return playerinfo
Example #17
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:])
def getPlayerInfo(players):
    queue = []
    for player in players:
        player_value = {}
        try:
            carrer_stats = playercareerstats.PlayerCareerStats(
                player_id=player["id"]).get_dict()
            player_value['full_name'] = player['full_name']
            stats = parseCareerStats(carrer_stats)
            player_value['FG_PCT'] = stats['FG_PCT']
            player_value['FG3_PCT'] = stats['FG3_PCT']
            player_value['FGA'] = stats['FGA']
            # Add points for 2 and 3
            player_value["2_Points"] = stats['FGA'] * stats['FG_PCT']
            player_value["3_Points"] = stats['FGA'] * stats['FG3_PCT']
            parse_selected.append(player_value)
        except requests.exceptions.Timeout:
            print("Failed and added to queue")
            queue.append(player)
            continue
    while (len(queue) != 0):
        player_value = {}
        try:
            player = queue[len(queue) - 1]
            carrer_stats = playercareerstats.PlayerCareerStats(
                player_id=player["id"]).get_dict()
            player_value['full_name'] = player['full_name']
            stats = parseCareerStats(carrer_stats)
            player_value['FG_PCT'] = stats['FG_PCT']
            player_value['FG3_PCT'] = stats['FG3_PCT']
            player_value['FGA'] = stats['FGA']
            player_value["2_Points"] = stats['FGA'] * stats['FG_PCT']
            player_value["3_Points"] = stats['FGA'] * stats['FG3_PCT']
            parse_selected.append(player_value)
            queue.pop(len(queue) - 1)
            print("Pop out of the queue")
        except requests.exceptions.Timeout:
            print("Request failed in queue")
            continue
Example #19
0
def queryPlayerFGPScrollGraph(pid):
    career = playercareerstats.PlayerCareerStats(player_id=pid, timeout= 60, headers=header)
    d = career.get_dict()
    jujaData = dict()
    jujaData["chart"] =dict()
    jujaData["chart"]["theme"] = "candy"
    jujaData["chart"]["caption"] = "FG% per season"
    jujaData["chart"]["numbersuffix"] = "%"
    jujaData["chart"]["xAxisName"] = "Season"
    jujaData["chart"]["yAxisName"] = "FG% Per Game"
    jujaData["chart"]["exportenabled"]= "1"
    jujaData["chart"]["exportmode"] = "client"
    jujaData["chart"]["exportfilename"] = "{}PPG".format(pid)
    jujaData["categories"] = list()
    cata = dict()
    cata["category"] = list()
    jujaData["categories"].append(cata)
    jujaData["dataSet"] = list()
    datem = dict()
    datem["data"] = list()
    jujaData["dataSet"].append(datem)
    jujaData["trendlines"] = list()
    trendLine = dict()
    trendLine["line"] = list()
    jujaData["trendlines"].append(trendLine)
    lineInfo = dict()
    total = 0
    i = len(d['resultSets'][0]['rowSet'])
    #print("This is a list of the careertotalRegularstats of Lebron: ")
    for item in d['resultSets'][0]['rowSet']:
        season = item[1]
        fgp = item[11]
        d = {}
        d["value"] = fgp*100
        total += d["value"]
        jujaData["dataSet"][0]["data"].append(d)
        kvPair = {"label" : season}
        jujaData["categories"][0]["category"].append(kvPair)
        
    avg = truncate((total/i),1)
    lineInfo["startvalue"] = avg
    lineInfo["endvalue"] = ""
    lineInfo["color"] = "#29C3BE"
    lineInfo["displayvalue"] = "Career average PPG"
    lineInfo["valueonright"] = "1"
    lineInfo["dashed"] = "1"
    lineInfo["thickness"] = "2"
    lineInfo["tooltext"] = "Career FG%" + str(truncate(avg,1))
    jujaData["trendlines"][0]["line"].append(lineInfo)
    pprint(jujaData, indent=2)
    return json.dumps(jujaData)
Example #20
0
    def get_career_stats(self):
        """A method to get player's career stats

            Args:
                self: self

            Returns:
                career_stats(dict): Dictionary with list of season stats and headers
        """

        if not self.id:
            return {}
        return json.loads(
            playercareerstats.PlayerCareerStats(
                player_id=self.id).get_json())['resultSets'][0]
Example #21
0
def generatePlayerCarrerStat():
    f = open("stattt.txt", "a")
    for player in active_players:
        id = player['id']

        time.sleep(0.5)
        player_info = playercareerstats.PlayerCareerStats(player_id=id,
                                                          timeout=1000)
        player_reg_stat = player_info.career_totals_regular_season.get_dict()
        player_stat = {
            "player": player,
            "reg_season_career_total": player_reg_stat
        }
        print(player_reg_stat)
        f.write(str(player_stat) + "\n")
def playerCheck(player):
    while (True):
        try:
            print("Player check inside")
            carrer_stats = playercareerstats.PlayerCareerStats(
                player_id=player["id"]).get_dict()
            base = carrer_stats['resultSets'][0]
            print("Player check")
            if findSeason('2019-20', base) is None:
                return False
            else:
                return True
        except requests.exceptions.Timeout:
            print("Player check failed")
            continue
def main():
    player_stats = json.loads(playercareerstats.PlayerCareerStats(player_id=2544).get_json())
    headers = player_stats["resultSets"][0]["headers"]
    row_set = player_stats["resultSets"][0]["rowSet"]

    print("Enter first year of the season to get stats for. It should be between 2003 and 2018:")
    year = get_year()

    for r in row_set:
        if year == r[1]:
            row = r
            break

    print("Here is stats for Lebron James for", year, "season:")
    for i in range(len(headers)):
        print(headers[i], '-', row[i])
Example #24
0
def parse_common_player_info(player_id: str):
    """
    Parse player info from CommonPlayerInfo endpoint (when player has not been insert in database)
    """
    player_json = json.loads(
        commonplayerinfo.CommonPlayerInfo(player_id=player_id).get_json())
    headers_player, row_set_player = get_result_set(player_json,
                                                    'CommonPlayerInfo')

    if row_set_player:
        data_player = row_set_player[0]

        player = {
            'personId': data_player[headers_player['PERSON_ID']],
            'firstName': data_player[headers_player['FIRST_NAME']],
            'lastName': data_player[headers_player['LAST_NAME']],
            'teamId': format_team(data_player[headers_player['TEAM_ID']])
        }

        parsed_player = parse_player(player)
        if parsed_player is not None:
            return parsed_player
        else:
            # in case player is not registered by data.nba.net api
            stats_json = json.loads(
                playercareerstats.PlayerCareerStats(
                    player_id=player_id,
                    per_mode36='PerGame',
                    league_id_nullable=APIProperty('LeagueID')).get_json())
            headers_stats, row_set_stats = get_result_set(
                stats_json, 'SeasonTotalsRegularSeason')

            # get stats for current season
            data_stats = row_set_stats[-1]
            return Player(id=data_player[headers_player['PERSON_ID']],
                          first_name=data_player[headers_player['FIRST_NAME']],
                          last_name=data_player[headers_player['LAST_NAME']],
                          team_id=format_team(
                              data_player[headers_player['TEAM_ID']]),
                          mpg=data_stats[headers_stats['MIN']],
                          ppg=data_stats[headers_stats['MIN']],
                          rpg=data_stats[headers_stats['REB']],
                          apg=data_stats[headers_stats['AST']],
                          spg=data_stats[headers_stats['STL']],
                          bpg=data_stats[headers_stats['BLK']])
    else:
        return None
Example #25
0
def career_stats(pid, per_mode):
    pl = playercareerstats.PlayerCareerStats(
        per_mode36=per_mode, player_id=pid).season_totals_regular_season
    stats = pl.get_dict()
    stats_h = [
        'Season', 'Team', 'Age', 'GP', 'GS', 'Min', 'FGM', 'FGA', 'FG PCT',
        'FG3M', 'FG3A', 'FG3 PCT', 'FTM', 'FTA', 'FT PCT', 'OREB', 'DREB',
        'REB', 'AST', 'STL', 'BLK', 'TOV', 'PF', 'PTS'
    ]
    stats_d = stats['data']
    stats_b = []
    for stat in stats_d:
        s = stat[4:]
        s.insert(0, stat[1])
        s[2] = int(s[2])
        stats_b.append(s)
    return stats_h, stats_b
def scrapePlayerStats():
    player_information = getAllCurrentPlayerIds(
    )  # get a list of player names and IDs
    for index, row in player_information.iterrows():
        curr_id = row['PERSON_ID']
        curr_full_name = row['DISPLAY_FIRST_LAST']
        formatted_full_name = curr_full_name.replace(" ", "_")

        current_player_stats = playercareerstats.PlayerCareerStats(
            curr_id).get_data_frames()[0]
        print(current_player_stats)
        filename = '{}datasets/player_stats/{}_Stats.csv'.format(
            filepath, formatted_full_name)

        current_player_stats.to_csv(filename, index=None, header=True)
        print("Wrote to {}".format(filename))
        time.sleep(5)
def get_player_shotchartdetail(player, season_id, season_type):
    # career df
    career_df = playercareerstats.PlayerCareerStats(
        player_id=player).get_data_frames()[0]

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

    # shotchardtdetail endpoint
    shotchartlist = shotchartdetail.ShotChartDetail(
        team_id=int(team_id),
        player_id=int(player),
        season_type_all_star=season_type,
        season_nullable=season_id,
        context_measure_simple="FGA").get_data_frames()

    return shotchartlist[0], shotchartlist[1]
Example #28
0
def getplayerseasonstats(playername,playerteam,year): ##get given season stats avg for a player
    players = commonallplayers.CommonAllPlayers().get_data_frames()
    players = players[0]
    listofnames = players['DISPLAY_FIRST_LAST']
    index = ((list(listofnames)).index(playername))
    ID = (players.loc[index, 'PERSON_ID'])
    career=playercareerstats.PlayerCareerStats(player_id=ID)
    career=career.get_data_frames()
    career=career[0]
    seasonstat=career.loc[career['SEASON_ID'].str[0:4]==str(year)]
    seasonstat=seasonstat.loc[seasonstat['TEAM_ABBREVIATION']==playerteam]  ##Just in case they switch teams
    totalgames=int(seasonstat['GP'])
    seasonstat.drop(['SEASON_ID','PLAYER_ID','LEAGUE_ID','TEAM_ID','TEAM_ABBREVIATION','PLAYER_AGE','GS','GP'],axis=1,inplace=True)
    seasonstat=seasonstat.divide(totalgames)
    seasonstat['FT_PCT']=seasonstat['FT_PCT']*totalgames
    seasonstat['FG_PCT']=seasonstat['FG_PCT']*totalgames
    seasonstat['FG3_PCT']=seasonstat['FG3_PCT']*totalgames
    return seasonstat
Example #29
0
def insert_stats(cur, conn, team_id):
    stat_names = [
        "PLAYER_ID", "SEASON_ID", "LEAGUE_ID", "TEAM_ID", "TEAM", "PLAYER_AGE",
        "GP", "GS", "MIN", "FGM", "FGA", "FG_PCT", "FG3M", "FG3A", "FG3_PCT",
        "FTM", "FTA", "FT_PCT", "OREB", "DREB", "REB", "AST", "STL", "BLK",
        "TOV", "PF", "PTS"
    ]
    index = {stat_names[i]: i for i in range(len(stat_names))}

    players = cur.execute(
        'SELECT player_id, name FROM players WHERE team_id = (?)',
        (team_id, )).fetchall()
    for player_id in players:
        stats = playercareerstats.PlayerCareerStats(
            player_id=player_id, per_mode36='PerGame').get_dict()
        for season in stats['resultSets'][0]['rowSet']:
            cur.execute('INSERT INTO NBA (player_id, season_id, team, minutes, points, rebounds, assists, field_goal_percentage, three_percentage, steals, blocks) \
                VALUES (?,?,?,?,?,?,?,?,?,?,?)'                                               , (season[index['PLAYER_ID']], season[index['SEASON_ID']], season[index['TEAM']], season[index['MIN']], season[index['PTS']], \
                    season[index['REB']], season[index['AST']], season[index['FG_PCT']], season[index['FG3_PCT']], season[index['STL']], season[index['BLK']],))
        conn.commit()
Example #30
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]