Skip to content
Irish1986 edited this page Sep 14, 2017 · 33 revisions

Table of Contents

Create a CSV file with all games in the 2015 Regular season

Create a CSV file with all player names and demographics

List all QBs that played against Buffalo

List the top 50 targeted Receivers during 2013 in weeks 1 thru 6

Calculate Third Down Conversion Rate for Week 1 games in 2013

Calculate Number of Sacks for a Team

Calculate Sack Yardage for a Team

Print Winners and Losers per Week

Various Filtering of Drives in a Single Game (Patriots @ Bills)

Basic Graphing using matplotlib

Print out a Team's Average Points For and Points Against in the 2013 Regular Season

Filtering Drives on Possession Time

Filtering Drives on Field Position

Filtering Drives on Game Clock

Find an individual player statistic on a game-by-game or a group of games

Calculate the Fantasy score of all players for a week

Create a CSV file with all games in the 2015 Regular season

import nflgame
import nflgame.sched
import csv

schedule_games = nflgame.sched.games

with open('2015 Schedule.csv', 'wb') as csvfile:
    schedulewriter = csv.writer(csvfile, delimiter=',')
    schedulewriter.writerow(['Home', 'Away', 'Week', 'Year'])
    for key in schedule_games:
        game = schedule_games[key]
        if game['year'] == 2015 and game['season_type'] == 'REG':
            schedulewriter.writerow([game['home'], game['away'], game['week'], game['year']])   

Create a CSV file with all player names and demographics

Credit to @ochawkeye

import nflgame
import csv

players = nflgame.players

with open('All Players2.csv', 'wb') as csvfile:
    playerwriter = csv.writer(csvfile, delimiter=',')
    playerwriter.writerow(['NFLID', 'Height', 'Weight', 'DOB', 'College'])
    for p in players:
        if '-' in players[p].height:
            height = '%s\'%s"' % (players[p].height[0], players[p].height[2:])
        else:
            height = players[p].height
        playerwriter.writerow([
            p,
            height,
            players[p].weight,
            players[p].birthdate,
            players[p].college])

List all QBs that played against Buffalo

This specific example lists all QBs that played against Buffalo in 2013. You can update the team variable to meet your specific needs

import nflgame

opponent_team = 'BUF'

games = nflgame.games_gen(2013, home=opponent_team, away=opponent_team)
players = nflgame.combine_max_stats(games)

for p in players.filter(team__ne=opponent_team, passing_att__ge=1):
    print '%s, %d completions for %d yards and %d touchdowns.' \
          % (p.name, p.passing_cmp, p.passing_yds, p.passing_tds)

List the top 50 targeted Receivers during 2013 in weeks 1 thru 6

import nflgame
games = nflgame.games(2013, week=[1, 2, 3, 4, 5, 6])
players = nflgame.combine(games, plays=True)

for p in players.sort('receiving_tar').limit(50):
    print p, p.receiving_tar

List the top 50 targeted Receivers during current season (alternate)

import nflgame

year, current_week = nflgame.live.current_year_and_week()
weeks = [x for x in range(1, current_week+1)]

games = nflgame.games(year, weeks)
players = nflgame.combine(games, plays=True)

for p in players.sort('receiving_tar').limit(50):
    print p, p.receiving_tar

Calculate Third Down Conversion Rate for Week 1 games in 2013

This is spawned from Issue 36 - https://github.com/BurntSushi/nflgame/issues/36 for more details

import nflgame

year, week, season_type = 2013, 1, 'REG'

def third_down(teamname, play_gen):
    attempts = 0
    conversions = 0
    for p in play_gen.filter(team=teamname, third_down_att=1):
        attempts += 1
        conversions += p.third_down_conv
    percentage = float(conversions)/float(attempts)*100
    return '%s: %s of %s (%.2f%%)' % (
        teamname, conversions, attempts, percentage)

games = nflgame.games(year, week, kind=season_type)
for game in games:
    print third_down(game.home, game.drives.plays())
    print third_down(game.away, game.drives.plays())

Calculate Number of Sacks for a Team

This is spawned from Issue 48 - https://github.com/BurntSushi/nflgame/issues/48

import nflgame

def get_total_sacks_given_up(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 get_total_sacks_earned(s, w, t):
    games = nflgame.games_gen(s, w, t, t)
    plays = nflgame.combine_plays(games)

    sks = 0
    for p in plays.filter(team__ne=t):
        if p.defense_sk > 0:
            sks += 1
    return sks

print get_total_sacks_earned(2013, None, "BAL") 			#Get all sacks earned by Baltimore defense in all of 2013
print get_total_sacks_given_up(2013, None, "BAL") 			#Get all sacks given up by Baltimore offense in all of 2013
print get_total_sacks_earned(2013, 7, "BAL")    			#Get all sacks by Baltimore in week 7 of 2013
print get_total_sacks_earned(2013, [1,2,3,4,5,6,7], "BAL") #Get all sacks by Baltimore in weeks 1 thru 7 of 2013

Calculate Sack Yardage for a Team

This is spawned from Issue 48 - https://github.com/BurntSushi/nflgame/issues/48

import nflgame

def get_total_sack_yardage(s, w, t):
	games = nflgame.games_gen(s, w, t, t)
	plays = nflgame.combine_plays(games)

	skyds = 0
	for p in plays.filter(team=t, defense_sk__gt=0):
		skyds += p.defense_sk_yds
	return skyds

print get_total_sack_yardage(2013, None, "BAL") 			#Get all sack yardage by Baltimore in all of 2013
print get_total_sack_yardage(2013, 7, "BAL")    			#Get all sack yardage by Baltimore in week 7 of 2013
print get_total_sack_yardage(2013, [1,2,3,4,5,6,7], "BAL")  #Get all sack yardage by Baltimore in weeks 1 thru 7 of 2013

Print Winners and Losers per Week

This is spawned from Issue 28 - https://github.com/BurntSushi/nflgame/issues/28

import nflgame
games = nflgame.games(2013, week=[1,2,3,4,5]) #Print for weeks 1-5 of the 2013 season - adjust as needed
for g in games:
	print "{0} Won Over {1} - Week {2}".format(g.winner, g.loser, g.schedule['week'])

Various Filtering of Drives in a Single Game (Patriots @ Bills)

import nflgame

# Utility function to print out some basic info about a drive
def print_drive_info(drive):
	print "Drive {0} - Team {1} - First Downs {2} - Result {3} - Total Yds {4} - Penalty Yds {5} - Play Count {6} - Possession Time {7} ({8} seconds) - From {9} Until {10}".format(drive.drive_num, drive.team, drive.first_downs, drive.result, drive.total_yds, drive.penalty_yds, drive.play_cnt, drive.pos_time, drive.pos_time.total_seconds(), drive.field_start, drive.field_end)	

#Find our game
g = nflgame.one(2013, 1, "BUF", "NE")

print "\nFilter & Print Drives with 3 or more First Downs"
for drive in g.drives.filter(first_downs__ge=3):
	print_drive_info(drive)

print "\nFilter & Print Drives with 5 or more Plays"
for drive in g.drives.filter(play_cnt__ge=5):
	print_drive_info(drive)

print "\nFilter & Print Drives Resulting in a Punt"
for drive in g.drives.filter(result="Punt"):
	print_drive_info(drive)

print "\nFilter & Print Drives with 20 or less Yards"
for drive in g.drives.filter(total_yds__le=20):
	print_drive_info(drive)

print "\nFilter & Print Drives where the Defense has more Penalty Yards than the Offense"
for drive in g.drives.filter(penalty_yds__gt=0):
	print_drive_info(drive)

print "\nFilter & Print Drives where the Offense has more Penalty Yards than the Defense"
for drive in g.drives.filter(penalty_yds__lt=0):
	print_drive_info(drive)

Basic Graphing using matplotlib

It is said that a picture is worth a thousand words. Using the open source matplotlib we can graph the stats from nflgame to give a visual representation.

For this example code to work you will need to install matplotlib and all of the prerequisites such as numpy. Here is the matplotlib home page where you can learn a bit more about the library - http://matplotlib.org/

Once you gotten familiar with the library you can follow these installation instructions - http://matplotlib.org/1.3.1/users/installing.html. Be sure to install the other requirements like numpy and libpng.

Once all has been installed the code below will generate a basic graph showing EJ Manuel's touchdowns thrown in 2013 as shown below. ![EJ Manuel TDs](http://front9technologies.com/EJ Manuel 2013 TDs.png)

You can also see a more advanced usage on the Draftalyzer site here where we plot passing yards and TDs against along with Standard Deviation.

import nflgame
import numpy
import matplotlib.pyplot as plt
from pylab import *

# Find our player
team_to_find = "BUF"
player_to_find = "E.Manuel"

# Create a list to store all of the TDs for our player
list_player_tds = []

# Get all of the games in 2013
games = nflgame.games_gen(2013, 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 into our list (or store 0 on an AttributeError)
	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 matplotlib plot 
plt.clf()

# Create a second list for our x-axis values 
xaxis = []
for temp_week in arr_tds:
	xaxis.append(len(xaxis) + 1)

# Create a blue line plot to show our TDs
p1, = plt.plot(xaxis, arr_tds, 'b', linewidth=2.0)	

# Create a legend for the plot defined above
legend([p1], ["TDs Per Game"])

# Label the ticks of our xaxis using our simple list
plt.xticks(xaxis, xaxis)

# Label the xaxis
plt.xlabel('Games')

# Label the yaxis
plt.ylabel('TDs Per Week by ' + player_to_find)		

# Set the y axis limits to 0 and the maximum TDs in a week plus 1
plt.ylim([0, max(arr_tds) + 1])

# Save our chart to a new PNG file. The higher the dpi value, the larger the image
savefig('EJ Manuel 2013 TDs.png',dpi=72)

Print out the Average Points For and Points Against for a Team in the 2013 Regular season

import nflgame

# We want the games Buffalo played in 2013
team_to_check = 'BUF'

# Create a list to store each score
game_scores_for = []
game_scores_against = []

# Get the games Buffalo played in the 2013 Regular Season
games = nflgame.games_gen(2013, home=team_to_check, away=team_to_check, kind='REG')

# Iterate through the games
for g in games:
	# If Buffalo was home, add the score_home to the points for list and the score_away to the points against list
	if g.home == team_to_check:
		game_scores_for.append(g.score_home)
		game_scores_against.append(g.score_away)
	# If Buffalo was away, add the score_away to the points for list and the score_home to the points against list
	else:
		game_scores_for.append(g.score_away)
		game_scores_against.append(g.score_home)

# Print our the sum of our values divided by the number of values. Cast to a float to get decimal points
print team_to_check, "has averaged", sum(game_scores_for)/float(len(game_scores_for)), "points scored per game in 2013"
print team_to_check, "has averaged", sum(game_scores_against)/float(len(game_scores_against)), "points against per game in 2013"

Filtering Drives on Possession Time

import nflgame

def print_drive_info(drive):
	print "Drive {0} - Team {1} - First Downs {2} - Result {3} - Total Yds {4} - Penalty Yds {5} - Play Count {6} - Possession Time {7} ({8} seconds) - From {9} Until {10}".format(drive.drive_num, drive.team, drive.first_downs, drive.result, drive.total_yds, drive.penalty_yds, drive.play_cnt, drive.pos_time, drive.pos_time.total_seconds(), drive.field_start, drive.field_end)

#Get all games from week 1 of 2013
games = nflgame.games(2013, week=1)
print "Drives Longer than 4:00 during Week 1"
for game in games:
	postime = nflgame.game.PossessionTime('4:00')
	#Filter drives greater than or equal to 4:00
	for drive in game.drives.filter(pos_time__ge=postime):
		print_drive_info(drive)


print "Drives Shorter than 0:30 during Week 1"
for game in games:
	#Filter drives less than or equal to 0:30
	postime = nflgame.game.PossessionTime('0:30')
	for drive in game.drives.filter(pos_time__le=postime):
		print_drive_info(drive)

Filtering Drives on Field Position

import nflgame

def print_drive_info(drive):
	print "Drive {0} - Team {1} - First Downs {2} - Result {3} - Total Yds {4} - Penalty Yds {5} - Play Count {6} - Possession Time {7} ({8} seconds) - From {9} Until {10}".format(drive.drive_num, drive.team, drive.first_downs, drive.result, drive.total_yds, drive.penalty_yds, drive.play_cnt, drive.pos_time, drive.pos_time.total_seconds(), drive.field_start, drive.field_end)

#Get all games from week 1 of 2013
games = nflgame.games(year=2013, week=1)
print "Drives Starting inside Opponent's 30 Yard Line"
for game in games:
	# Make a FieldPosition object using the opponent's 30 yard line
	pos = nflgame.game.FieldPosition(game.away, "{0} 30".format(game.home))
	#Filter drives greater than or equal to 4:00
	for drive in game.drives.filter(field_start__ge=pos):
		print_drive_info(drive)


print "Drives Starting inside Team's 5 Yard Line"
for game in games:
	# Make a FieldPosition object using the team's 5 yard line
	pos = nflgame.game.FieldPosition(game.home, "{0} 5".format(game.home))
	#Filter drives greater than or equal to 4:00
	for drive in game.drives.filter(field_start__le=pos):
		print_drive_info(drive)

Filtering Drives on Game Clock

import nflgame

def print_drive_info(drive):
	print "Drive {0} - Team {1} - First Downs {2} - Result {3} - Total Yds {4} - Penalty Yds {5} - Play Count {6} - Possession Time {7} ({8} seconds) - From {9} Until {10}".format(drive.drive_num, drive.team, drive.first_downs, drive.result, drive.total_yds, drive.penalty_yds, drive.play_cnt, drive.pos_time, drive.pos_time.total_seconds(), drive.field_start, drive.field_end)

#Get all games from week 1 of 2013
games = nflgame.games(year=2013, week=1)
print "Drives Starting After 5 Minutes Left of the 4th Quarter"
for game in games:
	# Make a GameClock object using the 4 quarter and 5 minutes left
	clock = nflgame.game.GameClock(4, '5:00')
	#Filter drives greater than or equal to 4:00
	for drive in game.drives.filter(time_start__ge=clock):
		print_drive_info(drive)


print "Drives Starting Within 1 Minute of the 1st Quarter"
for game in games:
	# Make a GameClock object using the 1 quarter and 14 minutes left
	clock = nflgame.game.GameClock(1, '14:00')
	#Filter drives greater than or equal to 4:00
	for drive in game.drives.filter(time_start__le=clock):
		print_drive_info(drive)

Find an individual player statistic on a game-by-game or a group of games

import nflgame

year = 2014
games = nflgame.games(year, home="PIT", away="PIT")
bigben = nflgame.find('Ben Roethlisberger')[0]
# bigben -> Ben Roethlisberger (QB, PIT)
# bigben.gsis_name -> B.Roethlisberger

for i, game in enumerate(games):
	if game.players.name(bigben.gsis_name):
		stats = game.players.name(bigben.gsis_name).passing_yds
		print 'Game {:2}, Week {:2} - {:4}'.format(
			i+1, game.schedule['week'], stats)

print '-'*25
players = nflgame.combine(games)
print '{:9} Season - {:4}'.format(
	year, players.name(bigben.gsis_name).passing_yds)

Calculate the Fantasy score of all players for a week

A simple script to calculate the fantasy score of all player for a given week. Adjust the scoring as per your league rules and run the code. Very useful for projection vs. actual analysis and other fun stuff.

Credit to @Irish1986

import nflgame

scoring = {
    # Passing
    'passing_yds' : lambda x : x*.04,
    'passing_tds' : lambda x : x*4,
    'passing_twoptm'  : lambda x : x*2,
    # Rushing
    'rushing_yds' : lambda x : x*.1,
    'rushing_tds' : lambda x : x*6,
    'kickret_tds' : lambda x : x*6,
    'rushing_twoptm' : lambda x : x*2,
    # Receiving
    'receiving_tds' : lambda x : x*6,
    'receiving_yds' : lambda x : x*.1,
    'receiving_rec' : lambda x : x*.5,
    'receiving_twoptm' : lambda x : x*2,
    # Kicker
    'kicking_fgm_yds' : lambda x : (5 if x >= 50 else (4 if x >= 40 else 3)),
    'kicking_xpmade' : lambda x : x*1,
    'kicking_xpmissed' : lambda x : x*-1,
    'kicking_fgmissed' : lambda x : x*-1,
    # Various
    'fumbles_lost' : lambda x : x*-2, 
    'passing_ints' : lambda x : x*-2,
}

def score_player(player):
    score = 0
    for stat in player._stats:
        if stat in scoring:
            score += scoring[stat](getattr(player,stat))    
    return score

players = nflgame.combine_game_stats(nflgame.games(2017, 1))
for p in players:
    score = score_player(p)
    print p.name,p.team,score