def getAllStatsByYearAndWeek(self): # Initialize variables year = 2013 week = 1 filename = '../stats/season' + str(year) + '_' + str(week) + '.csv' stats_fetcher = StatsFetcher() stats = self.tryToGetStats(year, week=1) # Keep looping while stats are being returned while True: # Check if year has any stats if not stats: print 'No stats found for year ' + str(year) break # Start at week 1 and keep going until no more data can be found week = 1 while week: stats = self.tryToGetStats(year, week) if stats: print 'Found stats for year ' + str(year) + ' week ' + str(week) nflgame.combine_game_stats(stats).csv(filename) week = week + 1 filename = '../stats/season' + str(year) + '_' + str(week) + '.csv' else: print 'No stats found for year ' + str(year) + ' week ' + str(week) week = False # Advance the year and check if data exists year = year - 1 stats = self.tryToGetStats(year, week=1) # If nothing went wrong return True return True
def gather_players(seasons, weeks): for season in seasons: for week in weeks: game = nflgame.games(season, week=week) filename = '../nfl_game_data/' + str(season) + '_' + str(week) + '.csv' try: nflgame.combine_game_stats(game).csv(filename) except TypeError: continue
def getFantasyPoints(seasons, weeks): """ Download game stats for every season and week and calculate the fantasy points scored for each player in each game. Args: seasons (list): List of seasons (int). weeks (list): List of weeks (int). Returns: dict: Dictionary of fantasy points scored. """ data = {} schedule = nflgame.sched.games for s in seasons: print s data[s] = {} for w in weeks: games = nflgame.games(s, w) players = nflgame.combine_game_stats(games) data[s][w] = [] positions = ["QB", "RB", "WR", "TE"] gen = (p for p in players if p.player.position in positions) for player in gen: points = calculateFantasyPoints(player) points.append(getOpponent(schedule, s, w, player)) data[s][w].append(points) return data
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 getSeasonStats(self, plyr, stat, season): data = [] # if season == 2014: # print "HERE" for x in range(1, 18): game = nflgame.games(season,week=x) if game == []: break players = nflgame.combine_game_stats(game) player = players.name(plyr) if player is None: data.append({'week':str(x),'active':'false'}) else: playerStats = player.stats week_obj = {'week':str(x)} if(stat == 'all'): for x in playerStats: week_obj[x] = playerStats[x] week_obj['active'] = 'true' data.append(week_obj) # if season == 2014: # print week_obj else: data.append({'week':str(x),stat:str(playerStats[stat]), 'active':'true'}) return data
def defense_team_stats(team_symbol, year, wk): # takes team symbol, year of games(s), week of game(s) # used for defensive team stats stats = { 'rushing_yds_allowed': 0, 'rushing_tds_allowed': 0, 'passing_yds_allowed': 0, 'passing_tds_allowed': 0, 'total_points_allowed': 0, 'passing_ints': 0, 'fumbles_forced': 0 } games = nflgame.games(year, week=wk, home=team_symbol, away=team_symbol) gameplayers = nflgame.combine_game_stats(games) for g in games: if g.home != team_symbol: stats['total_points_allowed'] += g.score_home if g.away != team_symbol: stats['total_points_allowed'] += g.score_away for p in gameplayers: if p.team != team_symbol: stats['rushing_yds_allowed'] += p.rushing_yds stats['rushing_tds_allowed'] += p.rushing_tds stats['passing_yds_allowed'] += p.passing_yds stats['passing_tds_allowed'] += p.passing_tds stats['passing_ints'] += p.passing_ints stats['fumbles_forced'] += p.fumbles_tot return stats
def getSeasonStats(self, plyr, stat, season): data = [] # if season == 2014: # print "HERE" for x in range(1, 18): game = nflgame.games(season, week=x) if game == []: break players = nflgame.combine_game_stats(game) player = players.name(plyr) if player is None: data.append({'week': str(x), 'active': 'false'}) else: playerStats = player.stats week_obj = {'week': str(x)} if (stat == 'all'): for x in playerStats: week_obj[x] = playerStats[x] week_obj['active'] = 'true' data.append(week_obj) # if season == 2014: # print week_obj else: data.append({ 'week': str(x), stat: str(playerStats[stat]), 'active': 'true' }) return data
def build_weekly_stats(season=2015, week=1): errors = 0 new_week, _ = Week.objects.get_or_create(season=season, number=week) print "..filling in data for {}".format(new_week) games = nflgame.games(season.year, week=week) players = nflgame.combine_game_stats(games) # qb stats for p in players.passing().sort('passing_yds').limit(30): try: db_player = Player.objects.get(playerid=p.playerid) #except Player.DoesNotExist: except Exception as e: print(e) errors += 1 continue else: weekly_stat, _ = WeeklyStats.objects.get_or_create(player=db_player, season=season, week=new_week) # qb stats weekly_stat.passing_attempts = p.passing_attempts weekly_stat.passing_cmps = p.passing_cmp weekly_stat.passing_yds = p.passing_yds weekly_stat.passing_tds = p.passing_tds weekly_stat.passing_ints = p.passing_ints weekly_stat.save() # rushing stats for p in players.rushing().sort('rushing_yds').limit(100): try: db_player = Player.objects.get(playerid=p.playerid) except Player.DoesNotExist: errors += 1 continue else: weekly_stat, _ = WeeklyStats.objects.get_or_create(player=db_player, season=season, week=new_week) weekly_stat.rushing_yds = p.rushing_yds weekly_stat.rushing_atts = p.rushing_att weekly_stat.rushing_tds = p.rushing_tds weekly_stat.save() for p in players.receiving().sort('receiving_yds').limit(200): try: db_player = Player.objects.get(playerid=p.playerid) except Player.DoesNotExist: errors += 1 continue else: weekly_stat, _ = WeeklyStats.objects.get_or_create(player=db_player, season=season, week=new_week) # rec stats weekly_stat.receiving_rec = p.receiving_rec weekly_stat.receiving_yds = p.receiving_yrds weekly_stat.receiving_tds = p.receiving_tds weekly_stat.save()
def rb_weekly_stats(year): d = {} for week in range(17): games = nflgame.games(int(year), int(week + 1)) players = nflgame.combine_game_stats(games) for p in players.rushing().sort('rushing_yds'): fp = 0.1 * float(p.rushing_yds) + float(6 * p.rushing_tds) rush_msg(p.rushing_att, p.rushing_yds, p.rushing_tds)
def top( message, pos_abbreviation, year ): # in this definition, message is the object, and position and year are passed to the function! # convert year into an int year = int(year) # if the position provided is not a position, then respond saying so if pos_abbreviation not in ['QB', 'RB', 'WR', 'K']: # TODO: move positions into an include like valid_positions to futureproof if more positions are added message.reply( 'You didn\'t give me a valid position! Please use QB, RB, WR, or K (TE support coming soon!)' ) return # same story if the year is invalid # TODO: make year range auto calculated based on current time if year not in range(2009, 2016): message.reply( 'You didn\'t give me a valid year! I only have data from 2009 - 2015' ) return # calculate the game stats using nflgame games = nflgame.games(year) players = nflgame.combine_game_stats(games) # intiialize response variable response = 'Here are the stats for the top 5 %s in %s:\n' % ( pos_abbreviation, year) # TODO: refactor the crap out of this mess (probably move the positions into a lookup array) # TODO: figure out how to add defense stats (may have to sum across all DEF players) # TODO (more urgent) add TE if pos_abbreviation == 'QB': for p in players.passing().sort('passing_yds').limit(5): msg = '*%s:* %d passes for %d yards and %d TDs\n' % ( p, p.passing_att, p.passing_yds, p.passing_tds) response += msg if pos_abbreviation == 'RB': for p in players.rushing().sort('rushing_yds').limit(5): yards_per_carry = int(float(p.rushing_yds) / float(p.rushing_att)) msg = '*%s:* %d rushes for %d yards (%d YPC) and %d TDs\n' % ( p, p.rushing_att, p.rushing_yds, yards_per_carry, p.rushing_tds) response += msg if pos_abbreviation == 'WR': for p in players.receiving().sort('receiving_yds').limit(5): msg = '*%s*: %d receptions for %d yards and %d TDs\n' % ( p, p.receiving_rec, p.receiving_yds, p.receiving_tds) response += msg if pos_abbreviation == 'K': for p in players.kicking().sort('kicking_yds').limit(5): msg = '*%s:* %d FG out of %d attempts and %d total XP\n' % ( p, p.kicking_fgm, p.kicking_fga, p.kicking_xpmade) response += msg message.reply(response)
def generate(): games = nflgame.games(int(year), week=1) players = nflgame.combine_game_stats(games) playerList = [] for p in players.passing().sort('passing_yds').limit(int(count)): player = addStats({'pos': 'QB'}, p, 'QB') if player is not None: playerList.append(player) yield makeResponse(playerList)
def build_weekly_stats(season=2015, week=1): errors = 0 new_week, _ = Week.objects.get_or_create(season=season, number=week) print "..filling in data for {}".format(new_week) games = nflgame.games(season.year, week=week) players = nflgame.combine_game_stats(games) # qb stats for p in players.passing().sort('passing_yds').limit(30): try: db_player = Player.objects.get(playerid=p.playerid) except Player.DoesNotExist: errors += 1 continue else: weekly_stat, _ = WeeklyStats.objects.get_or_create(player=db_player, season=season, week=new_week) # qb stats weekly_stat.passing_attempts = p.passing_attempts weekly_stat.passing_cmps = p.passing_cmp weekly_stat.passing_yds = p.passing_yds weekly_stat.passing_tds = p.passing_tds weekly_stat.passing_ints = p.passing_ints weekly_stat.save() # rushing stats for p in players.rushing().sort('rushing_yds').limit(100): try: db_player = Player.objects.get(playerid=p.playerid) except Player.DoesNotExist: errors += 1 continue else: weekly_stat, _ = WeeklyStats.objects.get_or_create(player=db_player, season=season, week=new_week) weekly_stat.rushing_yds = p.rushing_yds weekly_stat.rushing_atts = p.rushing_att weekly_stat.rushing_tds = p.rushing_tds weekly_stat.save() for p in players.receiving().sort('receiving_yds').limit(200): try: db_player = Player.objects.get(playerid=p.playerid) except Player.DoesNotExist: errors += 1 continue else: weekly_stat, _ = WeeklyStats.objects.get_or_create(player=db_player, season=season, week=new_week) # rec stats weekly_stat.receiving_rec = p.receiving_rec weekly_stat.receiving_yds = p.receiving_yrds weekly_stat.receiving_tds = p.receiving_tds weekly_stat.save()
def test(): games = nflgame.games(2018, week=5) players = nflgame.combine_game_stats(games) testPL = [] for p in players.rushing().sort('rushing_yds').limit(25): msg = '%s %d carries for %d yards and %d TDs' testPL.append(msg % (p, p.rushing_att, p.rushing_yds, p.rushing_tds)) return makeResponse(testPL)
def toprushers(year, count=100): try: weeks = ypc.get_weeks(year) plays = nflgame.combine_game_stats(nflgame.games( int(year), weeks)).rushing().sort('rushing_yds').limit(int(count)) topplayers = imap(ypc.get_rusher_stats, plays) return jsonify(result=list(topplayers)) except Exception as e: abort(400, e)
def rushing(): games = nflgame.games(2016, week=16) players = nflgame.combine_game_stats(games) rushing_results = [] for p in players.rushing().sort('rushing_yds').limit(5): message = '%s %d rushes for %d yards and %d TDs' rushing_results.append( message % (p, p.rushing_att, p.rushing_yds, p.rushing_tds)) return rushing_results
def passing(): games = nflgame.games(2016, week=16) players = nflgame.combine_game_stats(games) quarterback_result = [] for p in players.passing().sort('passing_yds').limit(5): message = '%s %d of %d passes for %d yards and %d TDs' quarterback_result.append( message % (p, p.passing_cmp, p.passing_att, p.passing_yds, p.passing_tds)) return quarterback_result
def generate(): games = nflgame.games(int(year), week=1) players = nflgame.combine_game_stats(games) playerList = [] for p in players.receiving().sort('receiving_yds').limit(int(count)): if p.guess_position == 'TE': player = addStats({'pos': 'TE'}, p, 'WR') if player is not None: playerList.append(player) yield makeResponse(playerList)
def getAllStatsByYear(self): # Initialize variables year = 2013 filename = '../stats/season' + str(year) + '.csv' stats_fetcher = StatsFetcher() stats = True # Keep looping while stats are being returned while stats: stats = self.tryToGetStats(year) if stats: print 'Found stats for year ' + str(year) nflgame.combine_game_stats(stats).csv(filename) year = year - 1 filename = '../stats/season' + str(year) + '.csv' else: print 'No stats found for year ' + str(year) return True
def receiving(): games = nflgame.games(2016, week=16) players = nflgame.combine_game_stats(games) receiving_result = [] for p in players.receiving().sort('receiving_yds').limit(5): message = '%s %d catches for %d yards and %d TDs' receiving_result.append( message % (p, p.receiving_rec, p.receiving_yds, p.receiving_tds)) return receiving_result
def populate_data(yr, wk, pid, pos_id): points = [] leave_out_week = 5 points.append(getFantasyPoints(yr, wk-1, pid)) points.append(getFantasyPoints(yr, wk-2, pid)) points.append(getFantasyPoints(yr, wk-3, pid)) points.append(getFantasyPoints(yr, wk-4, pid)) points.append(getFantasyPoints(yr, wk-5, pid)) points.append(getFantasyPoints(yr, wk-6, pid)) for i in range(0,6): if(points[i] == 0): leave_out_week = i break added = 0 games3 = [] games5 = [] points3 = 0 points5 = 0 for i in range(0,6): if(i != leave_out_week): if(added < 1): games1 = games[i] points1 = points[i]; if(added < 3): games3 = games3 + games[i] points3 = points3 + points[i] if(added < 5): games5 = games5 + games[i] points5 = points5 + points[i] added = added + 1 play1 = nflgame.combine_game_stats(games1) play3 = nflgame.combine_game_stats(games3) play5 = nflgame.combine_game_stats(games5) (p1_present, p1) = findPlayerById(play1, pid) (p3_present, p3) = findPlayerById(play3, pid) (p5_present, p5) = findPlayerById(play5, pid) if(pos_id == 0): populate_wr_data(yr, wk, p1, p3, p5, points1, points3, points5, pid) elif(pos_id == 1): populate_rb_data(yr, wk, p1, p3, p5, points1, points3, points5, pid) else: populate_qb_data(yr, wk, p1, p3, p5, points1, points3, points5, pid)
def get_passing_stats(): stats = pd.DataFrame() for year in years: game = nflgame.games(year) players = nflgame.combine_game_stats(game) df = pd.DataFrame([(p, p.passing_yds, p.passing_att, p.passing_cmp, p.passing_tds, p.rushing_tds) for p in players.passing()]) df.columns= ['QB','Passing Yards', 'Passing Atp', 'Passing Comp','Passing TDs', 'Rushing TDs'] df['year'] = year df['QB'] = df['QB'].astype(str) stats = stats.append(df) return stats
def get_receiving_stats(): stats = pd.DataFrame() for year in years: game = nflgame.games(year) players = nflgame.combine_game_stats(game) df = pd.DataFrame([(p, p.receiving_yds, p.receiving_rec, p.receiving_tds) for p in players.receiving()]) df.columns= ['WR','Receiving Yards', 'Receptions','Receiving TDs'] df['year'] = year df['WR'] = df['WR'].astype(str) stats = stats.append(df) return stats
def update_player_stats(self): print('Updating player stats...') for year, phase, week in update_sched.year_phase_week(year=self.year): if phase != 'PRE': print(' {} year: {}, week: {}'.format(phase, year, week)) try: games = nflgame.games(year, week, kind=phase) real_week = week + 17 if phase == 'POST' else week if len(games): players = nflgame.combine_game_stats(games) for player in players: if player.player: try: playerObj = NflPlayer.objects.get(gsis_id=player.player.player_id, active=True) except ObjectDoesNotExist: #print(' Did not find {}: {}'.format(player.player.player_id, player)) continue try: stat = NflStat.objects.get(week=real_week, player=playerObj) # if player.player.player_id == '00-0026138': # if phase == 'POST': # print(' Updating {}'.format(stat)) # update the stat data stat.td = player.tds stat.fg = player.kicking_fpm stat.two = player.twoptm stat.xp = player.kicking_xpmade stat.diff = 0 # if player.player.player_id == '00-0026138': # print(' updating {}'.format(stat)) stat.save() except ObjectDoesNotExist: # create the stat # if player.player.player_id == '00-0026138': # if phase == 'POST': # print(' Creating stat for {} {}'.format(week, player.player.player_id)) stat = NflStat.objects.create( week = real_week, td = player.tds, fg = player.kicking_fgm, xp = player.kicking_xpmade, two = player.twoptm, diff = 0, player = playerObj ) # if player.player.player_id == '00-0026138': # print(' creating {}'.format(stat)) stat.save() except TypeError: # needed for nflgame not pulling post season data correctly pass
def collect_qb_stats() -> pd.DataFrame: qb_data = pd.DataFrame() for year, week in tqdm(product(GAME_YEARS, GAME_WEEKS)): games = nflgame.games(year, week) players = nflgame.combine_game_stats(games) qb_stats = format_passing_stats(year, week, players, quarterbacks=QUARTERBACKS) qb_data = qb_data.append(pd.DataFrame(qb_stats)) qb_data.columns = ["year", "week", "player", "touchdowns", "passing_yds"] return qb_data
def get_player_score(player): year = np.random.choice([2014, 2015, 2016, 2017], p=[0.1, .15, .25, .5]) week = np.random.randint(1, 18) games = nflgame.games(year, week=week) games = nflgame.combine_game_stats(games) for person in games: if person.player is None: continue if player == person.player: return score_to_fantasy_points(person) return get_player_score(player)
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 k_stats(player_id, year, wk, team): # takes player's full name, year of game(s), week of game(s), player team # applies for all kickers stats = {'fgmade': 0, 'fga': 0, 'xpmade': 0, 'xpa': 0} games = nflgame.games(year, week=wk, home=team, away=team) gameplayers = nflgame.combine_game_stats(games) for p in gameplayers: if p.playerid == player_id: stats['fgmade'] = p.kicking_fgm stats['fga'] = p.kicking_fga stats['xpmade'] = p.kicking_xpmade stats['xpa'] = p.kicking_xpa return stats
def flex_stats(name, year): player = nflgame.find(name) for week in range(17): games = nflgame.games(int(year), int(week + 1)) players = nflgame.combine_game_stats(games) for p in players: if str(name) == str(p): fp = fps(p.receiving_rec, p.rushing_yds, p.rushing_tds, p.receiving_yds, p.receiving_tds) general_msg(int(week + 1), float(fp)) rush_msg(p.rushing_att, p.rushing_yds, p.rushing_tds) rec_msg(p.receiving_tar, p.receiving_rec, p.receiving_yds, p.receiving_tds)
def k_stats(player_id, year, wk, team): # takes player's full name, year of game(s), week of game(s), player team # applies for all kickers stats = {'fgmade':0, 'fga':0, 'xpmade':0, 'xpa':0} games = nflgame.games(year, week=wk, home=team, away=team) gameplayers = nflgame.combine_game_stats(games) for p in gameplayers: if p.playerid == player_id: stats['fgmade']=p.kicking_fgm stats['fga']=p.kicking_fga stats['xpmade']=p.kicking_xpmade stats['xpa']=p.kicking_xpa return stats
def generate(): games = nflgame.games(int(year), week=1) players = nflgame.combine_game_stats(games) player = nflgame.find(name, team=team)[0] for x in players: if x.player: if x.player.full_name: if x.player.full_name == player.full_name: p = addStats(player.__dict__, x, player.position) if p is not None: p = fillBlanks(p) yield makeResponse([p]) break
def generate(): print(datetime.datetime.now()) games = nflgame.games(int(year), week=10) print(datetime.datetime.now()) players = nflgame.combine_game_stats(games) print(datetime.datetime.now()) playerList = [] for p in players.rushing().sort('rushing_yds').limit(int(count)): player = addStats({'pos': 'RB'}, p, 'RB') if player is not None: playerList.append(player) print(datetime.datetime.now()) yield makeResponse(playerList)
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 run(): parser = argparse.ArgumentParser( description='Takes the passed week and gets fantasy score for players ' 'based on interest.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) aa = parser.add_argument aa('--year', default=2017, type=int, help='Pick a year to get fantasy points for.') aa('--week', default=1, type=int, help='Pick a week to get fantasy points for.') aa('--threshold', default=20, type=int, help='Show players with scores greater than threshold.') args = parser.parse_args() year = args.year week = args.week threshold = args.threshold players = nflgame.combine_game_stats(nflgame.games(year, week)) qbs = {} wrs = {} rbs = {} tes = {} for p in players: score = score_player(p) if score > threshold: #print p.guess_position,p.name,p.team,score,p.formatted_stats() if p.guess_position == 'QB': qbs[p.name] = score if p.guess_position == 'WR': wrs[p.name] = score if p.guess_position == 'RB': rbs[p.name] = score if p.guess_position == 'TE': tes[p.name] = score print len(qbs) print qbs print len(wrs) print wrs print len(rbs) print rbs print len(tes) print tes
def displayPointTotalsByYearAndWeek(year, week): list_fplayers = [] games = nflgame.games(2018, week=1) players = nflgame.combine_game_stats(games) for p in players: my_fplayer = FantasyPlayer(p) list_fplayers.append(my_fplayer) newlist = sorted(list_fplayers, key=lambda x: x.points) for fplayer in newlist: msg = '%s %3.2f' print msg % (fplayer.player, fplayer.points)
def get_player_to_points(year, week, custom_id_to_info): """ Gets a map of player ID to a tuple of the player's points and position """ player_id_to_points = {} games = nflgame.games(int(year), week=int(week)) players = nflgame.combine_game_stats(games) for player in players: custom_id = player.name + "-" + player.team if (custom_id in custom_id_to_info): points = calculate_player_points(player) player_id_to_points[custom_id] = (points, custom_id_to_info[custom_id]) print (player_id_to_points) return player_id_to_points
def playerover1000(): player_over_1000 = dict() for i in range(2009, 2016): season = nflgame.games(i) all_players = nflgame.combine_game_stats(season) qbs_4000 = filter(lambda x: x.passing_yds > 4000, all_players) run_1000 = filter(lambda x: x.rushing_yds > 1000, all_players) rec_1000 = filter(lambda x: x.receiving_yds > 1000, all_players) sumofqbs = len(qbs_4000) sumofrun = len(run_1000) sumofrec = len(rec_1000) obj = {'qbs': sumofqbs, 'run': sumofrun, 'rec': sumofrec} player_over_1000['playercount' + str(i)] = obj #10,5,10,11,9,11,12 return jsonify(**player_over_1000)
def top(message, pos_abbreviation, year): # in this definition, message is the object, and position and year are passed to the function! # convert year into an int year = int(year) # if the position provided is not a position, then respond saying so if pos_abbreviation not in ['QB','RB','WR','K']: # TODO: move positions into an include like valid_positions to futureproof if more positions are added message.reply('You didn\'t give me a valid position! Please use QB, RB, WR, or K (TE support coming soon!)') return # same story if the year is invalid # TODO: make year range auto calculated based on current time if year not in range(2009,2016): message.reply('You didn\'t give me a valid year! I only have data from 2009 - 2015') return # calculate the game stats using nflgame games = nflgame.games(year) players = nflgame.combine_game_stats(games) # intiialize response variable response = 'Here are the stats for the top 5 %s in %s:\n' % (pos_abbreviation, year) # TODO: refactor the crap out of this mess (probably move the positions into a lookup array) # TODO: figure out how to add defense stats (may have to sum across all DEF players) # TODO (more urgent) add TE if pos_abbreviation == 'QB': for p in players.passing().sort('passing_yds').limit(5): msg = '*%s:* %d passes for %d yards and %d TDs\n' % (p, p.passing_att, p.passing_yds, p.passing_tds) response += msg if pos_abbreviation == 'RB': for p in players.rushing().sort('rushing_yds').limit(5): yards_per_carry = int(float(p.rushing_yds) / float(p.rushing_att)) msg = '*%s:* %d rushes for %d yards (%d YPC) and %d TDs\n' % (p, p.rushing_att, p.rushing_yds, yards_per_carry, p.rushing_tds) response += msg if pos_abbreviation == 'WR': for p in players.receiving().sort('receiving_yds').limit(5): msg = '*%s*: %d receptions for %d yards and %d TDs\n' % (p, p.receiving_rec, p.receiving_yds, p.receiving_tds) response += msg if pos_abbreviation == 'K': for p in players.kicking().sort('kicking_yds').limit(5): msg = '*%s:* %d FG out of %d attempts and %d total XP\n' % (p, p.kicking_fgm, p.kicking_fga, p.kicking_xpmade) response += msg message.reply(response)
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 offense_team_stats(team_symbol, year, wk): # takes team symbol, year of games(s), week of game(s) # used for offensive team stats stats = {'rushing_yds':0, 'rushing_tds':0, 'passing_yds':0, 'passing_tds':0, 'total_points':0} games = nflgame.games(year, week=wk, home=team_symbol, away=team_symbol) gameplayers = nflgame.combine_game_stats(games) for g in games: if g.home == team_symbol: stats['total_points']+=g.score_home if g.away == team_symbol: stats['total_points']+=g.score_away for p in gameplayers: if p.team == team_symbol: stats['rushing_yds']+=p.rushing_yds stats['rushing_tds']+=p.rushing_tds stats['passing_yds']+=p.passing_yds stats['passing_tds']+=p.passing_tds return stats
def k_stats(name, year, wk): # takes players full name, year of game, week of game(s) # applies for all kickers playerlist = nflgame.find(name, team=None) if playerlist == []: return False else: player = playerlist[0] stats = {'fgmade':0, 'fga':0, 'xpmade':0, 'xpa':0} games = nflgame.games(year, week=wk) gameplayers = nflgame.combine_game_stats(games) for p in gameplayers: if p.name == player.gsis_name: stats['fgmade']+=p.kicking_fgm stats['fga']+=p.kicking_fga stats['xpmade']+=p.kicking_xpmade stats['xpa']+=p.kicking_xpa return stats
def topreceivers(year,count=100): def get_player_stats(ap): return { 'id': ap.playerid, 'name': nflgame.players[ap.playerid].full_name, 'team': str(ap.team), 'receiving_yds': ap.receiving_yds, 'receiving_rec': ap.receiving_rec, 'receiving_tds': ap.rushing_tds + ap.receiving_tds } try: current_year, current_week = nflgame.live.current_year_and_week() weeks = [x for x in range(1, current_week+1)] if int(year) == int(current_year) else [x for x in range(1, 18)] topplayers = map(get_player_stats, nflgame.combine_game_stats(nflgame.games(int(year), weeks)).receiving().sort('receiving_yds').limit(int(count))) gc.collect() return jsonify(result = topplayers) except (ValueError, KeyError, TypeError): abort(400, 'custom error message to appear in body')
def qb_stats(name, year, wk): # takes players full name, year of game, week of game(s) # applies for all quarterbacks playerlist = nflgame.find(name, team=None) if playerlist == []: return False else: player = playerlist[0] stats = {'rushing_yds':0, 'rushing_tds':0, 'passing_yds':0, 'passing_tds':0, 'passing_ints':0, 'fumbles':0} games = nflgame.games(year, week=wk) gameplayers = nflgame.combine_game_stats(games) for p in gameplayers: if p.name == player.gsis_name: stats['passing_yds']+=p.passing_yds stats['passing_tds']+=p.passing_tds stats['passing_ints']+=p.passing_ints stats['rushing_yds']+=p.rushing_yds stats['rushing_tds']+=p.rushing_tds stats['fumbles']+=p.fumbles_tot return stats
def flex_stats(name, year, wk): # takes players full name, year of game, week of game(s) # applies for all players that can play in the flex (RB, WR, TE) playerlist = nflgame.find(name, team=None) if playerlist == []: return False else: player = playerlist[0] stats = {'rushing_yds':0, 'rushing_tds':0, 'receiving_yds':0, 'receiving_tds':0, 'fumbles':0, 'puntret_tds':0, 'kickret_tds':0} games = nflgame.games(year, week=wk) gameplayers = nflgame.combine_game_stats(games) for p in gameplayers: if p.name == player.gsis_name: stats['rushing_yds']+=p.rushing_yds stats['rushing_tds']+=p.rushing_tds stats['receiving_yds']+=p.receiving_yds stats['receiving_tds']+=p.receiving_tds stats['fumbles']+=p.fumbles_tot stats['puntret_tds']+=p.puntret_tds stats['kickret_tds']+=p.kickret_tds return stats
def getStats(name, week, year): print 'SOMETHING HERE' name = str(name) week = int(week) year = int(year) games = nflgame.games(year=year, week=week) listofPlayers = nflgame.combine_game_stats(games) player = listofPlayers.name(name) if not player: Player.ERROR['message'] = 'Player does not exist.' return Player.ERROR else: playerStats = player.formatted_stats() Player.SUCCESS['message'] = playerStats player_save = Player( name=name, week=week, year=year, ) player_save.save() return Player.SUCCESS
def rushing_yards(): name, year, week = parse_request_arguments(request.args) games = fetch_games(year, week) players = nflgame.combine_game_stats(games) plays = [] key = 'rushing_yds|{}|{}'.format(year, week) data = REDIS.get(key) if not (data and len(data)): for player in players.rushing().sort('rushing_yds'): plays.append('{} {} carries for {} yards and {} TDs'.format( player, player.rushing_att, player.rushing_yds, player.rushing_tds)) plays = set_data_on_redis_key(key, plays, True) else: plays = data return plays
def main_stats(player_id, year, wk, team): # takes player's id, year of game(s), week of game(s), player team # applies for all skill position players (QB, RB, WR, TE) stats = {'rushing_yds':0, 'rushing_tds':0, 'receiving_yds':0, 'receiving_tds':0, 'fumbles':0, 'puntret_tds':0, 'kickret_tds':0, 'rushing_2pt':0, 'receiving_2pt':0, 'passing_yds':0, 'passing_tds':0, 'passing_ints':0, 'passing_2pt':0, 'receptions':0} games = nflgame.games(year, week=wk, home=team, away=team) gameplayers = nflgame.combine_game_stats(games) for p in gameplayers: if p.playerid == player_id: stats['rushing_yds']=p.rushing_yds stats['rushing_tds']=p.rushing_tds stats['receiving_yds']=p.receiving_yds stats['receiving_tds']=p.receiving_tds stats['fumbles']=p.fumbles_tot stats['puntret_tds']=p.puntret_tds stats['kickret_tds']=p.kickret_tds stats['rushing_2pt']=p.rushing_twoptm stats['receiving_2pt']=p.receiving_twoptm stats['passing_yds']=p.passing_yds stats['passing_tds']=p.passing_tds stats['passing_ints']=p.passing_ints stats['passing_2pt']=p.passing_twoptm stats['receptions']=p.receiving_rec return stats
def yearAndWeek(): games = nflgame.games(2015, 4) players = nflgame.combine_game_stats(games) return players
# Test year validity try: games = nflgame.games(year) except TypeError: print 'Type Error: Invalid Year' return False except: print "Unexpected error:", sys.exc_info()[0] raise return games # Initialize while loop parameters ## # TODO set year to most recent year with at least one week of games ## year = 2013 filename = '/var/www/fantasyfootball/year_stats/season' + str(year) + '.csv' games = True # While stats are being returned, keep looping while stats: stats = getStatsByYear(year) if stats: print 'Found stats for year ' + str(year) nflgame.combine_game_stats(games).csv(filename) year = year - 1 filename = '/var/www/fantasyfootball/year_stats/season' + str(year) + '.csv' print 'Last year with stats is ' + str(year)
def determine_winner_and_update_record(game, string): home = game['home'] away = game['visitor'] home_team_abbr = common.mapping.get(home) away_team_abbr = common.mapping.get(away) home_points = 0 away_points = 0 home_team = home_team_abbr if home_team_abbr in common.nflgamemappingReverse: home_team = common.nflgamemappingReverse.get(home_team) away_team = away_team_abbr if away_team_abbr in common.nflgamemappingReverse: away_team = common.nflgamemappingReverse.get(away_team) i = 1 weekstoget = [] while i < week_to_check: weekstoget.append(i) i += 1 home_games_list = [] away_games_list = [] if len(weekstoget) > 0: home_games_list = nflgame.games(2015, weekstoget, home_team, home_team, 'REG') away_games_list = nflgame.games(2015, weekstoget, away_team, away_team, 'REG') else: home_games_list = nflgame.games(2014, [15, 16, 17], home_team, home_team, 'REG') away_games_list = nflgame.games(2014, [15, 16, 17], away_team, away_team, 'REG') home_stats = nflgame.combine_game_stats(home_games_list) away_stats = nflgame.combine_game_stats(away_games_list) home_games = records[home_team_abbr]['win'] + records[home_team_abbr]['loss'] away_games = records[away_team_abbr]['win'] + records[away_team_abbr]['loss'] home_games = home_games if home_games is not 0 else 3 away_games = away_games if away_games is not 0 else 3 home_rushing = 0 away_rushing = 0 home_passing = 0 away_passing = 0 home_turnovers = 0 away_turnovers = 0 home_td = 0 away_td = 0 for p in home_stats: if p.team == home_team: home_passing += p.passing_yds home_rushing += p.rushing_yds home_turnovers += p.passing_ints home_turnovers += p.fumbles_lost home_td += p.passing_tds home_td += p.rushing_tds for p in away_stats: if p.team == away_team: away_passing += p.passing_yds away_rushing += p.rushing_yds away_turnovers += p.passing_ints away_turnovers += p.fumbles_lost away_td += p.passing_tds away_td += p.rushing_tds home_turnovers = home_turnovers/home_games away_turnovers = away_turnovers/away_games if away_turnovers < home_turnovers: away_points += 7 else: home_points += 7 home_passing = home_passing/home_games away_passing = away_passing/away_games if away_passing > home_passing: away_points += 10 else: home_points += 10 home_rushing = home_rushing/home_games away_rushing = away_rushing/away_games if away_rushing > home_rushing: away_points += 5 else: home_points += 5 home_td = home_td/home_games away_td = away_td/away_games if away_td > home_td: away_points += 12 else: home_points += 12 if away_points > home_points: string += "<div>{0} @ {1}</div> <div> Winner: {2}</div>".format(away, home, away) records[home_team_abbr]['loss'] += 1 records[away_team_abbr]['win'] += 1 else: string += "<div>{0} @ {1}</div> <div> Winner: {2}</div>".format(away, home, home) records[away_team_abbr]['loss'] += 1 records[home_team_abbr]['win'] += 1 return string
def get_nfldata(): # File Names weather_json = 'game_weather.json' # Years to process years = [2010, 2011, 2012, 2013, 2014] # Initializing Game Weather Dictionary game_weather = {} if os.path.exists(weather_json): with open(weather_json) as ifile: game_weather = json.load(ifile) weather_lookedup = False # For header initialization started_proc = 0 f = open('nflData.csv', 'w+') # Load data by year for year in years: logger.info('Processing Year: %d', year) games = nflgame.games(year) # Create a dictionary of positions players = nflgame.combine_game_stats(games) position = {} for p in players: stats = [ (p.passing_att, 'QB'), (p.rushing_att, 'RB'), (p.receiving_rec, 'WR'), (p.defense_tkl, 'DEF'), (p.defense_ast, 'DEF'), (p.kicking_fga, 'K'), (p.punting_yds, 'P'), ] position[p.playerid] = sorted(stats, reverse=True)[0][1] # Load data for each game for game in games: # Game Related Information gdate = str(game.schedule['month']) + '/' + str(game.schedule['day']) + '/' + str(game.schedule['year']) # All games are in the afternoon # OPEN: Handle exceptions with International Games gtime = game.schedule['time'] + ' PM' # Prepping Game Data gline = { 'game_eid': game.eid, 'game_week': game.schedule['week'], 'game_wday': game.schedule['wday'], 'game_date': gdate, 'game_time': gtime, 'home_team': game.home, 'away_team': game.away, 'score_home': game.score_home, 'score_away': game.score_away, 'home_stadium': stadium_info.teamStadium[game.home], 'home_field': stadium_info.fieldType[game.home] } logger.info('Loading Year %d, Week %d: %s v %s on %s at %s', year, game.schedule['week'], game.away, game.home, gdate, gtime) # Extract Weather Information logger.debug('Location: %s, Date: %s, Time: %s', stadium_info.teamLocation[game.home], gdate, gtime) if game.eid not in game_weather.keys(): weather_lookedup = True # Calling weather subroutine # game_weather[game.eid] = get_weather.fetch_weather(stadium_info.teamLocation[game.home], gdate, gtime) # Initializing Data if Absent if 'temperature' not in game_weather[game.eid].keys(): game_weather[game.eid]['temperature'] = 0 if 'windSpeed' not in game_weather[game.eid].keys(): game_weather[game.eid]['windSpeed'] = 0 if 'humidity' not in game_weather[game.eid].keys(): game_weather[game.eid]['humidity'] = 0 if 'apparentTemperature' not in game_weather[game.eid].keys(): game_weather[game.eid]['apparentTemperature'] = game_weather[game.eid]['temperature'] if 'summary' not in game_weather[game.eid].keys(): game_weather[game.eid]['summary'] = 'None' logger.debug('Weather Info: %s', game_weather[game.eid]) # Prepping Weather Data gline['game_temp'] = game_weather[game.eid]['temperature'] gline['game_ftemp'] = game_weather[game.eid]['apparentTemperature'] gline['game_weather'] = game_weather[game.eid]['summary'] gline['game_wind'] = game_weather[game.eid]['windSpeed'] gline['game_humid'] = game_weather[game.eid]['humidity'] # Query player data per game plines = game.players.cummstats() # Header information hline = plines.pop(0) if started_proc == 0: # Dictionary Header Information fields = ['year', 'game_eid', 'game_week', 'game_wday', 'game_date', \ 'game_time', 'home_team', 'away_team', 'score_home', 'score_away', \ 'game_temp', 'game_ftemp', 'game_weather', 'game_wind', 'game_humid', \ 'home_stadium', 'home_field'] \ + [key for key in hline] writer = csv.DictWriter(f, fields) writer.writeheader() started_proc = 1 # Populating statline information # Includes Year, Game Information & Player Information for pline in plines: pline['pos'] = position[pline['id']] sline = {'year': year} sline.update(gline) sline.update(pline) writer.writerow(sline) # Save JSON for weather information if new data accessed # Avoid unnecessary pings forecastIO server if weather_lookedup: with open(weather_json, 'w') as ofile: json.dump(game_weather, ofile) f.close()
import nflgame games = nflgame.games(2015, week=1) #Teams Offensive Ranks teamsPPG = nflgame.combine_game_stats(games) for t in teamsPPG.PPG().sort('PPG'): msg = 'The %s score %d points per game' print msg % (t, t.PPG) teamsPassYds = nflgame.combine_game_stats(games) for t in teamsPassYds.PassYds().sort('PassYds'): msg = 'The %s average %d passing yards per game' print msg % (t, t.PassYds) teamsRushYds = nflgame.combine_game_stats(games) for t in teamsRushYds.RushYds().sort('RushYds'): msg = 'The %s average %d rushing yards per game' print msg % (t, t.RushYds) teamsTotalYds = nflgame.combine_game_stats(games) for t in teamsTotalYds.TotalYds().sort('TotalYds'): msg = 'The %s average %d total yards per game' print msg % (t, t.TotalYds) teamsTO = nflgame.combine_game_stats(games) for t in teamsTO.TO().sort('TO'): msg = 'The %s average %d turnovers per game' print msg % (t, t.TO)
def getGames(self, year, week_num, home=None, away=None): games = nflgame.games(year=year, week=week_num) list_ofPlayers = nflgame.combine_game_stats(games) return list_ofPlayers
for i in self.wr: self.final_wr.append({'A_Name':i[0], 'B_Team':i[1], 'C_Pos':i[2], 'PTS':i[3]}) return pd.DataFrame(self.final_wr) ######################################################################### def rb_df(self): for i in self.rb: self.final_rb.append({'A_Name':i[0], 'B_Team':i[1], 'C_Pos':i[2], 'PTS':i[3]}) return pd.DataFrame(self.final_rb) ######################################################################### def qb_df(self): for i in self.qb: self.final_qb.append({'A_Name':i[0], 'B_Team':i[1], 'C_Pos':i[2], 'PTS':i[3]}) return pd.DataFrame(self.final_qb) ######################################################################### d = {} games = [] players = [] arr = [] count = 0 for i in range(1,12): games.append(nf.games(2015, week = i)) d['week'+str(i)] = nf.combine_game_stats(games[count]) count += 1 for i in range(1,12): for_now = d['week'+str(i)] instance_player_df = player_df(for_now) arr.append(instance_player_df.wr_df()) for i in range(1,12): np.savetxt('wide_receivers_tight_ends_week'+ str(i) + '.txt', arr[i-1], fmt='%r')
# print week_obj else: data.append({'week':str(x),stat:str(playerStats[stat]), 'active':'true'}) return data def getAllPlayerData(full_name, abbrev_name): names = full_name.split(' ') # nflgameid = '.'.join((names[0][0],names[1])) plyrstats = PlayerStats() plyrstats.addSeasons(abbrev_name,'all', 2009, 2014) plyrstats.write('player_data/' + str('_'.join(names)) + ".json") stat = 'all' game = nflgame.games(2014,week=14) players = nflgame.combine_game_stats(game) player = players.name('T.Brady') playerStats = player.stats week_obj = {'week':str(14)} if(stat == 'all'): for y in playerStats: week_obj[y] = playerStats[y] week_obj['active'] = 'true' print week_obj else: print week_obj modified = open('modified.json','w') jsonf = open('player_data/Tom_Brady.json','r+w')
# -*- coding: utf-8 -*- """ @author: mcgovey """ # import library import nflgame # store player stats without game details #nflgame.combine(nflgame.games(2015)).csv('season2015.csv') #import json currYearGames = nflgame.games(2015) allgames = nflgame.combine_game_stats(currYearGames) #with open('json2015.txt', 'w') as outfile: # json.dump(allgames, outfile) allgames.csv('season2015.csv')
from datetime import datetime start_time = datetime.now() import nflgame as nf import pandas as pd import numpy as np games = nf.games(2015, week = [13,14,15,16,17]) players = nf.combine_game_stats(games) name_arr = [] arr = [] tuples = [] running_backs = [] ########################################################################## def runner_gen(team): for p in players.rushing().filter(rushing_att_gte = 0).sort('rushing_att'): if (str(p.guess_position) == 'RB' or str(p.guess_position) == '') and str(p.team) == team: name_arr.append(str(p.name)) return name_arr ########################################################################## def rushing_stats(player, team): for i in player: mecca = str(players.rushing().filter(rushing_att_gte = 0).name(i)) if mecca == i: for p in players.rushing().filter(rushing_att_gte = 0).sort('rushing_att'): 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,)
d[field] = "" rows.append(d) fieldNames = ["name", "id", "home", "team", "pos", "week"] + fields rows = [dict((f, f) for f in fieldNames)] + rows csv.DictWriter(open(fileName, 'w+'), fieldNames).writerows(rows) """ This section does the actual tasks of writing to CSV Must change the week range """ import nflgame for weekNum in range(1,7): gameFile = nflgame.combine_game_stats(nflgame.games(2015, week = weekNum)) csvIterator(gameFile,weekNum,"2015week"+str(weekNum)+".csv") """ Function that combines all CSVs into one baby """ import glob import os os.getcwd() os.chdir("week2015\\") interesting_files = glob.glob("*.csv") header_saved = False with open('2015stats.csv','wb') as fout:
def yearAndWeek(): # Enter the year and week: games(year, week,) or games(year, week=None) games = nflgame.games(2015, 10) players = nflgame.combine_game_stats(games) return players
def determine_winner_and_update_record(game, string, stats): home = game['home'] away = game['visitor'] home_team_abbr = common.mapping.get(home) away_team_abbr = common.mapping.get(away) home_points = 0 away_points = 0 home_team = home_team_abbr if home_team_abbr in common.nflgamemappingReverse: home_team = common.nflgamemappingReverse.get(home_team) away_team = away_team_abbr if away_team_abbr in common.nflgamemappingReverse: away_team = common.nflgamemappingReverse.get(away_team) i = 1 weekstoget = [] while i < week_to_check: weekstoget.append(i) i += 1 home_games_list = [] away_games_list = [] if len(weekstoget) > 0: home_games_list = nflgame.games(2015, weekstoget, home_team, home_team, 'REG') away_games_list = nflgame.games(2015, weekstoget, away_team, away_team, 'REG') else: home_games_list = nflgame.games(2014, [15, 16, 17], home_team, home_team, 'REG') away_games_list = nflgame.games(2014, [15, 16, 17], away_team, away_team, 'REG') home_stats = nflgame.combine_game_stats(home_games_list) away_stats = nflgame.combine_game_stats(away_games_list) home_games = records[home_team_abbr]['win'] + records[home_team_abbr]['loss'] away_games = records[away_team_abbr]['win'] + records[away_team_abbr]['loss'] home_games = home_games if home_games is not 0 else 3 away_games = away_games if away_games is not 0 else 3 home_stats_totals = { 'passing_att' : 0, 'passing_yds' : 0, 'passing_cmp' : 0, 'passing_ints' : 0, 'passing_tds' : 0, 'rushing_tds' : 0, 'rushing_yds' : 0, 'rushing_att' : 0, 'fumbles_tot' : 0, 'fumbles_lost' : 0, 'puntret_tds' : 0, 'puntret_avg' : 0, 'kicking_xptot' : 0, 'kicking_xpmade' : 0, 'kicking_fga' : 0, 'kicking_fgm' : 0, 'defense_ffum' : 0, 'defense_int': 0, 'defense_sk' : 0 } away_stats_totals = { 'passing_att': 0, 'passing_yds': 0, 'passing_cmp': 0, 'passing_ints': 0, 'passing_tds': 0, 'rushing_tds': 0, 'rushing_yds': 0, 'rushing_att': 0, 'fumbles_tot': 0, 'fumbles_lost': 0, 'puntret_tds': 0, 'puntret_avg': 0, 'kicking_xptot': 0, 'kicking_xpmade': 0, 'kicking_fga': 0, 'kicking_fgm': 0, 'defense_ffum': 0, 'defense_int': 0, 'defense_sk': 0 } for p in home_stats: if p.team == home_team: home_stats_totals['passing_att'] += p.passing_att home_stats_totals['passing_yds'] += p.passing_yds home_stats_totals['passing_cmp'] += p.passing_cmp home_stats_totals['passing_ints'] += p.passing_ints home_stats_totals['passing_tds'] += p.passing_tds home_stats_totals['rushing_tds'] += p.rushing_tds home_stats_totals['rushing_yds'] += p.rushing_yds home_stats_totals['rushing_att'] += p.rushing_att home_stats_totals['fumbles_tot'] += p.fumbles_tot home_stats_totals['fumbles_lost'] += p.fumbles_lost home_stats_totals['puntret_tds'] += p.puntret_tds home_stats_totals['puntret_avg'] += p.puntret_avg home_stats_totals['kicking_xptot'] += p.kicking_xptot home_stats_totals['kicking_xpmade'] += p.kicking_xpmade home_stats_totals['kicking_fga'] += p.kicking_fga home_stats_totals['kicking_fgm'] += p.kicking_fgm home_stats_totals['defense_ffum'] += p.defense_ffum home_stats_totals['defense_int'] += p.defense_int home_stats_totals['defense_sk'] += p.defense_sk for p in away_stats: if p.team == away_team: away_stats_totals['passing_att'] += p.passing_att away_stats_totals['passing_yds'] += p.passing_yds away_stats_totals['passing_cmp'] += p.passing_cmp away_stats_totals['passing_ints'] += p.passing_ints away_stats_totals['passing_tds'] += p.passing_tds away_stats_totals['rushing_tds'] += p.rushing_tds away_stats_totals['rushing_yds'] += p.rushing_yds away_stats_totals['rushing_att'] += p.rushing_att away_stats_totals['fumbles_tot'] += p.fumbles_tot away_stats_totals['fumbles_lost'] += p.fumbles_lost away_stats_totals['puntret_tds'] += p.puntret_tds away_stats_totals['puntret_avg'] += p.puntret_avg away_stats_totals['kicking_xptot'] += p.kicking_xptot away_stats_totals['kicking_xpmade'] += p.kicking_xpmade away_stats_totals['kicking_fga'] += p.kicking_fga away_stats_totals['kicking_fgm'] += p.kicking_fgm away_stats_totals['defense_ffum'] += p.defense_ffum away_stats_totals['defense_int'] += p.defense_int away_stats_totals['defense_sk'] += p.defense_sk for stat, value in stats.iteritems(): total = home_stats_totals.get(stat) + away_stats_totals.get(stat) home_percent = 0 away_percent = 0 if total is not 0: home_percent = home_stats_totals.get(stat) / total away_percent = away_stats_totals.get(stat) / total home_points += home_percent * value away_points += away_percent * value if away_points > home_points: string += "<div>{0} @ {1}</div> <div> Winner: {2}</div>".format(away, home, away) records[home_team_abbr]['loss'] += 1 records[away_team_abbr]['win'] += 1 else: string += "<div>{0} @ {1}</div> <div> Winner: {2}</div>".format(away, home, home) records[away_team_abbr]['loss'] += 1 records[home_team_abbr]['win'] += 1 return string