spilchen / yahoo_fantasy_api Goto Github PK
View Code? Open in Web Editor NEWpython bindings for the Yahoo! Fantasy API (https://yahoo-fantasy-api.readthedocs.io/)
License: MIT License
python bindings for the Yahoo! Fantasy API (https://yahoo-fantasy-api.readthedocs.io/)
License: MIT License
Documentation appears to have been removed
I just ran a script for the first time in six months and I'm getting this error whenever calling roster
~/anaconda3/lib/python3.8/site-packages/yahoo_fantasy_api/team.py in roster(self, week, day)
93 plyr["position_type"] = next_item["position_type"]
94 else:
---> 95 plyr["position_type"] = next(it)["position_type"]
96 plyr["eligible_positions"] = _compact_eligible_pos(next(it))
97 plyr["selected_position"] = _compact_selected_pos(next(it))
KeyError: 'position_type'
When trying to gather week 1 stats for a player I do not get anything.
lg.player_stats('11662', 'week', None, 1) # current season
I get:
[{'player_id': 11662, 'name': 'Jonah Heim', 'position_type': 'B'}]
When attempting to return league_ids with a year specified, a RuntimeError is returned.
Code:
from yahoo_oauth import OAuth2
import yahoo_fantasy_api as yfa
oauth = OAuth2(None, None, from_file='oauth2.json')
if not oauth.token_is_valid():
oauth.refresh_access_token()
gm = yfa.Game(oauth, code='nfl')
gm.league_ids(year=2020)
Returns:
Traceback (most recent call last):
File "~/testing.py", line 18, in <module>
gm.league_ids(year=2020)
File "C:\Program Files\Python37\lib\site-packages\yahoo_fantasy_api\game.py", line 42, in league_ids
t = objectpath.Tree(self.yhandler.get_teams_raw())
File "C:\Program Files\Python37\lib\site-packages\yahoo_fantasy_api\yhandler.py", line 68, in get_teams_raw
return self.get("users;use_login=1/games/teams")
File "C:\Program Files\Python37\lib\site-packages\yahoo_fantasy_api\yhandler.py", line 25, in get
raise RuntimeError(response.content)
RuntimeError: b'{\n "error": {\n "xml:lang": "en-us",\n "yahoo:uri": "\\/fantasy\\/v2\\/users;use_login=1\\/games\\/teams?format=json",\n "description": "Team key 39.l.15338.t.1 does not exist.",\n "detail": ""\n }\n}'
I am able to successfully return league information, team information, etc if I manually input the league ID, however it makes it much more difficult to automate the querying of data if I manually need to identify the game ID for the current year (it is 399 for 2020 NFL for example) and league ID.
I also do not recognize the game ID (39), or league ID (15338) being returned in the traceback.
Any thoughts?
The existing draft_result() function does not work for live drafts, as the undrafted picks have no 'player key'
for p in t.execute('$..draft_results..draft_result'):
pk = p['player_key']
m = pat.search(pk)
if m:
pid = int(m.group(1))
p['player_id'] = pid
del p['player_key']
dres.append(p)
suggested solution
for p in t.execute('$..draft_results..draft_result'):
try:
pk = p['player_key']
m = pat.search(pk)
if m:
pid = int(m.group(1))
p['player_id'] = pid
del p['player_key']
dres.append(p)
except KeyError:
continue
Example: league.player_details("De'Aaron Fox")
throws the following:
File "[trunc]/yahoo_fantasy_api/yhandler.py", line 176, in get_player_raw
return self.get("league/{}/{}".format(league_id, player_stat_uri))
File [trunc]/yahoo_fantasy_api/yhandler.py", line 25, in get
raise RuntimeError(response.content)
RuntimeError: b'<?xml version="1.0" encoding="UTF-8"?>\n<error xml:lang="en-us" yahoo:uri="http://fantasysports.yahooapis.com/fantasy/v2/league/395.l.36985/players;search=D&#39;Angelo%20Russell/stats?format=json" xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" xmlns="http://www.yahooapis.com/v1/base.rng">\n <description>invalid param search (was modified by yiv_get_stripped )</description>\n <detail/>\n</error>'
Removing the apostrophe (league.player_details("DeAaron Fox")
) throws the following:
File "[trunc]/yahoo_fantasy_api/league.py", line 455, in player_details
for category in player['0']['player']:
TypeError: list indices must be integers or slices, not str
Funnily enough you can get the data by removing the entire chunk before the apostrophe, so in this case, league.player_details("Aaron Fox")
Version: 1.8.1. Briefly checked commits since then and didn't see anything that would fix this.
As of today, calls like lg.to_team(x).roster() are failing due to the following error:
in roster(self, week, day)
93 plyr["position_type"] = next_item["position_type"]
94 else:
---> 95 plyr["position_type"] = next(it)["position_type"]
96 plyr["eligible_positions"] = _compact_eligible_pos(next(it))
97 plyr["selected_position"] = _compact_selected_pos(next(it))
KeyError: 'position_type'
I am using it for hockey, but is there a way for me to get last 7 day or 14 day stats for a particular player?
thanks,
Craig
This resource is incredibly useful - thank you so much for working on it.
I'm curious about how you decipher some of yahoos requirements when submitting requests. For example, when trying to get player stats for a previous season:
https://fantasysports.yahooapis.com/fantasy/v2/league/{league_code}/players;position=G;start=0/stats;season=2018
doesn't seem to work but adding "type=season" to the request as you have done in your player_stats api works perfectly.
https://fantasysports.yahooapis.com/fantasy/v2/league/{league_code}/players;position=G;start=0/stats;type=season;season=2018
How do you know to do this? I've looked through the api documentation and although it's helpful 'enough' it certainly doesn't explain things in this level of detail.
Is it possible to retrieve the fantasy points earned by each athlete in each week? I understand this value would be unique to each league depending on scoring settings.
Is there a way to get an NBA player's rank and projected rank? I can't seem to figure it out.
Is there any way to incorporate FGA, FGM, FTA and FTM stats into the league.player_stats method for NBA fantasy leagues?
I am currently trying to aggregate team stats based on team's current rosters. Only FG% and FT% are displayed. Averaging these out would lead to inaccurate team values for team FG% and FT%.
I would like to know if it is possible to retrieve these values, or if there is a workaround to this.
Thank you!
While trying to run your example scripts I ran into an issue in which your scripts weren't seeing the correct version of python on my system. I use PyEnv to manage different versions of python and it was giving it fits. To resolve this you need to change the first line of your example scripts to this:
#!/usr/bin/env python
to make it robust enough to handle various environments.
Have you discovered if there is a rate limit? I don't know why I keep getting this error nor why I should be getting it. I do not believe it is a problem with my code since it does work as intended the majority of the time
Console log:
[2021-06-10 19:09:46,284 DEBUG] [yahoo_oauth.oauth.__init__] Checking
[2021-06-10 19:09:46,284 DEBUG] [yahoo_oauth.oauth.token_is_valid] ELAPSED TIME : 1270.8750066757202
[2021-06-10 19:09:46,284 DEBUG] [yahoo_oauth.oauth.token_is_valid] TOKEN IS STILL VALID
Traceback (most recent call last):
File "C:/Users/kipfe/PycharmProjects/FantasyBaseball/main.py", line 385, in <module>
getAllPlayers("season", 0)
File "C:/Users/kipfe/PycharmProjects/FantasyBaseball/main.py", line 326, in getAllPlayers
takenPitchers = getPitchers(type, 1)
File "C:/Users/kipfe/PycharmProjects/FantasyBaseball/main.py", line 237, in getPitchers
pitcherStats = lg.player_stats(allPID[i], req_type=type)
File "C:\Users\kipfe\PycharmProjects\FantasyBaseball\venv\lib\site-packages\yahoo_fantasy_api\league.py", line 687, in player_stats
stats += self._fetch_plyr_stats(game_code, next_player_ids,
File "C:\Users\kipfe\PycharmProjects\FantasyBaseball\venv\lib\site-packages\yahoo_fantasy_api\league.py", line 778, in _fetch_plyr_stats
json = self.yhandler.get_player_stats_raw(game_code, player_ids,
File "C:\Users\kipfe\PycharmProjects\FantasyBaseball\venv\lib\site-packages\yahoo_fantasy_api\yhandler.py", line 311, in get_player_stats_raw
return self.get(uri)
File "C:\Users\kipfe\PycharmProjects\FantasyBaseball\venv\lib\site-packages\yahoo_fantasy_api\yhandler.py", line 25, in get
raise RuntimeError(response.content)
RuntimeError: b'Request denied\r\n'
My league object:
from yahoo_oauth import OAuth2
import yahoo_fantasy_api as yfa
oAuth = OAuth2(None, None, from_file='OAuth2.json')
gm = yfa.Game(oAuth, 'mlb')
lg = gm.to_league('404.l.15530')
tmK = lg.team_key()
tm = lg.to_team(team_key=tmK)
Hi, I've just discovered that league.transactions(type,int)
is not filtering correctly the type, so:
league.transactions('add','')
league.transactions('drop','')
Return both the same: all add
, drop
and add/drop
transactions.
From my point of view, this logic is better, as I understand add
, drop
and add/drop
transactions are the same with different details; but I thought you should know the behavior is not the expected.
Thanks!
When returning standings using lg.standings(), is it possible to return a list of tuples where the first is the name of the team and the second entry is the current points?
example: [(first_place_team, 99),(second_place_team,93),..,(last_place_team, 70)]
This will be very helpful for my Points Only league. Thanks!
I've had really good success using yahoo_fantasy_api for some fantasy football player research. However I'm interested in utilizing it to help automate some mid-season customized rules by dropping/adding players from teams' rosters as the commissioner. I don't think I'm able to do this with the current functions available in YFA, and I am not well versed in API calls so I was hoping one of the dev's of this project could point me in the right direction or provide some sample code to execute commissioner drops and adds from the URI's "https://basketball.fantasysports.yahoo.com/nba/XXXXXX/Y/commishdropplayer" and "https://basketball.fantasysports.yahoo.com/nba/XXXXXX/Y/commishaddplayer"
Thanks!
When I run the following code:
oauth = yahoo_oauth.OAuth2(yahooapi_dict['clientid'], yahooapi_dict['clientsecret']) lg = yfa.game.Game(oauth, code = 'nfl').league_ids()
I get the following error:
RuntimeError: b'{\n "error": {\n "xml:lang": "en-us",\n "yahoo:uri": "\/fantasy\/v2\/users;use_login=1\/games\/teams?format=json",\n "description": "You do not have the appropriate OAuth scope permissions to perform this action.",\n "detail": ""\n }\n}'
Is this stemming from an error on my part?
Running the cleanup
function in oauth2_logger.py yields the following AttributeError
:
Traceback (most recent call last):
File "/Users/famendola/opt/anaconda3/bin/ybot_setup", line 140, in <module>
oauth2_logger.cleanup()
File "/Users/famendola/opt/anaconda3/lib/python3.8/site-packages/yahoo_fantasy_api/oauth2_logger.py", line 12, in cleanup
yahoo_oauth.yahoo_oauth.logger = logging.getLogger('mod_yahoo_oauth')
AttributeError: module 'yahoo_oauth' has no attribute 'yahoo_oauth'
When I try to add a player on the waiver list (for example player ID 6574) using the add_and_drop_players function, it throws up an error saying FAB balance must be a whole number between $0 and $999999999.
File "C:\pybaseballbot\fantasy_test.py", line 38, in
team.add_and_drop_players(6574, 6404)
File "C:\pybaseballbot\pybaseballbot\Lib\site-packages\yahoo_fantasy_api\team.py", line 174, in add_and_drop_players
self.yhandler.post_transactions(self.league_id, xml)
File "C:\pybaseballbot\pybaseballbot\Lib\site-packages\yahoo_fantasy_api\yhandler.py", line 241, in post_transactions
return self.post("league/{}/transactions".format(league_id), xml)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\pybaseballbot\pybaseballbot\Lib\site-packages\yahoo_fantasy_api\yhandler.py", line 60, in post
raise RuntimeError(response.content)
RuntimeError: b'\n\n FAB balance must be a whole number betweed $0 and $999999999.\n \n'
How do I get around this?
Hi, I want to ask a question I've faced. I get RuntimeError continuously when I use team.roster(1) and league.player_stats([0],'season'). My goal is to get every player's stats and make a .csv file.(I'm sure that I have exactly login)
This is my code:
from yahoo_oauth import OAuth2
import yahoo_fantasy_api as yfa
import json
sc = OAuth2(None, None, from_file='./varify.json')
gm = yfa.Game(sc, 'mlb')
ids = gm.league_ids(year=2021)
lg = gm.to_league(ids[1])
team_key = lg.team_key()
team = lg.to_team(team_key[0])
print(team.roster(1))
and this is the error message
[2021-07-22 04:23:40,810 DEBUG] [yahoo_oauth.oauth.__init__] Checking
[2021-07-22 04:23:40,810 DEBUG] [yahoo_oauth.oauth.token_is_valid] ELAPSED TIME : 816.7230370044708
[2021-07-22 04:23:40,810 DEBUG] [yahoo_oauth.oauth.token_is_valid] TOKEN IS STILL VALID
Traceback (most recent call last):
File "fantasy_api.py", line 14, in <module>
print(team.roster(1))
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/yahoo_fantasy_api/team.py", line 69, in roster
t = objectpath.Tree(self.yhandler.get_roster_raw(self.team_key,
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/yahoo_fantasy_api/yhandler.py", line 119, in get_roster_raw
return self.get("team/{}/roster{}".format(team_key, param))
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/yahoo_fantasy_api/yhandler.py", line 25, in get
raise RuntimeError(response.content)
RuntimeError: b'{\n "error": {\n "xml:lang": "en-us",\n "yahoo:uri": "\\/fantasy\\/v2\\/team\\/4\\/roster;week=1?format=json",\n "description": "Missing Resource ID for team",\n "detail": ""\n }\n}'
Thanks for your help! I am desired to know how to deal with this error!
I'm running into an issue when trying to parse player stats using the date req_type. The code snippet in question is as follows:
from yahoo_oauth import OAuth2
import yahoo_fantasy_api as yfa
import json
oauth = OAuth2(None, None, from_file='oauth2.json')
gm = yfa.Game(oauth, 'nhl')
ids = gm.league_ids(year=2020)
lg = gm.to_league(ids[0])
day = datetime.date(2021,1,16) # can select any random day the player has played
player=[3983] # can select any player
lg.player_stats(player[0],req_type='date',date=day)
And here is my output:
[2021-08-29 21:43:43,300 DEBUG] [yahoo_oauth.oauth.init] Checking
[2021-08-29 21:43:43,301 DEBUG] [yahoo_oauth.oauth.token_is_valid] ELAPSED TIME : 1052.1923336982727
[2021-08-29 21:43:43,303 DEBUG] [yahoo_oauth.oauth.token_is_valid] TOKEN IS STILL VALID
[{'player_id': 3983,
'name': 'Phil Kessel',
'position_type': 'P',
'GP': '-',
'G': '-',
'A': '-',
'PTS': '-',
'+/-': '-',
'PIM': '-',
'PPG': '-',
'PPA': '-',
'PPP': '-',
'SHP': '-',
'GWG': '-',
'SOG': '-',
'S%': '-',
'HIT': '-',
'BLK': '-'}]
For the date selected, we should see something for these categories. I can pull season info for players with no issues. I wonder if it's an issue with the datetime format? Any insight would be greatly appreciated.
I find that if the 'Waiver Type' league setting is "FAB w/ Continual rolling list tiebreak",
hence there is no Free Agents and all players are in waivers,
in this situation use waivers() may take a little bit of time,
so I think add the position argument to waivers() could be more efficiency.
No matter what input I try for date (using datetime.date) variable, it gives me this error "You cannot make changes to your roster for this date.". Also, is it not possible to just do the change immediately instead of at some future date?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.