def login(self, game=None): if game: self.game = game self.sc = game.sc else: self.sc = self._get_session() self.game = yfa.Game(self.sc, 'nba')
def test_ids_for_year(sc): gm = yfa.Game(sc, 'mlb') gm.inject_yhandler(mock_yhandler.YHandler()) ids = gm.league_ids(year=2017) assert (len(ids) == 1) print(ids) assert (ids[0] == '370.l.56877')
def yahoo_fantasy_league(sc): gm = yfa.Game(sc, NBA) league_id_list = gm.league_ids(year=SEASON) league_id = "".join(str(id) for id in league_id_list) league = gm.to_league(league_id) return league
def league(): """ Returns a league from the Yahoo API based on the config file. :return: dict representing the league """ oauth = authenticate() lg_obj = yapi.Game(oauth, 'nfl').to_league(CONFIG['league_id']) return lg_obj
def leag(idx = -1, file = '../trade_managment/oauth2.json'): ''' function to just return the leauge to abstract away the authentication in other files ''' oauth = OAuth2(None, None, from_file=file) g = yfa.Game(oauth, 'nhl') lg = yfa.League(oauth, g.league_ids()[-1]) return lg
def test_ids(sc): gm = yfa.Game(sc, 'mlb') gm.inject_yhandler(mock_yhandler.YHandler()) ids = gm.league_ids() for i in ids: print(i) assert (len(ids) == 12) print(ids) assert (ids[5] == '268.l.46645')
def main(league_id): sc = OAuth2(None, None, from_file="oauth2.json") gm = yfa.Game(sc, "nfl") lg = gm.to_league(league_id) print(f"The current week is {lg.current_week()}") print(get_alternative_standings(lg))
def scan_sports(self): for sport in SPORTS: game = yfa.Game(self.sc, sport) league_ids = list(game.league_ids()) if self.lake_sports: s = self.lake_sports.get(sport) if s: s.append(league_ids) else: self.lake_sports.update({sport: league_ids}) else: self.lake_sports = dict() self.lake_sports.update({sport: league_ids})
def get_team_data(sc, league_id: str, week: int): """ Returns: { "fantasy_content":{ "league": [ {league information}, {matchup information} ] } } """ gm = yfa.Game(sc, 'nba') return gm.to_league(league_id).matchups(week=week)
def fill_tables(sc): gm = yfa.Game(sc, 'nhl') lg = gm.to_league(gm.league_ids(year=2019)[0]) dummies = lg.teams() table_df = pd.DataFrame() # cleaning names for valid table entry for team in dummies: team['name'] = team['name'].replace(" ", "_") roster = lg.to_team(team['team_key']).roster() df = pd.DataFrame(roster) df['owner'] = team['name'] df['team_key'] = team['team_key'] df['position'] = df['eligible_positions'].apply('/'.join) df.drop(['eligible_positions'], inplace=True, axis=1) table_df = table_df.append(df, ignore_index=True) insert_db(table_df, 'league', 'replace')
def __init__(self, year, oauth2_file): sc = OAuth2(None, None, from_file = oauth2_file) game = yfa.Game(sc, "nba") league_name_id_dict = {} for item in game.league_ids(year=year): league_name_id_dict[game.to_league(item).settings()["name"]] = item if not league_name_id_dict: print("No fantasy teams in {}-{} seasons...".format(year, year + 1)) exit(0) questions = [ { "type": "rawlist", "name": "league", "message": "And the Fantasy league:", "choices": league_name_id_dict.keys() } ] answers = prompt(questions) self.__league = game.to_league(league_name_id_dict[answers["league"]])
async def get_league(league, year, ctx): """ :param league: str :param year: int :param ctx: commands.Context :return: League """ auth = await check_auth(ctx.message.author, ctx) league = league_check(league.lower()) if auth and league: game = yfa.Game(auth, league) ids = game.league_ids(year=year) if ids: league_id = ids[-1] return game.to_league(league_id) else: await ctx.send("It seems you don't play Fantasy for the " + league.upper()) elif auth: await ctx.send("That is an incorrect league.") return None
def setup_menubar(self): menuBar = QMenuBar(self) menuBar.setNativeMenuBar(False) self.setMenuBar(menuBar) leagueMenu = menuBar.addMenu("&League") years = [2021, 2020, 2019, 2018] fantasy_games = ['nhl', 'nfl'] for year in years: year_menu = leagueMenu.addMenu(str(year)) for game in fantasy_games: game_menu = year_menu.addMenu(game) gm = yfa.Game(self.oauth, game) ids = gm.league_ids(year) for id in ids: lg = gm.to_league(id) lg_action = QAction(lg.settings()['name'], self) lg_action.league_id = id lg_action.game_type = game lg_action.year = year game_menu.addAction(lg_action) game_menu.triggered[QAction].connect(self.league_selected)
def generate_teams(teamnames=None): oauth = OAuth2(None, None, from_file="oauth2.json") game = yfa.Game(oauth, 'nba') league_id = game.league_ids(year=2019) league = game.to_league(league_id[0]) # our league of 12 teams_ids = league.teams() # array of team ids in this league teams = [] schedule = scraper.get_schedule() for team_id in teams_ids: team_obj = league.to_team(team_id['team_key']) if teamnames: if team_id['name'] in teamnames: new_team = FantasyTeam(team_id['name'], team_obj, schedule) teams.append(new_team) print(new_team.stats, new_team.name) else: new_team = FantasyTeam(team_id['name'], team_obj, schedule) teams.append(new_team) print(new_team.stats, new_team.name) return teams
def __init__(self, lg_name): self.lg_name = lg_name self.lg = None self.prev_week= None self.all_matchup_stats = {} sc = OAuth2(None, None, from_file='brandon_permissions.json') gm = yfa.Game(sc, 'nba') all_curr_lgs= gm.league_ids(year= self.prev_year) #print (f"\nYahoo Fantasy Basketball League IDs ({self.prev_year} - {self.now.year}): {all_curr_lgs}") lg_dict = {} lg_name_check = 0 for lg_id in all_curr_lgs: lg = gm.to_league(lg_id) _lg_name = lg.matchups().get("fantasy_content").get("league")[0].get("name") # Check lg_name class argument to see if it is an existing league in the Yahoo Game object if lg_name.upper() == _lg_name.upper(): lg_name_check = 1 self.lg_name = _lg_name lg_dict[_lg_name] = lg_id if lg_name_check != 1: raise NameError(f"{self.lg_name} is not a valid league name.") _lg_id= lg_dict[self.lg_name] self.lg = gm.to_league(_lg_id) curr_week= self.lg.current_week() # TODO: add argument for week # #self.prev_week= 12 self.prev_week= curr_week - 1 self.scoreboard= self.lg.matchups(self.prev_week).get("fantasy_content").get("league")[1].get("scoreboard") self.all_matchups= self.scoreboard.get("0").get("matchups")
<year> Will restrict all leagues listed to this year. """ from docopt import docopt from yahoo_oauth import OAuth2 import yahoo_fantasy_api as yfa import logging if __name__ == '__main__': args = docopt(__doc__, version='1.0') logging.basicConfig( filename='cli.log', level=logging.INFO, format='%(asctime)s.%(msecs)03d %(module)s-%(funcName)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') logging.getLogger('yahoo_oauth').setLevel('WARNING') logging.getLogger('chardet.charsetprober').setLevel('WARNING') sc = OAuth2(None, None, from_file=args['<json>']) gm = yfa.Game(sc, args['<sport>']) league_ids = gm.league_ids(year=args['<year>']) for league_id in league_ids: # Older leagues have this "auto" in that, which we cannot dump any # particulars about. if "auto" not in league_id: lg = yfa.League(sc, league_id) settings = lg.settings() print("{:30} {:15}".format(settings['name'], league_id)) teams = lg.teams() for team in teams: print(" {:30} {:15}".format(team['name'], team['team_key'])) print("")
# Output Folder PATH outputFolder = r'C:\Users\phili\OneDrive\Documents\DataProjects\data' # Create a timestamp today = time.strftime('%Y%m%d') # #### Read-in Game and League settings for the Yahoo! Fantasy API # In[30]: # Construct league code leagueCode = gameToUse + '.l.' + leagueToUse # Set-up game collection gm = yfa.Game(sc, 'mlb') # Set-up league... lg = gm.to_league(leagueCode) # #### Read-in free agent, taken, and waivered players # In[31]: ##### Free Agents ##### # Batting battingFAs = lg.free_agents('B') battingFAs = pd.DataFrame(battingFAs)[columnsToUse] # Pitching
def get_dudes(my_league): starting_lineup = [] if my_league['platform'] == 'ESPN': from ff_espn_api import League league_id = my_league['league_id'] year = my_league['year'] swid = my_league['swid'] espn_s2 = my_league['espn_s2'] team_num = my_league['team_num'] league = League(league_id, year, espn_s2, swid) my_team = league.teams[team_num - 1] my_dudes = my_team.roster my_pals = [ dude.name for dude in my_dudes if not ('D/ST' in dude.eligibleSlots or 'K' in dude.eligibleSlots) ] my_pos = [ dude.position for dude in my_dudes if not ('D/ST' in dude.eligibleSlots or 'K' in dude.eligibleSlots) ] my_def = [ dude.proTeam for dude in my_dudes if 'D/ST' in dude.eligibleSlots ] my_kick = [dude.name for dude in my_dudes if 'K' in dude.eligibleSlots] teams = league.teams rosters = [team.roster for team in teams] rostered_pals = [] rostered_def = [] rostered_kick = [] for roster in rosters: dudes = [ dude.name for dude in roster if not ( 'D/ST' in dude.eligibleSlots or 'K' in dude.eligibleSlots) ] rostered_pals.extend(dudes) rostered_def.extend([ dude.proTeam for dude in roster if 'D/ST' in dude.eligibleSlots ]) rostered_kick.extend( [dude.name for dude in roster if 'K' in dude.eligibleSlots]) team_name = my_team.team_name boxscores = league.box_scores() for boxscore in boxscores: if boxscore.away_team.team_name == team_name: my_guys = boxscore.away_lineup elif boxscore.home_team.team_name == team_name: my_guys = boxscore.home_lineup for guy in my_guys: if guy.slot_position not in ['D/ST', 'K', 'BE']: starting_lineup.append(guy.name) elif my_league['platform'] == 'YAHOO': from yahoo_oauth import OAuth2 import yahoo_fantasy_api as yfa oauth_file = my_league['oauth_file'] lg_number = my_league['lg_number'] sc = OAuth2(None, None, from_file=oauth_file) gm = yfa.Game(sc, 'nfl') league = gm.to_league(lg_number) week = league.current_week() team_objs = league.teams() team_keys = [team['team_key'] for team in team_objs] teams = [league.to_team(key) for key in team_keys] rosters = [team.roster(week) for team in teams] rostered_pals = [] rostered_def = [] rostered_kick = [] for roster in rosters: dudes = [ dude['name'] for dude in roster if not ('K' in dude['eligible_positions'] or 'DEF' in dude['eligible_positions']) ] rostered_pals.extend(dudes) rostered_def.extend([ dude['name'] for dude in roster if 'DEF' in dude['eligible_positions'] ]) rostered_kick.extend([ dude['name'] for dude in roster if 'K' in dude['eligible_positions'] ]) my_team = league.to_team(league.team_key()) my_roster = my_team.roster(week) my_pals = [ dude['name'] for dude in my_roster if not ('K' in dude['eligible_positions'] or 'DEF' in dude['eligible_positions']) ] my_pos = [ dude['eligible_positions'][0] for dude in my_roster if not ('K' in dude['eligible_positions'] or 'DEF' in dude['eligible_positions']) ] my_def = [ dude['name'] for dude in my_roster if 'DEF' in dude['eligible_positions'] ] my_kick = [ dude['name'] for dude in my_roster if 'K' in dude['eligible_positions'] ] starting_lineup = [ dude['name'] for dude in my_roster if not dude['selected_position'] in ['BN', 'K', 'DEF'] ] def_map = { #This neglects the RAMS and the GIANTS because Yahoo is dumb and I don't want to figure out their player IDs. 'New England': 'NE', 'Chicago': 'CHI', 'Tampa Bay': 'TB', 'Tennessee': 'TEN', 'San Francisco': 'SF', 'New York': 'NYJ', 'Green Bay': 'GB', 'New Orleans': 'NO', 'Pittsburgh': 'PIT', 'Carolina': 'CAR', 'Detroit': 'DET', 'Seattle': 'SEA', 'Cleveland': 'CLE', 'Los Angeles': 'LAC', 'Kansas City': 'KC', 'Minnesota': 'MIN', 'Buffalo': 'BUF', 'Dallas': 'DAL', 'Houston': 'HOU', 'Jacksonville': 'JAX', 'Indianapolis': 'IND', 'Oakland': 'OAK', 'Washington': 'WAS', 'Baltimore': 'BAL', 'Philadelphia': 'PHI', 'Arizona': 'ARI', 'Atlanta': 'ATL', 'Cincinnati': 'CIN', 'Denver': 'DEN', 'Miami': 'MIA' } my_def = [def_map[d] for d in my_def] rostered_def = [def_map[d] for d in rostered_def] elif my_league['platform'] == 'SLEEPER': from sleeper_wrapper import League, Players import pickle import os.path league_id = my_league['league_id'] players_file = my_league['players_file'] team_num = my_league['team_num'] league = League(league_id) rosters = league.get_rosters() # Not supposed to call this all the time because it is a large file (5MB) if os.path.isfile(players_file): with open(players_file, 'rb') as f: players = pickle.load(f) else: P = Players() players = P.get_all_players() with open(players_file, 'wb') as f: pickle.dump(players, f) my_team = rosters[team_num - 1] my_dudes = [players[id] for id in my_team['players']] my_pals = [ dude['full_name'] for dude in my_dudes if not (('DEF' in dude['fantasy_positions']) or ('K' in dude['fantasy_positions'])) ] starting_dudes = [players[id] for id in my_team['starters']] starting_lineup = [ dude['full_name'] for dude in starting_dudes if not (('DEF' in dude['fantasy_positions']) or ('K' in dude['fantasy_positions'])) ] my_pos = [ dude['position'] for dude in my_dudes if not (('DEF' in dude['fantasy_positions']) or ('K' in dude['fantasy_positions'])) ] my_def = [ dude['player_id'] for dude in my_dudes if 'DEF' in dude['fantasy_positions'] ] my_kick = [ dude['full_name'] for dude in my_dudes if 'K' in dude['fantasy_positions'] ] rostered_teams = [roster['players'] for roster in rosters] rostered_players = sum(rostered_teams, []) rostered_dudes = [players[id] for id in rostered_players] rostered_pals = [ dude['full_name'] for dude in rostered_dudes if not (('DEF' in dude['fantasy_positions']) or ('K' in dude['fantasy_positions'])) ] rostered_def = [ dude['player_id'] for dude in rostered_dudes if 'DEF' in dude['fantasy_positions'] ] rostered_kick = [ dude['full_name'] for dude in rostered_dudes if 'K' in dude['fantasy_positions'] ] else: raise ValueError('League platform ' + league.platform + ' is not supported.') return my_pals, my_pos, rostered_pals, my_def, rostered_def, my_kick, rostered_kick, clean_names( starting_lineup)
from datetime import datetime import pandas as pd from yahoo_oauth import OAuth2 import yahoo_fantasy_api as yfa oauth = OAuth2(None, None, from_file='oauth2.json') f_year = 2021 gm = yfa.Game(oauth, 'nfl') ids = gm.league_ids(year=f_year) lg = gm.to_league(ids[1]) ab = lg.player_details("Antonio Brown") print(ab)
from yahoo_oauth import OAuth2 import yahoo_fantasy_api as yfa global oauth global gm global lg oauth = OAuth2(None, None, from_file='oauth2.json') gm = yfa.Game(oauth, 'nba') lg = gm.to_league('402.l.67232') if not oauth.token_is_valid(): oauth.refresh_access_token()
from yahoo_oauth import OAuth2 import yahoo_fantasy_api as yfa # Define Inputs oauth_file = 'oauth2.json' lg_number = '390.l.824038' # Access API sc = OAuth2(None, None, from_file=oauth_file) gm = yfa.Game(sc, 'nfl') league = gm.to_league(lg_number) week = league.current_week() team_objs = league.teams() team_keys = [team['team_key'] for team in team_objs] teams = [league.to_team(key) for key in team_keys] rosters = [team.roster(week) for team in teams] rostered_pals = [] for roster in rosters: dudes = [ dude['name'] for dude in roster if not ('K' in dude['eligible_positions'] or 'DEF' in dude['eligible_positions']) ] rostered_pals.extend(dudes) my_team = league.to_team(league.team_key()) my_roster = my_team.roster(week) my_pals = [ dude['name'] for dude in my_roster if not ('K' in dude['eligible_positions']
from yahoo_oauth import OAuth2 import yahoo_fantasy_api as yfa from csh_fantasy_bot.yahoo_scraping import generate_predictions, PredictionType oauth = OAuth2(None, None, from_file='oauth2.json') f_year = 2021 gm = yfa.Game(oauth, 'nhl') ids = gm.league_ids(year=f_year) lg = gm.to_league(ids[1]) league_id = lg.league_id print(lg) projections = generate_predictions(lg.league_id, predition_type=PredictionType.rest_season) print(projections.head()) yahoo_prediction_fname = f"./.cache/gui_draft/{league_id}-yahoo-predictions.csv" projections.to_csv(yahoo_prediction_fname, index=True) print(f'Wrote file: {yahoo_prediction_fname}')
def test_to_league(sc): gm = yfa.Game(sc, 'mlb') gm.inject_yhandler(mock_yhandler.YHandler()) lg = gm.to_league('370.l.56877') assert (type(lg) is yfa.League)
import time f = open(Config.config["srcroot"] + "scripts/WeekVars.txt", "r") year = int(f.readline().strip()) BBUPFL_LEAGUE_ID = "411.l.73833" leagues = [ "411.l.19172", "411.l.19179", "411.l.19183", "411.l.24112", "411.l.24120", "411.l.24125", "411.l.24135", "411.l.24137", "411.l.24142", \ "411.l.24147", "411.l.24158", "411.l.24159", "411.l.24160", "411.l.24162", "411.l.24167", "411.l.24187", "411.l.24190", "411.l.24193", \ "411.l.24194", "411.l.26239", "411.l.24195", "411.l.25450", "411.l.24211", "411.l.24207", "411.l.24210", "411.l.24201", "411.l.24204", \ "411.l.24205", "411.l.24202", "411.l.24209", "411.l.24748", "411.l.73532", BBUPFL_LEAGUE_ID] conn = OAuth2(None, None, from_file="yahoo_auth.json") if not conn.token_is_valid(): conn.refresh_access_token() game = yfa.Game(conn, "nhl") def sanitize(name): name = name.replace("(", "") name = name.replace(")", "") return name def updatePlayoffOdds(league_id): league = game.to_league(league_id) settings = league.settings() body = "" body += "LeagueBegin\n"
from yahoo_oauth import OAuth2 import yahoo_fantasy_api as yfa import json from collections.abc import Iterable sc = OAuth2(None, None, from_file='oauth2.json') #print(sc) gm = yfa.Game(sc, 'nba') #print(gm) lg = gm.to_league(gm.league_ids(year=2020)[0]) #print(lg) stat_ids = { "5": "FG%", "8": "FT%", "10": "3PT", "12": "PTS", "15": "REB", "16": "AST", "17": "STL", "18": "BLK", "19": "TO" } matchups_ret = lg.matchups(week=1) matchups = matchups_ret['fantasy_content']['league'][1]['scoreboard']['0'][ 'matchups'] #print(json.dumps(matchups, indent=2, sort_keys=True))