def update_master_player_list(self): try: players_old = pd.read_pickle('player_lists/master.pckl') players_new = player.PlayerList(league_id='00', season='2017-18', only_current=0).info() if (players_old != players_old): players_new.to_pickle('player_lists/master.pckl') except FileNotFoundError: players = player.PlayerList(league_id='00', season='2017-18', only_current=0) players = players.info() players.to_pickle('player_lists/master.pckl')
def get_player_shooting_splits(self): for season in self.seasons: player_list = nba_py_player.PlayerList(season=season).info() if isinstance(player_list, pandas.DataFrame): for index, row in player_list.iterrows(): if self.db.player_shooting_splits.count( { "SEASON_ID": season_to_season_id(season), "PLAYER_ID": str(row.PERSON_ID) }) > 0: print( "shooting splits of {} {} already exists, skipping" .format(season, row.DISPLAY_FIRST_LAST)) continue print("retrieving player shooting splits for {} {}".format( season, row.DISPLAY_FIRST_LAST)) shooting_splits = nba_py_player.PlayerShootingSplits( player_id=row.PERSON_ID, season=season).shot_5ft() if isinstance(shooting_splits, pandas.DataFrame): shooting_splits = shooting_splits.to_dict("records") if shooting_splits: for shooting_range in shooting_splits: shooting_range['PLAYER_ID'] = str(row.PERSON_ID) shooting_range['SEASON_ID'] = season_to_season_id( season) shooting_range[ 'PLAYER_NAME'] = row.DISPLAY_FIRST_LAST self.db.player_shooting_splits.insert_many( shooting_splits) else: print("shooting splits of {} {} not found".format( season, row.DISPLAY_FIRST_LAST))
def get_all_player_stats(): log_path = 'logs/players.json' if not os.path.exists(log_path): logs = {} else: logs = load_json(log_path) measure_types = [ 'Base', 'Advanced', 'Misc', 'Four Factors', 'Scoring', 'Opponent', 'Usage' ] for year in range(2016, 1900, -1): season = str(year) + "-" + str(year + 1)[2:] dir_path = os.path.join('players', season) if not os.path.exists(dir_path): os.makedirs(dir_path) player_list_path = os.path.join(dir_path, 'player_lists.json') player_list = player.PlayerList(season=season, only_current=1) write_json(player_list_path, player_list.json) for player_data in player_list.json['resultSets'][0]['rowSet']: player_id = player_data[0] player_name = player_data[2] print player_name, season for season_type in ['Playoffs', 'Regular Season']: for method, config in PLAYER_CONFIGS.iteritems(): types = [None] if 'measure_type' in config['params']: types = measure_types for measure_type in types: file_name = '_'.join([ method, measure_type ]) if measure_type else '_'.join([method]) dir_names = ['players'] + [ locals()[dir_name] for dir_name in config['path'] ] dir_path = os.path.join(*dir_names) if not os.path.exists(dir_path): os.makedirs(dir_path) file_path = os.path.join(dir_path, file_name + '.json') if (not os.path.exists(file_path) ) and not logs.has_key(file_path): try: print file_path params = dict([(param, locals()[param]) for param in config['params']]) print params write_json(file_path, getattr(player, method)(**params).json) time.sleep(3) except Exception as e: print e logs[file_path] = 'Error' write_json(log_path, logs) write_json(log_path, logs) time.sleep(3)
def get_player_list(self): try: players = pd.read_pickle('player_lists/' + self.year_to_use.get() + '.pckl') except FileNotFoundError: players = player.PlayerList(league_id='00', season=self.year_to_use.get(), only_current=0) players = players.info() players = players[players['ROSTERSTATUS'] == 1] players.to_pickle('player_lists/' + self.year_to_use.get() + '.pckl') return players
def test(): pid = get_player('Tim', 'Duncan') vs_pid = get_player('Stephen', 'Curry') assert player.PlayerList() thing = player.PlayerList().json # assert player.PlayerGeneralSplits(pid) # assert player.PlayerOpponentSplits(pid) assert player.PlayerLastNGamesSplits(pid) assert player.PlayerInGameSplits(pid) assert player.PlayerClutchSplits(pid) # assert player.PlayerShootingSplits(pid) assert player.PlayerPerformanceSplits(pid) assert player.PlayerYearOverYearSplits(pid) assert player.PlayerCareer(pid) assert player.PlayerProfile(pid) assert player.PlayerGameLogs(pid) assert player.PlayerShotTracking(pid) assert player.PlayerReboundTracking(pid) assert player.PlayerPassTracking(pid) assert player.PlayerDefenseTracking(pid) # assert player.PlayerShotLogTracking(pid) # assert player.PlayerReboundLogTracking(pid) assert player.PlayerVsPlayer(pid, vs_pid)
def get_player_ids(year='2016-17', only_curr=0): players = player.PlayerList(season=year, only_current=only_curr).info() year_start = int(year[0:4]) year_end = int('20' + year[-2:]) players.FROM_YEAR = pd.to_numeric(players.FROM_YEAR) players.TO_YEAR = pd.to_numeric(players.TO_YEAR) player_ids = [] for i in range(players.shape[0]): #if player's start yr is <= than the last yr of season AND his end yr >= first year of season if (players.FROM_YEAR.iloc[i] <= year_end) and (players.TO_YEAR.iloc[i] >= year_start): player_ids.append(players.PERSON_ID.iloc[i]) player_ids.sort() return player_ids
def __init__(self, season: str) -> None: """Initializer. """ # Configure logger self.logger = logging.getLogger(__name__) self.logger.setLevel(logging.DEBUG) formatter = logging.Formatter( fmt='%(asctime)s %(levelname)s %(message)s', datefmt='%Y/%m/%d %I:%M:%S' ) handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) self.logger.addHandler(handler) # Retrieve initial data self.season = season self.team_list = team.TeamList().info()[['TEAM_ID']][:30] self.player_list = player.PlayerList(season=season).info()[['PERSON_ID', 'ROSTERSTATUS']]
def testAll(self): assert player.PlayerList() assert player.PlayerSummary(self.playerId) # assert player.PlayerGeneralSplits(self.playerId) # assert player.PlayerOpponentSplits(self.playerId) assert player.PlayerLastNGamesSplits(self.playerId) assert player.PlayerInGameSplits(self.playerId) assert player.PlayerClutchSplits(self.playerId) # assert player.PlayerShootingSplits(self.playerId) assert player.PlayerPerformanceSplits(self.playerId) assert player.PlayerYearOverYearSplits(self.playerId) assert player.PlayerCareer(self.playerId) assert player.PlayerProfile(self.playerId) assert player.PlayerGameLogs(self.playerId) assert player.PlayerShotTracking(self.playerId) assert player.PlayerReboundTracking(self.playerId) assert player.PlayerPassTracking(self.playerId) assert player.PlayerDefenseTracking(self.playerId) # assert player.PlayerShotLogTracking(self.playerId) # assert player.PlayerReboundLogTracking(self.playerId) assert player.PlayerVsPlayer(self.playerId, self.vs_playerId)
def nba(): body = request.values['Body'] nba_players = player.PlayerList(league_id='00', season='2018-19', only_current=1).info() pid = nba_players[nba_players.DISPLAY_FIRST_LAST == str(body)]['PERSON_ID'] info = player.PlayerGameLogs(pid, season='2018-19').info() numbers = '\n' + '2018-19 Stats' + '\n' + 'PTS: ' + str( info.PTS.mean().round(1)) + '\n' + 'AST: ' + str( info.AST.mean().round(1)) + '\n' + 'REB: ' + str( info.REB.mean().round(1)) + '\n' + 'STL: ' + str( info.REB.mean().round(1)) + '\n' + 'BLK: ' + str( info.STL.mean().round(1)) ps = player.PlayerSummary(pid) ps = ps.info() ps = ps.to_dict() psa = str(body) + '\n' + 'TEAM: ' + str( ps['TEAM_NAME'][0]) + '\n' + 'HEIGHT: ' + str( ps['HEIGHT'][0]) + '\n' + 'POSITION: ' + str(ps['POSITION'][0]) fr = str(psa) + str(numbers) r = MessagingResponse() res = str(fr) r.message(res) return str(r)
def handle(self, *args, **options): from nba_py import player as PLAYER_API ap = PLAYER_API.PlayerList() result = ap.info() for row in result.itertuples(): # fetch player statistics team, created = Team.objects.get_or_create( name = row.TEAM_NAME, abbreviation = row.TEAM_ABBREVIATION, code = row.TEAM_CODE, city = row.TEAM_CITY, nba_id = row.TEAM_ID ) if Player.objects.filter(nba_id=row.PERSON_ID).exists(): player = Player.objects.get(nba_id=row.PERSON_ID) else: player = Player(nba_id = row.PERSON_ID) player.__dict__.update({ "nba_id": row.PERSON_ID, "full_name": row.DISPLAY_FIRST_LAST, "first_name": row.DISPLAY_LAST_COMMA_FIRST.split(',')[-1], "last_name": row.DISPLAY_LAST_COMMA_FIRST.split(',')[0], "player_code": row.PLAYERCODE, "from_year": row.FROM_YEAR, "to_year": row.TO_YEAR, "roster_status": bool(row.ROSTERSTATUS), "team": team, }) print ("filling players statistics") for p_id in Player.objects.all().values_list('nba_id', flat=True): p_cstats = PLAYER_API.PlayerCareer(p_id) for record in p_cstats.regular_season_totals().itertuples(): if not Team.objects.filter(pk=record.TEAM_ID).exists(): continue statistic, created = Statistic.objects.get_or_create( season_id = record.SEASON_ID, league_id = record.LEAGUE_ID, team = Team.objects.get(pk=record.TEAM_ID), age = record.PLAYER_AGE, gp = record.GP, gs = record.GS, min = record.MIN, fgm = record.FDM, fga = record.FGA, fg_pct = record.FG_PCT, fg3m = record.FG3M, ft_pct= record.FT_PCT, oreb = record.OREB, dreb = record.DREB, reb = record.REB, ast = record.AST, stl = record.STL, blk = record.BLK, tov = record.TOV, pf = record.PF, pts = record.PTS ) if created: player = Player.objects.get(nba_id=p_id) player.statistics.add(statistic)
def update_all_player_fantasy_score(): player_from_list = player.PlayerList(League.NBA, CURRENT_SEASON, 1).info() for nba_player in player_from_list: update_fantasy_score(nba_player['DISPLAY_FIRST_LAST'])
from nba_py import player import pandas import nba_py import json player_list = player.PlayerList(season='2016-17').info() list_id = player_list['PERSON_ID'] df = pandas.DataFrame() for id in list_id: print(id) season_totals = player.PlayerCareer(id).regular_season_totals() player_season = season_totals.loc[season_totals['SEASON_ID']=='2016-17'] df = df.append(player_season, ignore_index=True) print(df) df.to_pickle('16-17allplayers_totals')
def _get_query_results(params={}, flatten_keys=False): if 'module' not in params or 'sub_module' not in params or 'function' not in params: return [] if not flatten_keys and 'value_query' not in params: return [] if params['module'] == 'player': if 'first_name' not in params: return [] first = params['first_name'] last = params['last_name'] if 'last_name' in params else None team_id = params['team_id'] if 'team_id' in params else 0 measure_type = params[ 'measure_type'] if 'measure_type' in params else 'Base' per_mode = params['per_mode'] if 'per_mode' in params else 'PerGame' plus_minus = params['plus_minus'] if 'plus_minus' in params else 'N' pace_adjust = params['pace_adjust'] if 'pace_adjust' in params else 'N' rank = params['rank'] if 'rank' in params else 'N' league_id = params['league_id'] if 'league_id' in params else '00' season = params['season'] if 'season' in params else '2016-17' season_type = params[ 'season_type'] if 'season_type' in params else 'Regular Season' po_round = params['po_round'] if 'po_round' in params else '0' outcome = params['outcome'] if 'outcome' in params else '' location = params['location'] if 'location' in params else '' month = params['month'] if 'month' in params else '0' season_segment = params[ 'season_segment'] if 'season_segment' in params else '' date_from = params['date_from'] if 'date_from' in params else '' date_to = params['date_to'] if 'date_to' in params else '' opponent_team_id = params[ 'opponent_team_id'] if 'opponent_team_id' in params else '0' vs_conference = params[ 'vs_conference'] if 'vs_conference' in params else '' vs_division = params['vs_division'] if 'vs_division' in params else '' game_segment = params[ 'game_segment'] if 'game_segment' in params else '' period = params['period'] if 'period' in params else '0' shot_clock_range = params[ 'shot_clock_range'] if 'shot_clock_range' in params else '' last_n_games = params[ 'last_n_games'] if 'last_n_games' in params else '0' only_current = params['only_current'] if 'only_current' in params else 0 just_id = params['just_id'] if 'just_id' in params else True player_id = player.get_player(first, last_name=last, season=season, only_current=only_current, just_id=just_id) if params['sub_module'] == 'player_career': career = player.PlayerCareer(player_id) if params['function'] == 'all_star_season_totals': temp = career.all_star_season_totals() elif params['function'] == 'career_all_star_season_totals': temp = career.career_all_star_season_totals() elif params['function'] == 'college_season_career_totals': temp = career.college_season_career_totals() elif params['function'] == 'college_season_totals': temp = career.college_season_totals() elif params['function'] == 'post_season_career_totals': temp = career.post_season_career_totals() elif params['function'] == 'post_season_rankings': temp = career.post_season_rankings() elif params['function'] == 'post_season_totals': temp = career.post_season_totals() elif params['function'] == 'preseason_career_totals': temp = career.preseason_career_totals() elif params['function'] == 'preseason_season_totals': temp = career.preseason_season_totals() elif params['function'] == 'regular_season_career_totals': temp = career.regular_season_career_totals() elif params['function'] == 'regular_season_rankings': temp = career.regular_season_rankings() elif params['function'] == 'regular_season_totals': temp = career.regular_season_totals() else: return [] elif params['sub_module'] == 'player_clutch_splits': clutch = player.PlayerClutchSplits(player_id, team_id=team_id, measure_type=measure_type, per_mode=per_mode, plus_minus=plus_minus, \ pace_adjust=pace_adjust, rank=rank, league_id=league_id, season=season, season_type=season_type, po_round=po_round, outcome=outcome, \ location=location, month=month, season_segment=season_segment, date_from=date_from, date_to=date_to, opponent_team_id=opponent_team_id, \ vs_conference=vs_conference, vs_division=vs_division, game_segment=game_segment, period=period, shot_clock_range=shot_clock_range, \ last_n_games=last_n_games ) if params['function'] == 'last10sec_deficit_3point': temp = clutch.last10sec_deficit_3point() elif params['function'] == 'last1min_deficit_5point': temp = clutch.last1min_deficit_5point() elif params['function'] == 'last1min_plusminus_5point': temp = clutch.last1min_plusminus_5point() elif params['function'] == 'last30sec_deficit_3point': temp = clutch.last30sec_deficit_3point() elif params['function'] == 'last30sec_plusminus_5point': temp = clutch.last30sec_plusminus_5point() elif params['function'] == 'last3min_deficit_5point': temp = clutch.last3min_deficit_5point() elif params['function'] == 'last3min_plusminus_5point': temp = clutch.last3min_plusminus_5point() elif params['function'] == 'last5min_deficit_5point': temp = clutch.last5min_deficit_5point() elif params['function'] == 'last5min_plusminus_5point': temp = clutch.last5min_plusminus_5point() else: return [] elif params['sub_module'] == 'player_defense_tracking': temp = player.PlayerDefenseTracking(player_id, team_id=team_id, measure_type=measure_type, per_mode=per_mode, plus_minus=plus_minus, \ pace_adjust=pace_adjust, rank=rank, league_id=league_id, season=season, season_type=season_type, po_round=po_round, outcome=outcome, \ location=location, month=month, season_segment=season_segment, date_from=date_from, date_to=date_to, opponent_team_id=opponent_team_id, \ vs_conference=vs_conference, vs_division=vs_division, game_segment=game_segment, period=period, shot_clock_range=shot_clock_range, \ last_n_games=last_n_games ) elif params['sub_module'] == 'player_game_logs': if params['function'] == 'info': temp = player.PlayerGameLogs(player_id, league_id=league_id, season=season, season_type=season_type) else: return [] elif params['sub_module'] == 'player_general_splits': splits = player.PlayerGeneralSplits(player_id, team_id=team_id, measure_type=measure_type, per_mode=per_mode, plus_minus=plus_minus, \ pace_adjust=pace_adjust, rank=rank, league_id=league_id, season=season, season_type=season_type, po_round=po_round, outcome=outcome, \ location=location, month=month, season_segment=season_segment, date_from=date_from, date_to=date_to, opponent_team_id=opponent_team_id, \ vs_conference=vs_conference, vs_division=vs_division, game_segment=game_segment, period=period, shot_clock_range=shot_clock_range, \ last_n_games=last_n_games ) if params['function'] == 'days_rest': temp = splits.days_rest() elif params['function'] == 'location': temp = splits.location() elif params['function'] == 'month': temp = splits.month() elif params['function'] == 'pre_post_all_star': temp = splits.pre_post_all_star() elif params['function'] == 'starting_position': temp = splits.starting_position() elif params['function'] == 'win_losses': temp = splits.win_losses() else: return [] elif params['sub_module'] == 'player_in_game_splits': if params['function'] == 'by_actual_margin': temp = splits.by_actual_margin() elif params['function'] == 'by_half': temp = splits.by_half() elif params['function'] == 'by_period': temp = splits.by_period() elif params['function'] == 'by_score_margin': temp = splits.by_score_margin() else: return [] elif params['sub_module'] == 'player_last_n_games_splits': n_splits = player.PlayerLastNGamesSplits(player_id, team_id=team_id, measure_type=measure_type, per_mode=per_mode, plus_minus=plus_minus, \ pace_adjust=pace_adjust, rank=rank, league_id=league_id, season=season, season_type=season_type, po_round=po_round, outcome=outcome, \ location=location, month=month, season_segment=season_segment, date_from=date_from, date_to=date_to, opponent_team_id=opponent_team_id, \ vs_conference=vs_conference, vs_division=vs_division, game_segment=game_segment, period=period, shot_clock_range=shot_clock_range, \ last_n_games=last_n_games ) if params['function'] == 'game_number': temp = n_splits.gamenumber() elif params['function'] == 'last10': temp = n_splits.last10() elif params['function'] == 'last15': temp = n_splits.last15() elif params['function'] == 'last20': temp = n_splits.last20() elif params['function'] == 'last5': temp = n_splits.last5() else: return [] elif params['sub_module'] == 'player_list': player_list = player.PlayerList(league_id=league_id, season=season, only_current=only_current) if params['function'] == 'info': temp = player_list.info() else: return [] elif params['sub_module'] == 'player_opponent_splits': op_splits = player.PlayerOpponentSplits(player_id, team_id=team_id, measure_type=measure_type, per_mode=per_mode, plus_minus=plus_minus, \ pace_adjust=pace_adjust, rank=rank, league_id=league_id, season=season, season_type=season_type, po_round=po_round, outcome=outcome, \ location=location, month=month, season_segment=season_segment, date_from=date_from, date_to=date_to, opponent_team_id=opponent_team_id, \ vs_conference=vs_conference, vs_division=vs_division, game_segment=game_segment, period=period, shot_clock_range=shot_clock_range, \ last_n_games=last_n_games ) if params['function'] == 'by_conference': temp = op_splits.by_conference() elif params['function'] == 'by_division': temp = op_splits.by_division() elif params['function'] == 'by_opponent': temp = op_splits.by_opponent() else: return [] elif params['sub_module'] == 'player_pass_tracking': pass_tracking = player.PlayerPassTracking(player_id, team_id=team_id, measure_type=measure_type, per_mode=per_mode, plus_minus=plus_minus, \ pace_adjust=pace_adjust, rank=rank, league_id=league_id, season=season, season_type=season_type, po_round=po_round, outcome=outcome, \ location=location, month=month, season_segment=season_segment, date_from=date_from, date_to=date_to, opponent_team_id=opponent_team_id, \ vs_conference=vs_conference, vs_division=vs_division, game_segment=game_segment, period=period, shot_clock_range=shot_clock_range, \ last_n_games=last_n_games ) if params['function'] == 'passes_made': temp = pass_tracking.passes_made() elif params['function'] == 'passes_received': temp = pass_tracking.passes_received() else: return [] elif params['sub_module'] == 'player_performance_splits': performance_splits = player.PlayerPerformanceSplits(player_id, team_id=team_id, measure_type=measure_type, per_mode=per_mode, plus_minus=plus_minus, \ pace_adjust=pace_adjust, rank=rank, league_id=league_id, season=season, season_type=season_type, po_round=po_round, outcome=outcome, \ location=location, month=month, season_segment=season_segment, date_from=date_from, date_to=date_to, opponent_team_id=opponent_team_id, \ vs_conference=vs_conference, vs_division=vs_division, game_segment=game_segment, period=period, shot_clock_range=shot_clock_range, \ last_n_games=last_n_games ) if params['function'] == 'points_against': temp = performance_splits.points_against() elif params['function'] == 'points_scored': temp = performance_splits.points_scored() elif params['function'] == 'score_differential': temp = performance_splits.score_differential() else: return [] elif params['sub_module'] == 'player_profile': prof = player.PlayerProfile(per_mode=per_mode, league_id=league_id) if params['function'] == 'career_highs': temp = prof.career_highs() elif params['function'] == 'next_game': temp = prof.next_game() elif params['function'] == 'season_highs': temp = prof.season_highs() else: return [] elif params['sub_module'] == 'player_rebound_log_tracking': temp = player.PlayerReboundLogTracking(player_id, team_id=team_id, measure_type=measure_type, per_mode=per_mode, plus_minus=plus_minus, \ pace_adjust=pace_adjust, rank=rank, league_id=league_id, season=season, season_type=season_type, po_round=po_round, outcome=outcome, \ location=location, month=month, season_segment=season_segment, date_from=date_from, date_to=date_to, opponent_team_id=opponent_team_id, \ vs_conference=vs_conference, vs_division=vs_division, game_segment=game_segment, period=period, shot_clock_range=shot_clock_range, \ last_n_games=last_n_games ) elif params['sub_module'] == 'player_rebound_tracking': rb_tracking = player.PlayerReboundTracking(player_id, team_id=team_id, measure_type=measure_type, per_mode=per_mode, plus_minus=plus_minus, \ pace_adjust=pace_adjust, rank=rank, league_id=league_id, season=season, season_type=season_type, po_round=po_round, outcome=outcome, \ location=location, month=month, season_segment=season_segment, date_from=date_from, date_to=date_to, opponent_team_id=opponent_team_id, \ vs_conference=vs_conference, vs_division=vs_division, game_segment=game_segment, period=period, shot_clock_range=shot_clock_range, \ last_n_games=last_n_games ) if params['function'] == 'num_contested_rebounding': temp = rb_tracking.num_contested_rebounding() elif params['function'] == 'rebound_distance_rebounding': temp = rb_tracking.rebound_distance_rebounding() elif params['function'] == 'shot_distance_rebounding': temp = rb_tracking.shot_distance_rebounding() elif params['function'] == 'shot_type_rebounding': temp = rb_tracking.shot_type_rebounding() else: return [] elif params['sub_module'] == 'player_shooting_splits': if params['function'] == 'assisted_by': temp = rb_tracking.assisted_by() elif params['function'] == 'assisted_shots': temp = rb_tracking.assisted_shots() elif params['function'] == 'shot_5ft': temp = rb_tracking.shot_5ft() elif params['function'] == 'shot_8ft': temp = rb_tracking.shot_8ft() elif params['function'] == 'shot_areas': temp = rb_tracking.shot_areas() elif params['function'] == 'shot_types_detail': temp = rb_tracking.shot_types_detail() elif params['function'] == 'shot_types_summary': temp = rb_tracking.shot_types_summary() else: return [] elif params['sub_module'] == 'player_shot_log_tracking': temp = player.PlayerShotLogTracking(player_id, team_id=team_id, measure_type=measure_type, per_mode=per_mode, plus_minus=plus_minus, \ pace_adjust=pace_adjust, rank=rank, league_id=league_id, season=season, season_type=season_type, po_round=po_round, outcome=outcome, \ location=location, month=month, season_segment=season_segment, date_from=date_from, date_to=date_to, opponent_team_id=opponent_team_id, \ vs_conference=vs_conference, vs_division=vs_division, game_segment=game_segment, period=period, shot_clock_range=shot_clock_range, \ last_n_games=last_n_games ) if params['function'] == 'closest_defender_shooting': temp = rb_tracking.closest_defender_shooting() elif params['function'] == 'closest_defender_shooting_long': temp = rb_tracking.closest_defender_shooting_long() elif params['function'] == 'dribble_shooting': temp = rb_tracking.dribble_shooting() elif params['function'] == 'general_shooting': temp = rb_tracking.general_shooting() elif params['function'] == 'shot_clock_shooting': temp = rb_tracking.shot_clock_shooting() elif params['function'] == 'touch_time_shooting': temp = rb_tracking.touch_time_shooting() else: return [] # elif params['sub_module'] == 'player_shot_tracking': # elif params['sub_module'] == 'player_summary': # elif params['sub_module'] == 'player_vs_player': # elif params['sub_module'] == 'player_year_over_year_splits': elif params['module'] == 'game': pass elif params['module'] == 'team': pass else: # Failure case. pass if flatten_keys: return [ l for l in list(set([el for o in temp for el in o.keys()])) if l not in to_remove ] else: return { 'data': [o[params['value_query']] for o in temp], 'labels': [o[get_x_axis_key(params['function'])] for o in temp] }
def get_player_names(season): json = player.PlayerList(season=season).json return json
def insert_all_players(): playerFromList = player.PlayerList(League.NBA, CURRENT_SEASON, 1).info() for nba_player in playerFromList: add_player_to_database(nba_player['DISPLAY_FIRST_LAST'], None, None, None, nba_player['TEAM_ABBREVIATION']) sleep(1)
from nba_py import game from webscrape import getData from time import sleep from datetime import datetime from dateutil.relativedelta import relativedelta as tDelta from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot import plotly.graph_objs as go # Params current_year = int(datetime.date(datetime.now()).strftime('%Y'))-1 if datetime.date(datetime.now()).month < 11 else int(datetime.date(datetime.now()).strftime('%Y')) fantasy_team = ['john wall', 'rudy gobert', 'lonzo ball', 'khris middleton', 'jj redick', 'aaron gordon', 'andre drummond', 'darren collison', 'will barton', 'markieff morris', 'joe ingles', 'josh richardson', 'dewayne dedmon'] trade_for = ['kyle lowry', 'thaddeus young'] trading = ['john wall', 'jj redick'] <<<<<<< HEAD playerInfo = pd.DataFrame(player.PlayerList(season='2017-18', only_current=1).info()) """ def tradeEvaluator(current_team, proposed_players, receiving_players, season=2017): df = pd.DataFrame() for i in current_team: data = getData(i, 'GameLog', season) data['PLAYER_NAME'] = i.title() df = df.append(data) sleep(3) for i in receiving_players: data = getData(i, 'GameLog', season) data['PLAYER_NAME'] = i.title() df = df.append(data) sleep(3)
def get_all_short_player_bios(): return [ ShortPlayerBioNode(datum) for datum in nba_py_player.PlayerList(only_current=0).info() ]
def get_player_list(): """Return player list.""" players = player.PlayerList() return players.info()
player_now = player.PlayerGameLogs(id, league_id='00', season='2016-17', season_type='Regular Season') return player_now team_id = {"Atlanta Hawks":1610612737, "Boston Celtics": 1610612738, "Brooklyn Nets": 1610612751, \ "Charlotte Hornets" : 1610612766, "Chicago Bulls" : 1610612741, "Cleveland Cavaliers": 1610612739, \ "Dallas Mavericks" : 1610612742, "Denver Nuggets" : 1610612743, "Detroit Pistons" : 1610612765, \ "Golden State Warriors" : 1610612744, "Houston Rockets" : 1610612745, "Indiana Pacers": 1610612754, \ "Los Angeles Clippers" : 1610612746, "Los Angeles Lakers": 1610612747, "Memphis Grizzlies" : 1610612763, \ "Miami Heat" :1610612748, "Milwaukee Bucks" : 1610612749, "Minnesota Timberwolves" : 1610612750, \ "New Orleans Pelicans" : 1610612740, "New York Knicks": 1610612752, "Oklahoma City Thunder": 1610612760, \ "Orlando Magic" : 1610612753, "Philadelphia 76ers" : 1610612755, "Phoenix Suns" : 1610612756, \ "Portland Trail Blazers" : 1610612757, "Sacramento Kings" : 1610612758, "San Antonio Spurs" : 1610612759, \ "Toronto Raptors" : 1610612761, "Utah Jazz" : 1610612762, "Washington Wizards" : 1610612764 } players = player.PlayerList(league_id='00', season='2016-17', only_current=1) # for key, value in team_id.items(): # print(value) player_name = input('Enter a player\'s full name: ') print("Retrieving " + player_name + "'s data...") player_found = False players = players.info() for row, column in players.iterrows(): if(column["DISPLAY_FIRST_LAST"] == player_name): player_id = column["PERSON_ID"] player_found = True break if(not player_found):
from nba_py import player from nba_py.player import get_player import pandas as pd current_players = player.PlayerList(season = "2017-17").info() college_stats = pd.DataFrame() nba_stats = pd.DataFrame() for index, row in (current_players).iterrows(): college_stats = college_stats.append(player.PlayerCareer(row["PERSON_ID"]).college_season_career_totals()) nba_stats = nba_stats.append(player.PlayerCareer(row["PERSON_ID"]).regular_season_career_totals()) college_stats.to_csv("college_stats.csv") nba_stats.to_csv("regular_season_stats.csv")
def sync_all(self): all_player_id = player.PlayerList().info().loc[:, 'PERSON_ID'] for player_id in all_player_id: self.sync_one(player_id) self.sync_game_log()
def save_or_update_players(): players = Player.objects.all() print("updating players stats") playerList = player.PlayerList() for val in playerList.info(): playerApp = Player() playerApp.id_nba = val['PERSON_ID'] try: playerApp = Player.objects.get(id_nba=playerApp.id_nba) except Player.DoesNotExist: playerApp.id_nba = val['PERSON_ID'] player_summary = player.PlayerSummary(playerApp.id_nba) playerApp.name = player_summary.info().__getitem__( 0)['DISPLAY_FIRST_LAST'] playerApp.position = player_summary.info().__getitem__( 0)['POSITION'] playerApp.number = player_summary.info().__getitem__(0)['JERSEY'] playerApp.height = player_summary.info().__getitem__(0)['HEIGHT'] playerApp.weight = player_summary.info().__getitem__(0)['WEIGHT'] birth_date = player_summary.info().__getitem__(0)['BIRTHDATE'] playerApp.birth_date = birth_date[:10] playerApp.college = player_summary.info().__getitem__(0)['SCHOOL'] playerApp.draft = player_summary.info().__getitem__( 0)['DRAFT_YEAR'] playerApp.experience = player_summary.info().__getitem__( 0)['SEASON_EXP'] try: teamApp = Team.objects.get( name=player_summary.info().__getitem__(0)['TEAM_NAME']) playerApp.team = teamApp except Team.DoesNotExist: pass try: playerApp.save() player_general_splits = player.PlayerGeneralSplits( playerApp.id_nba) if player_general_splits.overall(): statistic1 = PlayerStatistic() try: statistic1 = PlayerStatistic.objects.get(player=playerApp) except PlayerStatistic.DoesNotExist: statistic1.season = Season.objects.get(year="2017/18") statistic1.player = playerApp statistic1.playoff = False statistic1.ppg = player_general_splits.overall().__getitem__( 0)['PTS'] statistic1.rpg = player_general_splits.overall().__getitem__( 0)['REB'] statistic1.apg = player_general_splits.overall().__getitem__( 0)['AST'] statistic1.bpg = player_general_splits.overall().__getitem__( 0)['BLK'] statistic1.spg = player_general_splits.overall().__getitem__( 0)['STL'] statistic1.tpg = player_general_splits.overall().__getitem__( 0)['TOV'] statistic1.mpg = player_general_splits.overall().__getitem__( 0)['MIN'] statistic1.ttp = player_general_splits.overall().__getitem__( 0)['FG3_PCT'] statistic1.fgp = player_general_splits.overall().__getitem__( 0)['FG_PCT'] statistic1.ftp = player_general_splits.overall().__getitem__( 0)['FT_PCT'] statistic1.ftm = player_general_splits.overall().__getitem__( 0)['FTM'] statistic1.fgm = player_general_splits.overall().__getitem__( 0)['FGM'] statistic1.ttm = player_general_splits.overall().__getitem__( 0)['FG3M'] statistic1.save() print("salvou ou atualizou jogador:" + playerApp.name) except ValueError: pass
''' Player Table Get All Recent Players Columns: PERSON_ID - PK DISPLAY_LAST_COMMA_FIRST ROSTERSTATUS FROM_YEAR TO_YEAR PLAYERCODE TEAM_ID - FK GAMES_PLAYED_FLAG ''' ap = player.PlayerList(season='2014-15', only_current=0) player_list = ap.info() #time.sleep(5) # Filter for only recent players mask = player_list.TO_YEAR.astype(int) > 2010 player_list = player_list[mask] player_list.set_index('PERSON_ID', inplace=True) #print player_list.head() print 'Total Players Queried =', player_list.shape[0] ''' Team Table Create Team Table from Player Table Columns: TEAM_ID - PK
def testPlayerList(self): playerlist = player.PlayerList(self.leagueId, self.season, 1) self.assertTrue((101, 13) == playerlist.info().shape) self.assertTrue(('Memphis' == playerlist.info()[0:1].TEAM_CITY).all())
''' Player Table Get All Recent Players Columns: PERSON_ID - PK DISPLAY_LAST_COMMA_FIRST ROSTERSTATUS FROM_YEAR TO_YEAR PLAYERCODE TEAM_ID - FK GAMES_PLAYED_FLAG ''' ap = player.PlayerList(season='2015-16', only_current=0) player_list = ap.info() #time.sleep(5) # Filter for only recent players mask = player_list.TO_YEAR.astype(int) > 2006 player_list = player_list[mask] player_list.set_index('PERSON_ID', inplace=True) #print player_list.head() print('Total Players Queried =', player_list.shape[0]) ''' Team Table Create Team Table from Player Table Columns: TEAM_ID - PK
from __future__ import print_function from nba_py import player # endpoint currently disabled on stats.nba.com # pd = player._PlayerDashboard('203507') # print(pd.starting_position()) ap = player.PlayerList() print(ap.info()) pc = player.PlayerSummary('203507') print(pc.headline_stats()) p_cstats = player.PlayerCareer('201939') print(p_cstats.regular_season_career_totals())
def update_player_info(season): ''' Updates the database table containing player information from two sources: 1. stats.nba.com 2. basketball-reference These two sources are needed since the player information from stats.nba.com only shows players on the team they are most recently on. bball-ref contains a record for each team a player has played for. The parameter is season, which should be whatever the current season is ''' conn = sqlite3.connect("DB/PLayer_Info.sqlite") # read in player list from stats.nba.com players = pd.read_sql("select * from NBA", conn) # read in player list from basketball-reference bball_ref = pd.read_sql("select * from BbRef", conn) # read in previous player info df player_info = pd.read_sql("select * from PlayerInfo", conn) players_update = pd.DataFrame() # grab the player list for season from stats.nba.com player_list = player.PlayerList(season=season, only_current=0).info() player_list['SEASON_YEAR'] = season players_update = players_update.append(player_list) # don't need these columns players_update = players_update.drop(['ROSTERSTATUS', 'DISPLAY_LAST_COMMA_FIRST', 'PLAYERCODE', 'GAMES_PLAYED_FLAG'], axis=1) # only keep the new players common = players.merge(players_update, on=['PERSON_ID','SEASON_YEAR', 'TEAM_ABBREVIATION'], suffixes=('','_x')) common = common[common.columns.drop(list(common.filter(regex='_x')))] diffs = players_update[(~players_update.PERSON_ID.isin(common.PERSON_ID))] diffs = diffs[diffs.TEAM_CODE > ''] players = players.append(diffs, sort=False) # save the new player list players.to_sql("NBA", conn, if_exists='replace', index=False) # filter on only players from 2006 and later players_post_06 = players[players.TO_YEAR > '2005'] # some names aren't the same between the two sources. this is a manual fix name_change = pd.read_csv("Data/PlayerInfo/bbref_namefix.csv", index_col=0) def namechange(player): try: return name_change.loc[player].stats_nba except: return player tqdm.pandas(desc='mybar') bball_ref.PLAYER_NAME = bball_ref.PLAYER_NAME.progress_apply(lambda x: namechange(x)) # map the player ID bball_ref['PLAYER_ID'] = bball_ref.PLAYER_NAME.progress_apply(lambda x: players_post_06[players_post_06.DISPLAY_FIRST_LAST == x].PERSON_ID.values[0]) # this player changed his name between seasons so he was causing lookup errors. manual fix indices = bball_ref[(bball_ref.PLAYER_NAME == 'Jeff Ayres') & (bball_ref.SEASON_YEAR < '2013-14')].index bball_ref.loc[indices, 'PLAYER_NAME'] = 'Jeff Pendergraph' # mapping for team ID's bball_to_teamID = pd.read_csv('Data/PlayerInfo/bball_teamID.csv', index_col=0) # add team IDs bball_ref['TEAM_ID'] = bball_ref.TEAM_ABBV.progress_apply(lambda x: bball_to_teamID.loc[x].values[0]) # only keep the new player info common = player_info.merge(bball_ref, on=['PLAYER_ID','SEASON_YEAR', 'TEAM_ID'], suffixes=('','_x')) common = common[common.columns.drop(list(common.filter(regex='_x')))] diffs = bball_ref.loc[~bball_ref.index.isin(common.index)] # save the new player info df player_info = player_info.append(diffs, sort=False) player_info.to_sql("PlayerInfo", conn, if_exists='replace', index=False) conn.close()
u'FG3_PCT', u'FTM', u'FTA', u'FT_PCT', u'OREB', u'DREB', u'REB', u'AST', u'TOV', u'STL', u'BLK', u'BLKA', u'PF', u'PFD', u'PTS', u'PLUS_MINUS', u'DD2', u'TD3', u'GP_RANK', u'W_RANK', u'L_RANK', u'W_PCT_RANK', u'MIN_RANK', u'FGM_RANK', u'FGA_RANK', u'FG_PCT_RANK', u'FG3M_RANK', u'FG3A_RANK', u'FG3_PCT_RANK', u'FTM_RANK', u'FTA_RANK', u'FT_PCT_RANK', u'OREB_RANK', u'DREB_RANK', u'REB_RANK', u'AST_RANK', u'TOV_RANK', u'STL_RANK', u'BLK_RANK', u'BLKA_RANK', u'PF_RANK', u'PFD_RANK', u'PTS_RANK', u'PLUS_MINUS_RANK', u'NBA_FANTASY_PTS_RANK', u'DD2_RANK', u'TD3_RANK' ] PRIMARY_KEYS = [ u'TEAM_ID', u'TEAM_NAME', u'PASS_TEAMMATE_PLAYER_ID', u'PLAYER_NAME' ] if __name__ == '__main__': players = player.PlayerList(only_current=0).info() players = players[players.TEAM_ABBREVIATION != ""] for method, group_names, file_path in METHODS: result = pd.DataFrame(columns=KEYS) for index, row in players.iterrows(): while True: try: data = getattr(player, method)( player_id=row['PERSON_ID'], per_mode=constants.PerMode.Totals, ) except Exception as e: traceback.print_exc() time.sleep(5) continue break