Skip to content

League

The top-level entry point. Wraps Yahoo Fantasy API access, projection fitting, simulation, and move analysis behind a single class.

import fantasyfb as fb
league = fb.League(name="My Team")

fantasyfb.league.League

League(name: str = None, season: int = None, week: int = None, injurytries: int = 10, num_sims: int = 10000, earliest: int = None, bestball: str = '', nfl_provider: NFLDataProvider = None, fit_matchup: bool = True, platform: str = 'yahoo', sleeper_league_id: str = None, client: FantasyPlatformClient = None, num_teams: int = 12, mock_scoring: str = 'ppr', roster_spots: DataFrame = None)

League class that gathers all relevant settings and statistics to simulate and assess the fantasy league in question.

Attributes:

Name Type Description
season

integer specifying the season of interest

week

integer specifiying the week of interest

oauth

yahoo_oauth object contain user credentials and auth tokens

lg

yahoo_fantasy_api league object used to connect to Yahoo's API

gm

yahoo_fantasy_api game object used to connect to Yahoo's API

name

string specifying the name of the fantasy to be analyzed

settings

dictionary containing the scheduling and roster settings for the league in question

scoring

dictionary containing the scoring categories and values for the league in question

teams

list of dictionaries containing identifiers for each fantasy team in the league

nfl_teams

dataframe containing different identifiers for each NFL team

nfl_schedule

dataframe containing NFL schedules throughout the years with elo statistics for both teams

players

dataframe containing demographics and rates for current NFL players

num_sims

integer specifying the number of Monte Carlo simulations to run

earliest

integer describing the earliest week to pull statistics from (YYYYWW)

schedule

dataframe containing the fantasy schedule for the league and season in question

Initializes a League object using the parameters provided and class functions defined below.

Parameters:

Name Type Description Default
name str

string describing the name of the fantasy team in question, defaults to None. For platform="sleeper", this identifies "my team" by matching against a Sleeper team's name or manager display name (raises ValueError if given but unmatched).

None
season int

integer specifying the season of interest, defaults to None.

None
week int

integer specifiying the week of interest, defaults to None.

None
injurytries int

integer specifying the number of attempts to pull injury statuses, defaults to 10.

10
num_sims int

integer specifying the number of Monte Carlo simulations to run, defaults to 10000.

10000
earliest int

integer describing the earliest week to pull statistics from (YYYYWW), defaults to None.

None
bestball str

which platform to use when implementing best ball settings/scoring, defaults to a blank string (no bestball).

''
platform str

which fantasy platform backend to use, "yahoo", "sleeper", or "generic" (a fully synthetic mock draft with no real league -- see issue #47), defaults to "yahoo".

'yahoo'
sleeper_league_id str

numeric Sleeper league ID (from the league URL), required when platform="sleeper".

None
client FantasyPlatformClient

pre-constructed client instance, bypasses platform/sleeper_league_id. Mainly for testing.

None
num_teams int

number of teams to synthesize, only used when platform="generic", defaults to 12.

12
mock_scoring str

generic scoring preset ("standard", "half_ppr", or "ppr"), only used when platform="generic", defaults to "ppr".

'ppr'
roster_spots DataFrame

custom roster shape (position/count columns, same schema as League.roster_spots -- base positions plus flex codes W/T, W/R/T, Q/W/R/T, plus BN/IR), only used when platform="generic". Defaults to None, which falls back to the fixed roster shape for mock_scoring (see issue #59).

None

latest_season instance-attribute

latest_season = datetime.datetime.now().year - int(datetime.datetime.now().month < 6)

Year of the most recent season

nfl_provider instance-attribute

nfl_provider = nfl_provider if nfl_provider is not None else NflreadpyProvider()

Pluggable NFL data backend; defaults to nflreadpy

season instance-attribute

season = season if type(season) == int else self.latest_season

Season of interest, defaults to most recent season when no value is provided

current_week instance-attribute

current_week = self.client.get_current_week()

Most recent week of the season of interest

my_team_key instance-attribute

my_team_key = self.client.get_my_team_key()

team_key of the team identified by name, if resolvable

week instance-attribute

week = week if type(week) == int else self.current_week

Week of interest during the season of interest, defaults to most recent week

num_sims instance-attribute

num_sims = num_sims if type(num_sims) == int else 10000

Number of simulations to run when assessing the league of interest

load_settings

load_settings(bestball: str = '')

Pulls league roster/schedule settings and scoring modifiers

Parameters:

Name Type Description Default
bestball str

which best ball settings to use if desired, defaults to "" (redraft).

''

load_fantasy_teams

load_fantasy_teams()

Pulls a list of all fantasy team names and ids for the league in question.

load_nfl_abbrevs

load_nfl_abbrevs()

Loads a translation table for all NFL team abbreviations across platforms.

Sourced from the active NFL data provider so the real_abbrev column matches whatever team codes the rest of the pipeline will see in stats and schedules.

load_nfl_schedule

load_nfl_schedule(path: str = 'NFLSchedule.csv')

Loads and processes the NFL schedule for use in future simulations.

Pulls the last eight seasons through the current season from the configured NFL data provider; the on-disk cache is bypassed because nflreadpy reads parquet locally and is already fast.

Parameters:

Name Type Description Default
path str

retained for backward compatibility, unused.

'NFLSchedule.csv'

pull_stats

pull_stats(start: int, finish: int, path: str = 'GameByGameFantasyFootballStats.csv')

Pulls per-game player and team-defense statistics for the requested YYYYWW range from the configured NFL data provider.

Parameters:

Name Type Description Default
start int

year and number of the first week of interest (YYYYWW, e.g. 202102 = week 2 of 2021).

required
finish int

year and number of the last week of interest (YYYYWW, e.g. 202307 = week 7 of 2023).

required
path str

retained for backward compatibility, unused.

'GameByGameFantasyFootballStats.csv'

add_points

add_points()

Calculates per-game fantasy points based on per-game statistics and provided scoring settings.

load_stats

load_stats(start: int, finish: int)

Loads individual player statistics for each game in the specified timeframe and calculates fantasy points based on league settings. Initially looks for pre-pulled statistics saved locally and pulls new stats when necessary.

Parameters:

Name Type Description Default
start int

year and number of the first week of interest (YYYYWW, e.g. 202102 = week 2 of 2021).

required
finish int

year and number of the last week of interest (YYYYWW, e.g. 202307 = week 7 of 2023).

required

load_parameters

load_parameters(earliest: int = None)

Initializes rate adjustment parameters for the projection engine.

Parameters:

Name Type Description Default
earliest int

YYYYWW of the earliest game to consider. Defaults to two seasons before the current one.

None

refit_matchup_weights

refit_matchup_weights(training_seasons: list = None) -> None

Refit MatchupModel coefficients via walk-forward least squares.

Defaults to training on the season prior to the current one. Costs ~5-10s on typical history; the default-weight model the constructor builds is competitive enough that this is only worth running when you want the small extra accuracy that comes from empirically fitting alpha and beta against your own scoring rules.

get_rates

get_rates(reload: bool = True)

Calculates the average and standard deviation of fantasy points for each player based on the specified prior and normalizing with respect to the provided weighting factors.

Parameters:

Name Type Description Default
reload bool

whether to reload the statistics dataframe, defaults to True.

True

get_schedule

get_schedule()

Pulls the fantasy schedule for the season in question as well as scores for all matchups up to the week in question.

starters

starters(week: int)

Identifies which players should be started on each fantasy team based on fantasy point projections and available roster spots.

Parameters:

Name Type Description Default
week int

week for which to identify starters.

required

bestball_sims

bestball_sims(payouts: list = [20, 20, 20])

Simulates the remainder of the fantasy season based on current rosters and best ball settings using Monte Carlo simulations.

Parameters:

Name Type Description Default
payouts list

list of prize amounts for first, second, and third, defaults to [800, 300, 100].

[20, 20, 20]

Returns:

Name Type Description
standings DataFrame

simulated results for the final season standings and playoff projections.

season_sims

season_sims(postseason: bool = True, payouts: list = [800, 300, 100], fixed_winner: list = None)

Simulates the remainder of the fantasy season based on current rosters and redraft settings using Monte Carlo simulations.

Parameters:

Name Type Description Default
postseason bool

whether to simulate the postseason in addition to the regular season, defaults to True.

True
payouts list

list of prize amounts for first, second, and third, defaults to [800, 300, 100].

[800, 300, 100]
fixed_winner list

list containing the week and team name of a fixed winner, defaults to None.

None

Returns:

Name Type Description
schedule DataFrame

simulated results for each matchup throughout the season in question

standings DataFrame

simulated results for the final season standings and playoff projections

war_sim

war_sim()

Simulates the wins-above-replacement (WAR) for each of the players eligible to roster.

possible_pickups

possible_pickups(**kwargs)

Analyze potential pickup moves.

possible_adds

possible_adds(**kwargs)

Analyze potential add moves.

possible_drops

possible_drops(**kwargs)

Analyze potential drop moves.

possible_trades

possible_trades(**kwargs)

Analyze potential trade moves.

perGameDelta

perGameDelta(team_name: str = None, postseason: bool = True, payouts: list = [800, 300, 100])

Simulates the remainder of the season and compares it to a simulation of the season given one team winning or losing each matchup.

Parameters:

Name Type Description Default
team_name str

name of team to analyze matchup values for, defaults to None (and therefore team of interest).

None
postseason bool

whether to analyze postseason gains or just regular season, defaults to True.

True
payouts list

list of payout amounts for top three finishers, defaults to [800, 300, 100].

[800, 300, 100]

Returns:

Type Description

pd.DataFrame: dataframe containing the impact and value of every matchup during the week of interest.