Exemplo n.º 1
0
def test():
    team_id = TEAMS['ATL']['id']
    player_id = get_player('Lebron', 'James')
    assert team.TeamList()
    assert team.TeamSummary(team_id)
    team_details = team.TeamDetails(team_id)
    assert team_details
    assert team_details.background()
    assert team_details.history()
    assert team.TeamCommonRoster(team_id)
    assert team.TeamGeneralSplits(team_id)
    assert team.TeamOpponentSplits(team_id)
    assert team.TeamLastNGamesSplits(team_id)
    assert team.TeamInGameSplits(team_id)
    assert team.TeamClutchSplits(team_id)
    assert team.TeamShootingSplits(team_id)
    assert team.TeamPerformanceSplits(team_id)
    assert team.TeamLineups(team_id)
    assert team.TeamPlayers(team_id)
    assert team.TeamPlayerOnOffDetail(team_id)
    assert team.TeamPlayerOnOffSummary(team_id)
    assert team.TeamGameLogs(team_id)
    assert team.TeamShotTracking(team_id)
    assert team.TeamReboundTracking(team_id)
    assert team.TeamPassTracking(team_id)
    assert team.TeamVsPlayer(team_id, player_id)
Exemplo n.º 2
0
def test():
    if os.path.exists(TEAMS_FILE):
        teams = pd.DataFrame.from_csv(TEAMS_FILE)
    else:
        teams = team.TeamList().info().dropna()
        teams.to_csv(TEAMS_FILE)
    all = None
    for index, row in teams.iterrows():
        data = team.TeamPassTracking(team_id=row['TEAM_ID'])
        passes_made = data.passes_made().drop([u'PASS_TYPE'], 1)
        passes_made.rename(columns={'PASS_FROM': 'PLAYER_NAME'}, inplace=True)

        passes_recieved = data.passes_recieved().drop([u'PASS_TYPE'], 1)
        passes_recieved.rename(columns={'PASS_TO': 'PLAYER_NAME'},
                               inplace=True)

        overall = passes_made.merge(
            passes_recieved,
            left_on=PRIMARY_KEYS,
            right_on=PRIMARY_KEYS,
            how='outer',
            suffixes=['_ON_MADE', '_ON_RECEIVED'
                      ]).dropna().drop(['TEAM_ID', 'PASS_TEAMMATE_PLAYER_ID'],
                                       1)
        if all is not None:
            all = pd.concat([all, overall])
        else:
            all = overall
        print overall
    all.to_csv('data/passdash.csv', index=False)
Exemplo n.º 3
0
def get_all_team_stats():
    log_path = 'logs/teams.json'
    if not os.path.exists(log_path):
        logs = {}
    else:
        logs = load_json(log_path)
    teams_list = team.TeamList()
    measure_types = [
        'Base', 'Advanced', 'Misc', 'Four Factors', 'Scoring', 'Opponent',
        'Usage'
    ]
    write_json('info/team_list.json', teams_list.json)
    for year in range(2016, 1900, -1):
        # if year >= 1999:
        #     continue
        for (league_id, team_id, start_year, end_year,
             team_abbr) in teams_list.info().values:
            if (not team_abbr
                ) or year < int(start_year) or year > int(end_year):
                continue
            season = str(year) + "-" + str(year + 1)[2:]
            for season_type in ['Playoffs', 'Regular Season']:
                path = os.path.join('teams', team_abbr, season, season_type)
                if not os.path.exists(path):
                    os.makedirs(path)
                print team_abbr, season, season_type, team_id
                for method, config in TEAM_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 = ['teams'] + [
                            locals()[dir_name] for dir_name in config['path']
                        ] + [file_name + '.json']
                        file_path = os.path.join(*dir_names)
                        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 ', '.join(params)
                                write_json(file_path,
                                           getattr(team,
                                                   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)
Exemplo n.º 4
0
def teamlist(request):
    theids = []
    abb = []

    teams = team.TeamList()
    many_teams = teams.info()

    theids = many_teams['TEAM_ID']
    abb = many_teams['ABBREVIATION']

    twolists = zip(theids, abb)

    context = {'theids': theids, 'twolists': twolists}
    return render(request, 'yearly/teamlist.html', context)
def get_splits(TEAMABR, ten=False, twenty=False, regseason=True):
    """returns the splits of a team over the past N days. Will consider changing this to a from - to thing for different dates. 
    
    Parameters
    ----------
    TEAMABR : str
    	Abbreviation of the desired team. Ex: Atlanta = ATL.  

    Returns 
    -------
    teamsplits : array	
    	Array of desired team's statistics over the previous N games. 

    """
    import numpy as np
    from nba_py import team
    teams = team.TeamList()
    teamids = teams.info()
    teamids = teamids[:-15]
    teamids = teamids[['TEAM_ID', 'ABBREVIATION']]

    teamids = teamids.rename(index=str, columns={"ABBREVIATION": "Team"})
    teamids = teamids.replace('BKN', 'BRK')
    teamids = teamids.sort_values('Team')

    TEAM_ID = teamids.loc[teamids['Team'] == TEAMABR].values[0, 0]
    teamids = pd.get_dummies(teamids)
    teamarray = teamids.loc[teamids['TEAM_ID'] == TEAM_ID].values[0, 1:]

    TEAM = team.TeamLastNGamesSplits(team_id=TEAM_ID, season='2017-18')
    if ten:
        df = TEAM.last10()
    if twenty:
        df = TEAM.last20()
    if regseason:
        TEAM = team.TeamGeneralSplits(team_id=TEAM_ID, season='2017-18')
        df = TEAM.overall()

# if five:
#df = TEAM

    df = df[[
        'OREB', 'DREB', 'REB', 'PF', 'STL', 'TOV', 'BLK', 'FG3_PCT', 'FG_PCT',
        'FT_PCT'
    ]].values

    teamsplits = np.concatenate((df[0], teamarray))
    return teamsplits
Exemplo n.º 6
0
    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']]
Exemplo n.º 7
0
def save_teams():

    # teams = Team.objects.all().delete()
    teams = Team.objects.all()
    if not teams:
        teamList = team.TeamList()
        for x in range(0, 29):
            val = teamList.info().__getitem__(x)
            team_summary = team.TeamSummary(val['TEAM_ID'])
            teamApp = Team()
            # print(team.TeamSummary(val['TEAM_ID']).info()[0])
            # teamApp.name = val['DISPLAY_FIRST_LAST']
            teamApp.name = team_summary.info()[0]['TEAM_NAME']
            teamApp.id_nba = val['TEAM_ID']
            division = Division.objects.get(
                name=team_summary.info()[0]['TEAM_DIVISION'])
            teamApp.division = division
            teamApp.fundation_date = team_summary.info()[0]['MIN_YEAR']
            teamApp.owner = team_summary.info()[0]['MIN_YEAR']
            teamApp.city = team_summary.info()[0]['TEAM_CITY']

            teamApp.save()
        update_team_stats(True)
 def testAll(self):
     assert team.TeamList()
     assert team.TeamSummary(self.teamId)
     team_details = team.TeamDetails(self.teamId)
     assert team_details
     # assert team_details.background()
     # assert team_details.history()
     assert team.TeamCommonRoster(self.teamId)
     assert team.TeamGeneralSplits(self.teamId)
     assert team.TeamOpponentSplits(self.teamId)
     assert team.TeamLastNGamesSplits(self.teamId)
     assert team.TeamInGameSplits(self.teamId)
     assert team.TeamClutchSplits(self.teamId)
     assert team.TeamShootingSplits(self.teamId)
     assert team.TeamPerformanceSplits(self.teamId)
     assert team.TeamLineups(self.teamId)
     assert team.TeamPlayers(self.teamId)
     assert team.TeamPlayerOnOffDetail(self.teamId)
     assert team.TeamPlayerOnOffSummary(self.teamId)
     assert team.TeamGameLogs(self.teamId)
     assert team.TeamShotTracking(self.teamId)
     assert team.TeamReboundTracking(self.teamId)
     assert team.TeamPassTracking(self.teamId)
     assert team.TeamVsPlayer(self.teamId, self.playerId)
Exemplo n.º 9
0
def create_todays_data():
    """Creates a dataset identical to the one used for the ML modeling. This is done by scraping the ngames averages
    of the teams just listed, along with the spread, and cominbing. 
    
    Returns 
    -------
    
    today_matchups : arr
        In accordance with the designated format of how these team statistics will be shaped, I did that here. 
        For further explanation, please refer to the "relevant stats" and "splits_optimizer" repo's which explain why I 
        use certain values, this function simply puts them in that shape for the games I want to predict. 
    
    
    home_teams : arr
        Array of the home teams. Since I next have to obtain the spread of these games, I'll line them up based on the 
        name of the home team. 
    """
    today = datetime.now()
    day = today.day
    month = today.month
    year = today.year

    matchups = get_todays_games()

    #matchups
    import numpy as np
    from nba_py import team
    teams = team.TeamList()
    teamids = teams.info()
    #print('predicting matchups of ', teamids)
    #  print()
    teamids = teamids[:-15]
    # print(teamids)
    teamids = teamids[['TEAM_ID', 'ABBREVIATION']]
    teamids = teamids.rename(index=str, columns={"ABBREVIATION": "Team"})
    teamids = teamids.replace('BKN', 'BRK')
    teamids = teamids.sort_values('Team')
    # print(teamids)
    todays_matchups = []
    home_teams = []
    road_teams = []
    for matchup in matchups:
        home_teams.append(matchup[1])
        road_teams.append(matchup[0])
        game_array = []
        for team_ in matchup:
            TEAM_ID = teamids.loc[teamids['Team'] == team_].values[0, 0]
            #   print(team_,TEAM_ID)

            TEAM_splits = team.TeamLastNGamesSplits(team_id=TEAM_ID,
                                                    season='2018-19')
            # print(TEAM_splits.last20())
            df = TEAM_splits.last20()

            #retain (and create) the columns proven to be correlated to outcome.
            df['AST/TO'] = df['AST'] / df['TOV']

            df = df[[
                'FGM', 'FG3M', 'FTM', 'DREB', 'AST', 'STL', 'TOV', 'BLK',
                'PTS', 'AST/TO', 'FG3_PCT', 'FG_PCT', 'FT_PCT'
            ]]
            # df['AST/TO'] = df['AST']/df['TOV']
            game_array.append(df.values)

        matchup_array = np.concatenate((game_array[0], game_array[1]), axis=1)
        todays_matchups.append(matchup_array)

    #quick formating!
    todays_matchups = np.array(todays_matchups)
    todays_matchups = todays_matchups[:, 0, :]
    return todays_matchups, home_teams, road_teams
Exemplo n.º 10
0
    u'VS_PLAYER_ID', u'VS_PLAYER_NAME'
]
MEASURE_TYPES = [
    'Base',
    'Advanced',
    'Misc',
    'Four Factors',
    'Scoring',
    'Opponent',
]

if __name__ == '__main__':
    if os.path.exists(TEAMS_FILE):
        teams = pd.DataFrame.from_csv(TEAMS_FILE)
    else:
        teams = team.TeamList().info().dropna()
        teams.to_csv(TEAMS_FILE)
    for measure_type in MEASURE_TYPES:
        all = None
        file_name = 'data/onoff_' + measure_type.lower().replace(' ',
                                                                 '_') + '.csv'
        for index, row in teams.iterrows():
            per_mode = constants.PerMode.Per100Possessions if measure_type == 'Misc' else constants.PerMode.Default
            data = team.TeamPlayerOnOffDetail(team_id=row['TEAM_ID'],
                                              measure_type=measure_type,
                                              per_mode=per_mode)
            on_court = data.on_court().drop([u'COURT_STATUS'], 1)
            off_court = data.off_court().drop([u'COURT_STATUS'], 1)

            overall = on_court.merge(off_court,
                                     left_on=PRIMARY_KEYS,
Exemplo n.º 11
0
from nba_py import team
from nba_py.constants import TEAMS
import json

team_list = team.TeamList().info(
)  # retrieve list of dicts that stores team info

# store game logs for each team in json file
for t in team_list:

    if t['ABBREVIATION'] is None:
        continue

    filepath = "team_stats_2010/" + t['ABBREVIATION'] + '.json'
    print(filepath)
    logs = None

    for year in range(2010, int(t['MAX_YEAR']) + 1):
        next_year = str((year + 1) % 100)

        if len(next_year) == 1:
            next_year = '0' + next_year

        season = str(year) + '-' + next_year
        print(season)
        season_log = team.TeamGameLogs(t['TEAM_ID'], season=season).info()

        if not logs:
            logs = season_log
        else:
            logs += season_log
Exemplo n.º 12
0
def create_team_id_dict():
    team_list = nba_py_team.TeamList().info()
    team_id_dict = {}
    for team_item in team_list:
        team_id_dict[team_item['ABBREVIATION']] = team_item
    return team_id_dict
Exemplo n.º 13
0
def main():


    print('Welcome to Abhi\'s NBA CLI!')
    loop=True
    while loop:
        # print('What would you like to do?')
        # print('1. Get information about a player')
        # # print()
        # print('2. View Completed/In Progress Games')
        # print('3. View Today\'s Upcoming Games')
        # # print()
        # print('9. Exit the program')
        # print('100. Used for testing')
        print_main_menu()
        main_choice = input("Pick a number from the list above\n")
        if int(main_choice) == 1:
            first_name = input("What is the first name of the player you'd like to view?\n")
            last_name = input("What is the last name?\n")

            print_player_information(first_name.strip(), last_name.strip())

        elif int(main_choice) == 2:
            print_scores()

        elif int(main_choice) == 3:
            print_upcoming_games()

        elif int(main_choice) == 4:
            team_choice = input("Enter the name of the team you'd like to view (ex. Boston Celtics)\n")
            print_team_information(team_choice)

        elif int(main_choice) == 5:
            board = Scoreboard()
            printer.pprint(board.east_conf_standings_by_day())
            
        elif int(main_choice) == 6:
            board = Scoreboard()
            printer.pprint(board.west_conf_standings_by_day())

        elif int(main_choice) == 9:
            print("Thank you for using Abhi's NBA Stats CLI!")
            return

        elif int(main_choice) == 100:
            # team_game_logs = team.TeamGameLogs("1610612738")
            # # print(type(team_game_logs))
            # printer.pprint(team_game_logs.info())
            # teamcommonroster = team.TeamCommonRoster("1610612738", season='2017-18')
            # coaches = teamcommonroster.coaches()
            # roster = teamcommonroster.roster()
            # print(coaches)
            # printer.pprint(roster)
            teamlist = team.TeamList(league_id='00')
            printer.pprint(teamlist.info())

        else:
            print("Invalid menu choice")


    last_choice = input("Would you like to run the program again? Press 1 to run again, or 2 to exit\n")
    if int(last_choice) == 1:
        main()
    elif int(last_choice) == 2:
        print("Thank you for using Abhi's NBA Stats CLI!")
        return