Ejemplo n.º 1
0
    def test_toi_shift_summary(self):
        from nhlscrapi.games.game import GameKey
        from nhlscrapi.games.toi import TOI
       
        toi = TOI(game_key=GameKey(2015,3,224))  # 2015, playoffs (3), NYR/WSH game 3 (game 224)

        try:
            toi.load_all()
        except Exception as e:
            self.assertEqual(0, 1, 'Loading error: {0}'.format(e))
        
        def get_most(shift_d, ex):
            return sorted(
                ((pn, sh) for pn, sh in shift_d.items() if pn not in ex),
                key=lambda k: -(k[1].game_summ['toi']['min']*60+k[1].game_summ['toi']['sec'])
            )[0]
            
        # players with most TOI excluding goalies
        # for home team, exclude number 70: Holty
        most_home_num, most_home_summ = get_most(toi.home_shift_summ, [70])
        # for away, exclude number 30: Lundqvist
        most_away_num, most_away_summ = get_most(toi.away_shift_summ, [30])
            
        # niskanen played 23:19
        self.assertEqual(most_home_num, 2)
        self.assertEqual(most_home_summ.game_summ['toi'], { 'min': 23, 'sec': 19 })
        
        # mcdonagh played 23:52
        self.assertEqual(most_away_num, 27)
        self.assertEqual(most_away_summ.game_summ['toi'], { 'min': 23, 'sec': 52 })
Ejemplo n.º 2
0
def build_rosters(session):
    for year in range(2008, 2018):
        game_num = 1
        while 1:
            game_key = GameKey(year, GameType.Regular, game_num)

            game = Game(game_key)

            if game.away_coach is None:
                break

            print('Working game {0}'.format(game_key.to_tuple()))

            _build_roster(session, game_key)

            game_num += 1

    session.commit()
def point_counter(start, end):
    season = 2010
    game_type = GameType.Regular
    san_jose = 'SAN JOSE SHARKS'

    csv_file = open('joe_thornton_points_summary.csv', 'w')
    csv_writer = csv.writer(csv_file)
    csv_writer.writerow(['Points', 'Vs_Team', 'Home/Away'])

    for i in range(start, end):
        game_num = i
        game_key = GameKey(season, game_type, game_num)

        game = Game(game_key)
        event_summary = EventSummary(game_key)

        if game.matchup is not None:
            # Check if San Jose was the home team
            if game.matchup['home'] == san_jose:
                # If the home team is San Jose assign the home_players attribute to home_players
                # This assigns a dictionary of players to home_players
                home_players = event_summary.home_players

                # Check if Joe Thornton played that game by checking if his number is in the dictionary
                # His number is 19
                if 19 in home_players:
                    # Points earned in that game is within the home_players dictionary
                    points = home_players[19]['p']
                    # Setting the vs_team variable to the team the Sharks played against
                    vs_team = game.matchup['away']
                    home_or_away = 'Home'

                    csv_writer.writerow([points, vs_team, home_or_away])

            # Check if San Jose was the away team
            if game.matchup['away'] == san_jose:
                # If the away team is San Jose assign the away_players attribute to away_players
                # This assigns a dictionary of players to home_players
                away_players = event_summary.away_players

                # Check if Joe Thornton played that game by checking if his number is in the dictionary
                # His number is 19
                if 19 in away_players:
                    # Points earned in that game is within the home_players dictionary
                    points = away_players[19]['p']
                    # Setting the vs_team variable to the team the Sharks played against
                    vs_team = game.matchup['home']
                    home_or_away = 'Away'

                    csv_writer.writerow([points, vs_team, home_or_away])

    csv_file.close()
Ejemplo n.º 4
0
 def test_game(self):
     from nhlscrapi.games.game import Game, GameKey, GameType
     from nhlscrapi.games.cumstats import Score, ShotCt, EvenStShotCt, Corsi, Fenwick
         
     fin_score = { }
     try:
         
         season = 2014                                    # 2013-2014 season
         game_num = 1226                                  #
         game_type = GameType.Regular                     # regular season game
         game_key = GameKey(season, game_type, game_num)
         
         # define stat types that will be counted as the plays are parsed
         cum_stats = {
           'Score': Score(),
           'Shots': ShotCt(),
           'EvenShots': EvenStShotCt(),
           'Corsi': Corsi(),
           'Fenwick': Fenwick()
         }
         game = Game(game_key, cum_stats=cum_stats)
         
         # will call all the http reqs (bc lazy)
         fin_score = game.cum_stats['Score']
     except Exception as e:
         self.assertEqual(0, 1, 'Loading error: {0}'.format(e))
     
     # final score test
     self.assertEqual(fin_score.total, { 'OTT': 3, 'PIT': 2 }, 'Incorrect final score: {}'.format(fin_score.total))
     
     # shootout goal tally test
     test_val = fin_score.shootout.total['OTT']
     self.assertEqual(test_val, 2, 'Incorrect OTT shootout goal count: {}'.format(test_val))
     
     # shot count test
     test_val = game.cum_stats['Shots'].total
     self.assertEqual(test_val, {'PIT': 28, 'OTT': 33}, 'Invalid shot count: {}'.format(test_val))
     
     # even strength shot count test
     test_val = game.cum_stats['EvenShots'].total
     self.assertEqual(test_val, {'PIT': 22, 'OTT': 18}, 'Invalid even strength shot count: {}'.format(test_val))
     
     # even strength shot attempt (corsi) test
     test_val = game.cum_stats['Corsi'].total
     self.assertEqual(test_val, {'PIT': 36, 'OTT': 39}, 'Invalid (Corsi) shot attempt count: {}'.format(test_val))
     
     # even strength, close, shot attempts ex blocks/misses (Fenwick) test
     test_val = game.cum_stats['Fenwick'].total
     self.assertEqual(test_val, {'PIT': 30, 'OTT': 29}, 'Invalid (Fenwick) shot attempt count: {}'.format(test_val))
    def RetrieveSingleGameData(self, season, game, game_type=2):
        """
		Retrieve Data from Specified Game
		TODO: Support pulling data from playoffs and preseason
		:param season: Season the game took place in
		:param game: number of the game to retrieve
		:param game_type: Type of game that we are attempting to grab, 1 = Preseason, 2 = Regular Season,
							3 = Playoff, DEFAULT 2
		"""
        gk = GameKey(season, game_type, game)
        g = Game(gk)
        data = g.load_all()
        if g.matchup == None:
            print("Unable to get matchup")
            return False
        game_id = self.insertGameInfo(season, game, g.matchup)
        teamName = g.matchup['home']
        self.addGameDataToQueueWithTeam(teamName, g.event_summary.home_players,
                                        game_id)
        teamName = g.matchup['away']
        self.addGameDataToQueueWithTeam(teamName, g.event_summary.away_players,
                                        game_id)
        return True
Ejemplo n.º 6
0
    def test_face_off_comparison(self):
        from nhlscrapi.games.game import GameKey
        from nhlscrapi.games.faceoffcomp import FaceOffComparison

        gk = GameKey(2015, 3,
                     224)  # 2015, playoffs (3), NYR/WSH game 3 (game 224)
        foc = FaceOffComparison(gk)

        try:
            foc.load_all()
            hth = foc.head_to_head(21, 21)  # laich v stepan
        except Exception as e:
            self.assertEqual(0, 1, 'Loading error: {0}'.format(e))

        # stepan 2/4 overall
        self.assertEqual(hth['away']['all'], {'won': 2, 'total': 4})

        # laich 1/1 in the defensive zone
        self.assertEqual(hth['home']['def'], {'won': 1, 'total': 1})

        # equivalently, stepan 0/1 in offensive
        self.assertEqual(hth['away']['off'], {'won': 0, 'total': 1})

        # face off win %
        rnd = {k: round(v, 2) for k, v in foc.fo_pct.items()}
        self.assertEqual(rnd, {'home': 0.57, 'away': 0.43})

        # neut zone face off records
        self.assertEqual(foc.by_zone['away']['neut'], {'won': 10, 'total': 24})
        self.assertEqual(foc.by_zone['home']['neut'], {'won': 14, 'total': 24})

        # neut zone face off %
        self.assertEqual(round(foc.fo_pct_by_zone['away']['neut'], 2), 0.42)

        # away off/home def zone face off records
        self.assertEqual(foc.by_zone['away']['off'], {'won': 9, 'total': 23})
        self.assertEqual(foc.by_zone['home']['def'], {'won': 14, 'total': 23})
Ejemplo n.º 7
0
from nhlscrapi.games.game import Game, GameKey, GameType
from nhlscrapi.games.cumstats import Score, ShotCt, Corsi, Fenwick
import io, json
for i in range(10, 13):
    season = 2011  # 2010-2011 season
    game_num = i
    gp = 1
    game_type = GameType.Regular
    try:  # regular season game
        game_key = GameKey(season, game_type, game_num)
        print "Game Number: ", i
        # define stat types that will be counted as the plays are parsed
        cum_stats = {
            'Score': Score(),
            'Shots': ShotCt(),
            'Corsi': Corsi(),
            'Fenwick': Fenwick()
        }
        game = Game(game_key, cum_stats=cum_stats)
        print('Final         : {}'.format(game.cum_stats['Score'].total))
        print('Shootout      : {}'.format(
            game.cum_stats['Score'].shootout.total))
        print('Shots         : {}'.format(game.cum_stats['Shots'].total))
        print('EV Shot Atts  : {}'.format(game.cum_stats['Corsi'].total))
        print('Corsi         : {}'.format(game.cum_stats['Corsi'].share()))
        print('FW Shot Atts  : {}'.format(game.cum_stats['Fenwick'].total))
        print('Fenwick       : {}'.format(game.cum_stats['Fenwick'].share()))

        game.load_all()
    except KeyError:
        print "Game Doesn't exist"
Ejemplo n.º 8
0
def point_counter(start, end, team_name, season_year, player_num, file_name):
    '''
    This function creates a csv of a player's game log from the nhlscrapi.
    start - enter the number of the game you want to start getting data from
    end - enter the number of the game you want to end on
    The start/end number correspond to specific game numbers. So for example if you want
    to get data for the whole season then enter 1 for start and 1231 for end. (1230 games played in 30 team NHL season)

    team_name - Name of the player's team given as a string in all capitals and spaces included
    season_year - Enter the season year as a number using the year that season ended on.
    For example, for the 2009-2010 season you would enter 2010.
    player_num - Enter the number of player
    file_name - Enter in a string of what you want the output file name to be.
    For example, 'red.csv'
    '''
    season = season_year
    game_type = GameType.Regular
    team = team_name
    file = file_name

    csv_file = open(file, 'w')
    csv_writer = csv.writer(csv_file)
    csv_writer.writerow(['Points', 'Vs_Team', 'Home/Away'])

    for i in range(start, end):
        game_num = i
        game_key = GameKey(season, game_type, game_num)

        game = Game(game_key)
        event_summary = EventSummary(game_key)

        if game.matchup is not None:
            if game.matchup['home'] == team:
                # If the home team is the supplied team, assign the home_players attribute to home_players
                # This assigns a dictionary of players to home_players
                home_players = event_summary.home_players

                # Check if the player played in said game by using his number(player_num)
                if player_num in home_players:
                    # Points earned in that game is within the home_players dictionary
                    points = home_players[player_num]['p']
                    # Setting the vs_team variable to the opponent
                    vs_team = game.matchup['away']
                    home_or_away = 'Home'

                    csv_writer.writerow([points, vs_team, home_or_away])

            if game.matchup['away'] == team:
                # If the away team is is the supplied team, assign the away_players attribute to away_players
                # This assigns a dictionary of players to home_players
                away_players = event_summary.away_players

                # Check if the player played in said game by using his number(player_num)
                if player_num in away_players:
                    # Points earned in that game is within the home_players dictionary
                    points = away_players[player_num]['p']
                    # Setting the vs_team variable to the opponent
                    vs_team = game.matchup['home']
                    home_or_away = 'Away'

                    csv_writer.writerow([points, vs_team, home_or_away])

    csv_file.close()