def _get_stats(season, week, kind): """ Memoized stats getter. Requires fully-specified arguments to make effective use of the cache. """ games = nflgame.games(season, week=week, kind=kind) return nflgame.combine_max_stats(games)
def get_player_stats(year, week): games = nflgame.games(year, week) players = nflgame.combine_max_stats(games) for player in players: fantasy_points = (player.passing_yds * .04 + player.passing_tds * 4 - player.passing_int + player.rushing_yds * .1 + player.rushing_tds * 6 + player.receiving_yds * .1 + player.kickret_tds * 6 + player.receiving_tds * 6 + (player.receiving_twoptm + player.rushing_twoptm + player.passing_twoptm) * 2 - player.fumbles_lost * 2 + player.fumbles_rec_tds * 6) two_point_conversions = player.receiving_twoptm + player.rushing_twoptm + player.passing_twoptm # try: p = Player(player.name, year, week, player.player.position, fantasy_points, player.passing_yds, player.passing_tds, player.passing_int, player.rushing_yds, player.rushing_tds, player.receiving_yds, player.receiving_tds, player.kickret_tds, two_point_conversions, player.fumbles_lost, player.fumbles_rec_tds) except AttributeError: p = Player(player.name, year, week, "N/A", fantasy_points, player.passing_yds, player.passing_tds, player.passing_int, player.rushing_yds, player.rushing_tds, player.receiving_yds, player.receiving_tds, player.kickret_tds, two_point_conversions, player.fumbles_lost, player.fumbles_rec_tds) db.session.add(p) db.session.commit()
def __init__(self, year=datetime.datetime.now().year, week=current_week() - 1): self.week = week self.year = year self.games = nflgame.games(self.year, week=self.week) self.players = nflgame.combine_max_stats(self.games)
def gen_player_stats(season, week, player_id, team, game=None): fp = 'nflleague/espn-league-json/cache/C{}.json' filepath = fp.format(player_id) cache = get_json(filepath, {}) game_eid = nflleague.players[player_id]['schedule'].get( str(season), {}).get(str(week), 'bye') week, season = str(week), str(season) if season not in cache.keys(): cache[season] = {} if week not in cache[season].keys() or (season, week) == (str( nflleague.c_year), str(nflleague.c_week)): if game_eid == 'bye': cache[season][week] = {'BYE': True} save_json(filepath, cache) return cache[season][week] if game == None: game = nflgame.game.Game(game_eid) game_status = get_game_status(game) #Only update if game is currently playing or player stats haven't been cached yet if game_status in ['NOT PLAYED', 'PREGAME']: return {} if game_status in ['PLAYING', 'HALFTIME' ] or week not in cache[season].keys(): player = None if player_id in nflleague.players: player = Player(season, week, player_id) print('Caching Player {}, {} {} (Y:{} W:{})'.format( player.full_name, team, player.position, season, week)) play_stats = nflgame.combine_max_stats([game]) player_stats = list(play_stats.filter(playerid=player_id)) if len(player_stats) != 0: cache[season][week] = player_stats[0].stats else: cache[season][week] = {} #Any specialty stats that need to be broken down by play or some other metric can be added here if player.position == 'K': #Need to break down kicker scoring by play here because most efficient way to find length of indvl field goal. #Adds num of field goals made in 0-39,40-49,50+ ranges to kicker's stats dictionary. play_stats = nflgame.combine_plays([game]) plays = list( filter(lambda p: p.has_player(player_id), play_stats)) cache[season][week] = defaultdict(int, cache[season][week]) for play in plays: if 'kicking_fgm' in play._stats: if play._stats['kicking_fgm_yds'] <= 39: cache[season][week]['kicking_fgm_0_39'] += 1 elif play._stats['kicking_fgm_yds'] <= 49: cache[season][week]['kicking_fgm_40_49'] += 1 elif play._stats['kicking_fgm_yds'] >= 50: cache[season][week]['kicking_fgm_50_100'] += 1 elif 'kicking_fgmissed' in play._stats and int( play._stats['kicking_fgmissed_yds']) <= 39: cache[season][week]['kicking_fgmissed_0_39'] += 1 save_json(filepath, cache) return cache[season][week]
def get_player_and_team_data(year, week, scoring_method='nfl.com'): """Returns a dataframe of stats for all teams and players (with nonzero useful stats) for a given week in a given season. If ppr is True, uses point-per-reception scoring. Otherwise uses 1/2 point per reception. """ df = pd.DataFrame() defense_two_pt_returns_dict = get_defense_two_pt_returns(year, week) player_scoring_dict = get_player_scoring_dict(method=scoring_method) team_scoring_dict = get_team_scoring_dict() for game in nflgame.games(year, week): for team, opp_score in zip([game.home, game.away], [game.score_away, game.score_home]): i_row = len(df) team = team df.loc[i_row, 'week'] = week df.loc[i_row, 'team'] = team df.loc[i_row, 'position'] = 'DEFENSE' df.loc[i_row, 'player'] = team + '-DEFENSE' for team_stat in team_scoring_dict: if team_stat == 'team_defense_two_pt_return': df.loc[i_row, team_stat] = ( defense_two_pt_returns_dict['teams'][team]) elif team_stat == 'team_points_allowed': df.loc[i_row, team_stat] = opp_score else: stat = team_stat.replace('team_', '') df.loc[i_row, team_stat] = get_team_defense_stat( game, team, stat) players = nflgame.combine_max_stats(nflgame.games(year, week)) for player in players: i_row = len(df) df.loc[i_row, 'week'] = week df.loc[i_row, 'team'] = player.team df.loc[i_row, 'position'] = player.guess_position df.loc[i_row, 'player'] = player.name df.loc[i_row, 'defense_two_pt_return'] = ( defense_two_pt_returns_dict['players'][player.name]) for stat in player._stats: if stat in player_scoring_dict: df.loc[i_row, stat] = getattr(player, stat) return df
# g.players.passing().csv("passers.csv") # time param # p.player will give you the position included in the name week_str = 1 subject = 'receiving' #-------------- MULTI WEEK OUTPUT ----------------------------------- for week_str in range(1,18): # this will run up to the week 17 game = nflgame.games(2009, week=week_str) players = nflgame.combine_max_stats(game) demo = nflgame.players headers = ["NEWPLAYER", "PLAYER", "WEEK", "TEAM", "HOME", "RECEIVING_LNG", "RECEIVING_LNGTD", "RECEIVING_REC", "RECEIVING_TAR", "RECEIVING_TDS", "RECEIVING_TWOPTA", "RECEIVING_TWOPTM", "RECEIVING_TWOPTMISSED", "RECEIVING_YAC_YDS", "RECEIVING_YDS"] with open("2009_%s_wk%d_max_stats_no_header.csv" % (subject, week_str), 'wb') as f: writer = csv.writer(f,delimiter=",") #writer.writerow(headers) for p in players.receiving(): writer.writerow([ p, "2009", "%d" % (week_str), p.team, p.home, p.receiving_lng, p.receiving_lngtd, p.receiving_rec,
player = [ p.player_id, p.playerid, p.profile_id, p.last_name, p.first_name, p.position, p.height, p.weight, p.birthdate, p.years_pro ] all_players.append(player) players_df = pd.DataFrame(columns=player_info, data=all_players) players_df = players_df.rename(columns={'player_id': 'id'}) #get individual player stats for each game all_player_stats = pd.DataFrame() for g in games: g.players.csv('player-stats.csv') player_stats = pd.read_csv('player-stats.csv') player_stats['eid'] = g.eid mstats = nflgame.combine_max_stats([g]) mstats.csv('my_stats.csv', True) my_stats = pd.read_csv('my_stats.csv') new_col = ['id'] + list( set(my_stats.columns).difference(set(player_stats.columns))) my_stats = my_stats[new_col] player_stats = pd.merge(player_stats, my_stats, on='id') all_player_stats = all_player_stats.append(player_stats) big_df = pd.merge(all_player_stats, game_data_df, how='left', on='eid') big_df = pd.merge(big_df, players_df, how='left', on='id') big_df.to_csv('player_data_b_{}.csv'.format(y)) all_years_data = all_years_data.append(big_df) #all_years_data.to_csv('player_data_2009_2018.csv') #Update to 2019
def run_stats_import(week, year): def left(s, amount): return s[:amount] def right(s, amount): return s[-amount:] def mid(s, offset, amount): return s[offset:offset + amount] year_string = str(year) + right(str(year + 1), 2) #print("Week, Owner, Punter, Team, Punts, Punt Yards, Blocks, Touchbacks, Fair Catches, Out-of_Bounds, 50+, 60+, 70+, Under 20, Under 10, Under 5, 1 Yd Line, Returns, Return Yards") open_file = 'data/season/season_{year}.csv'.format(year=year_string) with open(open_file, "wb") as data_csv: outputWriter = csv.writer(data_csv, delimiter=',') header_row = list() header_row.append("Week") header_row.append("Punter") header_row.append("Team") header_row.append("Punts") header_row.append("Punt Yards") header_row.append("Blocks") header_row.append("Touchbacks") header_row.append("Fair Catches") header_row.append("Out-of_Bounds") header_row.append("50+") header_row.append("60+") header_row.append("70+") header_row.append("Under 20") header_row.append("Under 10") header_row.append("Under 5") header_row.append("1 Yd Line") header_row.append("Returns") header_row.append("Return Yards") header_row.append("Holds") header_row.append("Misses") header_row.append("First Downs") header_row.append("TD") header_row.append("Fumbles") header_row.append("Int") header_row.append("Conduct") outputWriter.writerow(header_row) for i in week: print("Week " + str(i)) kind = 'REG' if i <= 17 else 'POST' woke = i if i <= 17 else i - 17 #print kind #print woke games = nflgame.games(year, week=i) #print year stats = nflgame.combine_max_stats(games) plays = nflgame.combine_plays(games) #print games for player in stats.punting(): #print week punt_name = player team = player.team punt_yards = player.punting_yds punt_under_20s = player.punting_i20 punt_blocks = player.punting_blk punt_count = player.punting_tot punt_touch_back = player.punting_touchback punt_downs = player.puntret_downed punts_under_20 = 0 punts_under_10 = 0 punts_under_5 = 0 punts_under_2 = 0 out_of_bounds = 0 fair_catch = 0 punts_over_50 = 0 punts_over_60 = 0 punts_over_70 = 0 returns = 0 holds = 0 misses = 0 fumbles = 0 interceptions = 0 first_downs = 0 passing_yds = 0 passing_tds = 0 rushing_yds = 0 rushing_tds = 0 touchdowns = 0 conduct = 0 for passing in stats.passing(): if passing == player: passing_yds = passing.passing_yds passing_tds = passing.passing_tds else: passing_yds = 0 passing_tds = 0 #print passing_yards #print passing_tds for rushing in stats.rushing(): if rushing == player: rushing_yds = rushing.rushing_yds rushing_tds = rushing.rushing_tds else: rushing_yds = 0 rushing_tds = 0 #print rushing_yards #print rushing_tds plays = nflgame.combine_plays(games) #play = '' return_list = [] for play in plays: if str(punt_name) in str(play) and "punts" in str( play) and "No Play" not in str(play): #description = play #print play punts_character = str(play).find("punts") punts_string = str(play)[int(punts_character):] comma_character = punts_string.find(",") yard_line = punts_string[:int(comma_character)] yard_line = right(yard_line, 2) try: yard_line = (re.findall('\d+', yard_line)) #[0] yard_line = int(yard_line[0]) touch_back = 0 except: yard_line = 0 touch_back = 1 #print yard_line return_yards = int(play.puntret_yds) return_list.append(return_yards) punt_length = int(play.punting_yds) #print punt_length if yard_line + return_yards < 20 and yard_line + return_yards > 0: punts_under_20 = punts_under_20 + 1 if yard_line + return_yards < 10 and yard_line + return_yards > 0: punts_under_10 = punts_under_10 + 1 if yard_line + return_yards < 5 and yard_line + return_yards > 0: punts_under_5 = punts_under_5 + 1 if yard_line + return_yards < 2 and yard_line + return_yards > 0: punts_under_2 = punts_under_2 + 1 if "out of bounds" in str(punts_string): out_of_bounds = out_of_bounds + 1 if "fair catch" in str(punts_string): fair_catch = fair_catch + 1 if punt_length >= 50: punts_over_50 = punts_over_50 + 1 if punt_length >= 60: punts_over_60 = punts_over_60 + 1 if punt_length >= 70: punts_over_70 = punts_over_70 + 1 if "out of bounds" not in str(punts_string) and "fair catch" not in str(punts_string) \ and touch_back == 0 and "downed" not in str(play): returns = returns + 1 elif str(punt_name) in str(play) and ( "holder" in str(play) or "Holder" in str(play)) and "No Play" not in str(play): #print play if "is GOOD" in str(play): holds = holds + 1 elif "is No Good" in str(play): #print play misses = misses + 1 elif str(punt_name) in str( play) and "Punt formation" in str( play) and "No Play" not in str( play) and "Delay of Game" not in str(play): print str(play) first_down_character = str(play).find("and") remaining_string = str( play)[int(first_down_character) + 4:] parentheses_character = remaining_string.find(")") remaining_string = remaining_string[: parentheses_character] yards_remaining = remaining_string yards_character = str(play).find("for ") remaining_string = str(play)[int(yards_character) + 4:] yards_character = remaining_string.find("yards") remaining_string = remaining_string[:yards_character] yards_gained = remaining_string #print yards_remaining #print yards_gained if "PENALTY" in str( play) and "Unsportsmanlike Conduct" in str( play): if "PENALTY on {team}-{punter}".format( team=team, punter=punt_name) in str(play): conduct = conduct + 1 if "INTERCEPTED" in str(play): interceptions = interceptions + 1 elif "FUMBLES" in str(play): if "{punter} FUMBLES".format( punter=punt_name) in str(play): fumbles = fumbles + 1 elif ("pass" in str(play) or "right end ran" in str(play) or "left end ran" in str(play) or "up the middle" in str(play)) and "INTERCEPTED" not in str( play) and "incomplete" not in str(play): if int(yards_gained) >= int( yards_remaining) and yards_gained > 0: first_downs = first_downs + 1 if "TOUCHDOWN" in str(play): touchdowns = touchdowns + 1 #print conduct #print interceptions #print fumbles #print first_downs #print touchdowns else: continue total_return_yards = sum(return_list) csv_data = list() #Convert date to string csv_data.append(i) csv_data.append(str(punt_name)) csv_data.append(str(team)) csv_data.append(punt_count) csv_data.append(punt_yards) csv_data.append(punt_blocks) csv_data.append(punt_touch_back) csv_data.append(fair_catch) csv_data.append(out_of_bounds) csv_data.append(punts_over_50) csv_data.append(punts_over_60) csv_data.append(punts_over_70) csv_data.append(punt_under_20s) csv_data.append(punts_under_10) csv_data.append(punts_under_5) csv_data.append(punts_under_2) csv_data.append(returns) csv_data.append(total_return_yards) csv_data.append(holds) csv_data.append(misses) csv_data.append(first_downs) csv_data.append(touchdowns) csv_data.append(fumbles) csv_data.append(interceptions) csv_data.append(conduct) outputWriter.writerow(csv_data) # data_csv.close
def generate_week_players(): s, w = nflgame.live.current_year_and_week() week_players = get_json('nflleague/players.json', identity_player()) nflgame_players = get_json(nflgame.player._player_json_file, {}) if len(week_players) == 1: for pid, plyr in nflgame_players.iteritems(): if plyr.get('team', False): team = plyr.get('team') if plyr.get('team') != 'JAC' else 'JAX' plyr['team'] = {str(s): {str(w): team}} plyr['position'] = { str(s): { str(w): plyr.get('position', 'NONE') } } else: plyr['position'] = {} plyr['team'] = {} plyr['schedule'] = {} plyr['gsis_name'] = '.'.join( [plyr['first_name'][0], plyr['last_name']]) week_players[pid] = plyr for season in range(2014, s + 1): for week in range(1, 18): if (season, week) == (s, w): break print(season, week) if str(season) in week_players['00-0000000']['team'].keys(): if str(week) in week_players['00-0000000']['team'][str( season)].keys(): continue print('S:{} W:{} passed'.format(season, week)) else: week_players['00-0000000']['team'][str(season)][str( week)] = 'NA' week_players['00-0000000']['position'][str(season)][str( week)] = 'NA' else: week_players['00-0000000']['team'][str(season)] = { str(week): 'NA' } week_players['00-0000000']['position'][str(season)] = { str(week): 'NA' } games = nflgame.games(season, week=week) players = nflgame.combine_max_stats(games) for plyr in players: team = nflgame.standard_team(plyr.team) if plyr.name == 'A.Robinson': print(plyr.name, week, team) if plyr.player != None: position = guess_pos(plyr) if str(season) not in week_players[ plyr.playerid]['team'].keys(): week_players[plyr.playerid]['team'][str(season)] = { str(week): team } week_players[plyr.playerid]['position'][str( season)] = { str(week): position } else: week_players[plyr.playerid]['team'][str(season)][str( week)] = team week_players[plyr.playerid]['position'][str(season)][ str(week)] = position #Fill in any unknown team weeks with most likely correct team for pid, plyr in week_players.iteritems(): if type(plyr['team']) == dict and str( season) not in plyr['team'].keys(): continue if plyr.get('position', '') == 'D/ST': continue #Only 1 position per season, so find most commonly guessed position and set to all games. For now count = collections.Counter() for pos in plyr['position'][str(season)].values(): count[pos] += 1 position = sorted(count.items(), key=lambda x: x[1], reverse=True)[0][0] for i in range(1, 18): plyr['position'][str(season)][str(i)] = position #Fill in Teams act = [] for week in range(1, 18): if str(week) in plyr['team'][str(season)].keys(): act.append(plyr['team'][str(season)][str(week)]) else: act.append(False) #Dont forget about the knile davis situation if not act[0]: T, index = False, 0 while (not T): T = act[index] index += 1 act[0] = T plyr['team'][str(season)]['1'] = T for i, team_week in enumerate(act, start=0): if not team_week: plyr['team'][str(season)][str(i + 1)] = plyr['team'][str( season)][str(i)] week_players[pid] = plyr #Build Defenses. Defenses will have constant team and position for did in nflgame.teams: if did[0] not in week_players: week_players[did[0]] = { "first_name": did[1], "full_name": did[3], "gsis_id": did[0], "gsis_name": ' '.join([did[2], 'D/ST']), "last_name": did[2], "position": "D/ST", "profile_url": "http://www.nfl.com/", "team": did[0], "schedule": {}, "status": 'ACT' } length = len(week_players) #Build game_eid dictionary for i, (pid, plyr) in enumerate(week_players.iteritems()): if type(plyr['team']) == dict and str( season) not in plyr['team'].keys(): #skip players who weren't statistically active continue week_players[pid]['schedule'][str(season)] = {} print(pid, plyr['full_name'], '{}%'.format(round((float(i) / length) * 100, 2))) for week in range(1, 18): if plyr.get('position') != 'D/ST': team = week_players[pid]['team'][str(season)][str(week)] else: team = week_players[pid]['team'] week_players[pid]['schedule'][str(season)][str( week)] = load_schedule_info(season, week, team) save_json('nflleague/players.json', week_players)
points += 3 points += +6 * getattr(player, 'rushing_tds') points += +1 * getattr(player, 'receiving_rec') points += +0.1 * getattr(player, 'receiving_yds') if getattr(player, 'receiving_yds') >= 100: points += 3 points += +6 * getattr(player, 'receiving_tds') points += -1 * getattr(player, 'fumbles_lost') points += +2 * getattr(player, 'passing_twoptm') points += +2 * getattr(player, 'rushing_twoptm') points += +2 * getattr(player, 'receiving_twoptm') return points games = nflgame.games(2018, week=1) players = nflgame.combine_max_stats(games) optimizer = get_optimizer(Site.DRAFTKINGS, Sport.FOOTBALL) player_list = [] print("[*] Downloading projection data.") for position in ['qb', 'rb', 'wr', 'te', 'defense', 'kicker']: r = requests.get( "https://d1qacz8ndd7avl.cloudfront.net/lineuphq/v1.00/2018-09-11/1/base/nfl-{}.json?timestamp=1536688800000" .format(position)).json() # First Name, # Last Name, #Position, # Team, # Salary, # Projected, # Floor, # Ceiling # Site id 2 - Fan Duel # Site id 20 - Draft Kings for player_id, player_dict in r['data']['results'].items(): data = {} data['first_name'] = player_dict['player']['first_name']
def run_stats_import(week_number, year): def left(s, amount): return s[:amount] def right(s, amount): return s[-amount:] def mid(s, offset, amount): return s[offset:offset + amount] #season = [2] #season = range(1,3) #year = 2016 year_string = str(year) + right(str(year + 1), 2) #print("Week, Owner, Punter, Team, Punts, Punt Yards, Blocks, Touchbacks, Fair Catches, Out-of_Bounds, 50+, 60+, 70+, Under 20, Under 10, Under 5, 1 Yd Line, Returns, Return Yards") open_file = 'data/season/season_{year}.csv'.format(year=year_string) with open(open_file, "wb") as data_csv: outputWriter = csv.writer(data_csv, delimiter=',') header_row = list() header_row.append("Week") header_row.append("Owner") header_row.append("Punter") header_row.append("Team") header_row.append("Punts") header_row.append("Punt Yards") header_row.append("Blocks") header_row.append("Touchbacks") header_row.append("Fair Catches") header_row.append("Out-of_Bounds") header_row.append("50+") header_row.append("60+") header_row.append("70+") header_row.append("Under 20") header_row.append("Under 10") header_row.append("Under 5") header_row.append("1 Yd Line") header_row.append("Returns") header_row.append("Return Yards") header_row.append("Holds") header_row.append("Misses") outputWriter.writerow(header_row) for week in week_number: print "Week: " + str(week) try: file = "roster/{year_number}/week{week_number}.txt".format( week_number=week, year_number=year) #print file f = open(file, "r") owner_set = eval(f.read()) print owner_set owner_set = dict((v, k) for k, v in owner_set.iteritems()) except: owner_set = dict() print owner_set games = nflgame.games(year, week=week) print year stats = nflgame.combine_max_stats(games) plays = nflgame.combine_plays(games) #print games for player in stats.punting(): #print week punt_name = player team = player.team punt_yards = player.punting_yds punt_blocks = player.punting_blk punt_under_20s = player.punting_i20 punt_count = player.punting_tot punt_touch_back = player.punting_touchback punt_downs = player.puntret_downed punts_under_20 = 0 punts_under_10 = 0 punts_under_5 = 0 punts_under_2 = 0 out_of_bounds = 0 fair_catch = 0 punts_over_50 = 0 punts_over_60 = 0 punts_over_70 = 0 returns = 0 holds = 0 misses = 0 plays = nflgame.combine_plays(games) #play = '' return_list = [] for play in plays: if str(punt_name) in str(play) and "punts" in str( play) and "No Play" not in str(play): #description = play #print play punts_character = str(play).find("punts") punts_string = str(play)[int(punts_character):] comma_character = punts_string.find(",") yard_line = punts_string[:int(comma_character)] yard_line = right(yard_line, 2) try: yard_line = (re.findall('\d+', yard_line)) #[0] yard_line = int(yard_line[0]) touch_back = 0 except: yard_line = 0 touch_back = 1 #print yard_line return_yards = int(play.puntret_yds) return_list.append(return_yards) punt_length = int(play.punting_yds) #print punt_length if yard_line + return_yards < 20 and yard_line + return_yards > 0: punts_under_20 = punts_under_20 + 1 if yard_line + return_yards < 10 and yard_line + return_yards > 0: punts_under_10 = punts_under_10 + 1 if yard_line + return_yards < 5 and yard_line + return_yards > 0: punts_under_5 = punts_under_5 + 1 if yard_line + return_yards < 2 and yard_line + return_yards > 0: punts_under_2 = punts_under_2 + 1 if "out of bounds" in str(punts_string): out_of_bounds = out_of_bounds + 1 if "fair catch" in str(punts_string): fair_catch = fair_catch + 1 if punt_length >= 50: punts_over_50 = punts_over_50 + 1 if punt_length >= 60: punts_over_60 = punts_over_60 + 1 if punt_length >= 70: punts_over_70 = punts_over_70 + 1 if "out of bounds" not in str(punts_string) and "fair catch" not in str(punts_string) \ and touch_back == 0 and "downed" not in str(play): returns = returns + 1 elif str(punt_name) in str(play) and ( "holder" in str(play) or "Holder" in str(play)) and "No Play" not in str(play): #print play if "is GOOD" in str(play): holds = holds + 1 elif "is No Good" in str(play): #print play misses = misses + 1 else: continue #print str(punt_name) + " Holds: " + str(holds) #print return_list total_return_yards = sum(return_list) owner = owner_set.get(str(player), "Free Agent") #print owner time.sleep(1) # print(str(week) +", " + str(owner) +", " + str(punt_name) +", " + \ # str(team) + ", " + str(punt_count) +", " + str(punt_yards) +", " + \ # str(punt_blocks) +", " + str(punt_touch_back) +", " + str(fair_catch) +", " + \ # str(out_of_bounds) +", " + str(punts_over_50) +", " + str(punts_over_60) +", " + \ # str(punts_over_70) +", " + str(punt_under_20s) +", " + str(punts_under_10) +", " + \ # str(punts_under_5) +", " + str(punts_under_2) +", " + str(returns) +", " + \ # str(total_return_yards)) csv_data = list() #Convert date to string csv_data.append(week) csv_data.append(str(owner)) csv_data.append(str(punt_name)) csv_data.append(str(team)) csv_data.append(punt_count) csv_data.append(punt_yards) csv_data.append(punt_blocks) csv_data.append(punt_touch_back) csv_data.append(fair_catch) csv_data.append(out_of_bounds) csv_data.append(punts_over_50) csv_data.append(punts_over_60) csv_data.append(punts_over_70) csv_data.append(punt_under_20s) csv_data.append(punts_under_10) csv_data.append(punts_under_5) csv_data.append(punts_under_2) csv_data.append(returns) csv_data.append(total_return_yards) csv_data.append(holds) csv_data.append(misses) outputWriter.writerow(csv_data) data_csv.close
def gen_defense_stats(season, week, team, game=None): fp = 'nflleague/espn-league-json/cache/C{}.json' filepath = fp.format(team) cache = get_json(filepath, {}) game_eid = nflleague.players[team]['schedule'][str(season)][str(week)] week, season = str(week), str(season) if season not in cache.keys(): cache[season] = {} if week not in cache[season].keys() or (season, week) == (str( nflleague.c_year), str(nflleague.c_week)): if game_eid == 'bye': cache[season][week] = {'BYE': True} save_json(filepath, cache) return cache[season][week] if game == None: game = nflgame.game.Game(game_eid) game_status = get_game_status(game) if game_status in ['NOT PLAYED', 'PREGAME']: return {} if game_status in ['PLAYING', 'HALFTIME' ] or week not in cache[season].keys(): print('Caching {} Defense (Y:{} W:{})'.format(team, season, week)) players = nflgame.combine_max_stats([game]) #individual players dst = filter( lambda p: p.team == team and (p.has_cat('defense') or p.has_cat('kickret') or p.has_cat( 'puntret')), players) cache[season][week] = {} if len(dst) != 0: for dst_plyr in dst: cache[season][week][dst_plyr.playerid] = dst_plyr._stats else: cache[season][week] = {} #combines all individual player stats dicts into one team stats category for access w/o initing player objs if not cache[season][week] == {}: val = cache[season][week].values() cache[season][week]['defense'] = reduce( lambda x, y: x + y, [Counter(dstats) for dstats in val]) else: cache[season][week]['defense'] = {} #team stats if game.home == team: cache[season][week]['defense']['defense_PA'] = game.score_away opponent = game.away if game.away == team: cache[season][week]['defense']['defense_PA'] = game.score_home opponent = game.home cache[season][week]['defense']['defense_rush'], cache[season][ week]['defense']['defense_pass'] = 0, 0 dst_team = filter(lambda t: t.team == opponent, players) for off_p in dst_team: try: #Find better way DEF = [ 'DE', 'DT', 'CB', 'SS', 'FS', 'MLB', 'OLB', 'ILB', 'DB', 'T', 'RT', 'LT', 'S', 'LB' ] if off_p.player.position not in DEF: cache[season][week]['defense'][ 'defense_rush'] += off_p.rushing_yds cache[season][week]['defense'][ 'defense_pass'] += off_p.passing_yds + off_p.passing_sk_yds except Exception as err: print(err) TYDA = cache[season][week]['defense']['defense_rush'] + cache[ season][week]['defense']['defense_pass'] cache[season][week]['defense']['defense_TYDA'] = TYDA save_json(filepath, cache) return cache[season][week]
def new_week(self, year, week): self.week = week self.year = year self.games = nflgame.games(self.year, week=self.week) self.players = nflgame.combine_max_stats(self.games)
def get_defense_score(year, week): teams = [ "NE", "NYJ", "MIA", "BUF", "PIT", "BAL", "CLE", "CIN", "HOU", "IND", "JAX", "TEN", "DEN", "KC", "SD", "OAK", "DAL", "WSH", "NYG", "PHI", "MIN", "GB", "DET", "CHI", "NO", "TB", "ATL", "CAR", "SF", "SEA", "ARI", "STL" ] games = nflgame.games(year, week) players = nflgame.combine_max_stats(games) for game in games: home_points = 0 away_points = 0 home_team = game.home home_points_allowed = game.score_away if home_points_allowed == 0: home_points += 10 elif home_points_allowed < 7: home_points += 7 elif home_points_allowed < 14: home_points += 4 elif home_points_allowed < 21: home_points += 1 elif home_points_allowed < 28: home_points += 0 elif home_points_allowed < 35: home_points -= 1 else: home_points -= 4 away_team = game.away away_points_allowed = game.score_home if away_points_allowed == 0: away_points += 10 elif away_points_allowed > 0 and away_points_allowed < 7: away_points += 7 elif away_points_allowed > 6 and away_points_allowed < 14: away_points += 4 elif away_points_allowed > 13 and away_points_allowed < 21: away_points += 1 elif away_points_allowed > 20 and away_points_allowed < 28: away_points -= 0 elif away_points_allowed > 27 and away_points_allowed < 35: away_points -= 1 else: away_points -= 4 for player in players.filter(team=home_team): home_points += ( player.defense_sk + player.defense_int * 2 + #player.fumbles_rcv * 2 + #player.fumbles_trcv * 2 + player.defense_safe * 2 + player.defense_ffum * 2 + player.defense_tds * 6 + player.defense_xpblk * 2 + player.kickret_tds * 6 + player.puntret_tds * 6) for player in players.filter(team=away_team): away_points += ( player.defense_sk + player.defense_int * 2 + #player.fumbles_rcv * 2 + #player.fumbles_trcv * 2 + player.defense_safe * 2 + player.defense_ffum * 2 + player.defense_tds * 6 + player.defense_xpblk * 2 + player.kickret_tds * 6 + player.puntret_tds * 6) home = Defense(home_team, week, year, home_points_allowed, home_points) away = Defense(away_team, week, year, away_points_allowed, away_points) db.session.add(home) db.session.add(away) db.session.commit()
def __init__(self, year, weeks): games = nflgame.games(year=year, week=weeks) # range(1, 18)) players = nflgame.combine_max_stats(games) """Build Dictionary of Players""" self.player_dict = self.make_player_dict(players)
def player_ranks(year, pos, weeks): # Define the variables position = pos year = year PL = {} #Blank dictionary for Players if position in ('WR', 'RB'): Rank1 = 12 #Top X number of players (most often 12 for RB1 and WR1; 5 for QBs). Rank2 = 24 #Top X number of players (most often 24 for RB2 and WR2; 10 for QBs). Rank3 = 36 #Top X number of players (most often 36 for RB3 and WR3; 15 for QBs). Rank4 = 48 #Top X number of players (most often 48 for RB4 and WR4; 20 for QBs). elif position in ('QB', 'TE', 'K'): Rank1 = 5 #Top X number of players (most often 12 for RB1 and WR1; 5 for QBs). Rank2 = 10 #Top X number of players (most often 24 for RB2 and WR2; 10 for QBs). Rank3 = 15 #Top X number of players (most often 36 for RB3 and WR3; 15 for QBs). Rank4 = 20 #Top X number of players (most often 48 for RB4 and WR4; 20 for QBs). elif position == 'ALL': Rank1 = 20 Rank2 = 40 Rank3 = 60 Rank4 = 80 max_pl = 200 ##List of all the players not in a specific position (i.e., QB has all players in the list except QBs). RBs are sometimes blank. QB = ('', 'K', 'WR', 'TE', 'RB', 'DB', 'DEF', 'OLB', 'CB', 'DE', 'C', 'P', 'SS', 'ILB', 'FS', 'OT', 'LS', 'LB', 'T', 'OG', 'FB', 'MLB', 'DT', 'G', 'SAF', 'DL', 'NT', 'OL') WR = ('K', 'QB', 'TE', 'RB', 'DB', 'DEF', 'OLB', 'CB', 'DE', 'C', 'P', 'SS', 'ILB', 'FS', 'OT', 'LS', 'LB', 'T', 'OG', 'FB', 'MLB', 'DT', 'G', 'SAF', 'DL', 'NT', 'OL') RB = ('K', 'WR', 'TE', 'QB', 'DB', 'DEF', 'OLB', 'CB', 'DE', 'C', 'P', 'SS', 'ILB', 'FS', 'OT', 'LS', 'LB', 'T', 'OG', 'MLB', 'DT', 'G', 'SAF', 'DL', 'NT', 'OL') TE = ('', 'K', 'WR', 'QB', 'RB', 'DB', 'DEF', 'OLB', 'CB', 'DE', 'C', 'P', 'SS', 'ILB', 'FS', 'OT', 'LS', 'LB', 'T', 'OG', 'FB', 'MLB', 'DT', 'G', 'SAF', 'DL', 'NT', 'OL') K = ('QB', 'WR', 'TE', 'RB', 'DB', 'DEF', 'OLB', 'CB', 'DE', 'C', 'P', 'SS', 'ILB', 'FS', 'OT', 'LS', 'LB', 'T', 'OG', 'FB', 'MLB', 'DT', 'G', 'SAF', 'DL', 'NT', 'OL') ALL = ('DB', 'DEF', 'OLB', 'CB', 'DE', 'C', 'P', 'SS', 'ILB', 'FS', 'OT', 'LS', 'LB', 'T', 'OG', 'MLB', 'DT', 'G', 'SAF', 'DL', 'NT', 'OL') season_length = len(weeks) #This for loop fills out the blank dictionary with points for w in weeks: week = w - min(weeks) + 1 games = nflgame.games(year=year, week=w) players = nflgame.combine_max_stats(games) print('Week ' + str(w) ) #Displays the week count so user can check where the code is. # Filter for player position and sort by most important attribute for points. if position == 'QB': position_list = QB PL = PL_maker(PL, players, position_list, season_length, week) elif position == 'WR': position_list = WR PL = PL_maker(PL, players, position_list, season_length, week) elif position == 'TE': position_list = TE PL = PL_maker(PL, players, position_list, season_length, week) elif position == 'RB': position_list = RB PL = PL_maker(PL, players, position_list, season_length, week) elif position == 'K': position_list = K PL = PL_maker(PL, players, position_list, season_length, week) elif position == 'ALL': position_list = ALL PL = PL_maker(PL, players, position_list, season_length, week) else: print("Check the position entry is correct.") break if position == 'K': for w in weeks: week = w - min(weeks) + 1 kicker = kicker_pts( year, w ) # need to output one number to replace the constructed PL dictionary # print(kicker) for player, points in kicker.iteritems(): try: PL[player][week - 1] = points except KeyError: pass # troubleshoot.find_player(player) #Prints an organized table of the players points by week for an easy check. # print tabulate.tabulate(PL, headers = "keys") ################################### #This Section Ranks Players based on their percentage to achieve top playing ability ################################### Pt_rank = {} #Blank dictionary for Rank1, Rank2, Rank3, and Rank4 PL_rank = {} #Blank dictionary for Player ranking. # for week in weeks: for w in weeks: week = w - min(weeks) + 1 # for weeks in range(season_length): PL_score = [] # Make a blank list to store weekly scores # PL1, PL2, PL3, PL4 = 0, 0, 0, 0 for key in PL: PL_score.append(PL[key][week - 1]) PL_rank[key] = {'Rank Score': [0] * 7} #Sort the scores and determine top Rank1, Rank2, Rank3, and Rank4 players. PL_score.sort(reverse=True) ##Error checker #print PL_score[Rank1-1], PL_score[Rank2-1], PL_score[Rank3-1], PL_score[Rank4-1] Pt_rank["Week " + str(week)] = [ PL_score[Rank1 - 1], PL_score[Rank2 - 1], PL_score[Rank3 - 1], PL_score[Rank4 - 1] ] pts_max = 0 for key in PL: PL1_total, PL2_total, PL3_total, PL4_total = 0, 0, 0, 0 for w in weeks: week = w - min(weeks) if PL[key][week] >= Pt_rank["Week " + str(week + 1)][0]: PL1_total = PL1_total + 1 elif PL[key][week] >= Pt_rank["Week " + str(week + 1)][1]: PL2_total = PL2_total + 1 elif PL[key][week] >= Pt_rank["Week " + str(week + 1)][2]: PL3_total = PL3_total + 1 elif PL[key][week] >= Pt_rank["Week " + str(week + 1)][3]: PL4_total = PL4_total + 1 else: 0 'Rank Score' PL_rank[key]['Rank Score'][1] = float( PL1_total) / season_length * 100.0 PL_rank[key]['Rank Score'][2] = float( PL1_total + PL2_total) / season_length * 100.0 PL_rank[key]['Rank Score'][3] = float( PL1_total + PL2_total + PL3_total) / season_length * 100.0 PL_rank[key]['Rank Score'][4] = float( PL1_total + PL2_total + PL3_total + PL4_total) / season_length * 100.0 PL_rank[key]['Rank Score'][5] = float(sum(PL[key])) PL_rank[key]['Rank Score'][6] = float(std_deviation(PL[key])) if int(sum(PL[key]) ) > pts_max: # Finds the maximum points scored for a week. pts_max = int(sum(PL[key])) for key in PL_rank: # PL_rank[key][0] = (sum(PL_rank[key][1:5]) / 100 + 2 * PL_rank[key][5] / pts_max) / 6 PL_rank[key]['Rank Score'][0] = (sum(PL_rank[key]['Rank Score'][1:5])/100 + \ 2*PL_rank[key]['Rank Score'][5]/pts_max)/6 #Determine player rank using the point percentages and 2 times the points b/c pts are most important. print(pts_max) #Re-assign PlayerID with Player Name games = nflgame.games(year, weeks) players = nflgame.combine_max_stats(games) for p in players: if p.playerid in PL.keys(): player_label = str(p) + '-' + str(p.guess_position) + '-' + str( p.team) PL_rank[player_label] = PL_rank.pop(p.playerid) PL_rank[player_label]['pos'] = position PL_rank[player_label]['gsis_id'] = p.playerid PL[p] = PL.pop(p.playerid) return {'PL': PL, 'Pt_rank': Pt_rank, 'PL_rank': PL_rank}
def find_player(player_number): games = nflgame.games(year, weeks) players = nflgame.combine_max_stats(games) for p in players: if p.playerid == player_number: print(str(p), p.playerid, p.guess_position)
def player_dir(player_number, year, week): games = nflgame.games(year, week) players = nflgame.combine_max_stats(games) for p in players: if p.playerid == player_number: print(str(p), p.guess_position, dir(p))