Beispiel #1
0
def showPlayerStat(player_ID, week_input):
    statJSON = {}
    stat_string_list = STAT_STRING_LIST

    db = nfldb.connect()
    q = nfldb.Query(db)

    q.game(season_year=2012, season_type='Regular', week=week_input)
    q.player(player_id=player_ID)

    # for p in q.sort([('gsis_id', 'asc'), ('time', 'asc')]).as_plays():
    # print p

    for p in q.as_aggregate():

        for index in xrange(len(stat_string_list)):
            key = stat_string_list[index]
            value = eval('p.' + stat_string_list[index])
            statJSON[key] = value
            #print key, value
    #Check for empty week stat due to BYE week
    if len(q.as_aggregate()) == 0:
        for index in xrange(len(stat_string_list)):
            key = stat_string_list[index]
            statJSON[key] = 0
    return statJSON
def analyze_malone():
    db = nfldb.connect()
    q = nfldb.Query(db)
    q.game(season_year__ge=2005).game(season_type='Regular')
    q.player(full_name="Robert Malone")
    all_plays = q.as_plays()

    plays = [{f: l.__getattribute__(f) for f in fields} for l in all_plays]
    punts = [x for x in plays if sum([x.get(n) for n in punt_fields]) > 0]

    # get the yardline out of the yardline object
    for p in punts:
        p['Field Position'] = p.get('yardline')
        p['yardline'] = p.get('yardline')._offset

    df = pd.DataFrame(punts)
    print(df.head())

    df['punting_yds'].plot(kind='hist', bins=42)
    plt.xlabel('Yards In Air')

    plt.suptitle('Punt Distances In Air From LOS    ', ha='right', fontsize='26')
    plt.title('Robert Malone\'s punts', loc='left', fontsize='16')
    plt.yticks([0,5,10,15,20])

    plt.tight_layout()
    plt.axhline(y=0, color='black', linewidth=1.3, alpha=.7)
    plt.text(x=-15, y=-3,
             s='footballstatsaredumb.wordpress.com',
             fontsize=14, color='xkcd:darkgreen', ha='left')
    plt.show()
Beispiel #3
0
    def __init__(self, name, **keyword_params):
        super(KickerStats, self).__init__()

        db = nfldb.connect()

        q = nfldb.Query(db)

        if 'year' in keyword_params:
            q.game(season_year=keyword_params['year'], season_type='Regular')
            if 'week' in keyword_params:
                q.game(week=keyword_params['week'])
        else:
            q.game(season_type='Regular')

        q.player(full_name=name, position='K')

        stats = q.as_aggregate()

        if len(stats) > 0:
            stats = stats[0]

            self.kicking_fga = stats.kicking_fga
            self.kicking_fgm = stats.kicking_fgm
            self.kicking_fgmissed = stats.kicking_fgmissed

            # maybe -- depends how this works. need to see if per kick or total kicks
            self.kicking_fgm_yds = stats.kicking_fgm_yds
            self.kicking_fgmissed_yds = stats.kicking_fgmissed_yds

            self.kicking_xpa = stats.kicking_xpa
            self.kicking_xpmade = stats.kicking_xpmade
            self.kicking_xpmissed = stats.kicking_xpmissed
def getOpponent(team_input, week_input):
	statJSON = {}
	STAT_STRING_OPPONENT = ['passing_yds', 'passing_tds',  'rushing_yds','receiving_yds', 'receiving_tds' ,'kickret_tds', 'fumbles_rec_tds','rushing_tds']	
	stat_string_list = STAT_STRING_OPPONENT
	stat_season_totals =  [0 for x in range(len(stat_string_list))]
	#stat_string_list = ['puntret_tds']	
	db = nfldb.connect()
	q = nfldb.Query(db)
	q.game(season_year=2012, season_type='Regular',  week=week_input, team=team_input)

	#check for bye week all stats = 0
	if len(q.as_games())==0:
		team_home_away = 'bye'
		statJSON['opponent']= 'bye'
		for index in xrange(len(stat_string_list)):
			statJSON[stat_string_list[index]+'_allowed'] = 0		
		return statJSON
	
	for p in q.as_games():				
		if p.away_team == team_input:
			opponent = p.home_team
		else:
			opponent = p.away_team
		statJSON['opponent'] = opponent
		#print "Team: ", team_input, " has Opponent: ", opponent
	
	q.game(season_year=2012, season_type='Regular',  week=week_input, team=opponent)	
	for p in q.as_games():					
		for index in xrange(len(stat_string_list)):
				stat = showStat(stat_string_list[index], opponent, week_input)
				statJSON[stat_string_list[index]+'_allowed'] = stat
				stat_season_totals[index] +=stat	
	
	#print statJSON
	return statJSON
Beispiel #5
0
def plays_for_game(request):
    """
    Return the Play objects as JSON for the given game's gsis_id.
    Expected request parameters:
        `gsisId` - The gsis_id of the game
    """
    gsis_id = request.GET.get("gsisId")

    db = nfldb.connect()
    q = nfldb.Query(db)
    q.game(gsis_id=gsis_id)
    q.sort(('time', 'desc'))

    plays = q.as_plays()
    playsJSON = []
    for p in plays:
        # print "Play time: ", p.time
        play = {
            "description": p.description,
            "down": p.down,
            "offensiveTeam": p.pos_team,
            "points": p.points,
            "scoringTeam": p.scoring_team,
            "time": str(p.time),
            "yardline": str(p.yardline),
            "yardsToGo": p.yards_to_go
        }
        playsJSON.append(play)

    return JsonResponse(playsJSON, safe=False)
def showPlayerStat(player_ID, week_input):
	statJSON={}	
	stat_string_list = STAT_STRING_LIST
	
	db = nfldb.connect()
	q = nfldb.Query(db)
		
	q.game(season_year=2012, season_type='Regular',  week=week_input)	
	q.player(player_id=player_ID)
	
	# for p in q.sort([('gsis_id', 'asc'), ('time', 'asc')]).as_plays():
		# print p	
	
	for p in q.as_aggregate():
		
		for index in xrange(len(stat_string_list)):
			key = stat_string_list[index]
			value = eval('p.'+stat_string_list[index])
			statJSON[key]=value
			#print key, value
	#Check for empty week stat due to BYE week
	if len(q.as_aggregate() )==0:
		for index in xrange(len(stat_string_list)):
			key = stat_string_list[index]			
			statJSON[key]=0	
	return statJSON
Beispiel #7
0
 def playerstats(self, **kwargs):
     player = kwargs['player']
     db = nfldb.connect()
     q = nfldb.Query(db)
     q.game(season_year=kwargs['season'], season_type='Regular')
     if kwargs['targtype'] == "non-redzone":
         pos1 = nfldb.FieldPosition.from_str('OWN 1')
         pos2 = nfldb.FieldPosition.from_str('OPP 21')
     #OPP 20 to OPP 10 yardline
     elif kwargs['targtype'] == 'redzone':
         pos1 = nfldb.FieldPosition.from_str('OPP 20')
         pos2 = nfldb.FieldPosition.from_str('OPP 11')
     #OPP 10 to OPP 6
     elif kwargs['targtype'] == 'goaline1':
         pos1 = nfldb.FieldPosition.from_str('OPP 10')
         pos2 = nfldb.FieldPosition.from_str('OPP 6')
     # OPP 5 to OPP 3
     elif kwargs['targtype'] == 'goaline2':
         pos1 = nfldb.FieldPosition.from_str('OPP 5')
         pos2 = nfldb.FieldPosition.from_str('OPP 3')
     #OPP 2 or OPP 1
     elif kwargs['targtype'] == 'goaline3':
         pos1 = nfldb.FieldPosition.from_str('OPP 2')
         pos2 = nfldb.FieldPosition.from_str('OPP 1')
     
     q.play(yardline__ge=pos1)
     q.play(yardline__le=pos2)
     q.player(full_name= player)
     for pp in q.as_aggregate():
         return pp
def showStatDefense(team_input, week_input):
	statJSON = {}
	#STAT_STRING_LIST_DEFENSE=['defense_sk', 'defense_int', 'defense_frec', 'defense_safe', 'defense_frec_tds', 'defense_int_tds', 'defense_misc_tds', 'kickret_tds']
	stat_string_list = STAT_STRING_LIST_DEFENSE	
	stat_season_totals =  [0 for x in range(len(stat_string_list))]
	#stat_string_list = ['puntret_tds']	
	db = nfldb.connect()
	q = nfldb.Query(db)
	q.game(season_year=2012, season_type='Regular',  week=week_input, team=team_input)
		
	for p in q.as_games():				
		if p.away_team == team_input:
			statJSON['points_allowed']= p.home_score
		else:
			statJSON['points_allowed']= p.away_score
	
	#check for bye week all stats = 0
	if len(q.as_games())==0:
		team_home_away = 'bye'
		for index in xrange(len(stat_string_list)):
			statJSON[stat_string_list[index]] = 0
		return statJSON
	
	for index in xrange(len(stat_string_list)):
			stat = showStat(stat_string_list[index], team_input, week_input)
			statJSON[stat_string_list[index]] = stat
			#stat_season_totals[index] +=stat	
	
	statJSON['defense_touchdowns'] = statJSON['defense_int_tds'] + statJSON['defense_frec_tds'] + statJSON['defense_misc_tds']
	#	for key, index in statJSON.items():	
		#print ("Totals Week: " +str(week_input) + " " + team_input + " " + key+ " "+ str(index) + '\n')	
	return statJSON
Beispiel #9
0
def week_choices(request):
    response_data = week_choices_dict()
    db = nfldb.connect()
    current_week = nfldb.current(db)
    response_data['current_year'] = current_week[1]
    response_data['current_week'] = current_week[2]
    return HttpResponse(json.dumps(response_data), content_type="application/json")
Beispiel #10
0
    def __init__(self, name):
        self.name = name

        # connect to database to get info
        db = nfldb.connect()

        q = nfldb.Query(db)
        q.player(full_name=name)

        # this currently gets the first player returned
        #  so we may need to change in future
        info = q.as_players()
        if len(info) > 0:
            info = info[0]
            # store basic info
            self.position = info.position
            self.uniform_number = info.uniform_number
            self.birthdate = info.birthdate
            self.height = info.height
            self.weight = info.weight
            self.college = info.college
            self.status = info.status
            self.team = info.team
            self.years_pro = info.years_pro
        else:
            self.position = types.Enums.player_pos.QB
            self.uniform_number = 1
            self.birthdate = "00/00/0000"
            self.height = 0
            self.weight = 0
            self.college = "RPI"
            self.status = "Nonexistent"
            self.team = "Free"
            self.years_pro = 0
Beispiel #11
0
    def __init__(self, name, **keyword_params):
        super(WideReceiverTightEndStats, self).__init__()

        db = nfldb.connect()

        q = nfldb.Query(db)

        if 'year' in keyword_params:
            q.game(season_year=keyword_params['year'], season_type='Regular')
            if 'week' in keyword_params:
                q.game(week=keyword_params['week'])
        else:
            q.game(season_type='Regular')

        q.player(full_name=name, position=keyword_params['position'])

        stats = q.as_aggregate()

        if len(stats) > 0:
            stats = stats[0]

            self.fumbles_tot = stats.fumbles_tot
            self.fumbles_lost = stats.fumbles_lost

            self.receiving_tar = stats.receiving_tar
            self.receiving_rec = stats.receiving_rec
            self.receiving_yds = stats.receiving_yds
            self.receiving_tds = stats.receiving_tds
            self.receiving_yac_yds = stats.receiving_yac_yds
Beispiel #12
0
def get_scores(year, end_year, pos):
    scores = []
    results = []
    while (year < end_year):
        print("{}{}{}".format("*" * 10, year, "*" * 10))
        db = nfldb.connect()
        q = nfldb.Query(db)
        q.game(season_year=year, season_type='Regular').player(position=pos)
        results = q.as_aggregate()
        for pp in results:
            s = score(pp)
            pp.score = s
            if (pp.score > 10):
                scores.append([pp.player.full_name, pp.score, year])
        year += 1

    results = sorted(results,
                     key=lambda pp: pp.score)  # Gives better K means results

    analyzeAndDisplayCategories(
        categorizeDown(results, 5, lambda player: player.score))

    analyzeAndDisplayCategories(
        kMeans(results, 5, 25, lambda player: player.score))

    analyzeAndDisplayCategories(
        kMeansVariant(results, 10, 50, lambda player: player.score))
    print(scores)
    return scores
Beispiel #13
0
def makeWinMatrix(players):

    db = nfldb.connect()

    # Get number of players in list
    size = len(players)
    playerInd = {}

    ind = 0

    print '\n index\tname'
    for x in players:
        x = x.split(' (')
        print str(ind) + '\t' + x[0]

        qd = nfldb.Query(db)
        qd.game(season_year=2015, season_type='Regular')
        pp = qd.player(full_name=x[0]).as_aggregate()
        for x in pp:
            playerInd[ind] = x
        ind += 1

    xcord = 0

    allWins = []
    allLoses = []
    while xcord < size - 1:
        winsList = []
        losesList = []
        check = playerInd[xcord]
        loses = 0
        ycord = 0
        while ycord < size - 1:
            losesList.append(0)
            if ycord != xcord:
                against = playerInd[ycord]
                wins, loses = calcWins(check, against, loses)
                winsList.append(wins)
            else:
                winsList.append(0)

            ycord += 1
        losesList[xcord] = loses
        rowWins = numpy.array([winsList])
        rowLoses = numpy.array([losesList])

        allWins.append(rowWins)
        allLoses.append(rowLoses)

        xcord += 1

    matrixWins = numpy.vstack(allWins)
    matrixLoses = numpy.vstack(allLoses)
    print '---------- Wins ----------'
    print(matrixWins)
    print '---------- Loses ----------'
    print(matrixLoses)

    return matrixWins, matrixLoses
Beispiel #14
0
def makeWinMatrix(players):

    db = nfldb.connect()

    # Get number of players in list
    size = len(players)
    playerInd = {}

    ind = 0

    print '\n index\tname'
    for x in players:
        x = x.split(' (')
        print str(ind) + '\t' + x[0]

        qd = nfldb.Query(db)
        qd.game(season_year=2015, season_type='Regular')
        pp = qd.player(full_name=x[0]).as_aggregate()
        for x in pp:
            playerInd[ind] = x
        ind += 1

    xcord = 0

    allWins = []
    allLoses = []
    while xcord < size-1:
        winsList = []
        losesList = []
        check = playerInd[xcord]
        loses = 0
        ycord = 0
        while ycord<size-1:
            losesList.append(0)
            if ycord != xcord:
                against = playerInd[ycord]
                wins, loses = calcWins(check, against, loses)
                winsList.append(wins)
            else:
                winsList.append(0)

            ycord += 1
        losesList[xcord] = loses
        rowWins = numpy.array([winsList])
        rowLoses = numpy.array([losesList])

        allWins.append(rowWins)
        allLoses.append(rowLoses)

        xcord += 1

    matrixWins = numpy.vstack(allWins)
    matrixLoses = numpy.vstack(allLoses)
    print '---------- Wins ----------'
    print(matrixWins)
    print '---------- Loses ----------'
    print(matrixLoses)

    return matrixWins, matrixLoses
Beispiel #15
0
def receiving_yds_player(request, player_id):
    if request.method == "POST":
        return HttpResponse('Cannot POST.')
    if request.method == "GET":
        db = nfldb.connect()
        q = nfldb.Query(db)
        data = {}
        seas_year = '2017'
        player = Player.objects.get(player_id=player_id)
        name = str(player)
        team = player.get_team()
        team_name = player.team.get_team_name()
        position = player.get_position()
        weeks = []
        receivingydperweek = {}

        games = q.game(season_year=seas_year, season_type='Regular',
                       team=team).as_games()
        drives = q.drive(pos_team=team).sort(('start_time', 'asc')).as_drives()

        for i in range(0, len(games)):
            if games[i].finished:
                weeks.append(games[i].week)

        for w in weeks:
            receivingydperweek[w] = []
        weeks.sort(key=int)
        for d in drives:
            receive_yds = 0
            for w in weeks:
                q = nfldb.Query(db).drive(gsis_id=d.gsis_id,
                                          drive_id=d.drive_id)
                q.player(full_name=name)
                q.game(week=w)
                results = q.aggregate(receiving_yds__ge=0).as_aggregate()
                if len(results) == 0:
                    continue
                tfb = results[0]
                receive_yds += tfb.receiving_yds

            for w in weeks:
                if w == d.game.week:
                    receivingydperweek[w] += [receive_yds]

        for w in weeks:
            receivingydperweek[w] = sum(receivingydperweek[w])

        data = {
            'player': player,
            'player_id': player_id,
            'name': name,
            'team': team,
            'team_name': team_name,
            'position': position,
            'weeks': weeks,
            'receiving_per_week': receivingydperweek,
        }
        return render(request, "player_receiving.html", {'data': data})
Beispiel #16
0
    def __init__(self, name, seasonyear):
        self.__name = name
        self.__seasonYear = seasonyear
        __nfldbConnect = nfldb.connect()

        q = nfldb.Query(__nfldbConnect).game(season_year=self.__seasonYear, season_type='Regular')
        for pp in q.as_aggregate():
            print pp.player
        return
Beispiel #17
0
 def games_played(self,player,year):
     db = nfldb.connect()
     q = nfldb.Query(db)
     q.game(season_year=year, season_type='Regular',)
     q.player(full_name=player)
     if q.as_games() != None:
         return len(q.as_games())
     else:
         return 0
Beispiel #18
0
 def __init__(self, name = "Team", short_name = "UNK", year = 2009):
     self.name = name
     self.short_name = short_name
     self.possession = False
     self.year = year
     self.db = nfl.connect()
     self.q = nfl.Query(self.db)
     self.q.player(team=short_name)
     self.roster = self.q.as_aggregate()
     print self.name
Beispiel #19
0
def passblock_player(request, player_id):
    if request.method == "POST":
        return HttpResponse('Cannot POST.')
    if request.method == "GET":
        db = nfldb.connect()
        q = nfldb.Query(db)
        data = {}
        seas_year = '2017'
        player = Player.objects.get(player_id=player_id)
        name = str(player)
        team = player.get_team()
        team_name = player.team.get_team_name()
        position = player.get_position()
        weeks = []
        blkperweek = {}

        games = q.game(season_year=seas_year, season_type='Regular',
                       team=team).as_games()

        for i in range(0, len(games)):
            if games[i].finished:
                weeks.append(games[i].week)

        for w in weeks:
            blkperweek[w] = []
        weeks.sort(key=int)

        for g in games:
            blocks = 0
            q = nfldb.Query(db).play(gsis_id=g.gsis_id)
            plays = q.player(full_name=name).as_plays()
            for p in plays:
                results = p.defense_pass_def
                blocks += results
                # print picks
                # print p

            for w in weeks:
                if w == g.week:
                    blkperweek[w] += [blocks]

        for w in weeks:
            blkperweek[w] = sum(blkperweek[w])

        data = {
            'player': player,
            'player_id': player_id,
            'name': name,
            'team': team,
            'team_name': team_name,
            'position': position,
            'weeks': weeks,
            'blocks_per_week': blkperweek,
        }
        return render(request, "player_blocks.html", {'data': data})
Beispiel #20
0
def module1():

    db = nfldb.connect()
    q = nfldb.Query(db)
    q.game(season_year=2013, season_type='Regular')

    for pp in q.sort('passing_yds').limit(10).as_aggregate():
        print pp.player, pp.passing_yds

    q.player(full_name="Tom Brady").play(passing_tds=1)
    for play in q.as_plays():
        print play
Beispiel #21
0
def get_weeklypts(team, week, year):
    players = []
    db = nfldb.connect()
    q = nfldb.Query(db)
    q.game(season_year=year, season_type='Regular', team=team, week=week )
    for p in q.as_players():
        if p.team == team and p.team != "UNK":  
            pts = get_weeklypoints(year,p.full_name, week)
            if pts != 0:
                players.append((p.full_name,str(p.position),str(p.team), week, pts)) 
                
    return players
Beispiel #22
0
def module1():

	db = nfldb.connect()
	q = nfldb.Query(db)
	q.game(season_year=2013, season_type='Regular')
	
	for pp in q.sort('passing_yds').limit(10).as_aggregate():
		print pp.player, pp.passing_yds
	
	q.player(full_name="Tom Brady").play(passing_tds=1)	
	for play in q.as_plays():
		print play
Beispiel #23
0
    def __init__(self, game_cfg=None):
        self.stub = path.abspath(path.dirname(__file__)) + "/../{0}"
        if game_cfg is None:
            game_cfg = self.stub.format(DEFAULT_FILE_LOCATION)
        super(GameEngine, self).__init__(game_cfg)

        # DB Connection
        self._conn = connect()

        # Game elements
        self.scoring_method = self._config_handler("scoring_method")
        self.fantasy_team = self._config_handler("fantasy_team", conn=self._conn)
Beispiel #24
0
    def query_players_by_year(self, year):
        db = nfldb.connect()
        q = nfldb.Query(db)
        q.game(season_year=year, season_type='Regular')

        # Only retrieving a limited amount to avoid more manual position tagging
        rushers = q.sort('rushing_yds').limit(100).as_aggregate()
        receivers = q.sort('receiving_yds').limit(100).as_aggregate()
        passers = q.sort('passing_yds').limit(35).as_aggregate()

        players = self.aggpps_to_players(rushers + receivers + passers)
        return players
Beispiel #25
0
 def testCheck(self):
     return
     db = nfldb.connect()
     calc = Trade.Calculator(PURE)
     q = nfldb.Query(db)
     q.game(season_year=2009, season_type='Regular')
     rushers = q.sort('rushing_yds').limit(100).as_aggregate()
     receivers = q.sort('receiving_yds').limit(100).as_aggregate()
     passers = q.sort('passing_yds').limit(35).as_aggregate()
     players = Trade.aggpps_to_players(rushers + receivers + passers)
     for rec,yds in calc.sort_position_more(players, 'TE'):
         print "{} {}".format(rec,yds)
Beispiel #26
0
def games_for_week(request):
    """
    Return the Game objects as JSON for the given NFL week.
    Expected request parameters:
        `year` - The year of the games to return
        `weekType` - Either `pre`(season), `reg`(ular season), or
            `post`(season)
        `week` - The number of the week within the context of the given year
            and week type
    """
    year = request.GET.get("year")
    week_type = request.GET.get("weekType")
    week_num = request.GET.get("week")

    db = nfldb.connect()
    q = nfldb.Query(db)

    if week_type == 'post' and week_num in ['4', '5']:
        # Super bowl is either week 4 or 5 based on year
        q.game(season_year=year,
               season_type=WEEK_TYPE_MAP[week_type],
               week=[4, 5])
    else:
        q.game(season_year=year,
               season_type=WEEK_TYPE_MAP[week_type],
               week=week_num)
    q.sort(('start_time', 'asc'))
    games = q.as_games()
    gamesJSON = []
    for g in games:
        game = {
            "gsisId": g.gsis_id,
            "awayTeam": g.away_team,
            "awayScore": g.away_score,
            "homeTeam": g.home_team,
            "homeScore": g.home_score,
            "dayOfWeek": str(g.day_of_week),
            "startYear": g.start_time.year,
            "startMonth": g.start_time.month,
            "startMonthName": g.start_time.strftime("%B"),
            "startDate": g.start_time.day,
            "startHour":
            g.start_time.strftime("%I").lstrip("0").replace(" 0", " "),
            "startMinute": g.start_time.strftime("%M"),
            "startAmPm": g.start_time.strftime("%p"),
            "timeZone": g.start_time.strftime("%Z"),
            "finished": g.finished,
            "isPlaying": g.is_playing
        }
        gamesJSON.append(game)

    return JsonResponse(gamesJSON, safe=False)
Beispiel #27
0
def nfldb(year = 2013):
    import nfldb
    db = nfldb.connect()
    q = nfldb.Query(db)

    q.game(season_year=year, season_type='Regular')
    for pp in q.sort('passing_yds').limit(15).as_aggregate():
        print pp.player, pp.passing_yds, pp.rushing_tds

    print "\n"

    for pp in q.sort('rushing_yds').limit(15).as_aggregate():
        print pp.player, pp.rushing_yds, pp.rushing_tds
Beispiel #28
0
def index(request, year=0, week=0, season_type='Regular'):
    db = nfldb.connect()
    current = nfldb.current(db)
    if year == 0:
        season_type, year, week = nfldb.current(db)
        return redirect('index', year, season_type.name, week)
    q = nfldb.Query(db).game(
        season_year=year,
        season_type=season_type,
        week=week).sort('start_time')
    games = q.as_games()
    return render(request, 'games/index.html',
                  {'games_list': games, 'current': current, 'year': year})
Beispiel #29
0
def player_matrix(name, year, weeks):     
    """
    Make a player matrix (DataFrame).
    Rows = weeks
    Columns = stats

    Step 1: Get stat categories relevant to player over the given time period (Cols)
    Step 2: Query all games in time period (get game objects), select those where the player played
    Step 3: Get player stats game by game, filling in categories/stats in empta data dict
    Step 4: Create #games x #categories dataframe
    """
    db = nfldb.connect()
    q = nfldb.Query(db)
    _labels  = q.player(full_name=name).as_aggregate()[0]
    _cols = list(_labels.fields)
    data = {}
    _index = []

    q.game(season_year=year, season_type='Regular', week=weeks)
    games = q.sort(('week', 'asc')).as_games()
    for i, g in enumerate(games):
        q = nfldb.Query(db).game(gsis_id=g.gsis_id)
        stats = q.player(full_name=name).as_aggregate()[0]

        for category in _cols:
	        if category not  in data:
	            data[category] = [getattr(stats, category, None)]
	        else:
	  	    data[category].append(getattr(stats, category, None))
        _index.append(str(g.season_year)+str(g.week))
    sorted_index = sorted(_index, key = sort_help)
    frame = pd.DataFrame(data=data, index=sorted_index)
     

    """
    Make a unique Fantasy Points Scoring Vector for this player.
    """

    cooper_vector_data = {}

    for k,v in fanduel_point_conversions.iteritems():
        if k in _cols:
            cooper_vector_data[k]=v


    cooper_vector = pd.Series(cooper_vector_data)
    cooper_vector = frame.dot(cooper_vector)
    frame['fantasy_points']=cooper_vector
    return frame
Beispiel #30
0
def get_ptsagainst(team, year):
    db = nfldb.connect()
    q = nfldb.Query(db)
    results = []
    q.game(season_year=year, season_type='Regular', team=team )
    for game in q.as_games():
        if game.finished:
            if game.home_team == team:
                opp = game.away_team
            elif game.away_team == team:
                opp = game.home_team
            players = get_weeklypts(opp,game.week,year)
            for x in players:
                results.append(x)
    return results
Beispiel #31
0
def player_detail(request, player_id):
    db = nfldb.connect()
    player = nfldb.Player.from_id(db, player_id)

    if (player is None):
        raise Http404
    player_games = get_player_stats_by_game(player_id, db)
    player_seasons = get_player_stats_by_season(player_id, db)
    template = select_player_template(player)
    return render(request, template,
                  {
                      'player': player,
                      'player_games': player_games,
                      'player_seasons': player_seasons
                  })
Beispiel #32
0
    def testAggPPToPlayer(self):
        playerDB = Trade.PlayerDB()
        db = nfldb.connect()
        q = nfldb.Query(db)
        q.game(gsis_id='2009091000')

        player1 = q.sort('passing_yds').limit(1).as_aggregate()[0]
        self.assertEqual(playerDB.aggpp_to_player(player1), self.test_player1)

        player2 = q.sort('rushing_yds').limit(1).as_aggregate()[0]
        self.assertEqual(playerDB.aggpp_to_player(player2), self.test_player2)
        
        player_list = [player1, player2]
        self.assertEqual(playerDB.aggpps_to_players(player_list), 
                        [self.test_player1, self.test_player2])
Beispiel #33
0
def main():
    global db, conf

    p = argparse.ArgumentParser(description='Run the NFLfan web interface.')
    p.add_argument('--config',
                   metavar='DIR',
                   default='',
                   help='Configuration directory.')
    p.add_argument('--debug',
                   action='store_true',
                   help='Enable Bottle\'s debug mode.')
    p.add_argument('--reload',
                   action='store_true',
                   help='Enable Bottle\'s reloading functionality.')
    p.add_argument('--port', type=int, default=8080)
    p.add_argument('--host', default='localhost')
    p.add_argument('--server',
                   default='wsgiref',
                   help='The web server to use. You only need to change this '
                   'if you\'re running a production server.')
    p.add_argument('--available-servers',
                   action='store_true',
                   help='Shows list of available web server names and quits.')
    args = p.parse_args()

    if args.available_servers:
        for name in sorted(bottle.server_names):
            try:
                __import__(name)
                print(name)
            except:
                pass
        sys.exit(0)

    bottle.TEMPLATE_PATH.insert(0, path.join(web_path, 'tpl'))
    db = nfldb.connect()
    conf = nflfan.load_config(providers=nflfan.builtin_providers,
                              file_path=args.config)

    builtins['db'] = db
    builtins['conf'] = conf

    bottle.install(exec_time)
    bottle.run(server=args.server,
               host=args.host,
               port=args.port,
               debug=args.debug,
               reloader=args.reload)
Beispiel #34
0
def showStat(stat_input, team_input, week_input):
    db = nfldb.connect()
    q = nfldb.Query(db)
    q.game(season_year=2012, season_type='Regular', week=week_input)

    query_string = stat_input + '__ne'
    query_stat = {}
    query_stat[query_string] = 0
    query_stat['team'] = team_input
    q.play(**query_stat)
    totals = 0
    for pp in q.as_aggregate():
        totals += eval('pp.' + stat_input)
        #print pp.player, eval('pp.'+stat_input)
    #print ("Totals Week: " +str(week_input) + " " + team_input + " " + stat_input+ " "+ str(totals) + '\n')
    return totals
def main(season_year):
    db = nfldb.connect()

    q = nfldb.Query(db).game(season_year=season_year, season_type='Postseason')

    team_file = 'playoff_' + str(season_year+1) + '_team_master.json'
    with open(team_file) as f:    
        teams = json.load(f)

    point_file = 'playoff_' + str(season_year+1) + '_point_key.json'
    with open(point_file) as f:    
        point_key = json.load(f)

    add_points_to_teams(db, teams, point_key, write_time=False)

    write_json(teams, write_dir='teams_'+str(season_year+1), write_time=False)
Beispiel #36
0
def game_detail(request, gsid):
    db = nfldb.connect()
    q = nfldb.Query(db).game(gsis_id=gsid)
    games = q.as_games()
    if (len(games) != 1):
        raise Http404
    game = games[0]
    year = game.season_year
    week = game.week
    season_type = game.season_type
    games = nfldb.Query(db).game(
        season_year=year,
        season_type=season_type,
        week=week).sort('start_time').as_games()
    q.player(team=game.away_team)
    away_pass = q.aggregate(passing_att__gt=0).sort(
        'passing_yds').as_aggregate()
    home_pass = nfldb.Query(db).game(
        gsis_id=gsid).player(
        team=game.home_team).aggregate(
        passing_att__gt=0).sort('passing_yds').as_aggregate()
    home_rec = nfldb.Query(db).game(
        gsis_id=gsid).player(
        team=game.home_team).aggregate(
        receiving_rec__gt=0).sort('receiving_yds').as_aggregate()
    away_rec = nfldb.Query(db).game(
        gsis_id=gsid).player(
        team=game.away_team).aggregate(
        receiving_rec__gt=0).sort('receiving_yds').as_aggregate()
    away_run = nfldb.Query(db).game(
        gsis_id=gsid).player(
        team=game.away_team).aggregate(
        rushing_att__gt=0).sort('rushing_yds').as_aggregate()
    home_run = nfldb.Query(db).game(
        gsis_id=gsid).player(
        team=game.home_team).aggregate(
        rushing_att__gt=0).sort('rushing_yds').as_aggregate()
    return render(request, 'games/detail.html',
                  {'game': game,
                   'away_run': away_run,
                   'home_run': home_run,
                   'away_pass': away_pass,
                   'home_pass': home_pass,
                   'home_rec': home_rec,
                   'away_rec': away_rec,
                   'games': games,
                   })
def showStat(stat_input, team_input, week_input):
	db = nfldb.connect()
	q = nfldb.Query(db)
	q.game(season_year=2012, season_type='Regular',  week=week_input)
	
	
	query_string = stat_input + '__ne'
	query_stat = {}
	query_stat[query_string] = 0;
	query_stat['team'] = team_input
	q.play( **query_stat)
	totals = 0
	for pp in q.as_aggregate():
		totals+= eval('pp.' + stat_input)
		#print pp.player, eval('pp.'+stat_input)
	#print ("Totals Week: " +str(week_input) + " " + team_input + " " + stat_input+ " "+ str(totals) + '\n')
	return totals
Beispiel #38
0
def get_fantasypoints(year, player):
    db = nfldb.connect()
    q = nfldb.Query(db)
    x = nfldb.Query(db)
    q.game(season_year=year, season_type='Regular')
    q.player(full_name=player)
    results = []
    for p in q.as_players():
        team = p.team
    for game in q.as_games():
        if game.home_team == team:
            opp =  game.away_team
        if game.away_team == team:
            opp = game.home_team
        week = game.week
        results.append((player, week, opp, get_weeklypoints(year,player,week)))
    return results
Beispiel #39
0
def get_weeklypoints(year, player, week):
    db = nfldb.connect()
    x = nfldb.Query(db)
    x.game(season_year=year, week=week, season_type='Regular')
    x.player(full_name=player)
    pts = 0
    for game in x.as_aggregate():
        if game.fumbles_lost:
            pts = pts - 1
        if game.puntret_tds:
            pts = pts + 6
        if game.fumbles_rec_tds:
            pts = pts + 6
        if game.rushing_att:
            if game.rushing_yds:
                pts = pts + (game.rushing_yds * .1)
                if game.rushing_yds > 100:
                    pts = pts + 3
            if game.rushing_tds:
                pts = pts + (game.rushing_tds * 6)
            if game.rushing_twoptm:
                pts = pts + (game.rushing_twoptm * 2)
        if game.passing_att:
            if game.passing_yds:
                pts = pts + (game.passing_yds * .04)
                if game.passing_yds > 300:
                    pts = pts + 3
            if game.passing_tds:
                pts = pts + (game.passing_tds * 4)
            if game.passing_int:
                pts = pts - 1
            if game.passing_twoptm:
                pts = pts + (game.passing_twoptm * 2)
        if game.receiving_tar:
            if game.receiving_yds:
                pts = pts + (game.receiving_yds * .1)
                if game.receiving_yds > 100:
                    pts = pts + 3
            if game.receiving_rec:
                pts = pts + game.receiving_rec
            if game.receiving_tds:
                pts = pts + (6 * game.receiving_tds)
            if game.receiving_twoptm:
                pts = pts + (2 * game.receiving_twoptm)
    return pts
    def __init__(self):
        self.db = nfl.connect()
        self.q = nfl.Query(self.db)
        self.conn = psycopg2.connect(database="nfldb", user="******", password="******", host="127.0.0.1", port="5432")
        c = self.conn.cursor()
        c.execute("""
            SELECT team_id
            FROM team
        """)
        teams = c.fetchall()
        for team in teams:
            #self.field_goal_chance(team[0], db, q)
        self.conn.close()

    def field_goal_chance(self, team_name): 
        self.q.player(team=team_name)
        roster = self.q.as_aggregate()
        attempts = 0
        made = 0
        for stats in roster:
            attempts += stats.kicking_fga
            made += stats.kicking_fgm
        chance = ( float(made) / float(attempts) ) * 1000
        c = self.conn.cursor()
        c.execute("""
            INSERT INTO team_stats (team_name, stat_key, stat_value)
            VALUES ( %s, %s, %d ) """ % ( team_name, 'field_goal_chance', chance )
        )

   
    def create_table(self):
        print "Open DB"
        c = conn.cursor()
        c.execute("""
            CREATE TABLE team_stats
            ( stat_id    INT     PRIMARY KEY     NOT NULL,
              team_name  VARCHAR(5)              NOT NULL, 
              stat_key   VARCHAR(255)            NOT NULL,
              stat_value INT                     NOT NULL
            );
        """)
        print "Table Created"

        conn.commit()
        conn.close()
Beispiel #41
0
    def get_best_name(self, n):
        db = nfldb.connect()

        toMatch = n.encode('ascii', 'ignore').lower()

        top = nfldb.player_search(db, n, limit=10)
        matches = list()

        for player, dist in top:
            if player.position is not types.Enums.player_pos.UNK:
                if player.first_name.lower(
                ) in toMatch and player.last_name.lower() in toMatch:
                    matches.append(player.full_name)

        if len(matches) > 0:
            return matches[0]

        return "PLAYER_NOT_FOUND"
def save_punt_data():
    print('Getting punt data from NFLDB')
    db = nfldb.connect()
    q = nfldb.Query(db)
    q.game(season_year__ge=2005).game(season_type='Regular')

    all_plays = q.sort('gsis_id').as_plays()
    plays = [{f: l.__getattribute__(f) for f in fields} for l in all_plays]
    punts = [x for x in plays if sum([x.get(n) for n in punt_fields]) > 0]

    # get the yardline out of the yardline object
    for p in punts:
        p['Field Position'] = p.get('yardline')
        p['yardline'] = p.get('yardline')._offset

    print('Saving punt data to CSV')
    df = pd.DataFrame(punts)
    df.to_csv(filename)
Beispiel #43
0
def main(season_year):
    db = nfldb.connect()

    q = nfldb.Query(db).game(season_year=season_year, season_type='Postseason')

    team_file = 'playoff_' + str(season_year + 1) + '_team_master.json'
    with open(team_file) as f:
        teams = json.load(f)

    point_file = 'playoff_' + str(season_year + 1) + '_point_key.json'
    with open(point_file) as f:
        point_key = json.load(f)

    add_points_to_teams(db, teams, point_key, write_time=False)

    write_json(teams,
               write_dir='teams_' + str(season_year + 1),
               write_time=False)
Beispiel #44
0
def getOpponent(team_input, week_input):
    statJSON = {}
    STAT_STRING_OPPONENT = [
        'passing_yds', 'passing_tds', 'rushing_yds', 'receiving_yds',
        'receiving_tds', 'kickret_tds', 'fumbles_rec_tds', 'rushing_tds'
    ]
    stat_string_list = STAT_STRING_OPPONENT
    stat_season_totals = [0 for x in range(len(stat_string_list))]
    #stat_string_list = ['puntret_tds']
    db = nfldb.connect()
    q = nfldb.Query(db)
    q.game(season_year=2012,
           season_type='Regular',
           week=week_input,
           team=team_input)

    #check for bye week all stats = 0
    if len(q.as_games()) == 0:
        team_home_away = 'bye'
        statJSON['opponent'] = 'bye'
        for index in xrange(len(stat_string_list)):
            statJSON[stat_string_list[index] + '_allowed'] = 0
        return statJSON

    for p in q.as_games():
        if p.away_team == team_input:
            opponent = p.home_team
        else:
            opponent = p.away_team
        statJSON['opponent'] = opponent
        #print "Team: ", team_input, " has Opponent: ", opponent

    q.game(season_year=2012,
           season_type='Regular',
           week=week_input,
           team=opponent)
    for p in q.as_games():
        for index in xrange(len(stat_string_list)):
            stat = showStat(stat_string_list[index], opponent, week_input)
            statJSON[stat_string_list[index] + '_allowed'] = stat
            stat_season_totals[index] += stat

    #print statJSON
    return statJSON
Beispiel #45
0
def getWR():
    print "\n\n-------------------------- TOP WRs --------------------------"
    receivers = {}

    db = nfldb.connect()
    q = nfldb.Query(db)

    q.game(season_year=2015, season_type='Regular')

    for pp in q.sort('receiving_yds').limit(50).as_aggregate():
        if str(pp.player) not in receivers and str(pp.player)[-3:-1] == 'WR':
            receivers[str(pp.player)] = calcFantasyScorePositional(pp)

    # for player in receivers:
    #     print player, receivers.get(player)

    receivers = getTop25(receivers)
    print len(receivers)
    return receivers
Beispiel #46
0
def getWR():
    print "\n\n-------------------------- TOP WRs --------------------------"
    receivers = {}

    db = nfldb.connect()
    q = nfldb.Query(db)

    q.game(season_year=2015, season_type='Regular')

    for pp in q.sort('receiving_yds').limit(50).as_aggregate():
        if str(pp.player) not in receivers and str(pp.player)[-3:-1] == 'WR':
            receivers[str(pp.player)] = calcFantasyScorePositional(pp)

    # for player in receivers:
    #     print player, receivers.get(player)

    receivers = getTop25(receivers)
    print len(receivers)
    return receivers
Beispiel #47
0
def getRB():
    print "\n\n-------------------------- TOP RBs --------------------------"
    runningbacks = {}

    db = nfldb.connect()
    q = nfldb.Query(db)

    q.game(season_year=2015, season_type='Regular')

    for pp in q.sort('rushing_yds').limit(50).as_aggregate():
        if str(pp.player) not in runningbacks and str(pp.player)[-3:-1]== 'RB':
            runningbacks[str(pp.player)] = calcFantasyScorePositional(pp)

    # for player in runningbacks:
    #     print player, runningbacks.get(player)

    runningbacks = getTop25(runningbacks)
    print len(runningbacks)

    return runningbacks
Beispiel #48
0
def search_player(request):
    if request.method == 'POST':
        form = SearchForm(request.POST)
        if form.is_valid():
            db = nfldb.connect()
            s_position = form.cleaned_data['position']
            s_name = form.cleaned_data['full_name']
            s_team = form.cleaned_data['team']
            player = None
            if s_team == 'None' and s_position == 'None':
                players = Player.objects.filter(full_name__contains=s_name)
                player, s_score = nfldb.player_search(db, s_name)
                #print 'Similarity score: %d, Player: %s' % (s_score, players)
            elif s_name == '' and s_position == 'None':
                players = Player.objects.filter(team=s_team)
            elif s_team == 'None' and s_name == '':
                players = Player.objects.filter(position=s_position)
            elif s_team == 'None':
                players = Player.objects.filter(position=s_position,
                                                full_name__contains=s_name)
                player, s_score = nfldb.player_search(db, s_name)
            else:
                players = Player.objects.filter(team=s_team,
                                                position=s_position,
                                                full_name__contains=s_name)
                player, s_score = nfldb.player_search(db, s_name)
            if len(players) == 1:
                link_id = player.player_id
                link_s = '/players/'
                link = link_s + link_id
                return HttpResponseRedirect(link)

            return render(request, "search_player.html", {
                'form': form,
                'players': players,
                'player': player
            })

    else:
        form = SearchForm()
    return render(request, "search_player.html", {'form': form})
Beispiel #49
0
def getTE():
    print "\n\n-------------------------- TOP TEs --------------------------"

    tightends = {}

    db = nfldb.connect()
    q = nfldb.Query(db)

    q.game(season_year=2015, season_type='Regular')

    for pp in q.sort('receiving_yds').limit(130).as_aggregate():
        if str(pp.player) not in tightends and str(pp.player)[-3:-1] == 'TE':
            tightends[str(pp.player)] = calcFantasyScorePositional(pp)

    # for player in tightends:
    #     print player, tightends.get(player)

    tightends = getTop25(tightends)
    print len(tightends)

    return tightends
Beispiel #50
0
def getQB():
    print "\n\n-------------------------- TOP QBs --------------------------"

    quarterbacks = {}

    db = nfldb.connect()
    q = nfldb.Query(db)

    q.game(season_year=2015, season_type='Regular')

    for pp in q.sort('passing_yds').limit(50).as_aggregate():
        if str(pp.player) not in quarterbacks and str(pp.player)[-3:-1] == 'QB':
            quarterbacks[str(pp.player)] = calcFantasyScorePositional(pp)

    # for player in quarterbacks:
    #     print player, quarterbacks.get(player)

    quarterbacks = getTop25(quarterbacks)
    print len(quarterbacks)

    return quarterbacks
Beispiel #51
0
def getTE():
    print "\n\n-------------------------- TOP TEs --------------------------"

    tightends = {}

    db = nfldb.connect()
    q = nfldb.Query(db)

    q.game(season_year=2015, season_type='Regular')

    for pp in q.sort('receiving_yds').limit(130).as_aggregate():
        if str(pp.player) not in tightends and str(pp.player)[-3:-1] == 'TE':
            tightends[str(pp.player)] = calcFantasyScorePositional(pp)

    # for player in tightends:
    #     print player, tightends.get(player)

    tightends = getTop25(tightends)
    print len(tightends)

    return tightends
Beispiel #52
0
def main():
    global db, conf

    p = argparse.ArgumentParser(
        description='Run the NFLfan web interface.')
    p.add_argument('--config', metavar='DIR', default='',
                   help='Configuration directory.')
    p.add_argument('--debug', action='store_true',
                   help='Enable Bottle\'s debug mode.')
    p.add_argument('--reload', action='store_true',
                   help='Enable Bottle\'s reloading functionality.')
    p.add_argument('--port', type=int, default=8080)
    p.add_argument('--host', default='localhost')
    p.add_argument('--server', default='wsgiref',
                   help='The web server to use. You only need to change this '
                        'if you\'re running a production server.')
    p.add_argument('--available-servers', action='store_true',
                   help='Shows list of available web server names and quits.')
    args = p.parse_args()

    if args.available_servers:
        for name in sorted(bottle.server_names):
            try:
                __import__(name)
                print(name)
            except:
                pass
        sys.exit(0)

    bottle.TEMPLATE_PATH.insert(0, path.join(web_path, 'tpl'))
    db = nfldb.connect()
    conf = nflfan.load_config(providers=nflfan.builtin_providers,
                              file_path=args.config)

    builtins['db'] = db
    builtins['conf'] = conf

    bottle.install(exec_time)
    bottle.run(server=args.server, host=args.host, port=args.port,
               debug=args.debug, reloader=args.reload)
Beispiel #53
0
def plyrStatsPull(adpPlyrId, minAdpPlayer, pos, year):
    attrib = {}
    score = {}

    db = nfldb.connect()

    player, _ = nfldb.player_search(db, minAdpPlayer, position=pos)

    q = nfldb.Query(db)
    q.player(player_id=player.player_id)
    q.game(season_year=year, season_type='Regular')
    for pp in q.as_aggregate():
        score['passYds'] = pp.passing_yds
        score['passTd'] = pp.passing_tds
        score['passInt'] = pp.passing_int
        score['pass2pt'] = pp.passing_twoptm
        score['rushYds'] = pp.rushing_yds
        score['rushTd'] = pp.rushing_tds
        score['rush2pt'] = pp.rushing_twoptm
        score['recYds'] = pp.receiving_yds
        score['recTd'] = pp.receiving_tds
        score['rec2pt'] = pp.receiving_twoptm
        score['recRec'] = pp.receiving_rec
        score['kRetTd'] = pp.kickret_tds
        score['pRetTd'] = pp.puntret_tds
        score['fumRecTd'] = pp.fumbles_rec_tds
        score['fumLost'] = pp.fumbles_lost
        attrib['pos'] = pos
        attrib['team'] = player.team
        attrib['playerName'] = minAdpPlayer
        plyrIdx = adpPlyrId

    df1 = pd.DataFrame(score, index=[plyrIdx])
    df1 = df1[[
        'passTd', 'passYds', 'passInt', 'pass2pt', 'rushTd', 'rushYds',
        'rush2pt', 'recTd', 'recYds', 'rec2pt', 'recRec', 'kRetTd', 'pRetTd',
        'fumRecTd', 'fumLost'
    ]]
    return df1
Beispiel #54
0
    def nfldb_playerquery(self, msg, matches):
        args = matches.group(1)

        parser = argparse.ArgumentParser(description='Query the nfldb for stats', prog="!nfl playerquery")
        parser.add_argument('-w','--week', dest='week', metavar="WEEK", type=int, help="Week to query")
        parser.add_argument('-y','--year', dest='year', metavar="YEAR", type=int, default=2014, help="Year to query")
        parser.add_argument('-p','--position', dest='position', metavar="POSITION", help="Position to query")
        parser.add_argument('-s','--stat', dest='stat', metavar="STAT", help="Stat to query")
        parser.add_argument('-c','--count', dest='count', metavar="COUNT", type=int, default=5, help="How many results to return (Max: 20)")
        parser.add_argument('-t','--team', dest='team', metavar="TEAM", help="Team to query, use short name i.e. NE")

        pargs = parser.parse_args(args.split())

        print(pargs)

        if pargs.position == None and pargs.stat == None:
            return "Either position, stat, or both must be specified"

        db = nfldb.connect()
        q = nfldb.Query(db)

        q.game(season_year=pargs.year)


        if pargs.position:
            q.player(position=pargs.position)

        if pargs.team:
            q.game(team=pargs.team)

        if pargs.stat:
            q.sort(pargs.stat)

        text = "Results:\n"
        for pp in q.limit(pargs.count).as_aggregate():
            text += "{}: {}\n".format(pp.player, getattr(pp, pargs.stat))

        return text
Beispiel #55
0
    def doit():
        log('-' * 79)
        log('STARTING NFLDB UPDATE AT %s' % now())

        log('Connecting to nfldb... ', end='')
        db = nfldb.connect()
        log('done.')

        # We always insert dates and times as UTC.
        log('Setting timezone to UTC... ', end='')
        nfldb.set_timezone(db, 'UTC')
        log('done.')

        if update_turnovers:
            update_game_turnovers(db, update_turnovers)
        elif update_schedules:
            update_game_schedules(db)
        elif simulate is not None:
            done = update_simulate(db)
            if done:
                log('Simulation complete.')
                return True
        else:
            with nfldb.Tx(db) as cursor:
                # Update players first. This is important because if an unknown
                # player is discovered in the game data, the player will be
                # upserted. We'd like to avoid that because it's slow.
                update_players(cursor, player_interval)

            # Now update games.
            update_games(db, batch_size=batch_size)

        log('Closing database connection... ', end='')
        db.close()
        log('done.')

        log('FINISHED NFLDB UPDATE AT %s' % now())
        log('-' * 79)
Beispiel #56
0
def five_qb_list(request):
    if request.method == "POST":
        return HttpResponse('Cannot POST.')
    if request.method == "GET":
        qbs = {}
        qbs['passing'] = []
        db = nfldb.connect()
        q = nfldb.Query(db)
        q.game(season_year=2017, season_type='Regular')
        for g in q.sort('passing_yds').limit(5).as_aggregate():
            qbs['passing'] += [{
                'id': g.player.player_id,
                'name': g.player.full_name,
                'yds': g.passing_yds,
            }]
            # print(g)
        # qbs = serializers.serialize(qbs)
        # return JsonResponse(qbs)
        # return HttpResponse(players, content_type="application/json")
        return render(request, "top.html", {'pass_list': qbs['passing']})

    else:
        return HttpResponse("404")
Beispiel #57
0
    def __init__(self, name, **keyword_params):
        super(QuarterbackStats, self).__init__()

        db = nfldb.connect()

        q = nfldb.Query(db)

        #case for carrer or yearly stats
        if 'year' in keyword_params:
            q.game(season_year=keyword_params['year'], season_type='Regular')
            if 'week' in keyword_params:
                q.game(week=keyword_params['week'])
        else:
            q.game(season_type='Regular')

        q.player(full_name=name, position='QB')

        stats = q.as_aggregate()

        if len(stats) > 0:
            stats = stats[0]
            self.passing_att = stats.passing_att
            self.passing_cmp = stats.passing_cmp
            self.passing_incmp = stats.passing_incmp
            self.passing_yds = stats.passing_yds
            self.passing_incmp_air_yds = stats.passing_incmp_air_yds
            self.passing_cmp_air_yds = stats.passing_cmp_air_yds
            self.passing_tds = stats.passing_tds
            self.passing_int = stats.passing_int
            self.passing_sk = stats.passing_sk

            self.rushing_att = stats.rushing_att
            self.rushing_yds = stats.rushing_yds
            self.rushing_tds = stats.rushing_tds

            self.fumbles_tot = stats.fumbles_tot
            self.fumbles_lost = stats.fumbles_lost
Beispiel #58
0
def showStatDefense(team_input, week_input):
    statJSON = {}
    #STAT_STRING_LIST_DEFENSE=['defense_sk', 'defense_int', 'defense_frec', 'defense_safe', 'defense_frec_tds', 'defense_int_tds', 'defense_misc_tds', 'kickret_tds']
    stat_string_list = STAT_STRING_LIST_DEFENSE
    stat_season_totals = [0 for x in range(len(stat_string_list))]
    #stat_string_list = ['puntret_tds']
    db = nfldb.connect()
    q = nfldb.Query(db)
    q.game(season_year=2012,
           season_type='Regular',
           week=week_input,
           team=team_input)

    for p in q.as_games():
        if p.away_team == team_input:
            statJSON['points_allowed'] = p.home_score
        else:
            statJSON['points_allowed'] = p.away_score

    #check for bye week all stats = 0
    if len(q.as_games()) == 0:
        team_home_away = 'bye'
        for index in xrange(len(stat_string_list)):
            statJSON[stat_string_list[index]] = 0
        return statJSON

    for index in xrange(len(stat_string_list)):
        stat = showStat(stat_string_list[index], team_input, week_input)
        statJSON[stat_string_list[index]] = stat
        #stat_season_totals[index] +=stat

    statJSON['defense_touchdowns'] = statJSON['defense_int_tds'] + statJSON[
        'defense_frec_tds'] + statJSON['defense_misc_tds']
    #	for key, index in statJSON.items():
    #print ("Totals Week: " +str(week_input) + " " + team_input + " " + key+ " "+ str(index) + '\n')
    return statJSON