Skip to content

Example Use Cases

Corey Schaf edited this page Jan 7, 2025 · 3 revisions

Examples of use cases

These are some examples of how to use the library to do various things. These come from my own analysis and experimentation. Each of these steps builds on the previous one. For example first you need the teams, then the players, then the stats.

1. Get all NHL teams

client = NHLClient(verbose=True)
teams = client.teams.teams_info()

Example Output:

[
{
 'conference': {'abbr': 'E', 'name': 'Eastern'},
 'division': {'abbr': 'M', 'name': 'Metropolitan'},
 'name': 'Washington Capitals',
 'common_name': 'Capitals',
 'abbr': 'WSH',
 'logo': 'https://assets.nhle.com/logos/nhl/svg/WSH_secondary_light.svg',
 'franchise_id': 24
},
...
]

2. Loading all roster players from each team for a given season. This uses the teams.roster endpoint.

This also assumes you have pandas installed and imported. If not you can just remove the pd stuff and have it work on lists.

def clean_name(ntype, name):
    """
    Clean the name of the player or team
    """
    return name[ntype]['default']

df_players = pd.DataFrame()

for team in teams:
    players = client.teams.roster(team_abbr=team['abbr'], season="20242025")
    for p in players['forwards'] + players['defensemen'] + players['goalies']:
        p['team'] = team['abbr']
        p['firstName'] = clean_name('firstName', p)
        p['lastName'] = clean_name('lastName', p)
    forwards, defense, goalies = players['forwards'], players['defensemen'], players['goalies']

    df_players = pd.concat(
        [df_players, 
         pd.DataFrame(forwards), 
         pd.DataFrame(defense), 
         pd.DataFrame(goalies)
         ], ignore_index=True)

3. Loading all summary statistics for each player we loaded in step 2.

This uses the query builder SeasonQuery along with FranchiseQuery to load the summary stats for each player. Note, some roster players who have not seen gametime will not appear here so expect nulls.

# will do this on a team by team basis, for the 2024-2025 season
from nhlpy.api.query.builder import QueryBuilder, QueryContext
from nhlpy.api.query.filters.franchise import FranchiseQuery
from nhlpy.api.query.filters.season import SeasonQuery
import time

sq = SeasonQuery(season_start="20242025", season_end="20242025")
query_builder = QueryBuilder()

test = None
df_player_stats = pd.DataFrame()

for team in teams: 
    #pause for 1 second
    time.sleep(1). # < --- I sometimes get rate limited, this is just to slow down a bit.
    fq = FranchiseQuery(franchise_id=team['franchise_id'])
    context = query_builder.build(filters=[fq, sq])

    data = client.stats.skater_stats_with_query_context(
        report_type='summary',
        query_context=context,
        aggregate=True
    )
    data_df = pd.DataFrame(data['data'])
    df_player_stats = pd.concat([df_player_stats, data_df], ignore_index=True)