def stats():
    playerId = players.find_players_by_full_name(
        request.args.get('player'))[0].get('id', None)

    player_info = json.loads(
        commonplayerinfo.CommonPlayerInfo(
            player_id=playerId).get_normalized_json()).get(
                'CommonPlayerInfo', None)[0]
    player_headline_stats = json.loads(
        commonplayerinfo.CommonPlayerInfo(
            player_id=playerId).get_normalized_json()).get(
                'PlayerHeadlineStats', None)[0]

    player_stats = json.loads(
        playerprofilev2.PlayerProfileV2(
            per_mode36="PerGame", player_id=playerId).get_normalized_json())

    teamId = player_info.get('TEAM_ID', None)

    profile_picture = "https://ak-static.cms.nba.com/wp-content/uploads/headshots/nba/%s/2019/260x190/%s.png" % (
        teamId, playerId)

    return {
        **player_info,
        **player_headline_stats,
        **player_stats, "profile_picture": profile_picture
    }
示例#2
0
def nba_player_name_from_jersey_search(team_player_ids, yahoo_jersey_number):

    for id in team_player_ids:
        nba_jersey_number = commonplayerinfo.CommonPlayerInfo(id).get_normalized_dict() \
            [COMMON_PLAYER_INFO][0][JERSEY_KEY]
        if nba_jersey_number == yahoo_jersey_number:
            nba_name = commonplayerinfo.CommonPlayerInfo(id).get_normalized_dict() \
            [COMMON_PLAYER_INFO][0][DISPLAY_FIRST_LAST]

            return nba_name
示例#3
0
def create_currentplayers_lists(season):

	season = '2021'
	players_df, players_list, playersid_list = create_players_list(season)

	# append to a height list
	#for player_id in player_id_list:

	response = commonplayerinfo.CommonPlayerInfo(player_id = playersid_list[69])

	time.sleep(0.1)

	content = json.loads(response.get_json())

	# transform contents into dataframe
	playersinfo_raw = content['resultSets'][0]

	headers = playersinfo_raw['headers']

	rows = playersinfo_raw['rowSet']

	playersinfo_df = pd.DataFrame(rows)

	playersinfo_df.columns = headers

	return playersinfo_df
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
示例#5
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."
示例#6
0
def player_info(request):
    if request.method == 'GET':
        id = request.GET['id']
        info = commonplayerinfo.CommonPlayerInfo(player_id=id)
        info = info.get_normalized_json()
        return HttpResponse(info)  # Sending a success response
    else:
        return HttpResponse("Request method is not a GET")
示例#7
0
def get_player_info(name):
    player_in = players.find_players_by_full_name(name)
    player_stats = commonplayerinfo.CommonPlayerInfo(player_in[0]['id']).player_headline_stats
    players_list.append('Name: ' + player_in[0]['full_name'])
    players_list.append('Year: ' + player_stats.get_dict()['data'][0][2]
                        + ', PPG: ' + str(player_stats.get_dict()['data'][0][3])
                        + ', APG: ' + str(player_stats.get_dict()['data'][0][4]) +
                        ', RPG: ' + str(player_stats.get_dict()['data'][0][5])
                        + ', PIE: '  + str(player_stats.get_dict()['data'][0][6])
                        )
def download_common_player_info(database=None):
    for player_id in database:
        # call nba_api and get common player info
        cpi = commonplayerinfo.CommonPlayerInfo(
            player_id).get_normalized_dict()

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

        # extract the response for player common info
        r.extract_player_common_info(player_id)
示例#9
0
 def __init__(self, id):
     self.id = id
     self.player_info = commonplayerinfo.CommonPlayerInfo(
         self.id).common_player_info.get_dict().get('data')[0]
     self.name = self.player_info[3]
     self.number = self.player_info[13]
     self.height = self.player_info[10]
     self.weight = self.player_info[11]
     self.team = self.player_info[17]
     self.birth_year = int(self.player_info[6][0:4])
     #self.stock_value = #get stock value
     self.performances = []
示例#10
0
 def printHeadlineStats(self, full_name="Stephen Curry"):
     id = self.getPlayerId(full_name)
     player_info = commonplayerinfo.CommonPlayerInfo(id)
     headline_stats = player_info.player_headline_stats.get_dict()
     with open('headline_stats.txt', 'w') as fp:
         fp.write("")
     for i in range(1, 6):
         print(headline_stats['headers'][i] + ": " +
               str(headline_stats['data'][0][i]))
         with open('headline_stats.txt', 'a') as fp:
             fp.write(headline_stats['headers'][i] + ": " +
                      str(headline_stats['data'][0][i]) + " | ")
示例#11
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
示例#12
0
 def printDraftInfoForPlayer(self, full_name="Stephen Curry"):
     id = self.getPlayerId(full_name)
     with open('draft_player.txt', 'w') as fp:
         fp.write("")
     player = commonplayerinfo.CommonPlayerInfo(id)
     common_info = player.common_player_info.get_dict()
     print("Draft Year: " + str(common_info['data'][0][27]))
     print("Round Number: " + str(common_info['data'][0][28]))
     print("Pick Number: " + str(common_info['data'][0][29]))
     with open('draft_player.txt', 'a') as fp:
         fp.write("Draft Year: " + str(common_info['data'][0][27]) + '\n')
         fp.write("Round Number: " + str(common_info['data'][0][28]) + '\n')
         fp.write("Pick Number: " + str(common_info['data'][0][29]) + '\n')
def get_player_common_info(player):
    player_info = commonplayerinfo.CommonPlayerInfo(
        player).get_data_frames()[0]
    name = player_info['DISPLAY_FIRST_LAST'][0]
    prior = 'Prior: ' + player_info['LAST_AFFILIATION'][0]
    height = 'Height: ' + player_info['HEIGHT'][0]
    weight = 'Weight: ' + player_info['WEIGHT'][0] + 'lbs'
    exp = 'Exp: ' + str(player_info['SEASON_EXP'][0])
    jersey = '#' + player_info['JERSEY'][0] + ' '
    team = ' | ' + player_info['TEAM_CITY'][0] + ' ' + player_info[
        'TEAM_NAME'][0]
    position = player_info['POSITION'][0]
    abrv = player_info['TEAM_ABBREVIATION'][0]
    team_logo = f'https://stats.nba.com/media/img/teams/logos/{abrv}_logo.svg'
    birthDate = date(int(player_info['BIRTHDATE'][0][0:4]),
                     int(player_info['BIRTHDATE'][0][5:7]),
                     int(player_info['BIRTHDATE'][0][8:10]))
    today = date.today()
    age = 'Age: ' + str(today.year - birthDate.year - (
        (today.month, today.day) < (birthDate.month, birthDate.day)))
    born = 'Born: ' + player_info['BIRTHDATE'][0][5:7] + '/' + player_info[
        'BIRTHDATE'][0][8:10] + '/' + player_info['BIRTHDATE'][0][0:4]
    draft = 'Drafted: ' + player_info['DRAFT_YEAR'][0] + ' Rnd ' + player_info[
        'DRAFT_ROUND'][0] + ' Pick ' + player_info['DRAFT_NUMBER'][0]

    player_stats = commonplayerinfo.CommonPlayerInfo(
        player).get_data_frames()[1]
    timeframe = player_stats['TimeFrame'][0].capitalize() + ' Stats'
    if list(player_stats.columns)[-1] == 'PIE':
        pie = str(player_stats['PIE'][0])
    else:
        pie = str(player_stats['ALL_STAR_APPEARANCES'][0])
    pts = str(player_stats['PTS'][0])
    reb = str(player_stats['REB'][0])
    ast = str(player_stats['AST'][0])

    return [jersey, name], height, weight, prior, age, born, draft, exp, [
        position, team
    ], team_logo, pts, reb, ast, pie
示例#14
0
 def printCommonPlayerInfo(self, full_name="Stephen Curry"):
     id = self.getPlayerId(full_name)
     player = commonplayerinfo.CommonPlayerInfo(id)
     common_info = player.common_player_info.get_dict()
     with open('general.txt', 'w') as fp:
         fp.write("")
     for i in range(0, 30):
         if (i == 0 or i == 3 or i == 4 or i == 5 or i == 15 or i == 16
                 or i == 19 or i == 21 or i == 24 or i == 25 or i == 26):
             continue
         print(common_info['headers'][i] + ": " +
               str(common_info['data'][0][i]))
         with open('general.txt', 'a') as fp:
             fp.write(common_info['headers'][i] + ": " +
                      str(common_info['data'][0][i]) + '\n')
示例#15
0
def getIds(fullName):
    # find player id by full name
    try:
        pd = players.find_players_by_full_name(fullName)
        player_id = pd[0]['id']
    except Exception:
        return "error"

    # get the player's current team (seems quite extensive to do
    # it like this, but I don't want ppl to have to enter in
    # a team name as well just to get a shot chart)
    info = commonplayerinfo.CommonPlayerInfo(player_id, headers=headers)
    team_id = info.common_player_info.get_data_frame()['TEAM_ID'][0]
    # return id's as key-value pair
    return {'player_id': player_id, 'team_id': team_id}
示例#16
0
    def get_team_id(self, player_id):
        """Match player id to team id which is necessary for shot info.

        :param int player_id:
            Player ID that is associated with player user provided.

        :returns team_id
        :rtype int
        """
        try:
            current_team_id = commonplayerinfo.CommonPlayerInfo(
                player_id=player_id)
        except requests.exceptions.ConnectionError:
            print("Request failed.")
        else:
            return current_team_id.common_player_info.data['data'][0][16]
示例#17
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
示例#18
0
def playerinfo(id=None):

    player_info = commonplayerinfo.CommonPlayerInfo(player_id=id)
    df = player_info.get_data_frames()[0]
    player_data = []
    for index, row in df.iterrows():
        data = {}
        data["a_Name"] = row["DISPLAY_FIRST_LAST"]
        data["e_School"] = row["SCHOOL"]
        data["f_Country"] = row["COUNTRY"]
        data["b_Height"] = row["HEIGHT"]
        data["c_Weight"] = row["WEIGHT"]
        data["d_Seasons"] = row["SEASON_EXP"]
        data["g_Draft_year"] = row["DRAFT_YEAR"]
        data["h_Draft_round"] = row["DRAFT_ROUND"]
        data["i_draft_number"] = row["DRAFT_NUMBER"]
        player_data.append(data)

    return jsonify(player_data)
示例#19
0
def insert_new_players(**kwargs):
    date_format_str = '%Y-%m-%d'
    date = kwargs['ds']
    staged_player_box_tuple = session.query(PlayerBoxStage.PLAYER_ID).join(
        LeagueGameLog.__table__).filter(LeagueGameLog.GAME_DATE == date).all()
    staged_players = [player[0] for player in staged_player_box_tuple]
    for player in staged_players:
        if not session.query(
                Player.PLAYER_ID).filter(Player.PLAYER_ID == player).first():
            new_player = commonplayerinfo.CommonPlayerInfo(
                player_id=player).get_dict()['resultSets'][0]['rowSet'][0]
            for n, col in enumerate(new_player):
                if col in ['', ' ']:
                    new_player[n] = None
            new_player[player_cols['DOB']] = datetime.strptime(
                new_player[player_cols['DOB']][0:10],
                date_format_str).strftime('%Y-%m-%d %H:%M:%S')
            if new_player[player_cols['HEIGHT']]:
                height_split = [
                    int(i)
                    for i in new_player[player_cols['HEIGHT']].split('-')
                ]
                new_player[player_cols[
                    'HEIGHT']] = height_split[0] * 12 + height_split[1]
            for col in ['WEIGHT', 'DRAFT_YEAR', 'DRAFT_ROUND', 'DRAFT_NUMBER']:
                if new_player[player_cols[col]] and new_player[
                        player_cols[col]] != 'Undrafted':
                    new_player[player_cols[col]] = int(
                        new_player[player_cols[col]])
                else:
                    new_player[player_cols[col]] = None
            limited_content = [
                new_player[value] for key, value in player_cols.items()
            ]
            for n, item in enumerate(limited_content):
                if type(item) == str:
                    if "'" in item:
                        limited_content[n] = item.replace("'", "''")
            insert_data(limited_content, ["prod.players"])
            time.sleep(4)
示例#20
0
def get_height(player_id):

	response = commonplayerinfo.CommonPlayerInfo(player_id)

	time.sleep(0.5)

	content = json.loads(response.get_json())

	# transform contents into dataframe
	playersinfo_raw = content['resultSets'][0]

	headers = playersinfo_raw['headers']

	rows = playersinfo_raw['rowSet']

	playersinfo_df = pd.DataFrame(rows)

	playersinfo_df.columns = headers

	height = playersinfo_df['HEIGHT'].tolist()

	return height
示例#21
0
def player_average_stats(player_name):
    player_search = players.find_players_by_full_name(player_name)
    plural = ""
    if len(player_search) == 0:
        print("No player with name '%s' found." % name)
        sys.exit(0)
    if len(player_search) > 1:
        plural = "s"
    print("Found player%s matching the name '%s'!" % (plural, name))
    for player in player_search:
        player_id = player['id']
        player_info = commonplayerinfo.CommonPlayerInfo(
            player_id=player_id).get_normalized_dict()

        # Display the players' information
        #print("----General Information----")
        #for info_key, info_value in player_info['CommonPlayerInfo'][0].items():
        #	print(info_key + ": " + str(info_value))
        for stats_key, stats_value in player_info["PlayerHeadlineStats"][
                0].items():
            if stats_key in ["PLAYER_ID", "PLAYER_NAME"]:
                continue
            print(stats_key + ": " + str(stats_value))
示例#22
0
    def get_player_info(self):

        # downlading information about the player from the NBA Stats API
        player_info = commonplayerinfo.CommonPlayerInfo(player_id=self.id)
        player_df = player_info.get_data_frames()[0]
        # choosing columns which are interesting to us
        player_columns = [
            'DISPLAY_FIRST_LAST', 'BIRTHDATE', 'SCHOOL', 'COUNTRY', 'HEIGHT',
            'WEIGHT', 'POSITION', 'TEAM_NAME', 'FROM_YEAR', 'TO_YEAR'
        ]
        player_df = player_df[player_columns]
        # changing these columns' names
        col = [
            'Name', 'Birthdate', 'School', 'Country', 'Height', 'Weight',
            'Position', 'Team', 'Played from', 'Played to'
        ]
        player_df.columns = col
        # formatting player's birthdate
        player_df['Birthdate'] = player_df['Birthdate'][0][:10]
        # changing data format to dictionary so it's easier to handle with jinja2
        player_df = player_df.to_dict()

        return player_df
示例#23
0
import json
from nba_api.stats.endpoints import commonplayerinfo as api
from pprint import pprint

players = json.loads(open("./All_Players.json").read())
header = {
    'Host': 'stats.nba.com',
    'Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent':
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36',
    'Accept':
    'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US,en;q=0.9',
    'Referer': 'https://stats.nba.com',
}
teams = []
for player in players:
    print("Fetching team for {}".format(player["full_name"]))
    info = api.CommonPlayerInfo(player["id"], headers=header)
    team_id = info.get_normalized_dict(
    )["CommonPlayerInfo"][0]["TEAM_ABBREVIATION"]
    if team_id not in teams:
        teams.append(team_id)
    print("{} team is {}".format(player["full_name"], team_id))
pprint(teams)
json.dumps(open("./team.json").write())
示例#24
0
#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'])

#print(players.find_players_by_first_name('lebron'))

#print(teams.find_teams_by_state('ohio'))

#print(big_fundamental)

# Basic Request
from nba_api.stats.endpoints import commonplayerinfo

player_info = commonplayerinfo.CommonPlayerInfo(player_id=2544)
player_dic = player_info.available_seasons.get_dict()

#print(player_dic)
print(player_info.common_player_info.get_data_frame())
示例#25
0
    async def career_stats(self, ctx, *, 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)

            career_stats = playercareerstats.PlayerCareerStats(
                player_id=object_id)

            df_career_stats = career_stats.get_data_frames()

            career_totals = df_career_stats[1].sum()

            # same process as before but this time all the columns are added up to later find career averages

            def get_per_game(metric):
                return round(
                    (career_totals.get(f'{metric}') / career_totals.get('GP')),
                    1)

            def get_percent(metric, attemped_metric):
                return round((career_totals.get(f'{metric}') /
                              career_totals.get(f'{attemped_metric}') * 100),
                             1)

            # these functions calculate per-game stats and field goal efficiences respectively

            career_ppg = get_per_game('PTS')
            career_fgp = get_percent('FGM', 'FGA')
            career_tpp = get_percent('FG3M', 'FG3A')
            career_ftp = get_percent('FTM', 'FTA')
            career_rpg = get_per_game('REB')
            career_apg = get_per_game('AST')
            career_spg = get_per_game('STL')
            career_bpg = get_per_game('BLK')
            career_tpg = get_per_game('TOV')
            # all major stats are stored as variables to be used in embedded message later

            career_stats_embed = discord.Embed(title=object_search,
                                               colour=discord.Colour(0x0e1cf5))

            player_info = commonplayerinfo.CommonPlayerInfo(
                player_id=object_id)

            df_player_info = player_info.get_data_frames()

            t_id = df_player_info[0].iat[0, 16]
            to_year = df_player_info[0].iat[0, 23]
            # this data is only being pulled for the sake of finding the player's picture for the thumbnail

            career_stats_embed.set_footer(text='gimme help | RIP Kobe')
            career_stats_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'
            )
            career_stats_embed.set_thumbnail(
                url=
                f'https://ak-static.cms.nba.com/wp-content/uploads/headshots/nba/{t_id}/{to_year}/260x190/{object_id}.png'
            )

            career_stats_embed.set_author(
                name=f'Career stat averages for `{object_search}')
            career_stats_embed.add_field(name='PPG', value=career_ppg)
            career_stats_embed.add_field(name='FG%', value=f'{career_fgp}%')
            career_stats_embed.add_field(name='3P%', value=f'{career_tpp}%')
            career_stats_embed.add_field(name='FT%', value=f'{career_ftp}%')
            career_stats_embed.add_field(name='RPG', value=career_rpg)
            career_stats_embed.add_field(name='APG', value=career_apg)
            career_stats_embed.add_field(name='SPG', value=career_spg)
            career_stats_embed.add_field(name='BPG', value=career_bpg)
            career_stats_embed.add_field(name='TPG', value=career_tpg)
            # career stat averages added embedded message

            await ctx.send(embed=career_stats_embed)

        except (UnboundLocalError, gspread.exceptions.CellNotFound):
            await ctx.send("""
            I think you spelled it wrong hombre, make sure you're using this format: `gimme career_stats Steph Curry`.
            Also, make sure you're not using shortened versions of names like `Steph Curry`.
            """)
示例#26
0
    async def player_info(self, ctx, *, object_search):

        try:
            object_row = (sheet.find(object_search).row)
            object_column = (sheet.find(object_search).col)
            # finds the coordinates of the cell containing the player name
            object_id = sheet.cell(object_row, object_column - 1).value
            # assigns the data in the cell to the left of the player name as a variable
            # this is the ID itself
            object_id = str(object_id)
            # NBA API cannot read the ID unless it's in string form

            player_info = commonplayerinfo.CommonPlayerInfo(
                player_id=object_id)

            df_player_info = player_info.get_data_frames()
            # Data appended to a DataFrame, from which it can easily be extracted

            t_id = df_player_info[0].iat[0, 16]
            to_year = df_player_info[0].iat[0, 23]

            jersey_number = df_player_info[0].iat[0, 13]
            position = df_player_info[0].iat[0, 14]
            height = df_player_info[0].iat[0, 10]
            weight = df_player_info[0].iat[0, 11]

            date_of_birth = df_player_info[0].iat[0, 6]
            date_of_birth = date_of_birth.rstrip('T00:00:00')

            draft_position = df_player_info[0].iat[0, 29]
            draft_round = df_player_info[0].iat[0, 28]
            # Pulled various pieces of data regarding the player
            # These will later be used by the bot

            player_embed = discord.Embed(title=object_search,
                                         colour=discord.Colour(0x0e1cf5))

            player_embed.set_footer(text='gimme help | RIP Kobe')
            player_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'
            )
            player_embed.set_thumbnail(
                url=
                f'https://ak-static.cms.nba.com/wp-content/uploads/headshots/nba/{t_id}/{to_year}/260x190/{object_id}.png'
            )
            # thumbnail is used to display the player picture

            player_embed.set_author(name=f'Player info for `{object_search}')
            player_embed.add_field(name='Jersey Number', value=jersey_number)
            player_embed.add_field(name='Position', value=position)
            player_embed.add_field(name='Height', value=height)
            player_embed.add_field(name='Weight', value=f'{weight} lbs')
            player_embed.add_field(name='Date of Birth', value=date_of_birth)
            player_embed.add_field(
                name='Drafted',
                value=f'Round: {draft_round} Pick: {draft_position}')
            # all data is added to embedded message to be more visually appealing

            await ctx.send(embed=player_embed)

        except (UnboundLocalError, gspread.exceptions.CellNotFound):
            await ctx.send("""
            I think you spelled it wrong hombre, make sure you're using this format: `gimme player_info Steph Curry`.
            Also, make sure you're not using shortened versions of names like `Steph Curry`.
            """)
示例#27
0
from nba_api.stats.endpoints import commonplayerinfo
from nba_api.stats.endpoints import playerdashboardbylastngames
from nba_api.stats.static import players

player_info = commonplayerinfo.CommonPlayerInfo(2544, "00")
lebron_dict = player_info.common_player_info.get_dict()
# lebron_log = playergamelog.PlayerGameLog(2544, 2017-18, "Regular Season")
# print(lebron_log)
lebron_last_5_games = playerdashboardbylastngames.PlayerDashboardByLastNGames(2544, 0, "Base", 0, 0, "N", "PerGame", 0, "N", "N", "2017-18", "Regular Season")
#lebron_last_5_games_2 = playerdashboardbylastngames.PlayerDashboardByLastNGames(2544, 0, "Base", 0, 0, "N", "PerGame", 0, "N", "N", "2017-18", "Regular Season", "03-20-2018", "03-10-2018")
lebron_5_game_dict = lebron_last_5_games.last5_player_dashboard.get_dict()
#lebron_5_game_dict_2 = lebron_last_5_games_2.last5_player_dashboard.get_dict()
print("Player:" + lebron_dict.get('data')[0][3] + ", Number: " + lebron_dict.get('data')[0][13] + "\n")
print(lebron_5_game_dict.get('data')[0][28])
print(players.find_players_by_full_name('LeBron James')[0].get('id'))
#print(lebron_5_game_dict_2.get('data')[0][28])
#print(lebron_5_game_dict_2)
示例#28
0
# format data for dataframe
df = pandas.DataFrame(result_sorted)
df.columns = ["Percent Change in Opp. RA FGA", "Player"]
cols = df.columns.tolist()
cols = cols[::-1]
df = df[cols]
print(df)

# format data for html table
print(
    "<table><tr><td>Player</td><td>Percent Change in <br />Opp. RA FGA</td></tr>"
)
for entry in result_sorted:
    print("\n<tr><td>" + entry[1] + "</td><td>" + str(entry[0]) + "</td></tr>")
print("\n</table>")

# correlation with height
# api calls
results_with_height = []
for entry in result_sorted:
    playerid = players.find_players_by_full_name(entry[1])[0]['id']
    height = commonplayerinfo.CommonPlayerInfo(
        player_id=playerid).common_player_info.data['data'][0][10]
    height_inches = height.split("-")[0] * 12 + height.split("-")[
        1]  #convert to inches
    results_with_height.append((entry[1], entry[0], height_inches))

#correlation
df = pandas.DataFrame(results_with_height)
df.corr()
print(df.corr())
示例#29
0
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 = []
Team2_PlayerInfo = []
Team1_PlayerCumeInfo = []
Team2_PlayerCumeInfo = []

for i in range(Team1_length):
    print(i)
    Team1_PlayerPIE = commonplayerinfo.CommonPlayerInfo(
        Team1_PlayerIds[i]).get_data_frames()[1][['PIE']]
    Team1_PlayerCumeInfo.append(
        playercareerstats.PlayerCareerStats(
            Team1_PlayerIds[i]).get_data_frames()[1])

    time.sleep(.8)
    Team1_PlayerPIE_List = Team1_PlayerPIE.values.tolist()
    Team1_PlayerInfo.append(Team1_PlayerPIE_List)
#sorts the data from best to worst player
Team1_PlayerPIE_Sorted = sorted(Team1_PlayerInfo, reverse=True)
print(Team1_PlayerPIE_Sorted)

for k in range(Team2_length):
    print(k)
    Team2_PlayerPIE = commonplayerinfo.CommonPlayerInfo(
        Team2_PlayerIds[k]).get_data_frames()[1][['PIE']]
示例#30
0
df_all_playerprofile = pd.DataFrame()
df_active_playerprofile = pd.DataFrame()
df_retire_playerprofile = pd.DataFrame()
df_playerID_mapping = pd.DataFrame()
pair = list()

# person_id = [893, 977, 202689]
for id in person_id:
    # Create id - name pair.
    pair.append([id, df_playerList.loc[id]['DISPLAY_FIRST_LAST']])
    playerprofile = playercareerstats.PlayerCareerStats(player_id=id)
    df_playerprofile = playerprofile.career_totals_regular_season.get_data_frame()
    df_playerprofile.insert(1,
                            "POSITION",
                            commonplayerinfo.CommonPlayerInfo(player_id=id)
                            .get_normalized_dict()['CommonPlayerInfo'][0]['POSITION'],
                            True)
    # player_name = df_playerList.loc[id]['DISPLAY_FIRST_LAST']
    # df_playerprofile.insert(0, "NAME", player_name, True)
    print(df_playerprofile)
    df_all_playerprofile = pd.concat(
        [df_all_playerprofile, df_playerprofile], axis=0, ignore_index=True)

    if df_playerList.loc[id]['ROSTERSTATUS'] == 1:
        df_active_playerprofile = pd.concat(
            [df_active_playerprofile, df_playerprofile], axis=0, ignore_index=True)

    else:
        df_retire_playerprofile = pd.concat(
            [df_retire_playerprofile, df_playerprofile], axis=0, ignore_index=True)