Package: yahoofantasy
🏆 Yahoo Fantasy API Wrapper 🏆The Yahoo Fantasy Sports API is difficult to comprehend, hasthis strange one-page documentation setupthat is hard to navigate, and seems to only want to conform to a small portion of the OAuth spec. This library/SDK makes your life easier if you want to write an app that interfaces with the Yahoo Fantasy Sports API.This library will work for any Yahoo Fantasy Sports API leagues/teams. It contains some common constructs and helper methods for head-to-head leagues for the NFL 🏈, MLB ⚾, NHL 🏒 and NBA 🏀.Table of ContentsInstallationBasic UsageAuthenticationConceptsCommand Line (CLI)DevelopmentInstallationpip install yahoofantasyYou will also need a application registered on theYahoo Developer Site. You'll need your client ID and secret. The app just needs to have read permissions. See below for instructions on how to set up your Yahoo Developer application if you don't have one already.Basic UsageYou're going to want to start off by logging in to your Yahoo Developer application, then creating a context. This context is where all of your API requests will originate and league information will live.yahoofantasyloginOnce you've logged in, create a context and use that to make requests. For example, to fetch all of your leagues for a given game/season:fromyahoofantasyimportContextctx=Context()leagues=ctx.get_leagues('mlb',2020)forleagueinleagues:print(league.name+" -- "+league.league_type)AuthenticationYou can use the built-inyahoofantasyCLI to obtain an access token and refresh token for your application. Follow these steps:Set up your Yahoo application to have a callback/redirect URI ofhttps://localhost:8000. If you already have an app that points to your local host on a different port or different path that's ok, you can customize later on.Installyahoofantasyif you haven't alreadypipinstallyahoofantasyLog in with your Yahoo account. This command will launch a browser that will ask you to authenticate to your app. It will then store the token in a local file that can be consumed by the yahoofantasy SDK.yahoofantasyloginNOTE: If you see a browser certificate warning that is ok, proceed anyway past the warning to save your token. This warning happens because Yahoo requires an HTTPS redirect URI and the local server uses an untrusted certificate.Tryyahoofantasy login --helpfor some advanced options, like customizing the port or redirect URIConceptsThere is a general hierarchy that head-to-head leagues will follow. This hierarchy is represented with classes within this library. This code walkthrough will help you understand the organization of the library. The following examples are intended to be read sequentially and assume you have aContextwith your logged in Yahoo credentials calledctx.Your account will belong to one or moreLeagueobjects.forleagueinctx.get_leagues('mlb',2019):print(f"{league.id}-{league.name}({league.league_type})")ALeaguewill contain multipleTeamobjects.fromyahoofantasyimportLeagueleague=League(ctx,'388.l.25000')# Use a manual league ID or get it from league.id aboveforteaminleague.teams():print(f"Team Name:{team.name}\tManager:{team.manager.nickname}")ATeamhas multiplePlayerobjects that define their lineup. This is their current lineup and not a lineup for a given weekforteaminleague.teams():players=team.players()forplayerinplayers:print(f"Player:{player.name.full}")ALeaguehasStandings, which is an ordered list ofTeamobjects.forteaminleague.standings():outcomes=team.team_standings.outcome_totalsprint(f"#{team.team_standings.rank}\t{team.name}\t"f"({outcomes.wins}-{outcomes.losses}-{outcomes.ties})")ALeaguewill contain multipleWeekobjects. AWeekcontains multipleMatchupobjects, which are a head-to-head matchup of twoTeamobjects for that week.week_3=league.weeks()[2]formatchupinweek_3.matchups:print(f"{matchup.team1.name}vs{matchup.team2.name}")AMatchupwill have multipleStatobjects for the two teams. AStatobject contains the display name of the stat as well as the value for the team.matchup=week_3.matchups[0]print(f"{matchup.team1.name}\tvs\t{matchup.team2.name}")forteam1_stat,team2_statinzip(matchup.team1_stats,matchup.team2_stats):print(f"{team1_stat.value}\t{team1_stat.display}\t{team2_stat.value}")The full sequence of these examples can be run in the examples folder under thereadme.pyscript, like so:cd examples
yahoofantasy login
python readme.pyCommand Line (CLI)This package comes with a built in CLI to let you do some handy tasks without writing any Python code. This is useful for exporting a spreadsheet with trades in your league, player performances, etc and doing some separate analysis on them.General PropertiesEach CLI command has these common properties/arguments to let you control its behavior-g/--game- which sport you are exporting (e.g., nfl, mlb)-s/--season- which season you are exporting (e.g., 2020, 2019, etc)-o/--output- the filename of the CSV to write to, defaults tostdoutwhich prints to stdout instead of to a fileIf you don't provide these parameters you will be prompted for the required ones when you run your command.
These parameters must be provided after thedumpcommand but before the type of export you want to complete. For example:yahoofantasydump-gnfl-s2020-opath/to/output.csvperformancesTypes of ExportsPlayer PerformancesDumps a CSV with every player that was owned for every week and their stats.yahoofantasydumpperformancesSimplified output example:nameweekmanagerpositionpointsPass TDRush YdsDrew Brees1Manager NameQB16.422Dalvin Cook1ManagerRB21.3050MatchupsIn a head-to-head league, a CSV dump of all manager matchups from the seasonyahoofantasydumpmatchupsSimplified output example:weekmanagerwinpointsproj_pointsopponentopp_pointsopp_proj_points1Manager 1False90.0133.55Manager 2142.68136.791Manager 2True142.68136.79Manager 190.0133.55Draft ResultsA CSV dump of every draft pickyahoofantasydumpdraftresultsSimplified output example:pickroundmanagerplayerpos11Manager 1Christian McCaffreyRB21Manager 2Saquon BarkleyRBTransactionsA CSV dump of every transaction made for a season. Includes trades, adds, drops, and commissioner movesyahoofantasydumptransactionsSimplified output example:typeplayer_typeplayerfromtotsweek_idxbiddropdropDamien HarrisElementary Mr Watsonwaivers09/09/2020, 20:57:1536add/dropaddJames RobinsonwaiversKittles taste the ðŸŒˆ09/11/2020, 00:22:2036Shell (Python interpreter)A command is available to drop you into a Python interpreter with access to yourContextobject as thectxvariable. From the directory where you ranyahoofantasy loginyou can run:yahoofantasyshellClearing cacheThe yahoofantasy library maintains its own persisted cache of certain Yahoo! API responses. This cuts down on the number of requests that need to be made and makes future function calls faster. Occasionally you may want to clear this cache but not lose your authentication data. You can do so by running the following CLI command from your yahoofantasy project directory:yahoofantasyclear-cacheDevelopmentIssues, pull requests, and contributions are more than welcome.Unit TestsTo run the tests, after install:py.testOr to keep running tests using testmon and drop into a pdb shell on failure (my preferred mode):pytest-watch--pdb----testmon-sReleasingI usebump2versionto manage version bumping. This will update the version number in the library, commit it, and create a version tag.bump2versionminor
gitpush