def main(): dot = League(dot_id, year) bob = League(bob_id, year) dot_scoreboard = dot.scoreboard() bob_scoreboard = bob.scoreboard() return render_template('matchups.html', bob = bob, dot = dot, bob_scoreboard = bob_scoreboard, dot_scoreboard = dot_scoreboard)
def standings(): dot = League(dot_id, year) bob = League(bob_id, year) def sort_standings(league): sortedLeague = sorted(league.teams, key=attrgetter('wins', 'points_for'), reverse=True) return sortedLeague bob = sort_standings(bob) dot = sort_standings(dot) return render_template('standings.html', bob = bob, dot = dot)
def get_matchup(): dot = League(dot_id, year) bob = League(bob_id, year) dot_score = dot.scoreboard() bob_score = bob.scoreboard() leagues = { bob: bob, dot: dot } data = { 'dot_matchup': dot_score, 'bob_matchup': bob_score } return jsonpickle.encode(data)
def loadLeague(reload=0): if sys.version_info[0] < 2: print(" requires python 2 or above") elif sys.version_info[0] == 2: picklePath = "lea2.gue" else: picklePath = "lea.gue" leagueID = 412124 year = 2017 weeksPlayed = 0 if reload == 1: league = League(leagueID, year) fSchedule = [] for i in range(1, 14): thisWeek = parseWeek(league, i) if thisWeek[0].homeScore == 0: played = 0 else: played = 1 weeksPlayed += played fSchedule.append([thisWeek, played]) teamKey = {} for i in range(len(league.teams)): teamKey[league.teams[i].team_id] = i leagueDB = [league, fSchedule, weeksPlayed, teamKey] with open(picklePath, "wb") as lFile: pickle.dump(leagueDB, lFile) else: with open(picklePath, "rb") as lFile: leagueDB = pickle.load(lFile) return leagueDB
def bot_main(function): bot_id = os.environ["BOT_ID"] league_id = os.environ["LEAGUE_ID"] try: year = os.environ["LEAGUE_YEAR"] except: year = 2017 bot = GroupMeBot(bot_id) league = League(league_id, year) if function == "get_matchups": text = get_matchups(league) bot.send_message(text) elif function == "get_scoreboard": text = get_scoreboard(league) bot.send_message(text) elif function == "get_scoreboard_short": text = get_scoreboard_short(league) bot.send_message(text) elif function == "get_close_scores": text = get_close_scores(league) bot.send_message(text) elif function == "init": try: text = os.environ["INIT_MSG"] bot.send_message(text) except: '''do nothing here, empty init message''' pass else: text = "Something happened. HALP" bot.send_message(text)
def create_league(message): """Get input from user to fill out the name and members of a new league :param message: string, to prompt the user to create the new league :return: dict, expected wins (set to 0.0) for each team in the league """ lg_name = input(message).strip() lg_id = int(input('Please enter the league id (see the url in any league page): ').strip()) # create a directory to contain power rankings files for this league path_to_league = os.path.join('leagues', '{} ({})'.format(lg_name, lg_id)) os.mkdir(path_to_league) espn_league = League(lg_id, 2017) # list of owner names as given by their espn accounts owners = [tm.owner for tm in espn_league.teams] # key value pairs of an owner and his cumulative expected wins for the season; start with zero expected_wins_dict = dict([(owner, 0.0) for owner in owners]) # avoid creating file with one or more spaces, so silently replace with hyphen rankings_filepath = os.path.join(path_to_league, '{}-00.csv'.format(lg_name.replace(' ', '-'))) # write owner, value to this first file with open(rankings_filepath, 'w') as f: writer = csv.writer(f) writer.writerows(expected_wins_dict.items()) return lg_name, lg_id, expected_wins_dict
def bot_main(function): bot_id = os.environ["BOT_ID"] league_id = os.environ["LEAGUE_ID"] try: year = os.environ["LEAGUE_YEAR"] except: year=2017 bot = GroupMeBot(bot_id) league = League(league_id, year) test = False if test: print(get_matchups(league)) print(get_scoreboard(league)) print(get_scoreboard_short(league)) print(get_close_scores(league)) print(get_power_rankings(league)) print(get_trophies(league)) function="get_final" #bot.send_message(get_trophies(league)) if function=="get_matchups": text = get_matchups(league) bot.send_message(text) elif function=="get_scoreboard": text = get_scoreboard(league) bot.send_message(text) elif function=="get_scoreboard_short": text = get_scoreboard_short(league) bot.send_message(text) elif function=="get_close_scores": text = get_close_scores(league) bot.send_message(text) elif function=="get_power_rankings": text = get_power_rankings(league) bot.send_message(text) elif function=="get_trophies": text = get_trophies(league) bot.send_message(text) elif function=="get_final": text = "Final " + get_scoreboard_short(league, True) text = text + "\n\n" + get_trophies(league) if test: print(text) else: bot.send_message(text) elif function=="init": try: text = os.environ["INIT_MSG"] bot.send_message(text) except: '''do nothing here, empty init message''' pass else: text = "Something happened. HALP" bot.send_message(text)
def retrieve_lg_info(league_id, year): # todo docstring # flag for whether league access was successful all_good = True try: league = League(league_id, year) # todo function for wrapping with this style except PrivateLeagueException: lg_id_message.text = ( '<b><p style="color: red;">League not viewable by public. ' '<a href="http://support.espn.com/articles/en_US/FAQ/Making-a-Private-League-' 'Viewable-to-the-Public?section=Fantasy-Football" target="_blank">' 'How to Resolve</a></p></b>') all_good = False except InvalidLeagueException: lg_id_message.text = '<b><p style="color: red;">League with id {} does not exist.</p></b>'.format( league_id) all_good = False except UnknownLeagueException: lg_id_message.text = '<b><p style="color: red;">{} Season for league with id {} does not exist.</p></b>'.format( year, league_id) all_good = False if all_good: lg_id_message.text = '<b><p style="color: #fcbf16;">Compiling data for League {}, \n{} Season</p></b>'.format( league_id, year) teams = league.teams number_teams = league.settings.team_count # not available to just pull from league object latest_week = teams[0].wins + teams[0].losses # list of owner names as given by their espn accounts all_owners = [tm.owner for tm in teams] # to be used for options in dropdown menus owners_list_dd = [(owner, owner) for owner in all_owners] # espnff team objects to retrieve data all_team_objs = [Team(tm.owner, tm.scores) for tm in teams] # valid regular season weeks all_weeks = [i for i in range(1, latest_week + 1)] # given the name of an owner, returns index where it's found in the team objects list owner_to_idx_dict = { tm_obj.owner: index for index, tm_obj in enumerate(all_team_objs) } return league, number_teams, latest_week, all_owners, owners_list_dd, all_team_objs, all_weeks, owner_to_idx_dict
def get_scoreboard_df(league_id, year, week): league = League(league_id, year) scoreboard = league.scoreboard(week=week) scoreboard_list_of_dicts = [{ 'Home_Team': matchup.home_team.team_name.title(), 'Home_Owner': clean_owner(matchup.home_team.owner.title()), 'Home_Score': matchup.home_score, 'Home_Wins': matchup.home_team.wins, 'Home_Losses': matchup.home_team.losses, 'Away_Team': matchup.away_team.team_name.title(), 'Away_Owner': clean_owner(matchup.away_team.owner.title()), 'Away_Score': matchup.away_score, 'Away_Wins': matchup.away_team.wins, 'Away_Losses': matchup.away_team.losses, 'Winner': matchup.home_team.team_name.title() if matchup.home_score > matchup.away_score else matchup.away_team.team_name.title(), 'Loser': matchup.home_team.team_name.title() if matchup.home_score < matchup.away_score else matchup.away_team.team_name.title() } for matchup in scoreboard] cols = ['Team', 'Owner', 'Score', 'Wins', 'Losses'] # Updating Wins and Losses based on this week's result for matchup_dict in scoreboard_list_of_dicts: if matchup_dict['Winner'] == matchup_dict['Home_Team']: matchup_dict['Home_Wins'] += 1 matchup_dict['Away_Losses'] += 1 for col in cols: matchup_dict['Winning_' + col] = str(matchup_dict['Home_' + col]) matchup_dict['Losing_' + col] = str(matchup_dict['Away_' + col]) else: matchup_dict['Away_Wins'] += 1 matchup_dict['Home_Losses'] += 1 for col in cols: matchup_dict['Winning_' + col] = str(matchup_dict['Away_' + col]) matchup_dict['Losing_' + col] = str(matchup_dict['Home_' + col]) scoreboard_df = pd.DataFrame(scoreboard_list_of_dicts) scoreboard_df = scoreboard_df[['Winning_' + col for col in cols] + ['Losing_' + col for col in cols]] return scoreboard_df
def hello(): if request.method == 'POST': if request.form['league_id'] and request.form['league_year']: league_id, league_year = request.form['league_id'], request.form[ 'league_year'] league = League(league_id, league_year) return render_template('main.html', league=league) return render_template('main.html') return render_template('main.html')
async def leagueid(self, ctx, *, id: str): try: try: self.league = League(int(id), 2017) except: await bot.say("Unable to find a league with ID \"" + id +"\".") print("New League ID: " + str(self.league.league_id)) await self.bot.say("The league has been changed to: " + self.league.settings.name) except discord.errors.Forbidden: await self.bot.say("Missing Permissions.")
def get_scoreboard(league_id, year): '''Gets current week's scoreboard''' league = League(league_id, year) matchups = league.scoreboard() score = [ '%s\t %s - %s\t %s' % (i.home_team.team_abbrev, i.home_score, i.away_score, i.away_team.team_abbrev) for i in matchups if i.away_team ] text = ['Score Update'] + score return '\n'.join(text)
def index(): league_id = 427822 year = 2018 league = League(league_id, year) response = {} response['matchups'] = get_matchups(league) response['scoreboard'] = get_scoreboard(league) response['scoreboard_short'] = get_scoreboard_short(league) response['power_rankings'] = get_power_rankings(league) response['trophies'] = get_trophies(league) errors = [] # return render_template('index.html') return render_template('index.html', response=response, errors=errors)
def initial_setup(): # read in private league settings from config.py league_id = config.league_id year = config.year # credentials to let us see a private league espn_s2 = config.espn_s2 swid = config.swid # get league info from ESPN league = League(league_id, year, espn_s2, swid) # define some variables for convenience global scoreboard global teams global settings global power_rankings scoreboard = league.scoreboard() teams = league.teams settings = league.settings power_rankings = league.power_rankings
def bot_main(function): bot_id = os.environ["BOT_ID"] league_id = os.environ["LEAGUE_ID"] try: year = os.environ["LEAGUE_YEAR"] except KeyError: year=2018 bot = GroupMeBot(bot_id) league = League(league_id, year) test = False if test: print(get_matchups(league)) print(get_scoreboard(league)) print(get_scoreboard_short(league)) print(get_close_scores(league)) print(get_power_rankings(league)) print(get_trophies(league)) function="get_final" #bot.send_message(get_trophies(league)) if function=="get_matchups": text = get_matchups(league) bot.send_message(text) elif function=="get_scoreboard": text = get_scoreboard(league) bot.send_message(text) elif function=="get_scoreboard_short": text = get_scoreboard_short(league) bot.send_message(text) elif function=="get_close_scores": text = get_close_scores(league) bot.send_message(text) elif function=="get_power_rankings": text = get_power_rankings(league) bot.send_message(text) elif function=="get_trophies": text = get_trophies(league) bot.send_message(text) elif function=="get_final": text = "Final " + get_scoreboard_short(league, True) text = text + "\n\n" + get_trophies(league) if test: print(text) else: bot.send_message(text) elif function=="get_random_phrase": text = random_phrase() bot.send_message(text) elif function=="predict_high": text = "I predict this weeks highest scorer will be..." bot.send_message(text) time.sleep(10) text = player_name() bot.send_message(text) elif function=="predict_low": text = "I predict this weeks lowest scorer will be..." bot.send_message(text) time.sleep(10) text = player_name() bot.send_message(text) elif function=="predict_td": text = "I predict the most touchdowns this week will be scored by..." bot.send_message(text) time.sleep(10) text = player_name() bot.send_message(text) elif function=="predict_champ": text = "I predict this years champion will be..." bot.send_message(text) time.sleep(45) text = player_name() bot.send_message(text) elif function=="predict_spoob": text = "I predict this years Spooby will be..." bot.send_message(text) time.sleep(45) text = player_name() bot.send_message(text) elif function=="init": try: text = os.environ["INIT_MSG"] bot.send_message(text) except KeyError: #do nothing here, empty init message pass else: text = "Something happened. HALP" bot.send_message(text)
def bot_main(function): try: bot_id = os.environ["BOT_ID"] except KeyError: bot_id = 1 try: slack_webhook_url = os.environ["SLACK_WEBHOOK_URL"] except KeyError: slack_webhook_url = 1 try: discord_webhook_url = os.environ["DISCORD_WEBHOOK_URL"] except KeyError: discord_webhook_url = 1 league_ids = os.environ["LEAGUE_ID"] league_ids = league_ids.split(",") try: year = os.environ["LEAGUE_YEAR"] except KeyError: year = 2018 bot = GroupMeBot(bot_id) slack_bot = SlackBot(slack_webhook_url) discord_bot = DiscordBot(discord_webhook_url) leagues = [] for league_id in league_ids: leagues.append(League(league_id, year)) test = False if test: for league in leagues: print(get_matchups(league)) print(get_scoreboard(league)) print(get_scoreboard_short(league)) print(get_close_scores(league)) print(get_power_rankings(league)) print(get_trophies(league)) function = "get_final" #bot.send_message(get_trophies(league)) bot.send_message("test complete") slack_bot.send_message("test complete") discord_bot.send_message("test complete") if function == "get_matchups": for league in leagues: text = get_matchups(league) bot.send_message(text) slack_bot.send_message(text) discord_bot.send_message(text) elif function == "get_scoreboard": for league in leagues: text = get_scoreboard(league) bot.send_message(text) slack_bot.send_message(text) discord_bot.send_message(text) elif function == "get_scoreboard_short": for league in leagues: text = get_scoreboard_short(league) bot.send_message(text) slack_bot.send_message(text) discord_bot.send_message(text) elif function == "get_close_scores": for league in leagues: text = get_close_scores(league) bot.send_message(text) slack_bot.send_message(text) discord_bot.send_message(text) elif function == "get_power_rankings": for league in leagues: text = get_power_rankings(league) bot.send_message(text) slack_bot.send_message(text) discord_bot.send_message(text) elif function == "get_trophies": for league in leagues: text = get_trophies(league) bot.send_message(text) slack_bot.send_message(text) discord_bot.send_message(text) elif function == "get_final": for league in leagues: text = "Final " + get_scoreboard_short(league, True) text = text + "\n\n" + get_trophies(league) if test: print(text) else: bot.send_message(text) slack_bot.send_message(text) discord_bot.send_message(text) elif function == "init": try: text = os.environ["INIT_MSG"] if text != '': bot.send_message(text) slack_bot.send_message(text) discord_bot.send_message(text) except KeyError: #do nothing here, empty init message pass else: text = "Something happened. HALP" bot.send_message(text) slack_bot.send_message(text) discord_bot.send_message(text)
def bot_main(function): try: bot_id = os.environ["BOT_ID"] except KeyError: bot_id = 1 try: webhook_url = os.environ["WEBHOOK_URL"] except KeyError: webhook_url = 1 league_id = os.environ["LEAGUE_ID"] try: year = os.environ["LEAGUE_YEAR"] except KeyError: year = 2018 bot = GroupMeBot(bot_id) #slack_bot = SlackBot(webhook_url) league = League(league_id, year) test = False if test: print(get_matchups(league)) print(get_scoreboard(league)) print(get_scoreboard_short(league)) print(get_close_scores(league)) print(get_power_rankings(league)) print(get_trophies(league)) function = "get_final" #bot.send_message(get_trophies(league)) bot.send_message("test complete") #slack_bot.send_message("test complete") if function == "get_matchups": text = get_matchups(league) bot.send_message(text) #slack_bot.send_message(text) elif function == "get_scoreboard": text = get_scoreboard(league) bot.send_message(text) #slack_bot.send_message(text) elif function == "get_scoreboard_short": text = get_scoreboard_short(league) bot.send_message(text) #slack_bot.send_message(text) elif function == "get_close_scores": text = get_close_scores(league) bot.send_message(text) #slack_bot.send_message(text) elif function == "get_power_rankings": text = get_power_rankings(league) bot.send_message(text) #slack_bot.send_message(text) elif function == "get_trophies": text = get_trophies(league) bot.send_message(text) #slack_bot.send_message(text) elif function == "get_final": text = "Final " + get_scoreboard_short(league, True) text = text + "\n\n" + get_trophies(league) if test: print(text) else: bot.send_message(text) #slack_bot.send_message(text) elif function == "init": try: text = os.environ["INIT_MSG"] bot.send_message(text) #slack_bot.send_message(text) except KeyError: #do nothing here, empty init message pass else: text = "Something happened. HALP" bot.send_message(text)
raise Exception("could not find bot user with the name " + ARGS.botname) if __name__ == '__main__': PARSER = argparse.ArgumentParser() PARSER.add_argument('-slacktoken', default='SLACK_FOOTBALL_TOKEN') PARSER.add_argument('-espnleague', default='ESPN_LEAGUE') PARSER.add_argument('-botname', default='footballbot') PARSER.add_argument('-espns2', default='ESPNS2') PARSER.add_argument('-swid', default='SWID') PARSER.add_argument('-websocketdelay', type=int, default=1) ARGS = PARSER.parse_args() ARGS.league = League(int(os.environ.get(ARGS.espnleague)), 2017, espn_s2=os.environ.get(ARGS.espns2), swid=os.environ.get(ARGS.swid)) # sc = ARGS.league.scoreboard(projections=True) # home_names = '\n'.join(map(lambda x: x.home_team.team_abbrev, sc)) # home_scores = '\n'.join(map(lambda x: x.home_score, sc)) # home_proj = '\n'.join(map(lambda x: x.home_projection, sc)) # print(home_scores) # exit() CLIENT = SlackClient(os.environ.get(ARGS.slacktoken)) BOTID = getfootballbot(ARGS, CLIENT) ARGS.atbot = "<@" + BOTID + ">" startloop(ARGS, CLIENT)
def createLeagueObject(leagueId, year=getCurrentYear()): return League(leagueId, year)
# use the most recent file from which to pull values latest_rankings = leagues[league_name][0] # no need to read from file if first run with a league (data already loaded) if expected_wins is None: # read in the most recent (cumulative) expected win values with open(latest_rankings, 'r') as infile: r = csv.reader(infile) expected_wins = {row[0]: float(row[1]) for row in r if row} week_num = int(input('Select a week to operate on: ').strip()) # used to pull data straight from ESPN league league_obj = League(league_id, 2017) sorted_scores = get_current_scores(league_obj, week_num) # for expected wins calculation num_teams = len(sorted_scores) # add expected number of wins for this week to the season-long cumulative value for idx, pair in enumerate(sorted_scores): # e.g., 12-team league, 2nd highest scorer would lose one matchup --> 1 - (1 * 1/11) = .909 expected wins ew_this_week = 1 - (idx * (1/(num_teams - 1))) sorted_scores[idx][1] = expected_wins[pair[0]] + ew_this_week
def bot_main(function): try: bot_id = os.environ["BOT_ID"] except KeyError: bot_id = 1 try: slack_webhook_url = os.environ["SLACK_WEBHOOK_URL"] except KeyError: slack_webhook_url = 1 try: discord_webhook_url = os.environ["DISCORD_WEBHOOK_URL"] except KeyError: discord_webhook_url = 1 league_id = os.environ["LEAGUE_ID"] try: year = os.environ["LEAGUE_YEAR"] except KeyError: year=2018 bot = GroupMeBot(bot_id) slack_bot = SlackBot(slack_webhook_url) discord_bot = DiscordBot(discord_webhook_url) league = League(league_id, year) test = False if test: print(get_matchups(league)) print(get_scoreboard(league)) print(get_scoreboard_short(league)) print(get_close_scores(league)) print(get_power_rankings(league)) print(get_trophies(league)) function="get_final" #bot.send_message(get_trophies(league)) bot.send_message("test complete") slack_bot.send_message("test complete") discord_bot.send_message("test complete") if function=="get_matchups": text = get_matchups(league) bot.send_message(text) slack_bot.send_message(text) discord_bot.send_message(text) elif function=="get_scoreboard": text = get_scoreboard(league) bot.send_message(text) slack_bot.send_message(text) discord_bot.send_message(text) elif function=="get_scoreboard_short": text = get_scoreboard_short(league) bot.send_message(text) slack_bot.send_message(text) discord_bot.send_message(text) elif function=="get_close_scores": text = get_close_scores(league) bot.send_message(text) slack_bot.send_message(text) discord_bot.send_message(text) elif function=="get_power_rankings": text = get_power_rankings(league) bot.send_message(text) slack_bot.send_message(text) discord_bot.send_message(text) elif function=="get_trophies": text = get_trophies(league) bot.send_message(text) slack_bot.send_message(text) discord_bot.send_message(text) elif function=="get_final": text = "Final " + get_scoreboard_short(league, True) text = text + "\n\n" + get_trophies(league) if test: print(text) else: bot.send_message(text) slack_bot.send_message(text) discord_bot.send_message(text) else: text = "Something happened. HALP" bot.send_message(text) slack_bot.send_message(text) discord_bot.send_message(text)
def rank(): return render_template('ranks.html', league=League(1140354, 2017).power_rankings(week=3))
def teams(): dot = League(dot_id, year) bob = League(bob_id, year) return render_template('teams.html', bob=bob, dot=dot)
def get_league(self, league_id, year): """Fetch the League object, passing auth_s2 and auth_swid for a private league.""" return League(league_id, year, self.__auth_s2, self.__auth_swid)
# Import table printing from prettytable import PrettyTable # Import the league class and set the ID from espnff import League league_id = 1743204 league_id = 1743205 # Output information to file output = open('output.txt', 'w') # An array for the years years = [2014, 2015, 2016, 2017] # Output league name s = "######################\n## " + League( league_id, 2018).settings.name + " ##\n######################\n" output.writelines(s) # For loop to go through every year for year in years: league = League(league_id, year) settings = league.settings matchup_count = int(settings.team_count / 2) # Print out year header s = "\n########\n# " + str(year) + " #\n########\n\n" output.writelines(s) # Hold all teams in teams array teams = league.teams
def matchups_handler(msg): league = League(LEAGUE_ID, YEAR) return get_matchups(league)
def power_graphs(league_id=None, year=None, espn_s2=None, swid=None, latestWeek=17): if league_id == None: raise Exception('Must enter league ID...Exiting') elif year == None: raise Exception('Must enter league year...Exiting') league = League(league_id, year, espn_s2, swid) wks = [] twks = [] trks = [] def find_index(df, column, find_term): df = df[column][df.index[df[column] == find_term]] return (df.index[0]) for i in range(0, latestWeek): w = i + 1 wk = league.power_rankings(week=w) wk = pd.DataFrame(wk, columns=['Score', 'Team']) wks.append(wk) wk = wks wks = [] for i in range(len(wk)): t = [] s = [] for x in range(len(wk[i])): tb = str(wk[i]['Team'][x]) tb = str(tb)[5:(len(tb) - 1)] t.append(tb) s.append(float(wk[i]['Score'][x])) ts = pd.DataFrame({'Team': t, 'Score': s}) wks.append(ts) for i in range(len(wks)): wks[i].sort_values('Team', inplace=True) wks[i].reset_index(drop=True, inplace=True) wksTeam = [] for i in range(len(wks)): place = [i + 1] place.extend(list(wks[i]['Score'])) wksTeam.append(place) c = ['Week'] c.extend(sorted(t)) ##Change this to fit your league's team names color_dict = { 'Team1': '#00e9ff', 'Team2': '#0083ff', "Team3": '#2e00ff', 'Team4': '#981E32', 'Team5': '#521f6d', 'Team6': '#d8ff00', "Team7": '#002C5F', 'Team8': '#ffa100', 'Team9': '#6d571f', 'Team10': '#ff0000', 'Team11': '#46b230', 'Team12': '#00ff11' } for i in range(len(sorted(t))): color_dict[t[i]] = color_dict['Team' + str(i + 1)] tpd = pd.DataFrame(data=wksTeam, columns=c) tpd.to_csv('wk' + str(len(wksTeam)) + ' power scores.csv', index=False) tpd = pd.read_csv('wk' + str(len(wksTeam)) + ' power scores.csv', index_col='Week') for i in range(len(wks)): test = wks[i].sort_values('Score', ascending=False) twks.append(test.reset_index(drop=True)) for x in range(len(twks)): place = [x + 1] for i in range(len(sorted(t))): place.append(find_index(twks[x], 'Team', sorted(t)[i]) + 1) trks.append(place) ranks = pd.DataFrame(data=trks, columns=c) ranks.to_csv('wk' + str(len(wksTeam)) + ' power rankings.csv', index=False) ranks = pd.read_csv('wk' + str(len(wksTeam)) + ' power rankings.csv', index_col='Week') lines = tpd.plot.line( title='Power Rankings', table=True, use_index=False, color=[color_dict.get(x, '#333333') for x in ranks.columns]) plt.axes().get_xaxis().set_visible(False) plt.legend(bbox_to_anchor=(1.25, 1), loc='upper right', borderaxespad=0.) plt.plot(marker='o') plt.subplots_adjust(0.13, 0.36, 0.81, 0.96, 0.2, 0.2) lines = ranks.plot.line( title='Power Score', table=True, use_index=False, color=[color_dict.get(x, '#333333') for x in ranks.columns]).invert_yaxis() plt.axes().get_xaxis().set_visible(False) plt.legend(bbox_to_anchor=(1.25, 1), loc='upper right', borderaxespad=0.) plt.plot(marker='o') plt.subplots_adjust(0.13, 0.36, 0.81, 0.96, 0.2, 0.2) plt.show()
def __init__(self, year, leagueID, cookie1, cookie2): self.projQB = pd.DataFrame() self.projRB = pd.DataFrame() self.projWR = pd.DataFrame() self.projTE = pd.DataFrame() self.league_id = leagueID self.year = year self.league = League(self.league_id, self.year, espn_s2=cookie1, swid=cookie2) self.teams = self.league.teams ''' self.teams[0].keepers = {'Josh Gordon':6,'JuJu Smith-Schuster':6} self.teams[1].keepers = {'David Johnson':16,'Michael Thomas':11} self.teams[2].keepers = {'Jordan Howard':11,'Marvin Jones':6} self.teams[3].keepers = {'Adam Thielen':7,'Dalvin Cook':42} self.teams[4].keepers = {'DeAndre Hopkins':42,'Melvin Gordon':15} self.teams[5].keepers = {'Joe Mixon':32,'Travis Kelce':23} self.teams[6].keepers = {'Ezekiel Elliott':56,'Jerick McKinnon':6} self.teams[7].keepers = {'Devonta Freeman':16,'Todd Gurley':53} self.teams[8].keepers = {'Leonard Fournette':43,'Keenan Allen':32} self.teams[9].keepers = {'Alvin Kamara':6,'Kareem Hunt':16} self.teams[0].tradeCosts = -15 self.teams[2].tradeCosts = -5 ''' self.settings = self.league.settings self.regSeason = self.settings.reg_season_count self.numTeams = self.settings.team_count self.numKeepers = self.settings.keeper_count self.rosterConstr = self.settings.roster self.auctionCap = 200 self.keeperCost = 0 self.tradeCosts = 0 self.numKept = 0 self.scoring = { 'pYards': 0.04, 'Int': -2, 'pTD': 4, 'p2PT': 2, 'rshYards': 0.1, 'rshTD': 6, 'rsh2PT': 2, 'recYards': 0.1, 'recTD': 6, 'rec': 0.5, 'rec2PT': 2, 'KRTD': 6, 'FRTD': 6, 'PRTD': 6, 'intTD': 6, 'fumL': -2, 'BPTD': 6, 'ret2PT': 2, 'sfty': 1 } self.positions = ['QB', 'RB', 'WR', 'TE'] self.projQB = pd.read_csv("projQB.csv", index_col='Player') self.projQB.dropna(inplace=True) self.projQB['YDS'] = self.projQB['YDS'].str.replace(',', '') self.projQB.ix[:, 1:] = self.projQB.ix[:, 1:].astype(float) self.projRB = pd.read_csv("projRB.csv", index_col='Player') self.projRB.dropna(inplace=True) self.projRB['YDS'] = self.projRB['YDS'].str.replace(',', '') self.projRB.ix[:, 1:] = self.projRB.ix[:, 1:].astype(float) self.projWR = pd.read_csv("projWR.csv", index_col='Player') self.projWR.dropna(inplace=True) self.projWR['YDS'] = self.projWR['YDS'].str.replace(',', '') self.projWR.ix[:, 1:] = self.projWR.ix[:, 1:].astype(float) self.projTE = pd.read_csv("projTE.csv", index_col='Player') self.projTE.dropna(inplace=True) self.projTE['YDS'] = self.projTE['YDS'].str.replace(',', '') self.projTE.ix[:, 1:] = self.projTE.ix[:, 1:].astype(float) ''' for team in range(0,len(self.teams)): self.keeperCost+=sum(self.teams[team].keepers.values()) self.tradeCosts+=self.teams[team].tradeCosts self.numKept+=len(self.teams[team].keepers.keys()) for keeper in self.teams[team].keepers: if keeper in self.projQB.index: self.projQB.drop(keeper,axis =0, inplace = True) elif keeper in self.projRB.index: self.projRB.drop(keeper,axis = 0, inplace = True) elif keeper in self.projWR.index: self.projWR.drop(keeper,axis=0, inplace = True) elif keeper in self.projTE.index: self.projTE.drop(keeper, axis = 0, inplace = True) else: print (keeper) print("you f****d up Aaron") ''' self.freeMoney = (self.numTeams * 200) + (self.tradeCosts) - self.keeperCost - ( (len(self.rosterConstr.keys()) - 1) * self.numTeams) + (self.numKept * self.numTeams) #print (self.rosterConstr) pass
self.name = name self.all_scores = scores self.wins = wins self.losses = losses def gettotal(self, scores): self.totalScore = 0 for score in scores: self.totalScore += score return self.totalScore # END SERIALIZABLE CLASSES # get my team's overall data and write to disk league = League(league_id, year) teams = league.teams my_team = next(team for team in teams if team.team_id == my_team_id) team_obj = TeamObj(my_team.team_name, my_team.scores, my_team.wins, my_team.losses) team_obj.gettotal(team_obj.all_scores) with open('team.json', 'w') as f: json.dump(team_obj.__dict__, f) # get my week's data and write to disk week = league.scoreboard(week=this_week) week_match = getmatch(week, my_team_id) # print(type(week_match)) # for vars in week_match: # print(type(vars)) # for key, value in week_match.items():
from espnff import League import matplotlib.pyplot as plt import numpy as np league_id = 692156 year = 2017 espn_s2 = 'AEBlxO7SfF6cuPjEvujvAbpQ5fmvr7oYPxIyQV9qsazYKOuNCN14sb%2FBGr4yOyXwUtLTS8a4igLp2SrraMI6lC1EoWiHHKPhUZyqMiS%2B7JCKSapXyDbqHnX8ur1Ga0q3d7sGe9i4gi8ZKbIqaZWhJBdEqqa2UXBDLrgoxpUade%2BzepUwahpfqOvzOr87TiXACwdcnRIqPmhXGW4SuPU8kMlLqWPgj3zL%2FGLKF%2B%2B2gZ1AQxgHUBXYIXpHatVRgWndZNPLIfehi8FV5Xmi8PZnWP2%2F' swid = "{E9BFC86F-E2A7-4FD8-BFC8-6FE2A71FD8B5}" league = League(league_id, year, espn_s2, swid) [ teamDave, teamLuke, teamFef, teamCody, teamAddy, teamJoel, teamEric, teamTanner, teamTracy, teamBrittain ] = league.teams labels = ('Dave', 'Luke', 'Fef', 'Cody', 'Addy', 'Joel', 'Eric', 'Tanner', 'Tracy', 'Brittain') #grab head2head wins winsH2H = np.zeros(shape=(10, 1)) i = 0 for teamName in league.teams: winsH2H[i] = teamName.wins i += 1 winsH2H = np.transpose(winsH2H)[0] def playEveryone(teamNames): weeklyScores = np.zeros(shape=(10, 14)) j = 0 for teamName in teamNames: # for each team weeklyScores[j] = teamName.scores j += 1