Пример #1
0
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
Пример #2
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)
Пример #3
0
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
Пример #4
0
def find_games_played(abbreviation):
    df1 = Schedule(abbreviation)
    counter = 0
    for game in df1:
        if (type(game.points_scored) == int):
            counter += 1
    return counter
Пример #5
0
    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')
Пример #6
0
    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
Пример #7
0
    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
Пример #9
0
    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')
Пример #10
0
    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
Пример #11
0
    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
Пример #12
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)
Пример #13
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()
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)
Пример #15
0
from sportsreference.nba.schedule import Schedule

por_schedule = Schedule('POR')
for game in por_schedule:
    print(game.date)
    print(game.time)
Пример #16
0
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 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
Пример #18
0
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)
Пример #19
0
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()
Пример #20
0
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()
Пример #21
0
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)
Пример #22
0
    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)
Пример #23
0
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))
Пример #24
0
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])