def fpDefense(team, year, week): points = 0 for w in week: games = nflgame.games_gen(year, w, team, team) points = points + defensePlays(team, year, w, games) games = nflgame.games_gen(year, w, team, team) points = points + defensePA(team, year, w, games) games = nflgame.games_gen(year, w, team, team) points = points + defenseYA(team, year, w, games) print points return points
def get_scores(self, year, week=None): games = nflgame.games_gen(year, week) players = nflgame.combine_play_stats(games) output = {} for p in players: score = 0 score += p.passing_tds * self.passing_tds_pts score += p.passing_yds * self.passing_yds_pts score += self.passing_yds_300_bonus if p.passing_yds >= 300 else 0 score += p.passing_ints * self.passing_ints_pts score += p.rushing_yds * self.rushing_yds_pts score += p.rushing_tds * self.rushing_tds_pts score += self.rushing_yds_100_bonus if p.rushing_yds >= 100 else 0 score += p.receiving_yds * self.receiving_yds_pts score += p.receiving_rec * self.receiving_rec_pts score += p.receiving_tds * self.receiving_tds_pts score += self.receiving_yds_100_bonus if p.receiving_yds >= 100 else 0 score += p.puntret_tds * self.puntret_tds_pts score += p.kickret_tds * self.kickret_tds_pts score += p.fumbles_lost * self.fumbles_lost_pts score += p.passing_twoptm * self.passing_twoptm_pts score += p.rushing_twoptm * self.rushing_twoptm_pts score += p.receiving_twoptm * self.receiving_twoptm_pts output[p.name] = score return output
def find(name, season, team=None, pos=None,players=None): if players==None: players = nflgame.combine_game_stats(nflgame.games_gen(int(season))) indexed={} for p in players: indexed[p.playerid] = p if pos is not None: pos = standard_position(pos) result = [] for pid, p in indexed.iteritems(): if pos is not None and pos != standard_position(p.guess_position): continue r = edit_name(p, name) if r >= 0.8: result.append((r, pid)) if len(result) == 0: return None result = heapq.nlargest(1, result) if team is not None and result[0][0] < 0.85: sameteam = lambda (r, pid): \ nflgame.standard_team(team) == indexed[pid].team result = filter(sameteam, result) if len(result) == 0: return None #may need to for return of player object return nflgame.players[result[0][1]]
def writeScoresToCSV(year): games = nflgame.games_gen(year) with open('Scores_'+str(year)+'.csv', 'wb') as csvfile: scorewriter = csv.writer(csvfile, delimiter=',') scorewriter.writerow(['Week', 'Home', 'Home_Score', 'Away', 'Away_Score']) for game in games: row = game.schedule['week'], game.home, game.score_home, game.away, game.score_away scorewriter.writerow(row)
def total_sacks_given(s,w,t): games = nflgame.games_gen(s,w,t,t) plays = nflgame.combine_plays(games) sks = 0 for p in plays.filter(team=t): if p.defense_sk > 0: sks += 1 return sks
def getKickRetTDsMade(self,s, w): games = nflgame.games_gen(s, w, self.team ,self.team) krtds = 0 # Bye Week ? If yes, get out of the function if games is None: return krtds plays = nflgame.combine_plays(games) for play in plays.filter(team__ne=self.team): if play.kickret_tds>0: krtds = krtds+1 return krtds
def getDefFGBlkMade(self,s, w): games = nflgame.games_gen(s, w, self.team ,self.team) fgblk = 0 # Bye Week ? If yes, get out of the function if games is None: return fgblk plays = nflgame.combine_plays(games) for play in plays.filter(team__ne=self.team): if play.defense_fgblk>0: fgblk = fgblk+1 return fgblk
def getDefSafetysMade(self,s, w): games = nflgame.games_gen(s, w, self.team ,self.team) sftys = 0 # Bye Week ? If yes, get out of the function if games is None: return sftys plays = nflgame.combine_plays(games) for play in plays.filter(team__ne=self.team): if play.defense_safe>0: sftys = sftys+1 return sftys
def getDefRecoveryTDsScored(self,s, w): games = nflgame.games_gen(s, w, self.team ,self.team) defRecTDs = 0 # Bye Week ? If yes, get out of the function if games is None: return defRecTDs plays = nflgame.combine_plays(games) for play in plays.filter(team__ne=self.team): if play.defense_frec_tds>0: defRecTDs = defRecTDs+1 return defRecTDs
def generatePlayerDataFile(player_name='todd gurley', years=range(2009, 2018)): poss_players = [p for p in nflgame.find(player_name) if p.position == 'RB'] if not poss_players: print 'could not find ', player_name, ' in nfl database.' exit(1) if len(poss_players) > 1: print 'found multiple ', player_name, '\'s!' exit(2) player = poss_players[0] # print dir(player) playerid = player.playerid # this list will be used as a constructor to the DataFrame # perhaps there is a slicker way to construct a DataFrame? datalist = [] for year in years: print 'reading {} season...'.format(year) for week in range(1, 18): # print 'looking at week ', week weekly_games = nflgame.games_gen(year, week) try: # use combine_play_stats() to get play-level information weekly_player_stats = nflgame.combine_game_stats(weekly_games) except TypeError: print str(year), ' not in database.' break for pstat in weekly_player_stats.rushing().filter( playerid=playerid): base_pts = getBasePoints(bro_league, pstat) datalist.append({ 'year': year, 'week': week, 'fantasy_points': base_pts, 'rushing_attempts': pstat.rushing_att, 'receptions': pstat.receiving_rec, 'yards': pstat.rushing_yds + pstat.receiving_yds, 'tds': pstat.rushing_td + pstat.receiving_td, '2pc': pstat.rushing_twoptm + pstat.receiving_twoptm # 'playerid':pstat.playerid }) df = pd.DataFrame(datalist) df.to_csv(playerFilename(player_name) + '.csv')
def GetGameData(year): games = nflgame.games_gen(year) a = pd.DataFrame() for g in games: Schedule = g.schedule s = pd.DataFrame.from_dict([Schedule]) extra = {'HScore': g.score_home, 'VScore': g.score_away, 'Winner': g.winner, 'Season': g.season()} e = pd.DataFrame.from_dict([extra]) r = pd.concat([s, e], axis=1) r['HVScoreDiff'] = r['HScore'] - r['VScore'] r['NDate'] = str(str(r.month[0]) + '/' + str(r.day[0]) + '/' + str(r.year[0])) a = pd.concat([a, r]) return a
def __init__(self, league_id, season, username=None, password=None, private=True, visible=False): print("Season {}".format(season)) self.visible = True if not visible and _pvd_avail: print('Starting Virtual Environment') self.display = Display(visible=0, size=(200, 200)) self.display.start() print('Virtual Environment Established') self.visible = visible self.browser = Page('firefox') self.season = season self.current_season, self.current_week = nflleague.c_year, nflleague.c_week self.league_id = league_id self.owners = dict #Needed for player ID matching self.player_game = nflgame.combine_game_stats( nflgame.games_gen(int(self.season))) if private: print('Signing in to ESPN.com') self.browser.get("http://games.espn.go.com/ffl/signin") sleep(3) self.browser.switch_to.frame( self.browser.find_element_by_name("disneyid-iframe")) if username == None: username == raw_input("Username: "******"Password: "******"//input[@placeholder='Username or Email Address']").send_keys( username) self.browser.find_element_by_xpath( "//input[@placeholder='Password (case sensitive)']").send_keys( password) self.browser.find_element_by_xpath( "//button[@type='submit']").click() sleep(5) print('Logged in to ESPN.com') filename = 'nflleague/espn-league-json/{}/{}/owner_info.json'.format( self.league_id, self.season) if os.path.isfile(filename): self.owners = json.loads(open(filename).read()) else: print('No Owner Info Available. Must generate first')
def getDefSacks(self,s, w): games = nflgame.games_gen(s, w, self.team , self.team) sks = 0 # Bye Week ? If yes, get out of the function if games is None: return sks plays = nflgame.combine_plays(games) for p in plays.filter(team__ne=self.team): if p.defense_sk > 0: sks += 1 return sks
def getDefReceptionsAllowed(self,s, w): games = nflgame.games_gen(s, w, self.team , self.team) receptions = 0 # Bye Week ? If yes, get out of the function if games is None: return receptions plays = nflgame.combine_plays(games) for p in plays.filter(team__ne=self.team, passing_att__ge=1): receptions += p.receiving_rec return receptions
def getDefPassingTDsAllowed(self,s, w): games = nflgame.games_gen(s, w, self.team , self.team) passTDs = 0 # Bye Week ? If yes, get out of the function if games is None: return passTDs plays = nflgame.combine_plays(games) for p in plays.filter(team__ne=self.team, passing_att__ge=1): passTDs += p.passing_tds return passTDs
def getDefInterceptions(self,s, w): games = nflgame.games_gen(s, w, self.team , self.team) interceptions = 0 # Bye Week ? If yes, get out of the function if games is None: return interceptions plays = nflgame.combine_plays(games) for p in plays.filter(team__ne=self.team, passing_int__gt=0): interceptions += p.passing_int return interceptions
def get_rushing_yds_against(seas, week, team): ''' Returns a tuple containing a team and rushing yards against said team for season and week(s) ''' games = nflgame.games_gen(seas, week, team, team) if games == None: # Catch all for teams that have moved or joined the league. return team, 0 plays = nflgame.combine_plays(games) yds = 0 for p in plays.filter(team__ne=team, rushing_yds__ge=1): yds += p.rushing_yds return team, yds
def getDefRushingYardsAllowed(self,s, w): games = nflgame.games_gen(s, w, self.team , self.team) rushYards = 0 # Bye Week ? If yes, get out of the function if games is None: return rushYards plays = nflgame.combine_plays(games) for p in plays.filter(team__ne=self.team, rushing_att__ge=1): rushYards += p.rushing_yds return rushYards
def get_rushing_yds(seas, week, team): ''' This will return a teams rushing yards for a specific season and week. ''' games = nflgame.games_gen(seas, week, team, team) if games == None: # Catch all for teams that have moved or joined the league. return team, 0 plays = nflgame.combine_plays(games) yds = 0 for p in plays.filter(team=team, rushing_yds__ge=1): if isDebug: print p yds += p.rushing_yds return team, yds
def GetRegSeasonRecord (team, year): team = str(team) year = int(year) games = nflgame.games_gen(year, week = None, home = team, away = team, kind = 'REG') for g in games: print g if (g.winner == team): w += 1 elif (g.loser == team): l += 1 else: print "ERROR: can not determine winner of this game" print 'W-L: ' + str(w) + '-' + str(l) return [int(w),int(l)]
def generateSummaryDataFile(fname, years, league_rules): # this list will be used as a constructor to the DataFrame # perhaps there is a slicker way to construct a DataFrame? datalist = [] for year in years: print 'reading {} season...'.format(year) games = nflgame.games_gen(year) # get game-level stats try: all_players = nflgame.combine_game_stats(games) except TypeError: print 'Could not open {} data.'.format(year) continue # for some reason "position" does allow any through and we must use "guess_position" top_players = {} top_players['QB'] = all_players.passing().filter( guess_position='QB').filter(passing_yds=lambda y: y >= 500) top_players['RB'] = all_players.rushing().filter( guess_position='RB').filter(rushing_yds=lambda y: y >= 200) top_players['WR'] = all_players.receiving().filter( guess_position='WR').filter(receiving_yds=lambda y: y >= 200) top_players['TE'] = all_players.receiving().filter( guess_position='TE').filter(receiving_yds=lambda y: y >= 200) top_players['K'] = all_players.kicking().filter( guess_position='K').filter(kicking_fgyds=lambda y: y >= 200) for (pos, players) in top_players.items(): for pstat in players: # print qbstat.rushing_lng, qbstat.rushing_lngtd # longest rush, longest TD rush # print qbstat.stats # dict of the stats # print qbstat.formatted_stats() # relatively nicely printed out version of the stats dict pfullname = pstat.player.full_name.strip() base_pts = getBasePoints(league_rules, pstat) # make a list of dicts to create a pandas data frame datalist.append({ 'position': pos, 'year': year, 'name': pfullname, 'fantasy_points': base_pts # 'playerid':pstat.playerid }) df = pd.DataFrame(datalist) df.to_csv(fname)
def team_record(team, year, week=17, type='total'): if week == 0: return [0, 0, 0] if type == 'total': games = nflgame.games_gen(year, week=range(1, week + 1), home=team, away=team) elif type == 'home': games = nflgame.games_gen(year, week=range(1, week + 1), home=team) elif type == 'away': games = nflgame.games_gen(year, week=range(1, week + 1), away=team) if games is None: try: team = alternate_team_names[team] if type == 'total': games = nflgame.games_gen(year, week=range(1, week + 1), home=team, away=team) elif type == 'home': games = nflgame.games_gen(year, week=range(1, week + 1), home=team) elif type == 'away': games = nflgame.games_gen(year, week=range(1, week + 1), away=team) except KeyError: return [0, 0, 0] wins, losses, ties = 0, 0, 0 try: for g in games: if g.winner == g.home + '/' + g.away: ties += 1 elif g.winner == team: wins += 1 else: losses += 1 return [wins, losses, ties] except TypeError: return [0, 0, 0]
def generateSummaryDataFile( fname, years ): # this list will be used as a constructor to the DataFrame # perhaps there is a slicker way to construct a DataFrame? datalist = [] for year in years: print 'reading {} season...'.format( year ) games = nflgame.games_gen( year ) # get game-level stats all_players = nflgame.combine_game_stats( games ) # top_qbs = all_players.passing().filter( playerid=lambda x: x in qb_ids ).sort('passing_yds').limit( 32 ) # for some reason "position" does allow any through and we must use "guess_position" top_players = {} top_players['QB'] = all_players.passing().filter( guess_position='QB' ).sort('passing_yds').limit( 32 ) top_players['RB'] = all_players.rushing().filter( guess_position='RB' ).sort('rushing_yds').limit( 64 ) top_players['WR'] = all_players.receiving().filter( guess_position='WR' ).sort('receiving_yds').limit( 64 ) top_players['TE'] = all_players.receiving().filter( guess_position='TE' ).sort('receiving_yds').limit( 24 ) # checked that kickers have a very flat response vs. preseason rank. # check again once we add bonuses for long FGs? # top_players['K'] = all_players.kicking().filter( guess_position='K' ).sort('kicking_fgyds').limit( 24 ) for (pos,players) in top_players.items(): for pstat in players: # print qbstat.rushing_lng, qbstat.rushing_lngtd # longest rush, longest TD rush # print qbstat.stats # dict of the stats # print qbstat.formatted_stats() # relatively nicely printed out version of the stats dict pfullname = pstat.player.full_name.strip() base_pts = getBasePoints( bro_league, pstat ) # make a list of dicts to create a pandas data frame ps_rank = getPreseasonRank( pos, year, pfullname ) datalist.append({'position':pos, 'year':year, 'name':pfullname, 'preseason_rank':ps_rank, 'fantasy_points':base_pts # 'playerid':pstat.playerid }) df = pd.DataFrame(datalist) df.to_csv( fname )
while True: sys.stdout.write(question + prompt) choice = raw_input().lower() if default is not None and choice == '': return valid[default] elif choice in valid: return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'no' "\ "(or 'y' or 'n').\n") print 'nflgame API loaded' print 'Compiling training sets...' print 'Compiling traing set for 2009 NFL season...' season2009 = nflgame.games_gen(2009, kind="REG") f = open('nfl2009ts_logsig_unscrubbed-14i-v1.1.csv','w') result = '' exampleCount = 0 for g in season2009: HT_AVG = nflgame.games_gen(2009, home=g.home, away=g.home, kind="REG") #get all games played by HOME team of present game before current week #compile average stats for for HOME team: YPG, PPG, YPGA, PPGA, TOpm, QB rating HT_YPG = 0 HT_PPG = 0 HT_YPGA = 0 HT_PPGA = 0 #HT_TOpm = 0 HT_TO = 0 HT_TA = 0 HT_QByds = 0 HT_QBatt = 0
while True: sys.stdout.write(question + prompt) choice = raw_input().lower() if default is not None and choice == '': return valid[default] elif choice in valid: return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'no' "\ "(or 'y' or 'n').\n") print 'nflgame API loaded' print 'Compiling training sets...' print 'Compiling traing set for 2009 NFL season...' season2009 = nflgame.games_gen(2009, week=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], kind="REG") f = open('nfl2009ts_logsig_scrubbed-v1.1.csv','w') result = '' exampleCount = 0 for g in season2009: HT_AVG = nflgame.games_gen(2009, week=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], home=g.home, away=g.home, kind="REG") #get all games played by HOME team of present game before current week #compile average stats for for HOME team: YPG, PPG, YPGA, PPGA, TOpm, QB rating HT_YPG = 0 HT_PPG = 0 HT_YPGA = 0 HT_PPGA = 0 HT_TOpm = 0 HT_QByds = 0 HT_QBatt = 0 HT_QBcomp = 0 HT_QBtd = 0
import nflgame import numpy import matplotlib.pyplot as plt from pylab import * # Find our player team_to_find = "GB" player_to_find = "A.Rodgers" # Create a list to store all of the TDs for our player list_player_tds = [] # Get all the games in 2014 games = nflgame.games_gen(2014, home=team_to_find, away=team_to_find) for game in games: players = game.players # Find our player and store the number of passing TDs to our list found_player = players.name(player_to_find) try: list_player_tds.append(found_player.passing_tds) except AttributeError: list_player_tds.append(0) # Convert the list of TDs into an array using numpy arr_tds = numpy.array(list_player_tds) # Clear the matploylib plot plt.clf() # Create a second list for our x-axis values xaxis = []
from decimal import Decimal, ROUND_DOWN import nflgame import csv import itertools print 'nflgame API loaded and updated' week = raw_input('What week of the season, 1-17?: ') filename = 'nfl_weeklystats_week' + str(week) + '.csv' f = open(filename,'a') numGames = raw_input('Enter the number of games to gather data for: ') f.write(numGames + ',12\n') for i in range(int(numGames)): awayTeam = raw_input('Enter the AWAY team: ').upper() homeTeam = raw_input('Enter the HOME team: ').upper() HT_AVG1 = nflgame.games_gen(2013, home=homeTeam, away=homeTeam, kind="REG") QBs = nflgame.combine(HT_AVG1) print 'Which HOME QB statistics to use?' for p in QBs.passing().sort("passing_att"): print p QBname = raw_input('Enter the quarterback name as it is written: ') QB_AVG = nflgame.games_gen(2013, kind="REG") playerStats = nflgame.combine(QB_AVG) QBplayer = playerStats.name(QBname) AT_AVG1 = nflgame.games_gen(2013, home=awayTeam, away=awayTeam, kind="REG") aQBs = nflgame.combine(AT_AVG1) print 'Which AWAY QB statistics to use?' for p in aQBs.passing().sort("passing_att"): print p aQBname = raw_input('Enter the quarterback name as it is written: ') aQB_AVG = nflgame.games_gen(2013, kind="REG")
from datetime import datetime start_time = datetime.now() import nflgame as nf import pandas as pd import numpy as np games = nf.games_gen(2015, week = 1, kind = 'POST') players = nf.combine_game_stats(games) name_arr = [] arr = [] tuples = [] wide_receivers = [] ########################################################################### def receiver_gen(team): for p in players.receiving().filter(receiving_rec_gte = 0).sort('receiving_rec'): if (str(p.guess_position) == 'WR' or str(p.guess_position) == '') and str(p.team) == team: name_arr.append(str(p.name)) return list(set(name_arr)) ########################################################################## def receiving_stats(player, team): for i in player: mecca = str(players.receiving().filter(receiving_rec_gte = 0).name(i)) if mecca == i: for p in players.receiving().filter(receiving_rec_gte = 0).sort('receiving_rec'): if str(p) == mecca and str(p.team) == team: holder = (str(p.name), str(p.team), str(p.guess_position), int(p.receiving_rec), int(p.receiving_yds), int(p.receiving_tds), int(p.rushing_yds), int(p.rushing_tds), int(p.fumbles_lost),) pts = round(sum((int(p.receiving_rec)*0.5, int(p.receiving_yds)*0.1, int(p.receiving_tds)*6.0, int(p.rushing_yds)*0.1, int(p.rushing_tds)*6.0, int(p.fumbles_lost)*-2.0)), 2) final = holder + (pts,) tuples.append(final) else: