nhlscrapi.games package — nhlscrapi documentation

# nhlscrapi.games package

## Submodules

## nhlscrapi.games.game module

class `nhlscrapi.games.game.` `Game`(game_key=None, cum_stats={})

  Bases: `object`

  This the primary interface to the collection of summary reports associated with every game. The supported reports include `PlayByPlay`, `TOI`, `Rosters`, and `FaceOffComparison`.

  Reports can be either lazy loaded at time of property calls or all loaded at once by calling `load_all()`.

  Parameters: | game_key – either object `GameKey` or (season, game_type, game_num) tuple cum_stats – dict, values are of type `AccumulateStats` to be collected in play-by-play
  Example: |

      #
      # example: using the Game object
      #
      from nhlscrapi.games.game import GameKey, Game
      from nhlscrapi.games.cumstats import Corsi

      gk = GameKey(2015, 2, 224)
      g = Game(gk, { 'Corsi': Corsi() })

      # since play-by-play hasn't yet been loaded the RTSS report will
      # be parsed and the Corsi computed for each team
      print(g.cum_stats['Corsi'].share())

      # load the rest of the reports
      g.load_all()

      # report back the game's linesman
      print(g.linesman)

  `away_coach`

    Returns: | coach for the away team
    Return type: | string

  `away_fo_summ`

    Returns: | away face off summary
    Return type: | dict keyed by player number

  `away_skaters`

    Returns: | the skaters that dressed for the away team
    Return type: | dict keyed by player number

  `away_toi`

    Returns: | TOI shift summary for skaters on the away team
    Return type: | dict keyed by player number, value `ShiftSummary`

  `cum_stats`

    Returns: | the computed cumulative stats of `AccumulateStats` from play-by-play
    Return type: | dict passed to ctor, values are type

  `home_coach`

    Returns: | coach for the home team
    Return type: | string

  `home_fo_summ`

    Returns: | home face off summary
    Return type: | dict keyed by player number

  `home_skaters`

    Returns: | the skaters that dressed for the home team
    Return type: | dict keyed by player number

  `home_toi`

    Returns: | TOI shift summary for skaters on the home team
    Return type: | dict keyed by player number, value `ShiftSummary`

  `linesman`

    Returns: | the linesman for the game
    Return type: | dict `{ number: 'name' }`

  `load_all`()

    Force all reports to be loaded and parsed instead of lazy loading on demand.

    Returns: | `self` or `None` if load fails

  `matchup`

    Return the game meta information displayed in report banners including team names, final score, game date, location, and attendance. Data format is

        {
            'home': home,
            'away': away,
            'final': final,
            'attendance': att,
            'date': date,
            'location': loc
        }

    Returns: | matchup banner info
    Return type: | dict

  `plays`

    Returns: | the plays from the game
    Return type: | list

  `refs`

    Returns: | refs for the game
    Return type: | dict `{ number: 'name' }`

class `nhlscrapi.games.game.` `GameKey`(season=2008, game_type=2, game_num=1, key_tup=None)

  Bases: `object`

  Unique identifier for a game. See constants for acceptable seasons and game counts. The key can be initialized by setting key_tup or the set of season, game type and game number.

  Parameters: | season – the season number denoted by year season ends game_type – enum, (1) pre season, (2) regular season or (3) playoffs game_num – the index number of the game key_tup – tuple (season, game_type, game_num)

  `game_type`

    Code indicating pre season (1), regular season (2) or playoffs (3)

    Returns: | int

  `season`

    Season of the keyed game. Season year is denoted by when the season ends. See constants for acceptable range of seasons considered. Not all years have supported summary reports ... or any reports at all.

    Returns: | int

  `to_tuple`()

    Return tuple version of the game key

    Returns: | tuple(season, game_type, game_num)

## nhlscrapi.games.playbyplay module

class `nhlscrapi.games.playbyplay.` `Play`(play_num=0, period=0, strength=0, time={'sec': 0, 'min': 20}, vis_on_ice={}, home_on_ice={}, event=None)

  Bases: `object`

  Contains base level of state info about a given play.

  `event` = None

    An object that inherits from `Event` that contains other specifics related to the given type of play

  `home_on_ice` = None

    Home skaters on the ice. `{ num: [position, name] }`

  `period` = None

    Current period

  `play_num` = None

    Number of player who made the play

  `strength` = None

    Enum of type `Strength` indicating either even strength, shorthanded, or power play

  `time` = None

    Time remaining in the period

  `vis_on_ice` = None

    Visiting skaters on the ice. `{ num: [position, name] }`

class `nhlscrapi.games.playbyplay.` `PlayByPlay`(game_key, cum_stats={}, init_cs_teams=True)

  Bases: `nhlscrapi.games.repscrwrap.RepScrWrap`

  Aggregator of `Play` objects that maintains the play-by-play data for a given game. Allows for custom stats of type `AccumulateStats` to be computed for the game.

  Example: |

      from nhlscrapi.games.game import GameKey
      from nhlscrapi.games.cumstats import ShotCt
      from nhlscrapi.games.playbyplay import PlayByPlay

      # define the game of interest and a stat accumulator
      pbp = PlayByPlay(
          game_key=GameKey(2015, 3, 224),
          cum_stats={ 'ShotCount': ShotCt() }
      )

      # compute and print results
      shot_cts = pbp.compute_stats()['ShotCount']
      print('Final Score:     {}'.format(shot_cts.total))

  `compute_stats`()

    Compute the stats defined in `self.cum_stats`.

    Returns: | collection of all computed `AccumulateStats`
    Return type: | dict

  `cum_stats` = None

    Dictionary of `AccumulateStats` to be computed

  `init_cs_teams` = None

    Boolean, (default) True if the `AccumulateStats` objects should have team names initialized.

  `plays`

    List of `Play` objects.

`nhlscrapi.games.playbyplay.` `Strength`

  Enum indicating play strength.

  alias of `Enum`

## nhlscrapi.games.rosters module

class `nhlscrapi.games.rosters.` `Rosters`(game_key)

  Bases: `nhlscrapi.games.repscrwrap.RepScrWrap`

  Roster report contains all players that dressed for the game, healthy scratches, coaches and officials. The roster for either home or away is returned as

      {
          player_num: {
              'pos': 'position',
              'name': 'player name'
          {
      }

  Parameters: | game_key – unique game identifier of type `GameKey`

  `away_coach`

    Returns: | the name of the away coach
    Return type: | string

  `away_scratches`

    Returns: | all away healthy scratches
    Returns: | dict

  `away_skaters`

    Returns: | all away skaters
    Return type: | dict

  `home_coach`

    Returns: | the name of the home coach
    Return type: | string

  `home_scratches`

    Returns: | all home healthy scratches
    Returns: | dict

  `home_skaters`

    Returns: | all home skaters
    Return type: | dict

  `linesman`

    Returns: | the linesman for the game
    Return type: | dict, `{ num: 'lm_name' }`

  `refs`

    Returns: | the refs for the game
    Return type: | dict, `{ num: 'ref_name' }`

## nhlscrapi.games.toi module

class `nhlscrapi.games.toi.` `ShiftSummary`(player_num=0, player_name={}, shifts=[], by_period={})

  Bases: `object`

  Player’s shift summary

  `by_period` = None

    Summary table by period in the form

        {
            'period': period_num,
            'shifts': shift_count,
            'avg': { 'min': min, 'sec': sec },
            'toi': { 'min': min, 'sec': sec },
            'ev_toi': { 'min': min, 'sec': sec },
            'pp_toi': { 'min': min, 'sec': sec },
            'sh_toi': { 'min': min, 'sec': sec }
        }

  `game_summ`

    Time on ice summary for the game

    Returns: | dict, same form as `self.by_period`

  `player_name` = None

    Player’s name: `{ 'first': '', 'last': '' }`

  `player_num` = None

    The number of the player

  `shifts` = None

    List of all shifts in the form

        [
            {
                'shift_num': shift_num,
                'period': period_num,
                'start': start_time     # (elapsed)
                'end': end_time         # (elapsed)
                'dur': length_of_shift,
                'event': EventType.Goal or EventType.Penalty
            }
        ]

class `nhlscrapi.games.toi.` `TOI`(game_key)

  Bases: `nhlscrapi.games.repscrwrap.RepScrWrap`

  Time on ice summary report. Produces the time on ice per shift by player for both home and away.

  Parameters: | game_key – unique game identifier of type `GameKey`

  `all_toi`

    Return

    Returns: | the `scrapr.toi.ShiftSummary` by player for the home/away team
    Return type: | dict `{ 'home/away': { player_num: shift_summary_obj } }`

  `away_shift_summ`

    Returns: | `ShiftSummary` by player for the away team
    Return type: | dict `{ player_num: shift_summary_obj }`

  `home_shift_summ`

    Returns: | `ShiftSummary` by player for the home team
    Return type: | dict `{ player_num: shift_summary_obj }`

  `load_all`()

    Loads all parts of the report.

    Returns: | `self` or `None` if load fails

## nhlscrapi.games.faceoffcomp module

class `nhlscrapi.games.faceoffcomp.` `FaceOffComparison`(game_key)

  Bases: `nhlscrapi.games.repscrwrap.RepScrWrap`

  Face-off Comparison and summary report. Produces the by player and head-to-head matchup face off totals by zone and overall. For either home or away the full summary data takes the following form

      {
          player_num: {
              'off/def/neut/all': { 'won': won, 'total': total }
          }
      }

  Parameters: | game_key – unique game identifier of type `GameKey`

  `away_fo`

    Property that returns the full by player face-off summary for the away team.

    Returns: | dict keyed by player num

  `by_zone`

    Returns the faceoff win/total breakdown by zone for home and away as

        { 'home/away': {
            'off/def/neut/all': { 'won': won, 'total': total }
            }
        }

    Returns: | dict

  `fo_pct`

    Get the by team overall face-off win %.

    Returns: | dict, `{ 'home': %, 'away': % }`

  `fo_pct_by_zone`

    Get the by team face-off win % by zone. Format is

    Returns: | dict `{ 'home/away': { 'off/def/neut': % } }`

  `head_to_head`(home_num, away_num)

    Return the head-to-head face-off outcomes between two players. If the matchup didn’t happen, `{ }` is returned.

    Parameters: | home_num – the number of the home team player away_num – the number of the away team player
    Returns: | dict, either `{ }` or the following

        {
            'home/away': {
                'off/def/neut/all': { 'won': won, 'total': total }
            }
        }

  `home_fo`

    Property that returns the full by player face-off summary for the home team.

    Returns: | dict keyed by player num

  `team_totals`

    Returns the overall faceoff win/total breakdown for home and away as

    Returns: | dict, `{ 'home/away': { 'won': won, 'total': total } }`

## nhlscrapi.games.cumstats module

class `nhlscrapi.games.cumstats.` `AccumulateStats`

  Bases: `object`

  Base class for accumulator classes. These classes keep tallies of specified events and are updated each time a play from `PlayByPlay` is processed. Examples include `ShotCt` and `Score`. This class is not intended to be used directly.

  `initialize_teams`(teams)
  `update`(play)

    Update the accumulator with the current play

    Returns: | new tally, `{ 'period': per, 'time': clock, 'team': cumul, 'play': play }`

class `nhlscrapi.games.cumstats.` `Corsi`

  Bases: `nhlscrapi.games.cumstats.EvenStShotAttCt`

  Tallies even strength shots on goal for each team. Increments if

  > - the play event inherits from `Shot`
  > - play happened at even strength

  Defined more for convention/nostalgia. Same as `EvenStShotAttCt`

  `share`()

    The Cori-share (% of shot attempts) for each team

    Returns: | dict, `{ 'home_name': %, 'away_name': % }`

class `nhlscrapi.games.cumstats.` `EvenStShotAttCt`

  Bases: `nhlscrapi.games.cumstats.ShotEventTallyBase`

  Tallies even strength shots on goal for each team. Increments if

  > - the play event inherits from `ShotAttempt`
  > - play happened at even strength

class `nhlscrapi.games.cumstats.` `EvenStShotCt`

  Bases: `nhlscrapi.games.cumstats.ShotEventTallyBase`

  Tallies even strength shots on goal for each team. Increments if

  > - the play event inherits from `Shot`
  > - play happened at even strength

class `nhlscrapi.games.cumstats.` `Fenwick`

  Bases: `nhlscrapi.games.cumstats.ShotEventTallyBase`

  Tallies if a goal is scored. Also tracks shootout goals. Increments if

  - the play event inherits from `ShotAttempt`
  - the play event does not inherit from `Block`
  - play happened at even strength
  `initialize_teams`(teams)
  `share`()

    Returns: | The Fenwick-share (% of unblocked even strength shot attempts) for each team
    Return type: | dict, `{ 'home_name': %, 'away_name': % }`

  `update`(play)

class `nhlscrapi.games.cumstats.` `Score`

  Bases: `nhlscrapi.games.cumstats.ShotEventTallyBase`

  Tallies if a goal is scored. Also tracks shootout goals. Increments if

  - the play event inherits from `Goal`
  - the play event inherits from `ShootOutGoal`
  `initialize_teams`(teams)
  `update`(play)

class `nhlscrapi.games.cumstats.` `ShootOut`

  Bases: `nhlscrapi.games.cumstats.ShotEventTallyBase`

  Tallies shootout goals. Increments if

  > - the play event inherits from `ShootOutGoal`

class `nhlscrapi.games.cumstats.` `ShotAttemptCt`

  Bases: `nhlscrapi.games.cumstats.ShotEventTallyBase`

  Tallies even strength shots on goal for each team. Increments if

  > - the play event inherits from `ShotAttempt`

class `nhlscrapi.games.cumstats.` `ShotCt`

  Bases: `nhlscrapi.games.cumstats.ShotEventTallyBase`

  Tallies shots on goal for each team. Increments if

  > - the play event inherits from `Shot`

class `nhlscrapi.games.cumstats.` `ShotEventTallyBase`(count_play)

  Bases: `nhlscrapi.games.cumstats.TeamIncrementor`

  Base class for all shot attempt based events

class `nhlscrapi.games.cumstats.` `TeamIncrementor`(get_team=None, count_play=None)

  Bases: `nhlscrapi.games.cumstats.AccumulateStats`

  Accumulator base class for team vs team stats such as score, shot count et c.

  Parameters: | get_team – function, takes a play and returns the team associated with it count_play – function, takes a play and returns True if it is a tally for the given accumulator’s definition.

  `tally` = None

    List of plays that lead to tallies, i.e. increments of the stat accumulator. E.g. a goal or shot.

  `update`(play)

    Update the accumulator with the current play

    Returns: | new tally
    Return type: | dict, `{ 'period': per, 'time': clock, 'team': cumul, 'play': play }`

## nhlscrapi.games.events module

class `nhlscrapi.games.events.` `Block`

  Bases: `nhlscrapi.games.events.ShotAttempt`

class `nhlscrapi.games.events.` `Event`(event_type=0, desc='')

  Bases: `object`

  Base class for event codes in the RTSS play-by-play reports

  `desc` = None

    The RTSS description of the play.

  `event_type` = None

    The `EventType` enum values corresponding to the event.

class `nhlscrapi.games.events.` `EventFactory`

  Bases: `object`

  Factory for creating event objects corresponding to the different types of plays (events) in RTSS play by play data. Constructor selected based upon the event enum `EventType.Events` passed.

  static `Create`(event_type)

    Factory method creates objects derived from :py:class`.Event` with class name matching the :py:class`.EventType`.

    Parameters: | event_type – number for type of event
    Returns: | constructed event corresponding to `event_type`
    Return type: | `Event`

  `event_list` = [<class 'nhlscrapi.games.events.Event'>, <class 'nhlscrapi.games.events.ShotAttempt'>, <class 'nhlscrapi.games.events.Shot'>, <class 'nhlscrapi.games.events.Goal'>, <class 'nhlscrapi.games.events.Miss'>, <class 'nhlscrapi.games.events.Block'>, <class 'nhlscrapi.games.events.Hit'>, <class 'nhlscrapi.games.events.FaceOff'>, <class 'nhlscrapi.games.events.Stoppage'>, <class 'nhlscrapi.games.events.PeriodEnd'>, <class 'nhlscrapi.games.events.GameEnd'>, <class 'nhlscrapi.games.events.ShootOutEnd'>, <class 'nhlscrapi.games.events.Penalty'>, <class 'nhlscrapi.games.events.Turnover'>, <class 'nhlscrapi.games.events.Takeaway'>, <class 'nhlscrapi.games.events.Giveaway'>, <class 'nhlscrapi.games.events.ShootOutAtt'>, <class 'nhlscrapi.games.events.ShootOutGoal'>]

    List of available events loaded dynamically by following the subclass structure of `Event`.

`nhlscrapi.games.events.` `EventType`

  Enum indicating event type.

  alias of `Enum`

class `nhlscrapi.games.events.` `FaceOff`

  Bases: `nhlscrapi.games.events.Event`

class `nhlscrapi.games.events.` `GameEnd`

  Bases: `nhlscrapi.games.events.Stoppage`

class `nhlscrapi.games.events.` `Giveaway`

  Bases: `nhlscrapi.games.events.Turnover`

class `nhlscrapi.games.events.` `Goal`

  Bases: `nhlscrapi.games.events.Shot`

class `nhlscrapi.games.events.` `Hit`

  Bases: `nhlscrapi.games.events.Event`

class `nhlscrapi.games.events.` `Miss`

  Bases: `nhlscrapi.games.events.ShotAttempt`

class `nhlscrapi.games.events.` `Penalty`

  Bases: `nhlscrapi.games.events.Event`

class `nhlscrapi.games.events.` `PeriodEnd`

  Bases: `nhlscrapi.games.events.Stoppage`

class `nhlscrapi.games.events.` `ShootOutAtt`(event_type=12)

  Bases: `nhlscrapi.games.events.Event`

class `nhlscrapi.games.events.` `ShootOutEnd`

  Bases: `nhlscrapi.games.events.Stoppage`

class `nhlscrapi.games.events.` `ShootOutGoal`

  Bases: `nhlscrapi.games.events.ShootOutAtt`

class `nhlscrapi.games.events.` `Shot`

  Bases: `nhlscrapi.games.events.ShotAttempt`

class `nhlscrapi.games.events.` `ShotAttempt`(event_type=1)

  Bases: `nhlscrapi.games.events.Event`

  `dist` = None

    Distance of shot in feet

  `is_penalty_shot` = None

    Flag indicating if it was a penalty shot

  `shooter` = None

    Shooter info `{ 'team': team, 'name': name, 'num': num }`

  `shot_type` = None

    Description of shot, e.g. Wrist Shot, et c

class `nhlscrapi.games.events.` `Stoppage`(event_type=11)

  Bases: `nhlscrapi.games.events.Event`

class `nhlscrapi.games.events.` `Takeaway`

  Bases: `nhlscrapi.games.events.Turnover`

class `nhlscrapi.games.events.` `Turnover`(to_type=0)

  Bases: `nhlscrapi.games.events.Event`

  Base class for Takeaway and Giveaway events. Not meant to be used directly

  class `TOType`
    `Giveaway` = 1
    `Takeaway` = 0
  `Turnover.` `turnover_type`

## nhlscrapi.games.gamesummary module

## nhlscrapi.games.plays module

## nhlscrapi.games.repscrwrap module

class `nhlscrapi.games.repscrwrap.` `RepScrWrap`(game_key, rep_reader)

  Bases: `object`

  Lazy matchup reader base. Reports can be read in pieces. Only need to read matchup on read of first part. Serves as the base class for all wrappers of report scrapers.

  Parameters: | game_key – `GameKey` of the game being loaded rep_reader – object of type `nhlscrapi.scrapr.ReportLoader`

  `game_key` = None

    Game key identifier of type `GameKey`

  `load_all`()

    Loads all parts of the report.

    Returns: | `self` or `None` if load fails

  `matchup`

    Return the game meta information displayed in report banners including team names, final score, game date, location, and attendance. Data format is

        {
            'home': home,
            'away': away,
            'final': final,
            'attendance': att,
            'date': date,
            'location': loc
        }

    Returns: | matchup banner info
    Return type: | dict

`nhlscrapi.games.repscrwrap.` `dispatch_loader`(scraper, loader_name)

  Decorator that enforces one time loading for scrapers. The one time loading is applied to partial loaders, e.g. only parse and load the home team roster once. This is not meant to be used directly.

  Parameters: | scraper – property name (string) containing an object of type `scrapr.ReportLoader` loader_name – name of method that does the scraping/parsing
  Returns: | function wrapper

## Module contents