def gen_cumulative_lists_from_weeks(self, league_start_date, my_date): # need to check that all dates up to start of date range / query date have been previously calculated # if dates up to start haven't been calculated, raise exception, since the cumulative tally won't make any sense self.check_tallied_dates(league_start_date, my_date) for category in self.crunch_dict['cumulative_data']['categories']: is_goalie = False if category in self.crunch_dict['master_categories']['boxscore']['goalie']: is_goalie = True for team in self.crunch_dict['teams']: assembled_weekly_list = [] for week in self.crunch_dict['weeks']: assembled_weekly_list.extend(self.crunch_dict['weeks'][week]['teams'][team]['skater' if not is_goalie else 'goalie'][category]) # when we do weekly tallies, use day of week to determine index # NHL starts on a wednesday, so here we trim the first 2 leading zeroes away assembled_weekly_list = assembled_weekly_list[2:] # we also need to trim the end away since there may be trailing zeroes if entire week hasn't been filled in my_date_index = Date_Utils.date_to_int(league_start_date, my_date) assembled_weekly_list = assembled_weekly_list[:my_date_index+1] # add up all the numbers self.crunch_dict['cumulative_data']['teams'][team][category] = self.gen_cumulative_data_list(assembled_weekly_list) pass # if we got here it was successful, and we can safely say we have cumulative data up to the query date self.crunch_dict['cumulative_data']['last_date'] = Date_Utils.date_to_string(my_date)
def get_week(self, date): sorted_weeks = sorted(self.league['week_from_date']) for start_date in sorted_weeks: if date < Date_Utils.string_to_date(start_date): date += timedelta(days=7) else: day_of_week = date.weekday() return self.league['week_from_date'][Date_Utils.date_to_string( date - timedelta(days=day_of_week))]
def check_tallied_dates(self, league_start_date, check_date): # build a list of all the tallied dates all_got_dates = [] for week in self.crunch_dict['weeks']: all_got_dates.extend(self.crunch_dict['weeks'][week]['got_dates']) all_got_dates = [Date_Utils.string_to_date(date_string) for date_string in sorted(all_got_dates)] # build a list of all dates from league start date all_check_dates = Date_Utils.gen_dates_list(league_start_date, check_date+timedelta(days=1)) # if there isn't an unbroken chain til the check_date, we can't tally cumulative data. # it doesn't really make sense to fill it all in, since that might not be what is desired. # so just raise an error and decide what to do after. for date_obj in all_check_dates: if date_obj not in all_got_dates: raise AssertionError("Not all dates up to {} have been tallied. Call data driver with date range {},{}".format(check_date, league_start_date, check_date))
def __init__(self): self.league = {} self.teams = {} self.players = {} self.weeks = {} self.NHL_teams = {} self.NHL_base_url = "https://statsapi.web.nhl.com/api/v1/" self.NHL_start_date = Date_Utils.string_to_date("2018-10-03")
def set_week_from_date(self, start_date, end_date, long_weeks=None): week_from_date = {} my_date = Date_Utils.string_to_date(start_date) live_end_date = Date_Utils.string_to_date(end_date) my_week = 1 while my_date < live_end_date: if long_weeks and my_week in long_weeks: # 1st half week_from_date[Date_Utils.date_to_string( my_date)] = 'week_{}a'.format(my_week) # 2nd half my_date += timedelta(days=7) week_from_date[Date_Utils.date_to_string( my_date)] = 'week_{}b'.format(my_week) else: week_from_date[Date_Utils.date_to_string( my_date)] = 'week_{}'.format(my_week) my_week += 1 my_date += timedelta(days=7) pass return week_from_date
def parse_raw_daily_schedule(self, date): schedule_url = self.NHL_base_url + "/schedule" schedule_url += "?date={}".format(Date_Utils.date_to_string(date)) r = requests.get(schedule_url) schedule_json = json.dumps(r.json(), indent=4) schedule_object = json.loads(schedule_json) if schedule_object['totalGames'] == 0: return games_list = schedule_object['dates'][0]['games'] for game_object in games_list: if game_object['gameType'] != 'R': continue game_id = game_object['gamePk'] self.parse_raw_boxscore(game_id, date)
def daily_update_teams_stats(self, nhl_yahoo_object, my_date): week = nhl_yahoo_object.get_week(my_date) day_of_week = my_date.weekday() my_date_string = Date_Utils.date_to_string(my_date) for team in nhl_yahoo_object.weeks[week]['teams']: for player in nhl_yahoo_object.weeks[week]['teams'][team]['starters']: if my_date_string in nhl_yahoo_object.weeks[week]['teams'][team]['starters'][player]: is_goalie = True if nhl_yahoo_object.weeks[week]['teams'][team]['starters'][player]['active_position'] == 'G' else False if not is_goalie: for category in self.crunch_dict['master_categories']['boxscore']['skater']: self.crunch_dict['weeks'][week]['teams'][team]['skater'][category][day_of_week] += nhl_yahoo_object.weeks[week]['teams'][team]['starters'][player][my_date_string][category] else: for category in self.crunch_dict['master_categories']['boxscore']['goalie']: self.crunch_dict['weeks'][week]['teams'][team]['goalie'][category][day_of_week] += nhl_yahoo_object.weeks[week]['teams'][team]['starters'][player][my_date_string][category]
def parse_player_game_stats(self, team_object, my_date): # go thru active skaters / goalies using list in team object # figure out if they are an active player for the week in question, and if so add their data to the fantasy team in question # also, check last known NHL team. If new, change the team. ######### need to decide if I should always switch, or only on todays date. I feel like always ######### week = self.get_week(my_date) NHL_team = team_object['team']['name'] roster = team_object['players'] for player_id in roster: player = roster[player_id]['person']['fullName'] if player in self.weeks[week]['starters'] and roster[player_id][ 'stats']: print(player) fantasy_team = self.weeks[week]['starters'][player] is_goalie = True if 'G' in self.players[player][ 'eligible_positions'] else False # update the correct fantasy team with the boxscore player_game_stats = roster[player_id]['stats'][ 'skaterStats' if not is_goalie else 'goalieStats'] self.weeks[week]['teams'][fantasy_team]['starters'][player][ Date_Utils.date_to_string(my_date)] = player_game_stats # check NHL team to ensure trades get accounted for FOR ACTIVE PLAYERS ################ if NHL_team != self.players[player]['last_known_NHL_team']: print( f"{player} got traded! From the {self.players[player]['last_known_NHL_team']}s to the {NHL_team}s" ) # make sure to set both players, and NHL teams, and REMOVE THE ENTRY FROM NHL_TEAMS self.NHL_teams[self.players[player] ['last_known_NHL_team']].remove(player) self.NHL_teams[NHL_team].append(player) self.players[player]['last_known_NHL_team'] = NHL_team
def __init__(self, **kwargs): self.oauth = self.get_oauth_session( "http://fantasysports.yahooapis.com/", kwargs['creds_json']) # the major components of the league are defined as object attributes that are dictionaries self.league = {} self.teams = {} self.players = {} self.weeks = {} # # we want to restore league from json file, so go to JSON object and do this league's restoral and return # if 'restoral' in kwargs: # print('restoring Yahoo League object....') # if 'JSON_object' not in kwargs: # print('error, need to restore to json object - use JSON_object in kwargs') # exit(1) # my_JSON = kwargs['JSON_object'] # my_JSON.restore_data(self, type(self).__name__, my_JSON, basic=True) # to make it easy, assume that each object either initializes league, scoring categories, weeks, and teams, or loads those from stored JSON if 'initialize' in kwargs: print('initializing Yahoo League object....') if 'league_url' not in kwargs or 'fantasy_url' not in kwargs or 'creds_json' not in kwargs: print( "error, need to initialize league with its URL, and yahoo's fantasy url, and a credentials file generated through OAuth." ) exit(1) self.league.update({ 'league_url': kwargs['league_url'], 'fantasy_url': kwargs['fantasy_url'] }) self.league.update({ 'league_info': self.parse_raw_league_data(kwargs['league_url']), 'scoring_categories': self.parse_raw_scoring_categories() }) # set start to usual Monday, rather than Wednesday # design: I store any dates as strings rather than live dates, for JSON. my_date = Date_Utils.string_to_date( self.league['league_info']['start_date']) - timedelta(days=2) self.league['start_date'] = Date_Utils.date_to_string(my_date) my_date = Date_Utils.string_to_date( self.league['league_info']['end_date']) self.league['end_date'] = Date_Utils.date_to_string(my_date) if 'long_weeks' in kwargs: self.league['week_from_date'] = self.set_week_from_date( self.league['start_date'], self.league['end_date'], long_weeks=kwargs['long_weeks']) else: self.league['week_from_date'] = self.set_week_from_date( self.league['start_date'], self.league['end_date']) self.league['date_from_week'] = { week: date for date, week in self.league['week_from_date'].items() } self.teams = self.parse_raw_league_teams()