예제 #1
0
    def test_teams_string_representation(self):
        expected = """Golden State Warriors (GSW)
Houston Rockets (HOU)
Denver Nuggets (DEN)
Cleveland Cavaliers (CLE)
Washington Wizards (WAS)
Los Angeles Clippers (LAC)
Boston Celtics (BOS)
Portland Trail Blazers (POR)
Phoenix Suns (PHO)
Toronto Raptors (TOR)
Oklahoma City Thunder (OKC)
Brooklyn Nets (BRK)
Minnesota Timberwolves (MIN)
San Antonio Spurs (SAS)
Indiana Pacers (IND)
Charlotte Hornets (CHO)
Los Angeles Lakers (LAL)
New Orleans Pelicans (NOP)
New York Knicks (NYK)
Milwaukee Bucks (MIL)
Miami Heat (MIA)
Atlanta Hawks (ATL)
Chicago Bulls (CHI)
Sacramento Kings (SAC)
Philadelphia 76ers (PHI)
Detroit Pistons (DET)
Orlando Magic (ORL)
Utah Jazz (UTA)
Memphis Grizzlies (MEM)
Dallas Mavericks (DAL)"""

        teams = Teams()

        assert teams.__repr__() == expected
예제 #2
0
 def __init__(self):
     #get team data
     self.teamNamesJson = []
     teams = Teams()
     for team in teams:
         self.teamNamesJson.append(team.name)
     self.teamNamesJson.sort()
예제 #3
0
def getStatsTillGame(abbrev, year, gameNum):
    team = Teams(year)(abbrev)
    stats = pd.DataFrame(np.zeros((gameNum, 49)))
    stats.columns = column_names
    for gameindex in range(1, gameNum):
        gamedata = team.schedule[gameindex].boxscore.dataframe
        if (gamedata['winner'][0] == "Home" and gamedata['winning_abbr'][0] == abbrev) or (gamedata['winner'][0] == "Away" and gamedata['losing_abbr'][0] == abbrev):
            gamedata.rename(columns=lambda x: x.replace("home_", "").replace("away", "opp"), inplace=True)
        else:
            gamedata.rename(columns=lambda x: x.replace("away_", "").replace("home", "opp"), inplace=True)

        for key, value in gamedata.iteritems(): 
            if(key in stats.columns):
                if(not gameindex == 1):
                    stats[key][gameindex-1] = stats[key][gameindex-2] + value[0]
                else:
                    stats[key][gameindex-1]  = value[0]

        for key, value in stats.iteritems(): 
            if("percentage" in key or "pace" in key):
                if(not "assist" in key and not "block" in key and not "steal" in key and not "turnover" in key and not "rebound" in key and not "pace" in key):
                   stats[key][gameindex-1] = stats[key.replace("_percentage","s")][gameindex-1]/stats[key.replace("percentage","attempts")][gameindex-1]
                else:
                    if(not gameindex == 1):
                        stats[key][gameindex-1] = stats[key][gameindex-1]/gameindex

    return(stats)
예제 #4
0
    def test_invalid_default_year_reverts_to_previous_year(
            self, *args, **kwargs):
        flexmock(utils) \
            .should_receive('_find_year_for_season') \
            .and_return(2018)

        teams = Teams()

        for team in teams:
            assert team._year == '2017'
예제 #5
0
    def test_nba_empty_page_returns_no_teams(self):
        flexmock(utils) \
            .should_receive('_no_data_found') \
            .once()
        flexmock(utils) \
            .should_receive('_get_stats_table') \
            .and_return(None)

        teams = Teams()

        assert len(teams) == 0
예제 #6
0
def schedule_for_the_day(mydate):
    for team in Teams():
        team_schedule = Schedule(team.abbreviation)
        for game in team_schedule:
            if (game.datetime.date() == mydate):
                if (game.location == "Away"):
                    print(game.time)
                    print(team.abbreviation,"@ ",game.opponent_abbr)
                    expected_points = both_teams_avg_game_points_previous_10(team.abbreviation, game.opponent_abbr, game.boxscore_index)
                    real_expected_points = round(expected_points, 2)
                    print("The expected total points scored for this game is " + str(real_expected_points))
                    points_scored = find_game_points(team.abbreviation, game.boxscore_index)
                    print("The total points scored in this game was " + str(points_scored))
                    print()
예제 #7
0
def load_teams_colors():
    raw_team_colors = pd.read_json(TEAMS_DATA_GITHUB)
    # scrape a team's primary colors for the graphs below.
    team_colors = {}

    # all team colors
    for team in Teams(year=2019):
        team_rgb_strings = (
            raw_team_colors.loc[raw_team_colors["name"] == team.name]
            ["colors"].item()["rgb"][0].split(" "))
        team_colors[team.name.upper()] = tuple(
            int(c) for c in team_rgb_strings)

    # add old teams, the SuperSonics, and New Jersey Nets
    team_colors["SEATTLE SUPERSONICS"] = tuple((0, 101, 58))
    team_colors["NEW JERSEY NETS"] = tuple((0, 42, 96))
    team_colors["NEW ORLEANS HORNETS"] = tuple((0, 119, 139))
    team_colors["NEW ORLEANS/OKLAHOMA CITY HORNETS"] = tuple((0, 119, 139))
    team_colors["CHARLOTTE BOBCATS"] = tuple((249, 66, 58))  # <--guess
    return team_colors
def get_list_of_team_abbrs():
    try:
        teams = Teams()
        teams_df = teams.dataframes
        abbr = list(teams_df.abbreviation.values)
    except Exception as ex:
        abbr = [
            "MIL",
            "LAC",
            "DAL",
            "HOU",
            "NOP",
            "MEM",
            "POR",
            "WAS",
            "PHO",
            "TOR",
            "CHO",
            "LAL",
            "PHI",
            "IND",
            "MIA",
            "DET",
            "SAS",
            "ATL",
            "GSW",
            "DEN",
            "SAC",
            "UTA",
            "OKC",
            "MIN",
            "CHI",
            "NYK",
            "BRK",
            "ORL",
            "BOS",
            "CLE",
        ]
        print(ex)
    return sorted(abbr)
예제 #9
0
def season_scraper(seasons):
    master_array = []
    schedule_df = None
    for season in tqdm(seasons):  #tqdm shows progress bar
        try:
            season_team_list = Teams(str(season))
            for team in season_team_list:
                team_schedule = team.schedule
                team_season_array = []
                for game in team_schedule:
                    boxscore = game.boxscore_index
                    team_season_array.append(
                        [str(season), team.name, boxscore, game.date])
                team_season_df = pd.DataFrame(
                    team_season_array,
                    columns=['Season', 'TeamName', 'BoxscoreIndex', 'date'])
                team_season_df['date'] = pd.to_datetime(team_season_df['date'])
                team_season_df = team_season_df.set_index('date')
                team_season_df['rollingGames'] = team_season_df[
                    'Season'].rolling('5D').count()

                if schedule_df is not None:
                    schedule_df = pd.concat([schedule_df, team_season_df],
                                            axis=0)
                else:
                    schedule_df = team_season_df
                #master_array.append([str(season),team.name,boxscore])

        except:
            print("didn't work")
            continue

    #schedule_df = pd.DataFrame(master_array, columns = ['Season','TeamName','BoxscoreIndex','rollingGames'])

    schedule_df.to_csv('output/schedule_test.csv', index=True)
    return schedule_df
예제 #10
0
async def nba(ctx):
    teams = Teams()
    for team in teams:
        await ctx.send((team.name, team.abbreviation))
예제 #11
0
def get_teams(year):
    teams = Teams(year=year)
    return sorted([team.name.upper() for team in teams])
예제 #12
0
import numpy as np
import pandas as pd
import category_encoders as ce
import itertools
# import warnings
import requests
from sklearn.neighbors import KNeighborsClassifier, NearestNeighbors
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from xgboost import XGBRegressor
from sportsreference.nba.roster import Roster, Player
from sportsreference.nba.player import AbstractPlayer
from sportsreference.nba.teams import Teams
from sklearn.metrics import r2_score, mean_squared_error

teams = Teams()
teamabbs = []
squadnames = []
for team in teams:
    teamabbs.append(team.abbreviation)
for abb in teamabbs:
    squad = Roster(abb, slim=True)
    squaddict = squad.players
    squadnames.append(list(squaddict.values()))
mergednames = list(itertools.chain.from_iterable(squadnames))

rawpast = pd.read_csv(
    "https://raw.githubusercontent.com/Build-Week-NBA-Longevity-Predictor/Data-Science/master/1976_to_2015_Draftees_edit2.csv"
)
rawpast = rawpast[rawpast['Yrs'] != 0]
past = rawpast[~rawpast['Player'].isin(mergednames)]
예제 #13
0
    def setup_method(self, *args, **kwargs):
        self.results = {
            'rank': 26,
            'abbreviation': 'DET',
            'name': 'Detroit Pistons',
            'games_played': 82,
            'minutes_played': 19805,
            'field_goals': 3269,
            'field_goal_attempts': 7282,
            'field_goal_percentage': .449,
            'three_point_field_goals': 631,
            'three_point_field_goal_attempts': 1915,
            'three_point_field_goal_percentage': .330,
            'two_point_field_goals': 2638,
            'two_point_field_goal_attempts': 5367,
            'two_point_field_goal_percentage': .492,
            'free_throws': 1140,
            'free_throw_attempts': 1586,
            'free_throw_percentage': .719,
            'offensive_rebounds': 908,
            'defensive_rebounds': 2838,
            'total_rebounds': 3746,
            'assists': 1732,
            'steals': 574,
            'blocks': 310,
            'turnovers': 973,
            'personal_fouls': 1467,
            'points': 8309,
            'opp_field_goals': 3144,
            'opp_field_goal_attempts': 6830,
            'opp_field_goal_percentage': .460,
            'opp_three_point_field_goals': 767,
            'opp_three_point_field_goal_attempts': 2098,
            'opp_three_point_field_goal_percentage': .366,
            'opp_two_point_field_goals': 2377,
            'opp_two_point_field_goal_attempts': 4732,
            'opp_two_point_field_goal_percentage': .502,
            'opp_free_throws': 1346,
            'opp_free_throw_attempts': 1726,
            'opp_free_throw_percentage': .780,
            'opp_offensive_rebounds': 656,
            'opp_defensive_rebounds': 2861,
            'opp_total_rebounds': 3517,
            'opp_assists': 1929,
            'opp_steals': 551,
            'opp_blocks': 339,
            'opp_turnovers': 1046,
            'opp_personal_fouls': 1434,
            'opp_points': 8401
        }
        self.abbreviations = [
            'BOS', 'CLE', 'TOR', 'WAS', 'ATL', 'MIL', 'IND', 'CHI', 'MIA',
            'DET', 'CHO', 'NYK', 'ORL', 'PHI', 'BRK', 'GSW', 'SAS', 'HOU',
            'LAC', 'UTA', 'OKC', 'MEM', 'POR', 'DEN', 'NOP', 'DAL', 'SAC',
            'MIN', 'LAL', 'PHO'
        ]
        flexmock(utils) \
            .should_receive('_todays_date') \
            .and_return(MockDateTime(YEAR, MONTH))

        self.teams = Teams()
예제 #14
0
def plot_team_season(teams,
                     stat,
                     start_season,
                     end_season,
                     opp=False,
                     xlabel="Year",
                     ylabel=None,
                     scatter=True,
                     return_type='img',
                     cum=False):
    """
    Uses Sportsreference
     Plots the graph of a team or a list of teams by seasons. Stats are from the regular season collected at the end of the season.
    :param teams: Basketball-reference id for team
    :type teams: String or list of strings
    :param stat: The statistical attribute of the player to plot
    :type stat: String
    :param start_season: Starting season from which to plot
    :type start_season: Integer
    :param end_season: Last season until which to plot
    :type end_season: Integer
    :param opp: Whether the stat is for the opponent
    :type opp: Bool
    :param xlabel: The label on the x-axis on the returned plot
    :type xlabel: String
    :param ylabel: The label on the y-axis on the returned plot
    :type ylabel: String
    :param scatter: Whether on not to include a dot for each data point in the graph
    :type scatter: Bool
    :param return_type: Various methods by which the graph can be returned
    :type return_type: "img": png image, "fig":Matplotlib figure and axes,"show": calls the matplotlib show function (appropriate for jupyter notebooks), "html": base64 image useful for rendering in html pages
    :param cum: Whether results are cumulative or not
    :type cum: Bool
    """
    if type(teams) is not list:
        teams = [teams]
    fig, ax = plt.subplots()
    tm_dict = {}
    if opp:
        stat = "opp_" + stat

    for year in range(start_season, end_season):
        tm = Teams(year)
        tm_dict[year] = tm

    for team in teams:
        x = []
        y = []
        for year in range(start_season, end_season):
            tm = tm_dict[year]
            x.append(year)
            if cum:
                try:
                    prev = y[-1]
                except:
                    prev = 0
                y.append(tm.dataframes.loc[team][stat] + prev)
            else:
                y.append(tm.dataframes.loc[team][stat])
        ax.plot(x, y, label=team)
        if scatter:
            ax.scatter(x, y)
        ax.legend()

    ax.xaxis.set_major_locator(MaxNLocator(integer=True))
    ax.set_xlabel(xlabel)
    if ylabel == None:
        ylabel = stat
    ax.set_ylabel(ylabel)

    return return_plot(stat, fig, ax, return_type)

def games_today(team_abbr):
    sched = Schedule(team_abbr)
    sched_df = sched.dataframe
    sched_df['team_abbr'] = team_abbr
    sched_df = sched_df[[
        'datetime', 'team_abbr', 'opponent_abbr', 'location', 'time'
    ]]
    sched_df = sched_df.reset_index(drop=True)
    sched_df = sched_df[sched_df['datetime'] == today]
    return sched_df


team_stats = pd.DataFrame()
for team in Teams():
    team_stats = team_stats.append(team.dataframe)
teams = Teams()
team_list = []
for team in teams:
    team_list.append(team.abbreviation)
nba = pd.DataFrame()
game_today = pd.DataFrame()
for i in range(len(team_list)):
    team_abbr = team_list[i]
    data = get_stats(team_abbr, team_stats)
    data['teamAbbr'] = team_abbr
    nba = nba.append(data, ignore_index=True)
nba = nba.set_index('teamAbbr')
matchups = pd.DataFrame()
for i in range(len(team_list)):
예제 #16
0
import sys, os
sys.path.append(os.path.dirname(os.path.dirname(sys.path[0])))
from sportsreference.nba.teams import Teams

for team in Teams():
    print(team.name)
    for player in team.roster.players:
        print(player.name)
    for game in team.schedule:
        print(game.dataframe)
        print(game.dataframe_extended)