Ejemplo n.º 1
0
def init_teams():
    nba_teams = teams.get_teams()
    i = 1
    for t in nba_teams:
        nba_teams_dict[i] = t['nickname']
        i += 1
    print(nba_teams_dict)
def all_games_of_one_team(teamA):
    nba_teams = teams.get_teams()
    teamA = [team for team in nba_teams if team['abbreviation'] == teamA][0]
    teamA_Id = teamA['id']
    gamefinder = leaguegamefinder.LeagueGameFinder(team_id_nullable=teamA_Id)
    games = gamefinder.get_data_frames()[0]
    return games
def getAllNbaTeams():
    """
    IMPORTANT: the list contains the teams in the NBA
    :return:
    """
    nba_teams = teams.get_teams()
    return nba_teams
Ejemplo n.º 4
0
 def get_team_id(team_abbrev):
     all_team = teams.get_teams()
     for team in all_team:
         for key, value in team.items():
             if key == 'abbreviation':
                 if value == team_abbrev:
                     return team['id']
def main(season):
    #All NBA Players Information in DataFrame
    nba_players_info = pd.concat([pd.DataFrame.from_dict(players.get_players()[i], orient='index').transpose() for i in range(len(players.get_players()))],ignore_index=True)
    
    #All NBA Teams Information in DataFrame
    nba_teams_info = pd.concat([pd.DataFrame.from_dict(teams.get_teams()[i], orient='index').transpose() for i in range(30)],ignore_index=True)
    
    #Players that are active right now
    players_active = nba_players_info[nba_players_info['is_active'] == True].reset_index(drop=True)
    
    #Players Active in Array
    players_active_array = players_active['full_name'].values
    
    #Teams in Array 
    teams_array = nba_teams_info['full_name'].values
    
    #Seasons in Array
    seasons = ['2018-19','2017-18','2016-17','2015-16','2014-15','2013-14','2012-13','2011-12','2010-11','2009-10']
    
    #Stephs ID
    steph_id = players.find_players_by_full_name('Steph')[1]['id']
    
    
    input_season_df = season_player(season, steph_id, players_active)
    input_season_df.to_csv("Steph_" + season + "_matchup.csv")
Ejemplo n.º 6
0
def get_year_by_year_data(outfile):
    all_teams = teams.get_teams()

    # Contains list of (id, name) tuples
    team_data = [(t['id'], t['full_name']) for t in all_teams]

    # Normalize stats by dividing by number of games
    params = {"per_mode_simple": "PerGame"}

    all_data = []

    for team in team_data:
        team_id, team_name = team

        print('fetching data for team ', team_name)
        team_stats_dataset = team_stats_endpoint.TeamYearByYearStats(
            team_id=team_id, **params)
        team_stats = team_stats_dataset.team_stats.get_data_frame()
        all_data.append(team_stats)

        # So we don't get throttled
        time.sleep(1)

    # Combine everyting into one bigass DF and compress it out 'outfile'
    full_data_frame = pd.concat(all_data, ignore_index=True)
    full_data_frame.to_feather(outfile)
Ejemplo n.º 7
0
def getDateInfo(date, gameonday):
    game = {}
    all_elo = pd.read_csv("./sim_data/2019-2020_data.csv")
    nba_teams = teams.get_teams()
    all_games = pd.read_csv("./game_data/allgames.csv",
                            dtype={"GAME_ID": "string"})
    all_games = all_games[['GAME_ID', 'GAME_DATE', "MATCHUP"]]
    on_date = all_games[all_games["GAME_DATE"] == date]
    on_date = on_date[~on_date["MATCHUP"].str.contains("vs.")]
    for i, gamez in on_date.iterrows():
        words = gamez["MATCHUP"].split(" ")
        gameid = gamez["GAME_ID"]
        home_team = []
        away_team = []
        for team in nba_teams:
            team_elo = float(
                all_elo.loc[all_elo['Date'] == date][team["nickname"]].values)
            if str(team['abbreviation']) == words[2]:
                home_team = [team["nickname"], team_elo]
            elif str(team['abbreviation']) == words[0]:
                away_team = [team["nickname"], team_elo]
        game_info = [*home_team, *away_team]
        game[gameid] = game_info
        game = removeGLeague(game)
    nbagameids = []
    for i in game.keys():
        nbagameids.append(i)
    values = game.values()
    values_list = list(values)
    home_elo = int(values_list[gameonday][1])
    away_elo = int(values_list[gameonday][3])
    h_elo_prob = 1 / (1 + 10**((away_elo - home_elo - 100) / 400))
    a_elo_prob = 1 - h_elo_prob
    return home_elo, away_elo, h_elo_prob, a_elo_prob, nbagameids[gameonday]
Ejemplo n.º 8
0
def get_nba_team_stats(start_year, type='regular'):
    # Getting Mavs team ID for example
    nba_teams = teams.get_teams()
    mavs_id = [
        team for team in nba_teams if team['full_name'] == 'Dallas Mavericks'
    ][0]

    # Get Mavs reg season yby DF to create empty DF with appropriate columns
    reg_season_yby_mavs = teamyearbyyearstats.TeamYearByYearStats(
        team_id=mavs_id['id']).get_data_frames()[0]
    reg_season_yby = pd.DataFrame(columns=reg_season_yby_mavs.columns)

    # Get Reg Season YBY stats for all teams, beginning in 2011-12
    for team in nba_teams:
        team_yby_stats = teamyearbyyearstats.TeamYearByYearStats(
            team_id=team['id']).get_data_frames()[0]
        team_yby_stats['START_YEAR'] = team_yby_stats['YEAR']
        start_year_index = team_yby_stats[team_yby_stats['YEAR'].str.slice(
            stop=4) == str(start_year)].index.values[0]
        team_yby_stats = team_yby_stats[(team_yby_stats.index >
                                         start_year_index)]
        reg_season_yby = reg_season_yby.append(team_yby_stats, sort=True)

    print('Number of unique team IDs: ', reg_season_yby['TEAM_ID'].nunique())
    reg_season_yby = reg_season_yby.set_index(['TEAM_ID', 'YEAR'])
    return reg_season_yby
Ejemplo n.º 9
0
def team_api(request):
    if request.method == 'GET':

        context = {}
        context['form'] = ChoiceTeam(teams=teams.get_teams())
        return render(request=request,
                      template_name='team.html',
                      context=context)
Ejemplo n.º 10
0
def get_all_teams(start=0, end=None):
    result_teams = []

    # get all teams from NBA-API
    nba_api_teams = teams.get_teams()

    if (end == None):
        end = len(nba_api_teams)

    counter = start

    # for every team from nba-api
    for idx in tqdm(range(start, end)):
        nba_api_team = nba_api_teams[idx]
        log_console('Processing\t' + nba_api_team['full_name'] + '\t' +
                    str(idx) + '/' + str(len(nba_api_teams)))

        # create nba_api_id attribute
        nba_api_team['nba_api_id'] = nba_api_team['id']

        common_info = TeamInfoCommon(league_id='00',
                                     team_id=nba_api_team['id'])
        common_info = common_info.get_dict()
        common_info = common_info['resultSets']
        common_info = filter(lambda R: R['name'] == 'TeamInfoCommon',
                             common_info)
        common_info = list(common_info)

        # list should be of size one after filtering
        if len(common_info) > 0:
            common_info = common_info[0]
            common_info_kv_mapping = {}
            attributes = common_info['headers']
            data = common_info['rowSet'][0]

            for idx in range(len(attributes)):
                common_info_kv_mapping[attributes[idx]] = data[idx]

            nba_api_team['confernce'] = common_info_kv_mapping[
                'TEAM_CONFERENCE']
            nba_api_team['division'] = common_info_kv_mapping['TEAM_DIVISION']
            nba_api_team['min_year'] = common_info_kv_mapping['MIN_YEAR']
            nba_api_team['max_year'] = common_info_kv_mapping['MAX_YEAR']

        else:
            # no result returned
            nba_api_team['conference'] = ''
            nba_api_team['division'] = ''
            nba_api_team['min_year'] = ''
            nba_api_team['max_year'] = ''

        # store team in result list
        result_teams.append(nba_api_team)
        counter += 1
        time.sleep(.8)

    return result_teams
Ejemplo n.º 11
0
def download_all_teams(database=None):
    # call nba_api and get all the teams
    all_teams = teams.get_teams()

    # intilialize respoinse with the specified database
    r = Response(all_teams, database=database)

    # extract the team data
    r.extract_teams()
Ejemplo n.º 12
0
    def _opponentTeamDetails(self):
        try:
            teams_dict = teams.get_teams()
            team_details = \
                [team for team in teams_dict if team[FULL_NAME].lower()
                 == self.opponentTeam.strip().lower()][0]

            return team_details
        except:
            return NA
Ejemplo n.º 13
0
    def inner():
        result = []
        for team in teams.get_teams():
            team_name, team_id = team['full_name'], team['id']
            # logger.info('Retrieving data for team {}, ID {}'.format(team_name, team_id))
            print('Retrieving data for team {}, ID {}'.format(
                team_name, team_id))
            result.append(_get_games_for_team(team_id, date_from, date_to))

        return pd.concat(result)
Ejemplo n.º 14
0
def baseTeams():
    team_dict = teams.get_teams()

    nbaCollection = db.get_collection("Teams")

    for team in team_dict:
        team1 = db.get_document(nbaCollection,
                                team['nickname'].replace(" ", ""))
        team1["value"] = team
        team1.save()
def get_all_games_between_two_teams(teamA, teamB):
    nba_teams = teams.get_teams()
    teamA = [team for team in nba_teams if team['abbreviation'] == teamA][0]
    teamA_Id = teamA['id']
    gamefinder = leaguegamefinder.LeagueGameFinder(team_id_nullable=teamA_Id)
    games = gamefinder.get_data_frames()[0]
    games.head()
    games_1718 = games
    teamB_games_1718 = games_1718[games_1718.MATCHUP.str.contains(teamB)]
    return teamB_games_1718
Ejemplo n.º 16
0
def get_stats_all():
	'''
	This function will return last game stats for each NBA team. 
	'''
	for team in teams.get_teams():
		try:
			get_stats(team['abbreviation'])
			print('processing...')
		except:
			print('Timed out for requests...need to wait for a while and retry.')
	print('done!')
    def get_team_num_vals(self):

        team_abbvs_dict = {}
        team_info = teams.get_teams()
        print(team_info)

        for team in range(0, len(team_info)):
            team_abbvs_dict[team_info[team]['abbreviation']] = team

        print(team_abbvs_dict)

        return team_abbvs_dict
Ejemplo n.º 18
0
def get_default_team_plyr_stats_dataframe():

    # get LAL team_id
    teams_dict = teams.get_teams()
    LAL = [x for x in teams_dict if x["full_name"] == "Los Angeles Lakers"][0]
    LAL_id = LAL["id"]

    # Params for defautl team-plyr stats dataframe
    TEAM_ID = LAL_id
    SEAS_ID = "2018-19"

    COLUMNS_OF_INTEREST = [
        "SEASON_ID",
        # "TEAM_ID",
        "TEAM_ABBREVIATION",
        "PLAYER_ID",
        "PLAYER",
        "NUM",
        "POSITION",
        "HEIGHT",
        "WEIGHT",
        "BIRTH_DATE",
        "PLAYER_AGE",
        # "EXP",
        "GP",
        "GS",
        "MIN",
        "FGM",
        "FGA",
        "FG_PCT",
        "FG3M",
        "FG3A",
        "FG3_PCT",
        "FTM",
        "FTA",
        "FT_PCT",
        # "OREB",
        # "DREB",
        "REB",
        "AST",
        "STL",
        "BLK",
        # "TOV",
        # "PF",
        "PTS",
    ]

    df = get_team_plyr_stats_dataframe(team_id=TEAM_ID,
                                       season_id=SEAS_ID,
                                       timeout_s=30)

    return df[COLUMNS_OF_INTEREST]
Ejemplo n.º 19
0
def main():

    ml_input_data = []
    ml_output_data = []

    years = [2017, 2018] # years to get data for
    for year in years:
        sleep(1)
        # get all the games in the NBA league for the season
        games = get_league_gamelogs(year)

        # create a map of every team's performance before each one of their games
        team_performance_map = {}
        for team in teams.get_teams():
            print(f'Getting team stats for {team["abbreviation"]}...')
            sleep(1)  # delay before next request to prevent getting temporarily banned from nba api
            team_id = team['id']
            team_gamelogs = get_team_gamelogs_for_season(team_id, year)
            team_gamelogs_accum = accumulate_team_gamelog_stats(team_gamelogs, year)
            team_performance_map[team_id] = team_gamelogs_accum

        team_estimated_metrics = get_team_estimated_metrics(year)

        # now, for every game, create an input / output pair to use in the ML model
        # keep list of all seen teams so that we don't use stats for a team that has not played any games yet as input
        seen_teams = set()
        for game in games:
            if game.home_team_id in seen_teams and game.away_team_id in seen_teams:
                # get home team stats
                # home_team_data = team_performance_map[game.home_team_id][str(game.game_id)]
                # # get away team stats
                # away_team_data = team_performance_map[game.away_team_id][str(game.game_id)]
                # # save input and expected output
                home_team_data = team_estimated_metrics[game.home_team_id]
                away_team_data = team_estimated_metrics[game.away_team_id]
                home_team_data.update(team_performance_map[game.home_team_id][str(game.game_id)])
                away_team_data.update(team_performance_map[game.away_team_id][str(game.game_id)])
                ml_input_data.append(encode_data(home_team_data, away_team_data))
                ml_output_data.append(1 if game.home_team_won else 0)
            else:
                seen_teams.add(game.home_team_id)
                seen_teams.add(game.away_team_id)

    # now write the input and output to files
    # write input and output to files
    # create directory if it doesn't exist
    if not os.path.exists(data_directory):
        os.makedirs(data_directory)
    # write input to file
    np.save(input_file, np.array(ml_input_data))
    # write output to file
    np.save(output_file, np.array(ml_output_data))
Ejemplo n.º 20
0
def get_team_id(team_name):
    # Below returns a list of dictionaries, 1 for each NBA team
    nba_teams = teams.get_teams()

    # Let's create a Pandas DataFrame using extracted list of dictionaries
    df_nba_teams = pd.DataFrame(nba_teams)

    for team in nba_teams:
        if team_name == team['full_name']:
            team_id = team['id']
            break

    return team_id
Ejemplo n.º 21
0
def main():
    ############################################################

    teams = Teams.get_teams()

    # go through each team
    for team in sorted(teams):
        print "-" * 60
        for key, value in team.items():
            # print all key value information
            # pertaining to teams(except id)
            if key != 'id':
                print "%-15s" % (str(key), ) + ": " + str(value)
Ejemplo n.º 22
0
def get_ra_fga_percentchange():
    centers = leaguedashplayerstats.LeagueDashPlayerStats(
        player_position_abbreviation_nullable="C")
    teams = teams.get_teams()

    # really just centers who play more than an mpg limit
    # mpg is calculated here as min / gp
    starting_centers = [
        center for center in centers.data_sets[0].data['data']
        if center[9] / center[5] > MINUTES_THRESHOLD
    ]

    result = {}

    # iterate through every combination of starting center and opposing team
    for center in starting_centers:
        percent_change_sum = 0

        for team in teams:
            # ignore matchup if center is facing own team (sanity check)
            if not team['id'] is center[2]:

                matchup_stats = teamvsplayer.TeamVsPlayer(
                    center[0], team['id'])

                #check if there were games played / is data
                if len(matchup_stats.shot_area_on_court.data['data']) == 0:
                    continue

                games_played = matchup_stats.overall.data['data'][0][4]
                games_played_matchup = matchup_stats.on_off_court.data['data'][
                    0][7]

                fga = matchup_stats.overall.data['data'][0][10] / games_played
                fga_oncourt = matchup_stats.on_off_court.data['data'][0][
                    13] / games_played_matchup
                ra_fga = matchup_stats.shot_area_overall.data['data'][0][
                    6] / games_played
                ra_fga_oncourt = matchup_stats.shot_area_on_court.data['data'][
                    0][9] / games_played_matchup

                # percent change of porportion of field goals attempted in
                # restricted area with center on the court
                percent_change = ((ra_fga_oncourt / fga_oncourt) -
                                  (ra_fga / fga)) / (ra_fga / fga)
                percent_change_sum += percent_change

        average_rim_intimidation = percent_change_sum / len(teams)
        result[center[1]] = average_rim_intimidation

    return result
Ejemplo n.º 23
0
 def team_roaster(self):
     all_team = teams.get_teams()
     all_teams = []
     for i in range(len(all_team)):
         team = {}
         team.update({
             'team_id': all_team[i]['id'],
             'team_name': all_team[i]['full_name'],
             'abbrev': all_team[i]['abbreviation'],
             'nickname': all_team[i]['nickname'],
             'city': all_team[i]['city']
         })
         all_team.append(team)
     return [teams for teams in all_team]
Ejemplo n.º 24
0
def get_team_id(team_abbreviation):
    # Get all the teams
    nba_teams = teams.get_teams()

    # Search for team based on abbreviation
    if (team_abbreviation != ''):
        team_to_find = [team for team in nba_teams if team['abbreviation'] == team_abbreviation][0]
    else:
        return None;

    # Get team_id based on team
    team_id = team_to_find['id']

    # Return team_id
    return team_id
Ejemplo n.º 25
0
def add_teams(conn):
    print('Reading team information')
    conn.execute('DROP TABLE IF EXISTS teams')
    conn.execute('VACUUM')
    conn.execute(
        'CREATE TABLE teams (ID INTEGER, ABBREVIATION TEXT, MASCOT TEXT, NAME TEXT, CITY TEXT, STATE TEXT, YEAR INTEGER)'
    )
    teams = TEAMS.get_teams()
    teams = json.dumps(teams)
    teams = pd.read_json(teams)
    teams.rename(columns={
        'full_name': 'NAME',
        'nickname': 'MASCOT',
        'year_founded': 'YEAR'
    },
                 inplace=True)
    teams.to_sql('teams', conn, if_exists='append', index=False)
def get_data():
    # Se obtienen todos lo equipos de la NBA
    nba_teams = teams.get_teams()
    dataframes_list = []
    for team in nba_teams:
        # Se hace una petición a la API para obtener los partidos de cada equipo
        gamefinder = leaguegamefinder.LeagueGameFinder(
            team_id_nullable=team['id'])
        games = gamefinder.get_data_frames()[0]
        # Se almacenan los partidos de cada equipo por separado
        games.to_csv(r'.\datasets\by_team\\' + team['abbreviation'] + '.csv')
        dataframes_list.append(games)
    # Se almacenan los datos de todos los partidos en un mismo dataset
    games_dataframe = pd.concat(dataframes_list, axis=0, ignore_index=True)
    games_dataframe.to_csv(r'.\datasets\dataset.csv')

    return games_dataframe
Ejemplo n.º 27
0
def build_team_id_dictionary(season):
    team_list = teams.get_teams()
    team_id = {}

    for team in team_list:
        abv = team["abbreviation"]

        if(abv == "BKN"):
            abv  = "BRK" #Nets
        elif(abv == "PHX"):
            abv  = "PHO" #Nets
        elif(abv == "CHA"):
            abv  = "CHO" #Nets
        else:
            pass

        team_id[abv] = team["id"]

    return team_id
Ejemplo n.º 28
0
def check_and_post(player_name, city):
    """The following function gets the last nuggets game, checks if it's a new game, and posts Nikola Jokic's stats to twitter. Some code snippets were lifted and
    modified from the nba_api and Twitter API Python documentation"""
    global last_game_date
    # Get all teams
    nba_teams = teams.get_teams()

    # Select the dictionary for the selected player's team, which contains their team ID
    player_team = [team for team in nba_teams
                   if team['abbreviation'] == city][0]
    team_id = player_team['id']

    # Query for games where the Nuggets were playing
    gamefinder = leaguegamefinder.LeagueGameFinder(team_id_nullable=team_id)

    # The first DataFrame of those returned is what we want.
    games = gamefinder.get_data_frames()[0]
    last_team_game = games.sort_values('GAME_DATE').iloc[-1]
    current_game_date = last_team_game["GAME_DATE"]

    # Get the stats of the game
    game_stats = boxscoretraditionalv2.BoxScoreTraditionalV2(
        last_team_game["GAME_ID"])

    # Search for player, and build a string of his stats
    for player in game_stats.player_stats.get_dict()["data"]:
        if player_name in player:
            stats = "{0}'s stats for {1} {2}: points: {3}, rebounds: {4}, assists: {5}".format(
                player_name, last_team_game["GAME_DATE"],
                last_team_game["MATCHUP"], player[-2], player[-8], player[-7])

    # Make Twitter API
    api = twitter.Api(consumer_key=ck,
                      consumer_secret=cs,
                      access_token_key=atk,
                      access_token_secret=ats)
    try:
        status = api.PostUpdate(stats)
        print("{0} just posted: {1}".format(status.user.name, status.text))
    except UnicodeDecodeError:
        print("Failed to post to Twitter")
        sys.exit(2)
Ejemplo n.º 29
0
def see_all_teams():
    nba_teams = teams.get_teams()
    for team in nba_teams:
        if db.session.query(db.exists().where(NBA_Team.name == team['full_name'])).scalar():
            pass
        else:
            for team in nba_teams:
                add_team = NBA_Team(abbrev = team['abbreviation'],
                name = team['full_name'],
                city = team['city'],
                state = team['state'])
                session.add(add_team)
                session.commit()

    all_teams = NBA_Team.query.all()
    names = []
    for t in all_teams:
        newlist = [t.name,t.city, t.state]
        names.append(newlist) # names will be a list of tuples
    return render_template('all_teams.html',team_names=names)
Ejemplo n.º 30
0
    def get_teams(self):
        """
        method to get all nba teams using the NBA api and create data frame with box scores.
        """
        self.team_info = teams.get_teams()
        for team in self.team_info:
            # we have to sleep when making requests or we'll get booted.
            time.sleep(5)
            temp_frame = leaguegamefinder.LeagueGameFinder(
                team_id_nullable=team['id'],
                season_nullable=self.seasons).get_data_frames()[0]

            self.df = self.df.append(temp_frame, ignore_index=True)

        # drop the columns we don't need.
        self.df.drop(columns=[
            'FGM', 'FGA', 'MIN', 'FG3M', 'FG3A', 'FTM', 'FTA', 'PLUS_MINUS',
            'TEAM_NAME', 'REB'
        ],
                     inplace=True)