Beispiel #1
0
    def setup_method(self, *args, **kwargs):
        self.results = {
            'week': 2,
            'boxscore_index': '201709170nor',
            'day': 'Sun',
            'date': 'September 17',
            'type': REGULAR_SEASON,
            'datetime': datetime(2017, 9, 17, 0, 0),
            'result': WIN,
            'overtime': 0,
            'location': AWAY,
            'opponent_abbr': 'NOR',
            'opponent_name': 'New Orleans Saints',
            'points_scored': 36,
            'points_allowed': 20,
            'pass_completions': 30,
            'pass_attempts': 39,
            'pass_yards': 436,
            'pass_touchdowns': 3,
            'interceptions': 0,
            'times_sacked': 2,
            'yards_lost_from_sacks': 11,
            'pass_yards_per_attempt': 11.2,
            'pass_completion_rate': 76.9,
            'quarterback_rating': 138.4,
            'rush_attempts': 31,
            'rush_yards': 119,
            'rush_yards_per_attempt': 3.8,
            'rush_touchdowns': 1,
            'field_goals_made': 3,
            'field_goals_attempted': 3,
            'extra_points_made': 3,
            'extra_points_attempted': 4,
            'punts': 3,
            'punt_yards': 111,
            'third_down_conversions': 6,
            'third_down_attempts': 12,
            'fourth_down_conversions': 0,
            'fourth_down_attempts': 0,
            'time_of_possession': '35:06'
        }
        flexmock(utils) \
            .should_receive('_todays_date') \
            .and_return(MockDateTime(YEAR, MONTH))
        flexmock(Boxscore) \
            .should_receive('_parse_game_data') \
            .and_return(None)
        flexmock(Boxscore) \
            .should_receive('dataframe') \
            .and_return(pd.DataFrame([{'key': 'value'}]))

        self.schedule = Schedule('NWE')
Beispiel #2
0
def sched(name, year):
    games_print = OrderedDict()
    team_abbrev = team_dict[name]
    team_schedule = Schedule(team_abbrev, year)
    for game in team_schedule:
        games_print[game.date] = game.opponent_name
    return games_print
Beispiel #3
0
def predict_nfl_game(team1, team2):
    dataset = {}
    teams = [team1, team2]
    for num, team in enumerate(teams):
        df = NFL_Schedule(team, year=2018).dataframe
        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_default_year_reverts_to_previous_year(self,
                                                           *args,
                                                           **kwargs):
        results = {
            'week': 2,
            'boxscore_index': '201709170nor',
            'day': 'Sun',
            'date': 'September 17',
            'type': REGULAR_SEASON,
            'datetime': datetime(2017, 9, 17, 0, 0),
            'result': WIN,
            'overtime': 0,
            'location': AWAY,
            'opponent_abbr': 'NOR',
            'opponent_name': 'New Orleans Saints',
            'points_scored': 36,
            'points_allowed': 20,
            'pass_completions': 30,
            'pass_attempts': 39,
            'pass_yards': 436,
            'pass_touchdowns': 3,
            'interceptions': 0,
            'times_sacked': 2,
            'yards_lost_from_sacks': 11,
            'pass_yards_per_attempt': 11.2,
            'pass_completion_rate': 76.9,
            'quarterback_rating': 138.4,
            'rush_attempts': 31,
            'rush_yards': 119,
            'rush_yards_per_attempt': 3.8,
            'rush_touchdowns': 1,
            'field_goals_made': 3,
            'field_goals_attempted': 3,
            'extra_points_made': 3,
            'extra_points_attempted': 4,
            'punts': 3,
            'punt_yards': 111,
            'third_down_conversions': 6,
            'third_down_attempts': 12,
            'fourth_down_conversions': 0,
            'fourth_down_attempts': 0,
            'time_of_possession': '35:06'
        }
        flexmock(utils) \
            .should_receive('_find_year_for_season') \
            .and_return(2018)
        flexmock(Boxscore) \
            .should_receive('_parse_game_data') \
            .and_return(None)
        flexmock(Boxscore) \
            .should_receive('dataframe') \
            .and_return(pd.DataFrame([{'key': 'value'}]))

        schedule = Schedule('NWE')

        for attribute, value in results.items():
            assert getattr(schedule[1], attribute) == value
    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('NWE')

        assert len(schedule) == 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
Beispiel #7
0
def display_results(my_year):

    # stores the abbreviated names in a dictionary which converts abbr names to full name
    abbrevName2Name = {}

    allTeams = Teams(year=my_year)

    # walk through all the teams, saving a dictionary of abbrev name to actual team name
    for team in allTeams:
        abbrevName2Name[team.abbreviation] = team.name

    # Loop forever
    while 1:
        name = input("Team Name (l/list/q/quit/stop): ")

        # this time we convert to UPPER, because we need abbreviated name in UpperCase
        name = name.upper()

        if (name == "") or (name == "Q") or (name == "QUIT") or (name
                                                                 == "STOP"):
            break

        if (name == "L") or (name == "LIST"):
            list_team_names(my_year)
            # "continue" goes back up to run the while loop again
            continue

        try:
            allgames = Schedule(name, year=my_year)
        except:
            print("This is an unknown team or an unavaliable year")
            # "continue" goes back up to run the while loop again
            continue

        teamName = abbrevName2Name[name]
        won = 0
        lost = 0
        tie = 0

        # Walk through all the the games, keeping track of
        #    - number of wins
        #    - number of losses
        #    - number of ties
        # And print out each games result to the user

        for game in allgames:
            # if points_allowed is equal "None", then there are no more valid games in this list
            if game.points_allowed is None:
                break

            oppAbbr = game.opponent_abbr.upper()
            oppName = abbrevName2Name[oppAbbr]

            if game.result is None:
                result = "Not Played"
            else:
                result = game.result

            if game.points_scored > game.points_allowed:
                won = won + 1
            elif game.points_scored < game.points_allowed:
                lost = lost + 1
            elif game.points_scored == game.points_allowed:
                tie = tie + 1

            print("%s %4s vs %24s %2d to %2d (%s)" %
                  (teamName, result, oppName, game.points_scored,
                   game.points_allowed, game.type))

        print("Record: Wins: %d Loss: %d Ties: %d" % (won, lost, tie))
Beispiel #8
0
from sportsreference.nfl.schedule import Schedule

houston_schedule = Schedule('HOU')
for game in houston_schedule:
    print(game.date, game.points_scored, game.points_allowed)
Beispiel #9
0
class TestNFLSchedule:
    @mock.patch('requests.get', side_effect=mock_pyquery)
    def setup_method(self, *args, **kwargs):
        self.results = {
            'week': 2,
            'boxscore_index': '201709170nor',
            'day': 'Sun',
            'date': 'September 17',
            'type': REGULAR_SEASON,
            'datetime': datetime(2017, 9, 17, 0, 0),
            'result': WIN,
            'overtime': 0,
            'location': AWAY,
            'opponent_abbr': 'NOR',
            'opponent_name': 'New Orleans Saints',
            'points_scored': 36,
            'points_allowed': 20,
            'pass_completions': 30,
            'pass_attempts': 39,
            'pass_yards': 436,
            'pass_touchdowns': 3,
            'interceptions': 0,
            'times_sacked': 2,
            'yards_lost_from_sacks': 11,
            'pass_yards_per_attempt': 11.2,
            'pass_completion_rate': 76.9,
            'quarterback_rating': 138.4,
            'rush_attempts': 31,
            'rush_yards': 119,
            'rush_yards_per_attempt': 3.8,
            'rush_touchdowns': 1,
            'field_goals_made': 3,
            'field_goals_attempted': 3,
            'extra_points_made': 3,
            'extra_points_attempted': 4,
            'punts': 3,
            'punt_yards': 111,
            'third_down_conversions': 6,
            'third_down_attempts': 12,
            'fourth_down_conversions': 0,
            'fourth_down_attempts': 0,
            'time_of_possession': '35:06'
        }
        flexmock(utils) \
            .should_receive('_todays_date') \
            .and_return(MockDateTime(YEAR, MONTH))
        flexmock(Boxscore) \
            .should_receive('_parse_game_data') \
            .and_return(None)
        flexmock(Boxscore) \
            .should_receive('dataframe') \
            .and_return(pd.DataFrame([{'key': 'value'}]))

        self.schedule = Schedule('NWE')

    def test_nfl_schedule_returns_correct_number_of_games(self):
        assert len(self.schedule) == NUM_GAMES_IN_SCHEDULE

    def test_nfl_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_nfl_schedule_returns_requested_match_from_date(self):
        match_two = self.schedule(datetime(2017, 9, 17))

        for attribute, value in self.results.items():
            assert getattr(match_two, attribute) == value

    def test_nfl_schedule_dataframe_returns_dataframe(self):
        df = pd.DataFrame([self.results], index=['NWE'])

        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_nfl_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_nfl_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_nfl_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('NWE')

        assert len(schedule) == 0

    def test_game_string_representation(self):
        game = self.schedule[0]

        assert game.__repr__() == 'September 7 - KAN'

    def test_schedule_string_representation(self):
        expected = """September 7 - KAN
September 17 - NOR
September 24 - HTX
October 1 - CAR
October 5 - TAM
October 15 - NYJ
October 22 - ATL
October 29 - SDG
November 12 - DEN
November 19 - RAI
November 26 - MIA
December 3 - BUF
December 11 - MIA
December 17 - PIT
December 24 - BUF
December 31 - NYJ
January 13 - OTI
January 21 - JAX
February 4 - PHI"""

        assert self.schedule.__repr__() == expected