def setup_method(self, *args, **kwargs): self.results = { 'game': 2, 'boxscore_index': '201610280NOP', 'date': 'Fri, Oct 28, 2016', 'time': '9:30p', 'datetime': datetime(2016, 10, 28), 'location': AWAY, 'opponent_abbr': 'NOP', 'opponent_name': 'New Orleans Pelicans', 'result': WIN, 'playoffs': False, 'points_scored': 122, 'points_allowed': 114, 'wins': 1, 'losses': 1, 'streak': 'W 1' } flexmock(Boxscore) \ .should_receive('_parse_game_data') \ .and_return(None) flexmock(Boxscore) \ .should_receive('dataframe') \ .and_return(pd.DataFrame([{'key': 'value'}])) flexmock(utils) \ .should_receive('_todays_date') \ .and_return(MockDateTime(YEAR, MONTH)) self.schedule = Schedule('GSW')
def both_teams_avg_game_points_previous_10(abbreviation1, abbreviation2, rboxscore_index): sched1 = Schedule(abbreviation1) sched2 = Schedule(abbreviation2) index_to_match = rboxscore_index game1 = 0 game2 = 0 for game in sched1: if index_to_match == game.boxscore_index: game1 = game.game for game in sched2: if index_to_match == game.boxscore_index: game2 = game.game estimate = total_game_points_scored_over_previous_10(abbreviation1, game1) + total_game_points_scored_over_previous_10(abbreviation2, game2) final_estimate = estimate / 2 return final_estimate
def test_invalid_default_year_reverts_to_previous_year( self, *args, **kwargs): results = { 'game': 2, 'boxscore_index': '201610280NOP', 'date': 'Fri, Oct 28, 2016', 'time': '9:30p', 'datetime': datetime(2016, 10, 28), 'location': AWAY, 'opponent_abbr': 'NOP', 'opponent_name': 'New Orleans Pelicans', 'result': WIN, 'points_scored': 122, 'points_allowed': 114, 'wins': 1, 'losses': 1, 'streak': 'W 1' } flexmock(Boxscore) \ .should_receive('_parse_game_data') \ .and_return(None) flexmock(Boxscore) \ .should_receive('dataframe') \ .and_return(pd.DataFrame([{'key': 'value'}])) flexmock(utils) \ .should_receive('_find_year_for_season') \ .and_return(2018) schedule = Schedule('GSW') for attribute, value in results.items(): assert getattr(schedule[1], attribute) == value
def find_games_played(abbreviation): df1 = Schedule(abbreviation) counter = 0 for game in df1: if (type(game.points_scored) == int): counter += 1 return counter
def find_game_points(abbreviation, boxscore_index): sched1 = Schedule(abbreviation) for game in sched1: if boxscore_index == game.boxscore_index: total_score = game.points_scored + game.points_allowed return total_score return 0
def game_stats(self, date): """ Fetches stats for player from their game on the specified date. Arguments --------- date : datetime.date Date of game. Returns ------- dict of stats or None if there was no game for the player on that date. """ if date.month > 7 and date.year != 2020: year_str = str(date.year) + '-' + str(date.year + 1)[-2:] year = date.year + 1 else: year_str = str(date.year - 1) + '-' + str(date.year)[-2:] year = date.year team_schedule = Schedule(self.player(year_str).team_abbreviation, year) try: boxscore = team_schedule(date).boxscore except: return None for player in boxscore.away_players + boxscore.home_players: if player.name == self.player.name: return stats(player)
def predict_nba_game(team1, team2): dataset = {} teams = [team1, team2] for num, team in enumerate(teams): df = NBA_Schedule(team, year=2020).dataframe.head(63) df = df[['points_scored']] forecast_out = int(1) print(df.shape) df['Prediction'] = df[['points_scored']].shift(-forecast_out) X = np.array(df.drop(['Prediction'], 1)) X = preprocessing.scale(X) X_forecast = X[-forecast_out:] X = X[:-forecast_out] y = np.array(df['Prediction']) y = y[:-forecast_out] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) clf = LinearRegression() clf.fit(X_train, y_train) confidence = clf.score(X_test, y_test) forecast_prediction = clf.predict(X_forecast) lists_of_forecast = forecast_prediction.tolist() if num == 0: dataset[team1] = { "confidence": confidence, "predicted_score": lists_of_forecast } else: dataset[team2] = { "confidence": confidence, "predicted_score": lists_of_forecast } json_forecast = json.dumps(dataset, default=str) return json_forecast
def test_invalid_2020_default_reverts_to_previous_year( self, *args, **kwargs): flexmock(utils) \ .should_receive('_find_year_for_season') \ .and_return(2021) schedule = Schedule('2017') assert 'Tue, Oct 25, 2016' in str(schedule)
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
def setup_method(self, *args, **kwargs): self.results = { 'game': 2, 'boxscore_index': '201610280NOP', 'date': '2016-10-28', 'datetime': datetime(2016, 10, 28), 'location': AWAY, 'opponent_abbr': 'NOP', 'result': WIN, 'points_scored': 122, 'points_allowed': 114, 'field_goals': 44, 'field_goal_attempts': 91, 'field_goal_percentage': .484, 'three_point_field_goals': 9, 'three_point_field_goal_attempts': 28, 'three_point_field_goal_percentage': .321, 'free_throws': 25, 'free_throw_attempts': 28, 'free_throw_percentage': .893, 'offensive_rebounds': 9, 'total_rebounds': 49, 'assists': 32, 'steals': 8, 'blocks': 2, 'turnovers': 14, 'personal_fouls': 22, 'opp_field_goals': 47, 'opp_field_goal_attempts': 100, 'opp_field_goal_percentage': .470, 'opp_three_point_field_goals': 5, 'opp_three_point_field_goal_attempts': 22, 'opp_three_point_field_goal_percentage': .227, 'opp_free_throws': 15, 'opp_free_throw_attempts': 23, 'opp_free_throw_percentage': .652, 'opp_offensive_rebounds': 12, 'opp_total_rebounds': 49, 'opp_assists': 29, 'opp_steals': 8, 'opp_blocks': 5, 'opp_turnovers': 13, 'opp_personal_fouls': 24 } flexmock(Boxscore) \ .should_receive('_parse_game_data') \ .and_return(None) flexmock(Boxscore) \ .should_receive('dataframe') \ .and_return(pd.DataFrame([{'key': 'value'}])) flexmock(utils) \ .should_receive('_todays_date') \ .and_return(MockDateTime(YEAR, MONTH)) self.schedule = Schedule('GSW')
def test_no_dataframes_extended_returns_none(self): flexmock(Schedule) \ .should_receive('_pull_schedule') \ .and_return(None) schedule = Schedule('DET') fake_game = flexmock(dataframe_extended=None) fake_games = PropertyMock(return_value=fake_game) type(schedule).__iter__ = fake_games assert schedule.dataframe_extended is None
def test_empty_page_return_no_games(self): flexmock(utils) \ .should_receive('_no_data_found') \ .once() flexmock(utils) \ .should_receive('_get_stats_table') \ .and_return(None) schedule = Schedule('GSW') assert len(schedule) == 0
def get_boston_three(): sched = Schedule('BOS') # sched[-3:] should be last three games of season # today is 2019-03-15 # these are the past three games played rather than last of season # prints 2019-03-09, 2019-03-11, 2019-03-14 for game in sched[-3:]: print(game.date) # celtics play wizards on 2019-04-09 celtics_last_game = "2019-04-09" all_dates = [game.date for game in sched] print(all_dates)
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()
def return_schedule_dataframe(year_abbr: tuple, dir_out: str): """TODO: this 'should' be a sqlite databse, but don't got time for dat https://docs.prefect.io/core/tutorials/advanced-mapping.html#reusability """ logger = prefect.context.get("logger") year, abbr = year_abbr logger.info("Looping: %s, %s", abbr, year) sched = Schedule(abbr, year=year) df_sched = sched.dataframe df_sched["team_abbr"] = abbr df_sched["year"] = year fp_out = os.path.join(dir_out, f"{year}-{abbr}.csv") df_sched.to_csv(fp_out, index=False) return (year, abbr, df_sched)
def plot_team_game(teams, stat, season, start_date, end_date, opp=False, xlabel="Time", ylabel=None, only_month=False, scatter=True, return_type="img", cum=False): """ Uses Sportsreference :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 season: The season in which the games are played :type season: Either in dashed form (2018-19) or single form (2019 means the season 2018-19) :param start_date: The date from which the data is plotted :type start_date: datetime.date format :param end_date: The date untill which data is plotted :type end_date: datetime.date format :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 """ fig, ax = plt.subplots() if type(teams) is not list: teams = [teams] for team in teams: x = [] y = [] sch = Schedule(team, season) for index, row in sch.dataframe.iterrows(): if start_date <= row['datetime'].date() <= end_date: box = Boxscore(index) stat_prefix = "" stat_prefix_reversal = {"home_": "away_", "away_": "home_"} if row['location'] == "Home": stat_prefix = "home_" elif row['location'] == "Away": stat_prefix = "away_" if opp: stat_prefix = stat_prefix_reversal[stat_prefix] x.append(row['datetime'].date()) if cum: try: prev = y[-1] except: prev = 0 y.append(int(box.dataframe[stat_prefix + stat]) + prev) else: y.append(int(box.dataframe[stat_prefix + stat])) ax.plot(x, y, label=team) if scatter: ax.scatter(x, y) ax.legend() if only_month: ax.xaxis.set_major_locator(MonthLocator()) ax.xaxis.set_major_formatter(DateFormatter("%y-%m")) fig.autofmt_xdate() ax.set_xlabel(xlabel) if ylabel == None: if opp: ax.set_ylabel("opp_" + stat) else: ax.set_ylabel(stat) return return_plot(stat, fig, ax, return_type)
def get_stats(team_abbr, team_stats): pd.options.mode.chained_assignment = None # default='warn' sched = Schedule(team_abbr) sched_df = sched.dataframe sched_df['datetime'] = sched_df['datetime'].dt.date team_df = pd.DataFrame() for game in sched: team_df = team_df.append(game.dataframe) team_df['datetime'] = team_df['datetime'].dt.date curr_sched = team_df[team_df['datetime'] <= yest] curr_sched['stk'] = curr_sched['streak'].str.replace('L ', '-').str.replace( 'W ', '') last_game = curr_sched.iloc[-1] # 'lastTen' lTen = curr_sched.tail(10) if 'Win' in lTen['result'].value_counts().index: last_game['lastTen'] = lTen['result'].value_counts()['Win'] else: last_game['lastTen'] = 0 # 'winPercent' last_game = last_game.fillna(0) last_game['winPercent'] = last_game['wins'] / last_game['game'] last_game = last_game.fillna(0) # Home win if 'Win' in curr_sched[curr_sched['location'] == 'Home']['result'].value_counts().index: last_game['homeWin'] = curr_sched[ curr_sched['location'] == 'Home']['result'].value_counts()['Win'] else: last_game['homeWin'] = 0 # Home loss if 'Loss' in curr_sched[curr_sched['location'] == 'Home']['result'].value_counts().index: last_game['homeLoss'] = curr_sched[ curr_sched['location'] == 'Home']['result'].value_counts()['Loss'] else: last_game['homeLoss'] = 0 # Away win if 'Win' in curr_sched[curr_sched['location'] == 'Away']['result'].value_counts().index: last_game['awayWin'] = curr_sched[ curr_sched['location'] == 'Away']['result'].value_counts()['Win'] else: last_game['awayWin'] = 0 # Away loss if 'Loss' in curr_sched[curr_sched['location'] == 'Away']['result'].value_counts().index: last_game['awayLoss'] = curr_sched[ curr_sched['location'] == 'Away']['result'].value_counts()['Loss'] else: last_game['awayLoss'] = 0 last_game['homeWin_Percent'] = last_game['homeWin'] / ( last_game['homeWin'] + last_game['homeLoss']) last_game['awayWin_Percent'] = last_game['awayWin'] / ( last_game['awayWin'] + last_game['awayLoss']) last_game = last_game[[ 'stk', 'lastTen', 'winPercent', 'homeWin_Percent', 'awayWin_Percent' ]] # 'teamPTS_pg', team_stats[ 'teamPTS_pg'] = team_stats['points'] / team_stats['games_played'] # 'teamTO_pg', team_stats[ 'teamTO_pg'] = team_stats['turnovers'] / team_stats['games_played'] # 'teamFG%_pg', team_stats['teamFG%_pg'] = team_stats['field_goal_percentage'] # 'team2P%_pg', team_stats['team2P%_pg'] = team_stats['two_point_field_goal_percentage'] # 'team3PA_pg', team_stats['team3PA_pg'] = team_stats[ 'three_point_field_goal_attempts'] / team_stats['games_played'] # 'teamTRB_perc', team_stats['teamTRB_perc'] = team_stats['total_rebounds'] * 100 / ( team_stats['total_rebounds'] + team_stats['opp_total_rebounds']) # 'teamTO_perc', team_stats['teamTO_perc'] = team_stats['turnovers'] * 100 / ( team_stats['field_goal_attempts'] * .44 + team_stats['free_throw_attempts'] + team_stats['turnovers']) # 'PPS', team_stats[ 'PPS'] = team_stats['points'] / team_stats['field_goal_attempts'] # 'teamSTL/TO', team_stats['teamSTL/TO'] = team_stats['steals'] / team_stats['turnovers'] # pyth%13.91', # Calculation: ptsFor ^ 13.91 / (ptsFor ^ 13.91 + ptsAgnst ^ 13.91) team_stats['pyth%13.91'] = team_stats['points']**13.91 / ( team_stats['points']**13.91 + team_stats['opp_points']**13.91) # 'lpyth13.91', team_stats['lpyth13.91'] = 82 - team_stats['pyth%13.91'] * 82 #mov team_stats['mov'] = (team_stats['points'] - team_stats['opp_points']) / team_stats['games_played'] stats = team_stats.loc[team_abbr].append(last_game) stats = stats[[ 'teamPTS_pg', 'teamTO_pg', 'teamFG%_pg', 'team2P%_pg', 'team3PA_pg', 'teamTRB_perc', 'PPS', 'teamSTL/TO', 'pyth%13.91', 'lpyth13.91', 'teamTO_perc', 'mov', 'stk', 'lastTen', 'winPercent', 'homeWin_Percent', 'awayWin_Percent' ]] return stats
def total_game_points_scored_over_previous_10(abbreviation, game, year): game_number = game df2 = Schedule(abbreviation, year).dataframe df_onlylast10 = df2.iloc[(game_number - 11):(game_number-1)] return df_onlylast10.points_allowed.mean() + df_onlylast10.points_scored.mean()
def find_avg_ppg_over_last_10(abbreviation): games_played = find_games_played(abbreviation) df2 = Schedule(abbreviation).dataframe df_onlylast10 = df2.iloc[(games_played - 10):games_played] return df_onlylast10.points_scored.mean()
class TestNBASchedule: @mock.patch('requests.get', side_effect=mock_pyquery) def setup_method(self, *args, **kwargs): self.results = { 'game': 2, 'boxscore_index': '201610280NOP', 'date': 'Fri, Oct 28, 2016', 'time': '9:30p', 'datetime': datetime(2016, 10, 28), 'location': AWAY, 'opponent_abbr': 'NOP', 'opponent_name': 'New Orleans Pelicans', 'result': WIN, 'playoffs': False, 'points_scored': 122, 'points_allowed': 114, 'wins': 1, 'losses': 1, 'streak': 'W 1' } flexmock(Boxscore) \ .should_receive('_parse_game_data') \ .and_return(None) flexmock(Boxscore) \ .should_receive('dataframe') \ .and_return(pd.DataFrame([{'key': 'value'}])) flexmock(utils) \ .should_receive('_todays_date') \ .and_return(MockDateTime(YEAR, MONTH)) self.schedule = Schedule('GSW') def test_nba_schedule_returns_correct_number_of_games(self): assert len(self.schedule) == NUM_GAMES_IN_SCHEDULE def test_nba_schedule_returns_requested_match_from_index(self): match_two = self.schedule[1] for attribute, value in self.results.items(): assert getattr(match_two, attribute) == value def test_nba_schedule_returns_requested_match_from_date(self): match_two = self.schedule(datetime(2016, 10, 28)) for attribute, value in self.results.items(): assert getattr(match_two, attribute) == value def test_nba_schedule_dataframe_returns_dataframe(self): df = pd.DataFrame([self.results], index=['PHO']) match_two = self.schedule[1] # Pandas doesn't natively allow comparisons of DataFrames. # Concatenating the two DataFrames (the one generated during the test # and the expected one above) and dropping duplicate rows leaves only # the rows that are unique between the two frames. This allows a quick # check of the DataFrame to see if it is empty - if so, all rows are # duplicates, and they are equal. frames = [df, match_two.dataframe] df1 = pd.concat(frames).drop_duplicates(keep=False) assert df1.empty def test_nba_schedule_dataframe_extended_returns_dataframe(self): df = pd.DataFrame([{'key': 'value'}]) result = self.schedule[1].dataframe_extended frames = [df, result] df1 = pd.concat(frames).drop_duplicates(keep=False) assert df1.empty def test_nba_schedule_all_dataframe_returns_dataframe(self): result = self.schedule.dataframe.drop_duplicates(keep=False) assert len(result) == NUM_GAMES_IN_SCHEDULE assert set(result.columns.values) == set(self.results.keys()) def test_nba_schedule_all_dataframe_extended_returns_dataframe(self): result = self.schedule.dataframe_extended assert len(result) == NUM_GAMES_IN_SCHEDULE def test_no_games_for_date_raises_value_error(self): with pytest.raises(ValueError): self.schedule(datetime.now()) def test_empty_page_return_no_games(self): flexmock(utils) \ .should_receive('_no_data_found') \ .once() flexmock(utils) \ .should_receive('_get_stats_table') \ .and_return(None) schedule = Schedule('GSW') assert len(schedule) == 0 def test_game_string_representation(self): game = self.schedule[0] assert game.__repr__() == 'Tue, Oct 25, 2016 - SAS' def test_schedule_string_representation(self): expected = """Tue, Oct 25, 2016 - SAS Fri, Oct 28, 2016 - NOP Sun, Oct 30, 2016 - PHO Tue, Nov 1, 2016 - POR Thu, Nov 3, 2016 - OKC Fri, Nov 4, 2016 - LAL Mon, Nov 7, 2016 - NOP Wed, Nov 9, 2016 - DAL Thu, Nov 10, 2016 - DEN Sun, Nov 13, 2016 - PHO Wed, Nov 16, 2016 - TOR Fri, Nov 18, 2016 - BOS Sat, Nov 19, 2016 - MIL Mon, Nov 21, 2016 - IND Wed, Nov 23, 2016 - LAL Fri, Nov 25, 2016 - LAL Sat, Nov 26, 2016 - MIN Mon, Nov 28, 2016 - ATL Thu, Dec 1, 2016 - HOU Sat, Dec 3, 2016 - PHO Mon, Dec 5, 2016 - IND Wed, Dec 7, 2016 - LAC Thu, Dec 8, 2016 - UTA Sat, Dec 10, 2016 - MEM Sun, Dec 11, 2016 - MIN Tue, Dec 13, 2016 - NOP Thu, Dec 15, 2016 - NYK Sat, Dec 17, 2016 - POR Tue, Dec 20, 2016 - UTA Thu, Dec 22, 2016 - BRK Fri, Dec 23, 2016 - DET Sun, Dec 25, 2016 - CLE Wed, Dec 28, 2016 - TOR Fri, Dec 30, 2016 - DAL Mon, Jan 2, 2017 - DEN Wed, Jan 4, 2017 - POR Fri, Jan 6, 2017 - MEM Sun, Jan 8, 2017 - SAC Tue, Jan 10, 2017 - MIA Thu, Jan 12, 2017 - DET Mon, Jan 16, 2017 - CLE Wed, Jan 18, 2017 - OKC Fri, Jan 20, 2017 - HOU Sun, Jan 22, 2017 - ORL Mon, Jan 23, 2017 - MIA Wed, Jan 25, 2017 - CHO Sat, Jan 28, 2017 - LAC Sun, Jan 29, 2017 - POR Wed, Feb 1, 2017 - CHO Thu, Feb 2, 2017 - LAC Sat, Feb 4, 2017 - SAC Wed, Feb 8, 2017 - CHI Fri, Feb 10, 2017 - MEM Sat, Feb 11, 2017 - OKC Mon, Feb 13, 2017 - DEN Wed, Feb 15, 2017 - SAC Thu, Feb 23, 2017 - LAC Sat, Feb 25, 2017 - BRK Mon, Feb 27, 2017 - PHI Tue, Feb 28, 2017 - WAS Thu, Mar 2, 2017 - CHI Sun, Mar 5, 2017 - NYK Mon, Mar 6, 2017 - ATL Wed, Mar 8, 2017 - BOS Fri, Mar 10, 2017 - MIN Sat, Mar 11, 2017 - SAS Tue, Mar 14, 2017 - PHI Thu, Mar 16, 2017 - ORL Sat, Mar 18, 2017 - MIL Mon, Mar 20, 2017 - OKC Tue, Mar 21, 2017 - DAL Fri, Mar 24, 2017 - SAC Sun, Mar 26, 2017 - MEM Tue, Mar 28, 2017 - HOU Wed, Mar 29, 2017 - SAS Fri, Mar 31, 2017 - HOU Sun, Apr 2, 2017 - WAS Tue, Apr 4, 2017 - MIN Wed, Apr 5, 2017 - PHO Sat, Apr 8, 2017 - NOP Mon, Apr 10, 2017 - UTA Wed, Apr 12, 2017 - LAL Sun, Apr 16, 2017 - POR Wed, Apr 19, 2017 - POR Sat, Apr 22, 2017 - POR Mon, Apr 24, 2017 - POR Tue, May 2, 2017 - UTA Thu, May 4, 2017 - UTA Sat, May 6, 2017 - UTA Mon, May 8, 2017 - UTA Sun, May 14, 2017 - SAS Tue, May 16, 2017 - SAS Sat, May 20, 2017 - SAS Mon, May 22, 2017 - SAS Thu, Jun 1, 2017 - CLE Sun, Jun 4, 2017 - CLE Wed, Jun 7, 2017 - CLE Fri, Jun 9, 2017 - CLE Mon, Jun 12, 2017 - CLE""" assert self.schedule.__repr__() == expected
def plot_player_game(players, season, stat, start_date=datetime.date(1900, 1, 1), end_date=datetime.date(3000, 1, 1), only_month=False, xlabel="Time", ylabel=None, scatter=True, return_type="img", cum=False): """ Uses Sportsreference Plots the graphs of players according to their performance in particular games. :param players: Basketball-reference id of a player or list of players :type players: String or list of strings :param season: The season in which the games are played :type season: Either in dashed form (2018-19) or single form (2019 means the season 2018-19) :param stat: The statistical attribute of the player to plot :type stat: String :param start_date: The date from which the data is plotted :type start_date: datetime.date format :param end_date: The date untill which data is plotted :type end_date: datetime.date format :param only_month: Wheter or not the ticks on the x-axis only contain months. (Recommended when plotting dates extending across dates more than a couple of months) :type only_month: Bool :param xlabel: The label on the x-axis on the returned plot :type xlabel: String :param ylabel: The label on the x-axis on the returned plot :type ylabel: String :param scatter: Wheter 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: Wheter results are cumulative or not :type cum: Bool """ if type(players) is not list: players = [players] player_obj = get_player_obj(players) fig, ax = plt.subplots() for player in player_obj: season = date_format(season) team = player(season).team_abbreviation sch = Schedule(team, date_format(season, format_as="single")) sch_df = sch.dataframe x = [] y = [] for index, row in sch_df.iterrows(): if start_date <= row['datetime'].date() <= end_date: box = Boxscore(index) if row['location'] == "Home": for boxplay in box.home_players: if boxplay.player_id == player.player_id: x.append(row['datetime'].date()) if cum: try: prev = y[-1] except: prev = 0 y.append(boxplay.dataframe[stat] + prev) else: y.append(boxplay.dataframe[stat]) elif row['location'] == "Away": for boxplay in box.away_players: if boxplay.player_id == player.player_id: x.append(row['datetime'].date()) if cum: try: prev = y[-1] except: prev = 0 y.append(boxplay.dataframe[stat] + prev) else: y.append(boxplay.dataframe[stat]) ax.plot(x, y, label=player.name) if scatter: ax.scatter(x, y) ax.legend() if only_month: ax.xaxis.set_major_locator(MonthLocator()) ax.xaxis.set_major_formatter(DateFormatter("%y-%m")) fig.autofmt_xdate() ax.set_xlabel(xlabel) if ylabel == None: ylabel = stat ax.set_ylabel(ylabel) return return_plot(stat, fig, ax, return_type)
from sportsreference.nba.schedule import Schedule por_schedule = Schedule('POR') for game in por_schedule: print(game.date) print(game.time)
import pandas as pd from sportsreference.nba.teams import Teams from sportsreference.nba.schedule import Schedule import os from config import config # For a team: gsw = Schedule("GSW", year=2018) x = gsw.dataframe teams = Teams() teams.dataframes teams = Teams() for team in teams: print(team.name) for team in teams: schedule = team.schedule # Returns a Schedule instance for each team # Returns a Pandas DataFrame of all metrics for all game Boxscores for # a season. df = team.schedule.dataframe_extended # Read in the scraped data df = pd.read_csv("~/Desktop/historical_dataframe.csv") # 1) I can tack on the abbreviations (which I have for every year up through Chicago)
def run(self, ngrams, vars, args): response = requests.get( "https://stats.nba.com/js/data/playermovement/NBA_Player_Movement.json" ) test = response.json() trades = [ x for x in test['NBA_Player_Movement']['rows'] if x['Transaction_Type'] == 'Trade' ] trade = trades[0]['TRANSACTION_DESCRIPTION'] receivingTeam = trade.split(' received')[0] givingTeam = trade.split('from ')[1] givingTeam = givingTeam[:-1] player = trade.split('received ')[1] player = player.split('from')[0] playerList = player.split(' ') role = playerList[0] playerList.pop(0) player = ' '.join(playerList) #Assume input is team name, all lowercase if vars['receivingTeam'] == "Atlanta Hawks" or vars[ 'receivingTeam'] == "Atlanta" or vars[ 'receivingTeam'] == "Hawks": team = 'ATL' elif vars['receivingTeam'] == "Boston Celtics" or vars[ 'receivingTeam'] == "Boston" or vars[ 'receivingTeam'] == "Celtics": team = 'BOS' elif vars['receivingTeam'] == "Brooklyn Nets" or vars[ 'receivingTeam'] == "Brooklyn" or vars[ 'receivingTeam'] == "Nets": team = 'BKN' elif vars['receivingTeam'] == "Charlotte Hornets" or vars[ 'receivingTeam'] == "Charlotte" or vars[ 'receivingTeam'] == "Hornets": team = 'CHA' elif vars['receivingTeam'] == "Chicago Bulls" or vars[ 'receivingTeam'] == "Chicago" or vars[ 'receivingTeam'] == "Bulls": team = 'CHI' elif vars['receivingTeam'] == "Cleveland Cavaliers" or vars[ 'receivingTeam'] == "Cleveland" or vars[ 'receivingTeam'] == "Cavaliers": team = 'CLE' elif vars['receivingTeam'] == "Dallas Mavericks" or vars[ 'receivingTeam'] == "Dallas" or vars[ 'receivingTeam'] == "Mavericks": team = 'DAL' elif vars['receivingTeam'] == "Denver Nuggets" or vars[ 'receivingTeam'] == "Denver" or vars[ 'receivingTeam'] == "Nuggets": team = 'DEN' elif vars['receivingTeam'] == "Detroit Pistons" or vars[ 'receivingTeam'] == "Detroit" or vars[ 'receivingTeam'] == "Pistons": team = 'DET' elif vars['receivingTeam'] == "Golden State Warriors" or vars[ 'receivingTeam'] == "GSW" or vars[ 'receivingTeam'] == "Warriors": team = 'GSW' elif vars['receivingTeam'] == "Houston Rockets" or vars[ 'receivingTeam'] == "Houston" or vars[ 'receivingTeam'] == "Rockets": team = 'HOU' elif vars['receivingTeam'] == "Indiana Pacers" or vars[ 'receivingTeam'] == "Indiana" or vars[ 'receivingTeam'] == "Pacers": team = 'IND' elif vars['receivingTeam'] == "LA Clippers" or vars[ 'receivingTeam'] == "Clippers": team = 'LAC' elif vars['receivingTeam'] == "Los Angeles Lakers" or vars[ 'receivingTeam'] == "Lakers": team = 'LAL' elif vars['receivingTeam'] == "Memphis Grizzlies" or vars[ 'receivingTeam'] == "Memphis" or vars[ 'receivingTeam'] == "Grizzlies": team = 'MEM' elif vars['receivingTeam'] == "Miami Heat" or vars[ 'receivingTeam'] == "Miami": team = 'MIA' elif vars['receivingTeam'] == "Milwaukee Bucks" or vars[ 'receivingTeam'] == "Milwaukee" or vars[ 'receivingTeam'] == "Bucks": team = 'MIL' elif vars['receivingTeam'] == "Minnesota Timberwolves" or vars[ 'receivingTeam'] == "Minnesota" or vars[ 'receivingTeam'] == "Timberwolves": team = 'MIN' elif vars['receivingTeam'] == "New Orleans Pelicans" or vars[ 'receivingTeam'] == "Pelicans" or vars[ 'receivingTeam'] == "NoLa": team = 'NOP' elif vars['receivingTeam'] == "New York Knicks" or vars[ 'receivingTeam'] == "Knicks" or vars['receivingTeam'] == "NY": team = 'NYK' elif vars['receivingTeam'] == "Oklahoma City Thunder" or vars[ 'receivingTeam'] == "Thunder" or vars['receivingTeam'] == "OKC": team = 'OKC' elif vars['receivingTeam'] == "Orlando Magic" or vars[ 'receivingTeam'] == "Orlando" or vars[ 'receivingTeam'] == "Magic": team = 'ORL' elif vars['receivingTeam'] == "Philadelphia SeventySixers" or vars[ 'receivingTeam'] == "Philly" or vars[ 'receivingTeam'] == "SeventySixers" or vars[ 'receivingTeam'] == "76ers": team = 'PHI' elif vars['receivingTeam'] == "Phoenix Suns" or vars[ 'receivingTeam'] == "Phoenix" or vars[ 'receivingTeam'] == "Suns": team = 'PHX' elif vars['receivingTeam'] == "Portland Trail Blazers" or vars[ 'receivingTeam'] == vars['receivingTeam'] == "Portland" or vars[ 'receivingTeam'] == "Trail Blazers": team = 'POR' elif vars['receivingTeam'] == "Sacramento Kings" or vars[ 'receivingTeam'] == "Sacramento" or vars[ 'receivingTeam'] == "Kings": team = 'SAC' elif vars['receivingTeam'] == "San Antonio Spurs" or vars[ 'receivingTeam'] == "San Antonio" or vars[ 'receivingTeam'] == "Spurs": team = 'SAS' elif vars['receivingTeam'] == "Toronto Raptors" or vars[ 'receivingTeam'] == "Toronto" or vars[ 'receivingTeam'] == "Raptors": team = 'TOR' elif vars['receivingTeam'] == "Utah Jazz" or vars[ 'receivingTeam'] == "Utah" or vars['receivingTeam'] == "Jazz": team = 'UTA' elif vars['receivingTeam'] == "Washington Wizards" or vars[ 'receivingTeam'] == "Washington" or vars[ 'receivingTeam'] == "Wizards": team = 'WAS' else: #error handling? idk if needed return "I didn't get that" wins = 0 losses = 0 teamSchedule = Schedule(team) for game in teamSchedule: if game.result == 'Win': wins += 1 else: losses += 1 return "The {} are currently {} and {} ".format( vars['receivingTeam'], wins, losses)
async def nba_schedule(ctx, a): #todo - convert to uppercase and regex check for 3characters, print error if wrong team_schedule = Schedule(a) for game in team_schedule: await ctx.send( (game.date, game.result, game.opponent_abbr, game.boxscore_index))
def team_record(abbr): wins = str([game.wins for game in Schedule(abbr) if game.wins][-1]) losses = str([game.losses for game in Schedule(abbr) if game.losses][-1]) return "-".join([wins, losses])