nhlscrapi.games package

Submodules

nhlscrapi.games.game module

class nhlscrapi.games.game.Game(game_key=None, cum_stats={})[source]

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
event_summary = None

The EventSummary summary

face_off_comp = None

The FaceOffComparison summary

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()[source]

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
play_by_play = None

The PlayByPlay summary

plays
Returns:the plays from the game
Return type:list
refs
Returns:refs for the game
Return type:dict { number: 'name' }
rosters = None

The Rosters summary

toi = None

The TOI summary

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

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()[source]

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)[source]

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)[source]

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()[source]

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)[source]

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={})[source]

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)[source]

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()[source]

Loads all parts of the report.

Returns:self or None if load fails

nhlscrapi.games.faceoffcomp module

class nhlscrapi.games.faceoffcomp.FaceOffComparison(game_key)[source]

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)[source]

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.eventsummary module

class nhlscrapi.games.eventsummary.EventSummary(game_key)[source]

Bases: nhlscrapi.games.repscrwrap.RepScrWrap

Event summary report. Produces the team shot/face-off summary by strength as well as the by player stats including scoring, TOI by situation et c.

Parameters:game_key – unique game identifier of type GameKey
away_fo

Away team face off summary by strength.

Returns:dict of the form
{
    'ev/pp/sh/tot': { 'won': goals, 'total': shots }
}
away_players

Property that returns the away team by player summary..

Returns:dict of the form
{
    'num': {
        'pos': pos,
        'name': { 'first': first, 'last': last },
        'g/a/p/pm/pn/pim/shifts/s/ab/ms/ht/gv/tk/bs': value
        'fo': { 'won': won, 'tot': total },
        'toi': {
            'tot/avg/pp/sh/ev': { 'min': mins, 'sec': secs }
        }
    }
}
away_shots

Property that returns the away team shot summary by situation.

Returns:dict of the form
{
    'agg': { 'ev/pp/sh/tot': { 'g': goals, 's': shots } },
    'det': { '5v5/5v4/5v3/et c': { 'g': goals, 's': shots } }
}
filter_players(pl_filter)[source]

Return the subset home and away players that satisfy the provided filter function.

Parameters:pl_filter – function that takes a by player dictionary and returns bool
Returns:dict of the form { 'home/away': { by_player_dict } }. See home_players() and away_players()
goal_scorers()[source]

Return home/away by player info for the game’s goal scorers.

Returns:dict of the form { 'home/away': { by_player_dict } }. See home_players() and away_players()
had_penalties()[source]

Return home/away by player info for players who had a penalty.

Returns:dict of the form { 'home/away': { by_player_dict } }. See home_players() and away_players()
home_fo

Home team face off summary by strength.

Returns:dict of the form
{
    'ev/pp/sh/tot': { 'won': goals, 'total': shots }
}
home_players

Property that returns the home team by player summary..

Returns:dict of the form
{
    'num': {
        'pos': pos,
        'name': { 'first': first, 'last': last },
        'g/a/p/pm/pn/pim/shifts/s/ab/ms/ht/gv/tk/bs': value
        'fo': { 'won': won, 'tot': total },
        'toi': {
            'tot/avg/pp/sh/ev': { 'min': mins, 'sec': secs }
        }
    }
}
home_shots

Property that returns the home team shot summary by situation.

Returns:dict of the form
{
    'agg': { 'ev/pp/sh/tot': { 'g': goals, 's': shots } },
    'det': { '5v5/5v4/5v3/et c': { 'g': goals, 's': shots } }
}
point_getters()[source]

Return home/away by player info for the game’s point getters.

Returns:dict of the form { 'home/away': { by_player_dict } }. See home_players() and away_players()
sort_players(sort_key=None, sort_func=None, reverse=False)[source]

Return all home and away by player info sorted by either the provided key or function. Must provide at least one of the two parameters. Can sort either ascending or descending.

Parameters:
  • sort_key – (def None) dict key to sort on
  • sort_func – (def None) sorting function
  • reverse – (optional, def False) if True, sort descending
Returns:

dict of the form { 'home/away': { by_player_dict } }. See home_players() and away_players()

top_by_func(sort_func)[source]

Return home/away by player info for the players on each team who come in first according to the provided sorting function. Will perform ascending sort.

Parameters:sort_func – function that yields the sorting quantity
Returns:dict of the form { 'home/away': { by_player_dict } }. See home_players() and away_players()
top_by_key(sort_key)[source]

Return home/away by player info for the players on each team that are first in the provided category.

Parameters:sort_key – str, the dictionary key to be sorted on
Returns:dict of the form { 'home/away': { by_player_dict } }. See home_players() and away_players()
top_toi()[source]

Return home/away by player info for the players on each team who logged the most time on ice.

Returns:dict of the form { 'home/away': { by_player_dict } }. See home_players() and away_players()
totals()[source]

Computes and returns dictionary containing home/away by player, shots and face-off totals

Returns:dict of the form { 'home/away': { 'all_keys': w_numeric_data } }

nhlscrapi.games.gamesummary module

nhlscrapi.games.cumstats module

class nhlscrapi.games.cumstats.AccumulateStats[source]

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)[source]
update(play)[source]

Update the accumulator with the current play

Returns:new tally, { 'period': per, 'time': clock, 'team': cumul, 'play': play }
class nhlscrapi.games.cumstats.Corsi[source]

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()[source]

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

Returns:dict, { 'home_name': %, 'away_name': % }
class nhlscrapi.games.cumstats.EvenStShotAttCt[source]

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[source]

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[source]

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)[source]
share()[source]
Returns:The Fenwick-share (% of unblocked even strength shot attempts) for each team
Return type:dict, { 'home_name': %, 'away_name': % }
update(play)[source]
class nhlscrapi.games.cumstats.Score[source]

Bases: nhlscrapi.games.cumstats.ShotEventTallyBase

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

initialize_teams(teams)[source]
update(play)[source]
class nhlscrapi.games.cumstats.ShootOut[source]

Bases: nhlscrapi.games.cumstats.ShotEventTallyBase

Tallies shootout goals. Increments if

class nhlscrapi.games.cumstats.ShotAttemptCt[source]

Bases: nhlscrapi.games.cumstats.ShotEventTallyBase

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

class nhlscrapi.games.cumstats.ShotCt[source]

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)[source]

Bases: nhlscrapi.games.cumstats.TeamIncrementor

Base class for all shot attempt based events

class nhlscrapi.games.cumstats.TeamIncrementor(get_team=None, count_play=None)[source]

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)[source]

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[source]

Bases: nhlscrapi.games.events.ShotAttempt

class nhlscrapi.games.events.Event(event_type=0, desc='')[source]

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[source]

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)[source]

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[source]

Bases: nhlscrapi.games.events.Event

class nhlscrapi.games.events.GameEnd[source]

Bases: nhlscrapi.games.events.Stoppage

class nhlscrapi.games.events.Giveaway[source]

Bases: nhlscrapi.games.events.Turnover

class nhlscrapi.games.events.Goal[source]

Bases: nhlscrapi.games.events.Shot

class nhlscrapi.games.events.Hit[source]

Bases: nhlscrapi.games.events.Event

class nhlscrapi.games.events.Miss[source]

Bases: nhlscrapi.games.events.ShotAttempt

class nhlscrapi.games.events.Penalty[source]

Bases: nhlscrapi.games.events.Event

class nhlscrapi.games.events.PeriodEnd[source]

Bases: nhlscrapi.games.events.Stoppage

class nhlscrapi.games.events.ShootOutAtt(event_type=12)[source]

Bases: nhlscrapi.games.events.Event

class nhlscrapi.games.events.ShootOutEnd[source]

Bases: nhlscrapi.games.events.Stoppage

class nhlscrapi.games.events.ShootOutGoal[source]

Bases: nhlscrapi.games.events.ShootOutAtt

class nhlscrapi.games.events.Shot[source]

Bases: nhlscrapi.games.events.ShotAttempt

class nhlscrapi.games.events.ShotAttempt(event_type=1)[source]

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)[source]

Bases: nhlscrapi.games.events.Event

class nhlscrapi.games.events.Takeaway[source]

Bases: nhlscrapi.games.events.Turnover

class nhlscrapi.games.events.Turnover(to_type=0)[source]

Bases: nhlscrapi.games.events.Event

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

class TOType[source]
Giveaway = 1
Takeaway = 0
Turnover.turnover_type

nhlscrapi.games.repscrwrap module

class nhlscrapi.games.repscrwrap.RepScrWrap(game_key, rep_reader)[source]

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_keyGameKey of the game being loaded
  • rep_reader – object of type nhlscrapi.scrapr.ReportLoader
game_key = None

Game key identifier of type GameKey

load_all()[source]

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)[source]

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