コード例 #1
0
    def game_result_stats(self, games):
        """
        Generates stats for the result for each game if known, converting it into terms of a home win/loss,
        tie or unknown result (i.e game hasn't been played)
        :param games:
        :return:
        """
        import nflgame

        header = ['result']
        data = []
        data.append(header)

        print 'Generating game result stats'

        for game in games:
            # for convenience
            year, week = game['year'], game['week']
            home, away = game['home'], game['away']

            result_dictionary = {home: 'win', home + '/' + away: 'tie', away: 'loss'}

            try:
                winner = nflgame.one(year, week, home, away).winner
                result = result_dictionary[winner]
            except (AttributeError, KeyError):
                result = 'UNK'

            game['result'] = result

            row = [game[h] for h in header]
            data.append(row)

        return data
コード例 #2
0
ファイル: Player.py プロジェクト: indioenviejo/nfldfs
    def getPassingTDs(self,season,week):
        
        #Value that will be returned from the function.
        passTDs = 0
        
        # Get statistics for the current game
        game = nflgame.one(season, week, self.team, self.team)
        
        # Bye Week ? If yes, get out of the function
        
        if game is None:
            return passTDs

        # Get all the players with the name
        # Sometimes you may have multiple players 
        # with the same name
        currentPlayers = game.players
        
        # Iterate through all the players with that name
        for p in currentPlayers:
            # Make sure the position, player name and team name matches 
            # with the current player's and that the stats dictionary has 
            # the passing_tds key 
            if p.player is not None and p.player.gsis_id==self.gsis_id and "passing_tds" in p.stats:
                if "passing_tds" in p.stats:
                    passTDs = p.stats["passing_tds"]
        return passTDs
コード例 #3
0
def main(home, away, year, week, reg_post, output_gdb, output_fc):
    print('Create drive feature class.')
    create_drive_feature_class(output_gdb, output_fc)

    print('Getting game data.')
    game = nflgame.one(year, week, home, away, reg_post)

    print('Getting drive data.')
    drives = get_game_drives(game)
    drive_count = get_num_drives(drives)
コード例 #4
0
def main(home, away, year, week, reg_post, output_gdb, output_fc):
    print('Create drive feature class.')
    create_drive_feature_class(output_gdb, output_fc)

    print('Getting game data.')
    game = nflgame.one(year, week, home, away, reg_post)

    print('Getting drive data.')
    drives = get_game_drives(game)
    drive_count = get_num_drives(drives)
コード例 #5
0
ファイル: nfl.py プロジェクト: knubie/nfl-bot
def score(bot, trigger):
  teams = re.match(r"(\w+) @ (\w+)", trigger.group(2))
  away, home = teams.group(1, 2)
  year, week = nflgame.live.current_year_and_week()
  away = away.upper()
  home = home.upper()
  game = nflgame.one(year, week, home, away, kind='REG', started=True)
  if game:
    bot.say(game.nice_score())
  else:
    bot.say('No games found.')
コード例 #6
0
ファイル: nfl.py プロジェクト: knubie/nfl-bot
 def say_play():
   global last_play
   game = nflgame.one(year, week, home, away, started=True)
   current_play = list(reversed(list(game.drives.plays().sort("gameclock", descending=True))))[0].__str__()
   if current_play != last_play:
     last_play = current_play
     # https://cdn.secure.espn.go.com/combiner/i?img=/i/teamlogos/nfl/500/scoreboard/PIT.png&w=56&h=56
     formatted = re.sub("\((\w+), ", r"http://i.nflcdn.com/static/site/6.0/img/teams/\1/\1_logo-20x20.gif **", last_play)
     formatted = formatted.replace(")", "** -", 1)
     formatted = re.sub("\((\d{1,2}:\d{1,2})\)", r"*\1* - ", formatted)
     bot.say(formatted)
コード例 #7
0
ファイル: Player.py プロジェクト: indioenviejo/nfldfs
 def getHomeFldAdv(self,season,week):
     # Get statistics for the current game
     game = nflgame.one(season, week, self.team, self.team)
     
     if game ==None:
         return "BYE"
     
     if game.away == self.team:
         return "AWY"
     elif game.home == self.team:
         return "HME"
コード例 #8
0
def printGames(week, gameResults):
    for resultgame in gameResults:
        awayScore = ''
        homeScore = ''
        gameWithScore = nflgame.one(year=2018,
                                    week=week,
                                    home=str(resultgame['home']),
                                    away=str(resultgame['away']))
        if gameWithScore is not None:
            awayScore = str(gameWithScore.score_away)
            homeScore = str(gameWithScore.score_home)
        print '{\"eid\": \"' + str(resultgame['eid']) + '\", \"week\": \"' + str(resultgame['week']) + '\", \"homeTeam\": \"' + str(resultgame['home']) + '\", \"homeScore\": \"' + homeScore + \
              '\", \"awayTeam\": \"' + str(resultgame['away']) + '\", \"awayScore\": \"' + awayScore + '\"}'
    exit()
コード例 #9
0
ファイル: DST.py プロジェクト: indioenviejo/nfldfs
    def getPointsGivenUp(self,s, w):
        game = nflgame.one(s,w,self.team, self.team)
        ptsGVU = 0
        
        # Bye Week ? If yes, get out of the function
        if game is None:
            return ptsGVU    
        
    
        if game.away == self.team:
            ptsGVU = game.score_home
        elif game.home == self.team:
            ptsGVU = game.score_away

        return ptsGVU
コード例 #10
0
 def update(self):
     game = nflgame.one(2017, week=17, home=self.home, away=self.away)
     if game is None:
         home_score = 0
         away_score = 0
     else:
         if game.game_over():
             self.completed = True
         if game.playing():
             self.inProgress = True
         else:
             self.inProgress = False
         self.home_score = game.score_home
         self.away_score = game.score_away
     self.updatedAt = datetime.now()
コード例 #11
0
ファイル: mybot.py プロジェクト: AyeJayTwo/lombardi
def get_game_stats(message, year, week, team):
	year = int(year)
	week = int(week)
	
	# nflgame requrires team abbreviations are uppercase
	game = nflgame.one(year,week=week,home=team.upper(),away=team.upper())
	
	# TODO: build actual validation for the year, week, team and improve the error reporting
	if len(year) <> 4:
		message.reply("NFL has been around for only the past 50ish years. Might want to try a 4 digit year")
		return
	if week > 25:
		message.reply("As much as I'd like, there aren't that many weeks in the NFL season")
		return
	if game is None:
		message.reply("Yeah...I didn't find that game. Try again?")
		return

	# format the scoring summary
	scoring_summary = ''
	for x in game.scores:
		scoring_summary += x+'\n'

	# initialize the response
	response = 'Stats for %s\n(in week %d of the %d season):\n' % (game, week, year)
	
	# TODO: refactor the crap out of this when my eyes aren't closing against my will:
	stats_list = [
	'First Downs:',
	'Total Yards:',
	'Passing Yards:',
	'Rushing Yards:',
	'Penalties:',
	'Penalty Yards:',
	'Turnovers:',
	'Punts:',
	'Punt Yards:',
	'Punt Average:',
	'Possession Time:']

	# add game stats to the response
	for x in range(0,11):
		response += '%s %s - %s\n' % (stats_list[x], game.stats_away[x], game.stats_home[x])

	# add scoring summary to the response
	response += '\nScoring Summary:\n%s' % scoring_summary

	message.reply(response)
コード例 #12
0
def get_game_stats(message, year, week, team):
    year = int(year)
    week = int(week)

    # nflgame requrires team abbreviations are uppercase
    game = nflgame.one(year, week=week, home=team.upper(), away=team.upper())

    # TODO: build actual validation for the year, week, team and improve the error reporting
    if len(year) <> 4:
        message.reply(
            "NFL has been around for only the past 50ish years. Might want to try a 4 digit year"
        )
        return
    if week > 25:
        message.reply(
            "As much as I'd like, there aren't that many weeks in the NFL season"
        )
        return
    if game is None:
        message.reply("Yeah...I didn't find that game. Try again?")
        return

    # format the scoring summary
    scoring_summary = ''
    for x in game.scores:
        scoring_summary += x + '\n'

    # initialize the response
    response = 'Stats for %s\n(in week %d of the %d season):\n' % (game, week,
                                                                   year)

    # TODO: refactor the crap out of this when my eyes aren't closing against my will:
    stats_list = [
        'First Downs:', 'Total Yards:', 'Passing Yards:', 'Rushing Yards:',
        'Penalties:', 'Penalty Yards:', 'Turnovers:', 'Punts:', 'Punt Yards:',
        'Punt Average:', 'Possession Time:'
    ]

    # add game stats to the response
    for x in range(0, 11):
        response += '%s %s - %s\n' % (stats_list[x], game.stats_away[x],
                                      game.stats_home[x])

    # add scoring summary to the response
    response += '\nScoring Summary:\n%s' % scoring_summary

    message.reply(response)
コード例 #13
0
ファイル: views.py プロジェクト: huntermcp/bets
def matchup_finished(request):
    timenow = datetime.datetime.now().replace(tzinfo=timezone('US/Eastern'))
    matchups = Matchup.objects.filter(league = 'NFL',date__lte = timenow, game_completed = 'No')
    for matchup in matchups:
        week = 4
        kind = 'REG'
        year = 2015
	
        game = nflgame.one(year,week=week,kind=kind,away=matchup.away_team.city_id, home=matchup.home_team.city_id)
        if game:
            print game.away
	    if game.game_over():
                matchup.away_score = game.score_away
                matchup.home_score = game.score_home
	        matchup.game_completed = "Yes"
                matchup.save()

    return redirect('/picks/adminfun')
コード例 #14
0
ファイル: Player.py プロジェクト: indioenviejo/nfldfs
 def getWeekStatus(self,season,week):
     # Get statistics for the current game
     game = nflgame.one(season, week, self.team, self.team)
 
     if game is None:
         return "BYE"
 
     # Get all the players with the name
     # Sometimes you may have multiple players 
     # with the same name
 
     currentPlayers = game.players
     
     # Iterate through all the players with that name
     for p in currentPlayers:
         # Make sure the position, player name and team name matches 
         # with the current player's
         if p.player is not None and p.player.gsis_id==self.gsis_id:
             return p.player.status
コード例 #15
0
ファイル: Player.py プロジェクト: indioenviejo/nfldfs
 def getTwoPtsRushing(self,season,week):
     #Value that will be returned from the function.
     twoPts = 0
     # Get statistics for the current game
     game = nflgame.one(season, week, self.team, self.team)
     
     # Bye Week ? If yes, get out of the function
     if game is None:
         return twoPts            
     
     # Get all the players with the name. Sometimes you may have multiple players 
     # with the same name.        
     currentPlayers = game.players
     
     # Iterate through all the players with that name
     for p in currentPlayers:
         # Make sure the position, player name and team name matches 
         # with the current player's and that the stats dictionary has 
         # the fumbles_lost key 
         if p.player is not None:
             if "rushing_twoptm" in p.stats and "rushing_twoptm" in p.stats:
                 twoPts = p.stats["rushing_twoptm"]
     return twoPts
コード例 #16
0
ファイル: Player.py プロジェクト: indioenviejo/nfldfs
    def getOFRTD(self,season,week):
        #Value that will be returned from the function.
        OFRTD = 0
        
        # Get statistics for the current game
        game = nflgame.one(season, week, self.team, self.team)

        # Bye Week ? If yes, get out of the function
        if game is None:
            return OFRTD

        # Get all the players with the name. Sometimes you may have multiple players 
        # with the same name.        
        currentPlayers = game.players
        
        # Iterate through all the players with that name
        for p in currentPlayers:
            # Make sure the position, player name and team name matches 
            # with the current player's and that the stats dictionary has 
            # the receiving_rec key 
            if p.player is not None and p.player.gsis_id==self.gsis_id and "fumbles_trcv" in p.stats:
                if "fumbles_trcv" in p.stats:
                    OFRTD = p.stats["fumbles_trcv"]
        return OFRTD
コード例 #17
0
#
# 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)

# Finds aggregate team stats for single games, will be good to build the total defense yds allowed module.
# #Find our game
g = nflgame.one(2013, 1, "BUF", "NE")

print g.stats_home
print g.stats_away

# Finds and list specific player states aggregated by entire an entire game.
# games = nflgame.games(year=2017, week=9, kind='REG')
# for game in games:
#     for pp in game.players:
#         print pp, pp.team, pp.stats

# Finds and list specific plays made by players aggregated by week.
# games = nflgame.games(2017, week=9)
# plays = nflgame.combine_plays(games)
# for p in plays:
#     print p.players
コード例 #18
0
def playerStats():
    game = nflgame.one(2015, 1, "NE", "PIT")
    tom_brady = game.players.name("T.Brady")
    return tom_brady.formatted_stats()
コード例 #19
0
ファイル: stats.py プロジェクト: Havko/playertracker
def playerStats():
	game = nflgame.one(2015, 1, "NE", "PIT")
	tom_brady = game.players.name("T.Brady")
	return tom_brady.formatted_stats()
コード例 #20
0
ファイル: nfl-bot.py プロジェクト: knubie/nfl-bot
def say_play(message):
    global index
    global prev_desc

    game = nflgame.one(year, week, home, away, season)

    # desc = list(reversed(list(game.drives.plays())))[0].__str__()

    # if game.has_started
    play = list(reversed(list(game.drives.plays())))[0]
    # else
    # play = list(game.drives.plays())[index]
    desc = play.desc

    print(desc)

    index = index + 1
    if desc != prev_desc:
        print('different')
        prev_desc = desc

        # Team with posession
        posteam = play.data['posteam']

        time = play.data['time']
        # 'END QUARTER 1' etc, returns u'' for time
        if time == u'': time = u'0:00'

        quarter = str(play.data['qtr'])
        down = play.data['down']
        yards_to_go = str(play.data['ydstogo'])
        note = play.data['note']
        if note != None and note != u'PENALTY':
            note = note + ' - '
        else:
            note = u''

        if down == 0:
            down_and_yards = u''
        else:
            down_and_yards = ordinal(down) + ' and ' + yards_to_go

        yard_line = play.data['yrdln']
        prefix = u''
        if yard_line != u'':
            team_yard_line = re.search("(\w+) \d+", yard_line).group(1)
            yard_line_int = int(re.search("\w+ (\d+)", yard_line).group(1))
            if team_yard_line == posteam:
                raw_yards = str((50 - yard_line_int) + 50) + ' yards'
            else:
                raw_yards = str(yard_line_int) + ' yards'

            relative_yard_line = ':' + team_yard_line.lower() + ': ' + str(yard_line_int)
        else:
            raw_yards = u''
            relative_yard_line = u''


        if yard_line != u'' and down != 0:
            prefix = u' @ '

        # TODO: Add flair for when play is in RED ZONE
        
        # TODO: Account for odd messages:
        # Timeout #1 by DET at 08:53.
        # END QUARTER 1
        # Timeout #2 by BAL at 01:28. BAL charged with final time out due to injured player.
        # Two-Minute Warning
        # END GAME

        # meta = re.search("\(\w+, ([^\)]*)\)", last_play).group(1)
        # meta = re.sub("\(\w+, ([^\)]*)\) ", "", last_play)

        desc = re.sub("\(\w+, ([^\)]*)\) ", "", desc)

        desc = re.sub("\((\d{0,2}:\d{0,2})\) ", "", desc)

        # Names
        desc = re.sub("([A-Z]{1}\.[A-Z]+[a-zA-Z]+)", r"_\1_", desc)

        # Yard
        desc = bold("(-*\d{1,2} yards*)", desc)
        # desc = re.sub("(-*\d{1,2} yards*)", r"*\1*", desc)

        # Injured
        desc = bold("(injured)", desc)
        # desc = re.sub("(injured)", r"*\1*", desc)

        # Incomplete
        desc = bold("(incomplete)", desc)
        # desc = re.sub("(incomplete)", r"*\1*", desc)

        # Intercepted
        desc = bold("(INTERCEPTED)", desc)
        # desc = re.sub("(INTERCEPTED)", r"*\1*", desc)

        # Touchdown
        desc = bold("(TOUCHDOWN)", desc)
        # desc = re.sub("(TOUCHDOWN)", r"*\1*", desc)

        # Good
        desc = bold("(GOOD)", desc)
        # desc = re.sub("(GOOD)", r"*\1*", desc)

        # Muff
        desc = bold("(MUFFS)", desc)
        # desc = re.sub("(MUFFS)", r"*\1*", desc)

        # Recovered
        desc = bold("(RECOVERED)", desc)
        # desc = re.sub("(RECOVERED)", r"*\1*", desc)

        # Nullified
        desc = bold("(NULLIFIED)", desc)
        # desc = re.sub("(NULLIFIED)", r"*\1*", desc)

        # Penalty
        # penalty = re.search(" (Penalty .*)", desc, re.IGNORECASE)
        # only_penalty = re.search("PENALTY", desc)

        parts = re.split('\. ', desc)
        parts = [p + '.' if not p.endswith('.') else p for p in parts]

        attachments = []

        for i, part in enumerate(parts):
            if i == 0:
                attachment = {
                    'author_name': time + ' - Q' + quarter,
                    # 'title': meta,
                    'title': note + down_and_yards + prefix + relative_yard_line,
                }
            else:
                attachment = {}

            attachment['mrkdwn_in'] = ['text']

            penalty = re.search("Penalty", part, re.IGNORECASE)
            injured = re.search("injured", part, re.IGNORECASE)
            recovered = re.search("recovered", part, re.IGNORECASE)

            if penalty != None:
                attachment['color'] = '#F2D300'
                part = re.sub("([^A-Z])([A-Z]{2,3})([^A-Z])", lambda m: m.group(1) + ':' + m.group(2).lower() + ': ', part, 1)

            if recovered != None:
                part = re.sub("([^A-Z])([A-Z]{2,3})(-)", lambda m: m.group(1) + ':' + m.group(2).lower() + ': ', part, 1)

            if injured != None:
                attachment['color'] = '#B4161D'

            attachment['text'] = part

            attachments.append(attachment)

        message.send_webapi(':' + posteam.lower() + ':', json.dumps(attachments))
コード例 #21
0
ファイル: nfl-bot.py プロジェクト: knubie/nfl-bot
def score(message):
    game = nflgame.one(year, week, home, away, season)
    message.send_webapi(':' + away + ': *' + str(game.score_away) + ' - ' + str(game.score_home) + '* :' + home + ':')
コード例 #22
0
ファイル: defense.py プロジェクト: bioneer27/fantasydefense
for i in range(0,32):
    if rush_d[i][0] == guess:
        print rush_d[i][1]
        defense = "The %s rush defense is ranked %d"
        print defense % (guess, i+1)
        print (i+1)


weeks = 0
# Stratify passing options, limit to main four options
strat = numpy.array([0,0,0,0])
strat = strat.astype(float)
for i in range(1,curr):
# Query game data, one game per week for 16 weeks
    game = nflgame.one(2015, i, guess, guess)
# Compile player data for a game

    try:

        game.players.passing()

    except AttributeError:
        continue     

    opp   = 0
    yards = 0
    week_strat = numpy.array([0,0,0,0])
    week_strat = week_strat.astype(float)
# Sort and run for best receiving results
    for p in game.players.receiving().sort("receiving_yds"):
コード例 #23
0
# tmp['roster'] # display roster
# tmp['stats_0'] # Team Stats & Rankings

# %%
"""     # Advanced Stats
    adv_URL = 'https://www.pro-football-reference.com/teams/' + team + '/' + str(year) + '_advanced.htm'
    advstats = pd.read_html(team_URL)
    advstats_dict = {}
    pd.read_html('//*[@id="advanced_defense"]/tbody/tr[1]')

    import lxml.html as LH
    url = 'https://www.espn.com/nfl/stats/player/_/view/defense/table/defensiveInterceptions/sort/interceptions/dir/desc'
    r = requests.get(url)
    root = LH.fromstring(r.content)
    
    for table in root.xpath('//*[contains(concat( " ", @class, " " ), concat( " ", "Table2__title--remove-capitalization", " " ))]'):
        header = [text(th) for th in table.xpath('//th')]        # 1
        data = [[text(td) for td in tr.xpath('td')]  
                for tr in table.xpath('//tr')]                   # 2
        data = [row for row in data if len(row)==len(header)]    # 3 
        data = pd.DataFrame(data, columns=header)                # 4
        print(data)  """

# %%
pd.read_html(
    'https://www.pro-football-reference.com/teams/nyg/2019_roster.htm')
# %%
import nflgame
nflgame.one(2011, 17, "NE", "BUF")
# %%
コード例 #24
0
import nflgame


game = nflgame.one(2011, 17, "NE", 'BUF')
for p in game.players.passing():
    print p, p.passing_cmp, p.passing_att, p.passing_yds