Exemplo n.º 1
0
def turnovers_per_week(team, year):

    try:
        season_games = nflgame.games(year, home=team, away=team)
    except TypeError:
        team = alternate_team_names[team]
        season_games = nflgame.games(year, home=team, away=team)

    week_list = []
    turnover_list = []
    turnover_dif_list = []

    for g in season_games:
        w = g.schedule['week']
        if g.is_home(team):
            team_turnovers = g.stats_home.turnovers
            opponent_turnovers = g.stats_away.turnovers
            turnover_dif = opponent_turnovers - team_turnovers
        else:
            team_turnovers = g.stats_away.turnovers
            opponent_turnovers = g.stats_home.turnovers
            turnover_dif = opponent_turnovers - team_turnovers

        week_list.append(w)
        turnover_list.append(team_turnovers)
        turnover_dif_list.append(turnover_dif)

    turnover_dict = {
        'week': week_list,
        'turnovers': turnover_list,
        'turnover_dif': turnover_dif_list
    }

    return turnover_dict
Exemplo n.º 2
0
def stats_to_csv():
    cmd = 'stat (every statistic from a game), stat_p (statistics of every player from an entire season) and both'

    print("\nCommands to use: " + cmd)

    choice = input("\nType in the command you want to use: ")
    choice = choice.lower()

    year = input("Year: ")
    __year__ = f'{year}'

    if choice == "stat":
        games.players.csv('player-stats.csv')

    elif choice == "stat_p":
        nflgame.combine(nflgame.games(__year__)).csv('season_stats.csv')

    elif choice == "both":
        games.players.csv('player-stats.csv')

        nflgame.combine(nflgame.games(__year__)).csv('season_stats.csv')

    else:
        print("\nNot a valid command!")
        print("\nUse " + cmd)
Exemplo n.º 3
0
def check_bets(bet_groups):
    year, week = nflgame.live.current_year_and_week()
    all_games = nflgame.games(year, week=week, started=False)

    os.system('clear')

    index = {}
    for game in all_games:
        index[game.home] = (game.score_home - game.score_away, game)
        index[game.away] = (game.score_away - game.score_home, game)

    out = ''
    for group in bet_groups:
        out += '--------------------------------------------------\n'
        for bet in group:
            if bet.team in index:
                (diff, game) = index[bet.team]
                score = diff + float(bet.spread)
                if str(game.time) == 'Pregame': mark = '(pre) '
                elif score == 0: mark = '(push)'
                elif score < 0: mark = '(lose)'
                else: mark = '(win) '

                out += '%3s %-5s %s %3s %2d - %2d %-3s [%s]\n' % (
                    bet.team, bet.spread, mark, game.away, game.score_away,
                    game.score_home, game.home, game.time)
            else:
                out += '%3s %-5s (unstarted)\n' % (bet.team, bet.spread)

    out += '--------------------------------------------------\n'

    return out
Exemplo n.º 4
0
def find_stat_columns():
    """
    Find all statistic names for players in nflgame.

    :return: list of set of statistic names
    """

    stat_columns = set()
    phases = [('PRE', 4), ('REG', 17), ('POST', 4)]
    seasons = [i for i in range(2009, datetime.datetime.now().year)]

    for season in seasons:
        for phase, num_weeks in phases:
            for week in range(1, num_weeks + 1):
                try:
                    games = nflgame.games(year=season, week=week,
                                          kind=phase)
                except TypeError:
                    continue

                players = nflgame.combine_play_stats(games)
                for player in players:
                    for stat in player._stats:
                        stat_columns.add(stat)

    return stat_columns
Exemplo n.º 5
0
def displayPointTotalsByVegas(line, ou):
    start = 2016
    end = 2018

    weeks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]

    first_place_distro = PlayerDistribution()
    second_place_distro = PlayerDistribution()
    #third_place_distro = PlayerDistribution()
    my_game_ids = []

    for i in range(start, end):
        games = nflgame.games(i, week=weeks)
        for game in games:
            if isCloseEnough(homeScore=game.score_home,
                             awayScore=game.score_away,
                             line=line,
                             ou=ou):
                player_list = displayPointTotalsByGame(game.eid)
                val = getPlayerType(player_list[0], game)
                print(val)
                if val is not None:
                    first_place_distro.distro_dict[val] += 1
                #first_place_distro.distro_dict[getPlayerType(player_list[0], game)] += 1
                second_place_distro.distro_dict[getPlayerType(
                    player_list[1], game)] += 1
                #third_place_distro.distro_dict[getPlayerType(player_list[2], game)] += 1
                my_game_ids.append(game.eid)

    print(first_place_distro.distro_dict)
    print(second_place_distro.distro_dict)
def create_all_players(host, port, year, kind, game_weeks):
  games = []
  for week in game_weeks:
    for game in nflgame.games(year, week = week, kind = kind):
      games.append(Game(game, week))

  if not games:
    raise RuntimeError("Couldn't find any {}-games in {}, did you get the year right?".format(kind, year))

  offensive_players = {}
  defensive_players = {}

  for game in games:
    for player in game.offensive_players():
      if player.playerid not in offensive_players:
        offensive_players[player.playerid] = player
    for player in game.defensive_players():
      if player.team not in defensive_players:
        defensive_players[player.team] = player

  all_players = dict(offensive_players.items() + defensive_players.items())
  total_no_players = len(all_players.keys())
  counter = 1
  for key, value in all_players.iteritems():
    print "Uploading player "+value.name+" "+str(counter)+"/"+str(total_no_players)
    response = value.get_api_facade(host, port).create()
    if response.status_code != 200:
      print "Error creating player "+player.name+" code was "+str(response.status_code)
    counter += 1
Exemplo n.º 7
0
def create_all_players(host, port, year, kind, game_weeks):
    games = []
    for week in game_weeks:
        for game in nflgame.games(year, week=week, kind=kind):
            games.append(Game(game, week))

    if not games:
        raise RuntimeError(
            "Couldn't find any {}-games in {}, did you get the year right?".
            format(kind, year))

    offensive_players = {}
    defensive_players = {}

    for game in games:
        for player in game.offensive_players():
            if player.playerid not in offensive_players:
                offensive_players[player.playerid] = player
        for player in game.defensive_players():
            if player.team not in defensive_players:
                defensive_players[player.team] = player

    all_players = dict(offensive_players.items() + defensive_players.items())
    total_no_players = len(all_players.keys())
    counter = 1
    for key, value in all_players.iteritems():
        print "Uploading player " + value.name + " " + str(
            counter) + "/" + str(total_no_players)
        response = value.get_api_facade(host, port).create()
        if response.status_code != 200:
            print "Error creating player " + player.name + " code was " + str(
                response.status_code)
        counter += 1
Exemplo n.º 8
0
    def get_rushing_yards_per_team(self, home, away):

        rushing_yards_home = []
        rushing_yards_away = []

        for year in self.nfl_years:
            games = nflgame.games(year)

            for g in games:
                if g.home == home and g.away == away:
                    rushing_home = 0

                    for rushing in g.data['home']['stats']['rushing']:
                        rushing_home = rushing_home + g.data['home']['stats']['rushing'][rushing]['yds']

                    rushing_yards_home.append(rushing_home)

                    # ===================================================================================

                    rushing_away = 0

                    for rushing in g.data['away']['stats']['rushing']:
                        rushing_away = rushing_away + g.data['away']['stats']['rushing'][rushing]['yds']

                    rushing_yards_away.append(rushing_away)

        return [rushing_yards_home, rushing_yards_away]
Exemplo n.º 9
0
def multi_player_points(player_names,years,ppr):
    ids_found = {}
    stats = {}
    for name in player_names:
        ids_found[name] = set()
        stats[name] = []
    for year in years:
        year = int(year)
        games = nflgame.games(year)
        for game in games:
            for player in game.max_player_stats():
                name = full_name(player)
                if name in ids_found:
                    ids_found[name].add(player.playerid)
                    stats[name].append(score_stats.score(player.stats, ppr))
    # check unique
    should_return = True
    for name in player_names:
        if len(ids_found[name])!= 1:
            should_return = False
            print("unable to find unique id for player " + name + str(ids_found[name]))
    if should_return :
        return stats
    else:
        return None
Exemplo n.º 10
0
def get_plays(years, weeks, indexes=-1):
    all_plays = []
    for y in years:
        print(y)
        for w in weeks:
            #print(w)
            try:
                games = nflgame.games(y, week=w, kind='REG')
            except:
                continue
            current = data[(data["schedule_season"] == y)
                           & (data["schedule_week"] == str(w))]
            if not indexes == -1:
                games = [games[i] for i in indexes]
            for g in games:
                t1 = g.home
                t2 = g.away
                t1 = fix_name(t1)
                t2 = fix_name(t2)
                #print(t2)
                spread = list(
                    current.loc[(current["team1"] == t1)
                                & (current["team2"] == t2)]["vegas_spread"])
                if len(spread) > 0:
                    h, a, cur_plays = get_all_plays2(g, spread[0])
                    if h != g.score_home or a != g.score_away:
                        #print("Actual: " + str(g.score_home) + "-" + str(g.score_away) + ", Mine: " + str(h) + "-" +
                        #    str(a) + " " + str(g.home) + " " +str(g.away))
                        continue
                    all_plays += cur_plays
    return all_plays
Exemplo n.º 11
0
def _get_stats(season, week, kind):
    """
    Memoized stats getter. Requires fully-specified arguments to make effective
    use of the cache.
    """
    games = nflgame.games(season, week=week, kind=kind)
    return nflgame.combine_max_stats(games)
Exemplo n.º 12
0
def raw_nfl_data_out():
    print "%s,%s,%s,%s,%s,%s,%s,%s" % ( "season","week","gametype","home","home_score","away","away_score","home_score_margin" )
    for s in y:
            for k in gametype:
                    games = nfl.games(s,kind=k)
                    for g in games:
                        print "%i, %i, %s, %s, %i, %s, %i, %i" % (g.season(), g.schedule['week'],k ,g.home,g.score_home,g.away,g.score_away,g.score_home-g.score_away)
def fetch_defense_stats():
    # team defense statistics
    statistics = {}
    for team in map(lambda x: x[0], nflgame.teams):
        statistics[team] = create_empty_entry()

    for year in range(2009, 2015):
        for week in range(1, 18):
            for game in nflgame.games(year=year, week=week):
                home = game.home
                away = game.away
                statistics[home][str(year)][str(week)] = {
                    'home': home,
                    'away': away,
                    'points_allowed': game.score_away,
                    'passing_yards_allowed': game.stats_away[2],
                    'rushing_yards_allowed': game.stats_away[3],
                    'turnovers': game.stats_away[6],
                    'played': True

                }
                statistics[away][str(year)][str(week)] = {
                    'home': home,
                    'away': away,
                    'points_allowed': game.score_home,
                    'passing_yards_allowed': game.stats_home[2],
                    'rushing_yards_allowed': game.stats_home[3],
                    'turnovers': game.stats_home[6],
                    'played': True
                }

    return statistics
Exemplo n.º 14
0
def getPlayerStats(plyr,stat): 
	game = nflgame.games(2012,week=[2,3,4,6])
	players = nflgame.combine(game)
	player = players.name(plyr)
	playerStats = player.stats
	if stat in playerStats:
		print 'stat: ',stat,' value = ',playerStats[stat]
Exemplo n.º 15
0
def get_player_stats(year, week):
    games = nflgame.games(year, week)
    players = nflgame.combine_max_stats(games)
    for player in players:
        fantasy_points = (player.passing_yds * .04 + player.passing_tds * 4 -
                          player.passing_int + player.rushing_yds * .1 +
                          player.rushing_tds * 6 + player.receiving_yds * .1 +
                          player.kickret_tds * 6 + player.receiving_tds * 6 +
                          (player.receiving_twoptm + player.rushing_twoptm +
                           player.passing_twoptm) * 2 -
                          player.fumbles_lost * 2 + player.fumbles_rec_tds * 6)

        two_point_conversions = player.receiving_twoptm + player.rushing_twoptm + player.passing_twoptm

        #

        try:
            p = Player(player.name, year, week, player.player.position,
                       fantasy_points, player.passing_yds, player.passing_tds,
                       player.passing_int, player.rushing_yds,
                       player.rushing_tds, player.receiving_yds,
                       player.receiving_tds, player.kickret_tds,
                       two_point_conversions, player.fumbles_lost,
                       player.fumbles_rec_tds)
        except AttributeError:
            p = Player(player.name, year, week, "N/A", fantasy_points,
                       player.passing_yds, player.passing_tds,
                       player.passing_int, player.rushing_yds,
                       player.rushing_tds, player.receiving_yds,
                       player.receiving_tds, player.kickret_tds,
                       two_point_conversions, player.fumbles_lost,
                       player.fumbles_rec_tds)

        db.session.add(p)
    db.session.commit()
def getFantasyPoints(seasons, weeks):
    """
    Download game stats for every season and week and calculate the fantasy
    points scored for each player in each game.

    Args:
        seasons (list): List of seasons (int).
        weeks (list): List of weeks (int).

    Returns:
        dict: Dictionary of fantasy points scored.
    """
    data = {}
    schedule = nflgame.sched.games
    for s in seasons:
        print s
        data[s] = {}
        for w in weeks:
            games = nflgame.games(s, w)
            players = nflgame.combine_game_stats(games)
            data[s][w] = []
            positions = ["QB", "RB", "WR", "TE"]
            gen = (p for p in players if p.player.position in positions)
            for player in gen:
                points = calculateFantasyPoints(player)
                points.append(getOpponent(schedule, s, w, player))
                data[s][w].append(points)
    return data
def get_games(years):
    """
    Given a list of N years, N .csv files will be written,
    each containing game data for the regular season of that year.
    """
    for year in years:
        f = file('games/games_%s.csv' % year, 'w')
        print_header(f)

        games = nflgame.games(int(year))
        for game in games:
            home_team = game.home
            home_score = game.score_home
            away_team = game.away
            away_score = game.score_away
            week = game.schedule['week']

            f.write(
                '%s,%s,%d,%d,%d,%d\n' %
                (year, home_team, 1, week, home_score, away_score)
            )
            f.write(
                '%s,%s,%d,%d,%d,%d\n' %
                (year, away_team, 0, week, away_score, home_score)
            )
        f.close()
Exemplo n.º 18
0
    def getNextQuestion(self, cfg):
        while True:
            week = random.randrange(self._firstWeek, self._lastWeek+1)
            year = random.randrange(self._firstYear, self._thisYear+1)
            print year, week
            try:
                games = nflgame.games(year, week=week)
                g = random.randrange(0, len(games))
                game = games[g]
                if game.score_away_q5 > 0 or game.score_home_q5 > 0:
                    continue

                self.homeTeam = game.home
                self.awayTeam = game.away
                self.gameDate = datetime.datetime(game.schedule['year'], game.schedule['month'], game.schedule['day'])
                self.gameTime = game.schedule['time']

                self.homeScores = [game.score_home_q1, game.score_home_q2, game.score_home_q3, game.score_home_q4]
                self.awayScores = [game.score_away_q1, game.score_away_q2, game.score_away_q3, game.score_away_q4]
                self.homeFinalScore = game.score_home
                self.awayFinalScore = game.score_away

                break
            except:
                pass
        return self
Exemplo n.º 19
0
def current_week():
    # returns current week of season
    year = date.today().year
    for x in range(1, 18):
        games = nflgame.games(year, week=x, home=None, away=None, kind='REG', started=False)
        if games == []:
            return x-1
Exemplo n.º 20
0
def create_schedule(year):
    df = pd.read_excel('2010_betting.xlsx')
    df['schedule_week'] = df['schedule_week'].replace({
        'WildCard': 0,
        'Wildcard': 0,
        'Division': 1,
        'Conference': 2,
        'Superbowl': 3,
        'SuperBowl': 3
    })
    df = df.astype({'schedule_week': 'int64'})
    df['schedule_date'] = pd.to_datetime(df['schedule_date'])
    df = df.reset_index()
    df = df.drop(['index', 'Unnamed: 0'], axis=1)
    games = nflgame.games(year=year, started=True)
    for game in games:
        week = game.schedule['week']
        date = datetime.datetime(game.schedule['year'], game.schedule['month'],
                                 game.schedule['day'])
        home_team = abbrev(game.home, 'team')
        away_team = abbrev(game.away, 'team')
        home_score = game.score_home
        away_score = game.score_away
        df.loc[len(df)] = [
            date, year, week, 'FALSE', home_team, home_score, away_score,
            away_team, 0, 0, 0, 0, 0, 0, 0, 0, 0
        ]
    df.to_excel('2010_out.xlsx')
    return df
Exemplo n.º 21
0
def update_stats(host, port, year, kind, game_week):
    games = nflgame.games(year, week=game_week, kind=kind)

    for nfl_game in games:
        game = Game(nfl_game, game_week)
        for player in game.all_players():
            update_player_stats(host, port, player)
Exemplo n.º 22
0
def update_winners(week=None):
    # get current year and week
    year, week_ = current_year_and_week()

    week = week if week is not None else week_

    # get all games in week
    pickem = SeasonPickem.objects.select_related()\
        .filter(game__week=week).all()

    # get results for week
    game_list = games(year, week=week)
    game_dict = {(g.away, g.home): g for g in game_list}

    for p in pickem:
        game = p.game
        winner = Winner.objects.filter(game=game).first()
        if winner is None:
            game_results = game_dict.get(
                (game.away_team.abbr, game.home_team.abbr))
            if game_results is not None:
                winner_abbr = game_results.winner
                if winner_abbr is not None:
                    if len(winner_abbr) > 3:
                        winner_abbr = 'TIE'
                    winner = Team.objects.filter(abbr=winner_abbr).first()
                    new_winner = Winner(game=game, winner=winner)
                    new_winner.save()
Exemplo n.º 23
0
def fetch_games(year, week, team = None):
    games = nflgame.games(year, week)
    if team:
        for game in games:
            if game.home == team or game.away == team:
                return [ game ]
    return games
Exemplo n.º 24
0
def main():
    # Necessary lists
    seasonList, seasons, score, firstDowns, totalYards, passingYards, rushingYards, penaltyCount, penaltyYards, \
    turnovers, puntCount, puntYards, puntAverage = [], [], [], [], [], [], [], [], [], [], [], [], []
    # Creates each season
    for x in range(0,8):
        seasonListIteration = nflgame.games(x+2009)
        seasons += [x+2009 for y in range (0, len(seasonListIteration))]
        seasonList += seasonListIteration
    # Populates lists for each season
    for x in seasonList:
        score += [x.score_home, x.score_away]
        firstDowns += [x.stats_home.first_downs, x.stats_away.first_downs]
        totalYards += [x.stats_home.total_yds, x.stats_away.total_yds]
        passingYards += [x.stats_home.passing_yds, x.stats_away.passing_yds]
        rushingYards += [x.stats_home.rushing_yds, x.stats_away.rushing_yds]
        penaltyCount += [x.stats_home.penalty_cnt, x.stats_away.penalty_cnt]
        penaltyYards += [x.stats_home.penalty_yds, x.stats_away.penalty_yds]
        turnovers += [x.stats_home.turnovers, x.stats_away.turnovers]
        puntCount += [x.stats_home.punt_cnt, x.stats_away.punt_cnt]
        puntYards += [x.stats_home.punt_yds, x.stats_away.punt_yds]
        puntAverage += [x.stats_home.punt_avg, x.stats_away.punt_avg]
    # Writes .CSV with format Score, First Downs, Total Yards, Passing Yards, Rushing Yards, Penalty Count,
    # Penalty Yards, Turnovers, Punt Count, Punt Yards, Punt Average
    with open('NFL Stats Rewrite.csv', 'wb') as csvfile:
        gameWriter = csv.writer(csvfile, delimiter=',', quotechar=',', quoting=csv.QUOTE_MINIMAL)
        gameWriter.writerow(['Score', 'First Downs', 'Total Yards', 'Passing Yards', 'Rushing Yards', 'Penalty Count',
                             'Penalty Yards', 'Turnovers', 'Punt Count', 'Punt Yards', 'Punt Average'])
        for x in range(0, len(score)):
            gameWriter.writerow(
                [score[x], firstDowns[x], totalYards[x], passingYards[x], rushingYards[x], penaltyCount[x],
                 penaltyYards[x], turnovers[x], puntCount[x], puntYards[x], puntAverage[x]])
Exemplo n.º 25
0
def update_week(week):
    """
    Update stats & points for the Week's DefenseWeek and PlayerWeek children.
    """
    teams = {team.abbreviation: initialize_defense_week(week, team)
             for team in NFLTeam.query.all()}
    games = nflgame.games(week.season.year, week=week.number)
    for game in games:
        try:
            teams[game.winner].wins = 1
        except (KeyError, AttributeError):
            pass
        teams[game.home].points_allowed = game.score_away
        teams[game.away].points_allowed = game.score_home
    player_stats = nflgame.combine_play_stats(games)
    for player in player_stats:
        update_defense_by_player(teams[player.team], player)
        update_player_week(player, week)
    for defense in teams.values():
        try:
            defense._score_defense()
        except TypeError:
            # for teams on bye
            pass
    db.session.merge(week)
    db.session.commit()
Exemplo n.º 26
0
def getRushers(year=None):
	games = nflgame.games(int(year))
	players = nflgame.combine(games)
	myQuery = {}
	for p in players.rushing().sort("rushing_yds").limit(10):
		myQuery[str(p)] = p.rushing_yds
	return render_template('index.html', year=year, myQuery=myQuery, player="rushers")
Exemplo n.º 27
0
def getNFLGames(year):
    if year not in nflGames:
        games = nflgame.games(year, kind='REG')
        nflGames[year] = games
    else:
        games = nflGames[year]
    return [(str(game.winner), str(game.loser)) for game in games]
Exemplo n.º 28
0
    def generate_matrices(self, season, weeks, kind="REG"):
        games = nflgame.games(season, week=weeks, kind=kind)
        games_matrix = np.identity(len(self.teams_array))

        team_index_map = {
            team: team_index
            for team_index, team in enumerate(self.teams_array)
        }
        game_wins_dict = {}

        for game in games:
            if game.winner not in game_wins_dict:
                game_wins_dict[game.winner] = 0
            game_wins_dict[game.winner] += self.wins_update_formula(game)

            games_matrix[team_index_map[game.winner]][team_index_map[
                game.loser]] += 1
            games_matrix[team_index_map[game.loser]][team_index_map[
                game.winner]] += 1

        wins_array = np.array([0] * len(self.teams_array))
        for team in game_wins_dict:
            wins_array[team_index_map[team]] = game_wins_dict[team]

        return games_matrix, wins_array
Exemplo n.º 29
0
def get_game_data(name, team, book, year):

    if __name__ == '__main__':
        try:
            player = nflgame.find(name)[0]
        except BaseException:
            return

    if '(, )' in str(player):
        print ("Player Inactive, or Player Not Found\n\n")
        return

    print ("*" *79)
    print (player)

    data = create_csv(player)
    data.append_separator(name)

    print (str(year) + '\n')
    data.append_separator(year)
    games = nflgame.games(year, home=team, away=team)
    for game in games:
        plyr = game.players.name(player.gsis_name)
        print ('-'*79)
        print (game)
        to_csv(data, plyr, game, year, player.position)

    with open(name + '.xls', 'wb') as f:
        f.write(data.xls)
    book.add_sheet(data)
Exemplo n.º 30
0
 def __init__(self,
              year=datetime.datetime.now().year,
              week=current_week() - 1):
     self.week = week
     self.year = year
     self.games = nflgame.games(self.year, week=self.week)
     self.players = nflgame.combine_max_stats(self.games)
Exemplo n.º 31
0
def away_rushing_tds_in_year(year, player, team):
    avg = 0.0
    away_games = nflgame.games(year, home=team)
    players = nflgame.combine(away_games)
    this_player = players.name(player)
    avg += this_player.rushing_tds
    print year, this_player, this_player.rushing_tds, (avg / 8)
Exemplo n.º 32
0
 def getSeasonStats(self, plyr, stat, season):
     data = []
     # if season == 2014:
     # 	print "HERE"
     for x in range(1, 18):
         game = nflgame.games(season, week=x)
         if game == []:
             break
         players = nflgame.combine_game_stats(game)
         player = players.name(plyr)
         if player is None:
             data.append({'week': str(x), 'active': 'false'})
         else:
             playerStats = player.stats
             week_obj = {'week': str(x)}
             if (stat == 'all'):
                 for x in playerStats:
                     week_obj[x] = playerStats[x]
                 week_obj['active'] = 'true'
                 data.append(week_obj)
                 # if season == 2014:
                 # 	print week_obj
             else:
                 data.append({
                     'week': str(x),
                     stat: str(playerStats[stat]),
                     'active': 'true'
                 })
     return data
Exemplo n.º 33
0
def rushing(teams, year, weeks, season_type):
    # Create Team Dictionaries for Offense and Defense Passing.
    team_off = {}
    team_def = {}
    season_length = len(weeks)

    for i in teams:
        team_off[i] = [0] * season_length
        team_def[i] = [0] * season_length

    for week in weeks:
        print('Rushing Calc week ' + str(week) + ' of ' + str(season_length))
        games = nflgame.games(year=year, week=week, kind=season_type)

        # Assign Offense passing per week achieved and defensive passing yards allowed.
        for g in games:
            team_off[g.home][week - 1] = g.stats_home.rushing_yds
            team_off[g.away][week - 1] = g.stats_away.rushing_yds
            team_def[g.home][week - 1] = g.stats_away.rushing_yds
            team_def[g.away][week - 1] = g.stats_home.rushing_yds

    # Sum all of the passing yards.
    off = {}
    defen = {}
    for key in team_off:
        result_off = sum(team_off[key])
        result_defen = sum(team_def[key])
        off[key] = result_off
        defen[key] = result_defen

    return off, defen
Exemplo n.º 34
0
def create_games_rows(cur):
    year, week = live.current_year_and_week()
    games = nflgame.games(year, week=week)
    values = []

    for game in games:
        date = str(game.schedule['year']) + '-' + str(
            game.schedule['month']
        ).zfill(2) + '-' + str(game.schedule['day']) + ' ' + (
            pd.to_datetime(game.schedule['time'] + game.schedule['meridiem']) -
            pd.Timedelta(hours=1)).strftime('%H:%M:00')
        try:
            values.append("'" + str(game.gamekey) + "', '" + game.away +
                          "', '" + game.home + "', '" + str(date) + "'")
        except:
            print(
                f"Couldn't create game number: {game.gamekey} for {game.away} @ {game.home}"
            )

    for value in values:
        sql = (f"""
        INSERT INTO games (id, away_team, home_team, game_start)
        VALUES ({value})
        ON CONFLICT DO NOTHING;
        """)
        cur.execute(sql)

    return [year, week]
Exemplo n.º 35
0
def defense_team_stats(team_symbol, year, wk):
    # takes team symbol, year of games(s), week of game(s)
    # used for defensive team stats
    stats = {
        'rushing_yds_allowed': 0,
        'rushing_tds_allowed': 0,
        'passing_yds_allowed': 0,
        'passing_tds_allowed': 0,
        'total_points_allowed': 0,
        'passing_ints': 0,
        'fumbles_forced': 0
    }
    games = nflgame.games(year, week=wk, home=team_symbol, away=team_symbol)
    gameplayers = nflgame.combine_game_stats(games)
    for g in games:
        if g.home != team_symbol:
            stats['total_points_allowed'] += g.score_home
        if g.away != team_symbol:
            stats['total_points_allowed'] += g.score_away
    for p in gameplayers:
        if p.team != team_symbol:
            stats['rushing_yds_allowed'] += p.rushing_yds
            stats['rushing_tds_allowed'] += p.rushing_tds
            stats['passing_yds_allowed'] += p.passing_yds
            stats['passing_tds_allowed'] += p.passing_tds
            stats['passing_ints'] += p.passing_ints
            stats['fumbles_forced'] += p.fumbles_tot
    return stats
Exemplo n.º 36
0
def third_down_pct_per_week(team, year):

    try:
        season_games = nflgame.games(year, home=team, away=team)
    except TypeError:
        team = alternate_team_names[team]
        season_games = nflgame.games(year, home=team, away=team)

    week_list = []
    third_down_pct_list = []

    for g in season_games:
        week_list.append(g.schedule['week'])
        third_down_pct_list.append(third_down_pct_game(team, g))

    return {'week': week_list, 'third_down_pct': third_down_pct_list}
Exemplo n.º 37
0
	def getSeasonStats(self, plyr, stat, season):   
		data = []
		# if season == 2014:
		# 	print "HERE"
		for x in range(1, 18):
			game = nflgame.games(season,week=x)
			if game == []:
				break
			players = nflgame.combine_game_stats(game)
			player = players.name(plyr)
			if player is None:
				data.append({'week':str(x),'active':'false'})
			else:
				playerStats = player.stats
				week_obj = {'week':str(x)}
				if(stat == 'all'):
					for x in playerStats:
						week_obj[x] = playerStats[x]
					week_obj['active'] = 'true'
					data.append(week_obj)
					# if season == 2014:
					# 	print week_obj
				else:
					data.append({'week':str(x),stat:str(playerStats[stat]), 'active':'true'})
		return data
Exemplo n.º 38
0
def print_top_rushers_by_ben(num_results=50, year=None, weeks=None):
    '''
    This will print players with highest rushing yards and 
    show stats of attempts and yardage gains.
    '''
    if year is None:
        year, current_week = nflgame.live.current_year_and_week()
    if weeks is None:
        unused_var, current_week = nflgame.live.current_year_and_week()
        weeks = [x for x in range(1, current_week + 1)]

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

    stars = [[None]]

    #print "\nStars:"
    for p in players.sort('rushing_yds').limit(num_results):
        #print p, p.team, p.rushing_att, p.rushing_yds
        player = p, p.team, p.rushing_att, p.rushing_yds
        stars.append(player)

    print "\n\nBest Rushers: "
    count = 1
    for p in stars:
        if p[0] != None:
            name = p[0]
            team = p[1]
            attempts = p[2]
            yards = p[3]
            avg_yds_carry = int((float(yards) / attempts))
            print "{0:<2} {1:<16} {2:<3}  A:{3:<4} Y:{4:<5} AVG:{5:<2}".format(
                count, name, team, attempts, yards, avg_yds_carry)
            count += 1
Exemplo n.º 39
0
def team_targets(team):
    team_initials = nflgame.standard_team(team)
    if team_initials == 'SD':
        team_initials = 'LAC'
    if team_initials == 'JAC':
        team_initials = 'JAX'
    games = nflgame.games(2017, home=team_initials, away=team_initials)
    target_dict = {}
    for i, game in enumerate(games):
        target_dict[i + 1] = api.receiving_targets(game, team_initials)
    all_players = []
    for player_dict in target_dict.values():
        all_players += player_dict.keys()
    all_players = list(set(all_players))
    data = [[
        player_dict[player_name] if player_name in player_dict.keys() else ''
        for player_name in all_players
    ] for player_dict in target_dict.values()]
    background_colors = COLORS[:len(all_players)]
    labels = map(str, all_players)

    schedule = api.get_team_schedule(team_initials, 2017)
    print team_initials
    return render_template('team_targets.html',
                           team=team,
                           data=data,
                           background_colors=background_colors,
                           labels=labels,
                           schedule=convert(schedule),
                           teamInitials=team_initials)
Exemplo n.º 40
0
def get_defense_two_pt_returns(year, week):
    """Returns a dictionary of `players` and `teams` Counters, which store the
    number of defensive 2 point returns awarded to any player and team for a
    given week of play. This function is necessary because there don't seem to
    be easy ways to get this stat otherwise.
    """
    defense_two_pt_returns_dict = {
        'players': Counter(),
        'teams': Counter(),
    }
    for game in nflgame.games(year, week):
        home_team, away_team = game.home, game.away
        for play in nflgame.combine_plays([game]):
            if ('DEFENSIVE TWO-POINT ATTEMPT' in str(play)
                    and 'ATTEMPT SUCCEEDS' in str(play)):
                # Determine scoring team
                if play.team == home_team:
                    team = away_team
                else:
                    team = home_team
                # Guess scoring player. Can't find any stats for this, but the
                # scoring player is usually listed at the beginning of the
                # sentence before "ATTEMPT SUCCEEDS" in the play description.
                sentences = str(play).split('. ')
                i = -1
                while 'ATTEMPT SUCCEEDS' not in sentences[i + 1]:
                    i += 1
                player = sentences[i].split()[0]
                # Add to counters for player and team
                defense_two_pt_returns_dict['players'][player] += 1
                defense_two_pt_returns_dict['teams'][team] += 1
    return defense_two_pt_returns_dict
Exemplo n.º 41
0
 def make_team_stats(self):
     """
     Collect all stats for a given year, week(s), team(s).
     """
     for year in self.year:
         for week in self.week:
             if year < CURRENT_YEAR or (year == CURRENT_YEAR and week <= CURRENT_WEEK):
                 games = ng.games(year, week)
                 for game in games:
                     if 'home' in self.site and game.home in self.which_team:
                         home_team = self.teams[game.home][year][week]
                         home_team['OWN']['game'] = game
                         home_team['OWN']['OPP'] = game.away
                         home_team['OWN']['pts'] = game.score_home
                         home_team['OPP']['pts'] = game.score_away
                         home_team['OWN_TOTAL']['OPP'] = game.away
                         self.add_defense_stats(game.home, year, week, game)
                         self.add_passing_stats(game.home, year, week, game)
                         self.add_rushing_stats(game.home, year, week, game)
                     if 'away' in self.site and game.away in self.which_team:
                         away_team = self.teams[game.away][year][week]
                         away_team['OWN']['game'] = game
                         away_team['OWN']['OPP'] = '@ ' + game.home
                         away_team['OWN']['pts'] = game.score_away
                         away_team['OPP']['pts'] = game.score_home
                         away_team['OWN_TOTAL']['OPP'] = game.home
                         self.add_defense_stats(game.away, year, week, game)
                         self.add_passing_stats(game.away, year, week, game)
                         self.add_rushing_stats(game.away, year, week, game)
Exemplo n.º 42
0
def home_passing_tds_in_year(year, player, team):
    avg = 0.0
    home_games = nflgame.games(year, home=team)
    players = nflgame.combine(home_games)
    this_player = players.name(player)
    avg += this_player.passing_tds
    print year, this_player, this_player.passing_tds, (avg / 8)
Exemplo n.º 43
0
def matchup_weight(game, prev_seasons=2, verbose=False):

    # for convenience
    year, week = game['year'], game['week']
    home, away = game['home'], game['away']
    gamekey = game['gamekey']

    h_team = [home, away, home, away]
    a_team = [away, home, away, home]
    kinds = ['REG', 'REG', 'POST', 'POST']

    if verbose:
        print home, ' AT ', away, year, week
        print '---------'

    matchups = []
    for h, a, k in zip(h_team, a_team, kinds):
        try:
            game_matches = nflgame.games(year=range(year,
                                                    year - (prev_seasons + 1),
                                                    -1),
                                         home=h,
                                         away=a,
                                         kind=k)
            for g in game_matches:
                if g.schedule['gamekey'] != gamekey:
                    matchups.append(g)
        except (TypeError, AttributeError) as e:
            pass

    home_matchup_wins, away_matchup_wins = 0, 0
    for m in matchups:
        if verbose:
            print m, m.schedule['season_type'], m.schedule['year'], m.schedule[
                'week']

        if m.winner == home:
            home_matchup_wins += 1
        elif m.winner == away:
            away_matchup_wins += 1
        else:
            home_matchup_wins += 0.5
            away_matchup_wins += 0.5

    total = sum([home_matchup_wins, away_matchup_wins])
    if total == 0:
        home_matchup_wpct, away_matchup_wpct = 0, 0
    else:
        home_matchup_wpct = round(home_matchup_wins / float(total), 3)
        away_matchup_wpct = round(away_matchup_wins / float(total), 3)

    if verbose:
        print '---------'
        print '({}) {} - {} ({})'.format(home_matchup_wins, home, away,
                                         away_matchup_wins)
        print '{} - {}'.format(home_matchup_wpct, away_matchup_wpct)

        print '\n'

    return home_matchup_wpct - away_matchup_wpct
Exemplo n.º 44
0
def load_all_games(request):
    n = 0
    for w in range(17):
        games = nflgame.games(2016, week=w + 1)
        if len(games) == 0:
            break
        for game in games:

            home_name = str(game.home)
            away_name = str(game.away)

            # Small hack in case the Jacksonville Jaguars games are inputted
            # with 'JAX' and not 'JAC'
            if str(game.home) == 'JAX':
                home_name = 'JAC'
            elif str(game.away) == 'JAX':
                away_name = 'JAC'

            home_team = Team.objects.filter(short_name=home_name)[0]
            away_team = Team.objects.filter(short_name=away_name)[0]

            g = Game(home_team=home_team, away_team=away_team, week=w+1, home_score=game.score_home, away_score=game.score_away, \
             home_points_q1=game.score_home_q1, home_points_q2=game.score_home_q2, home_points_q3=game.score_home_q3, \
             home_points_q4=game.score_home_q4, away_points_q1=game.score_away_q1, away_points_q2=game.score_away_q2, \
             away_points_q3=game.score_away_q3, away_points_q4=game.score_away_q4)

            g.save()
            n += 1

    return HttpResponse('Loaded %d games' % n)
Exemplo n.º 45
0
def getPlayerStats(plyr, stat):
    game = nflgame.games(2012, week=[2, 3, 4, 6])
    players = nflgame.combine(game)
    player = players.name(plyr)
    playerStats = player.stats
    if stat in playerStats:
        print 'stat: ', stat, ' value = ', playerStats[stat]
Exemplo n.º 46
0
def print_top_receivers_by_ben(num_results=50):
    '''
    This will print players with highest targets and 
    show stats of completions and yardage gains.
    '''
    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)

    stars = [[None]]

    #print "\nStars:"
    for p in players.sort('receiving_tar').limit(num_results):
        #print p, p.receiving_tar, p.receiving_rec, p.receiving_yds
        player = p, p.team, p.receiving_tar, p.receiving_rec, p.receiving_yds
        stars.append(player)

    print "\n\nBest Receivers: "
    count = 1
    for p in stars:
        if p[0] != None:
            #print "%d. %s targets: %d times for a total of %d cmplts and %d yards." % (count, p[0], p[1], p[2], p[3])
            name = p[0]
            team = p[1]
            targets = p[2]
            cmplt = p[3]
            yards = p[4]
            completion_percent = int(100 * (float(cmplt) / targets))
            print "{0:<2} {1:<16} {2:<3}  T:{3:<4} R:{4:<4} Y:{5:<5} C:{6:<2}%".format(
                count, name, team, targets, cmplt, yards, completion_percent)
            count += 1
Exemplo n.º 47
0
    def updateScores(self):
        cur = self.conn.cursor()

        # query for all games that are not in final state
        sql = "Select id, week, home_team, away_team, season FROM games WHERE final=0 ORDER BY week"
        cur.execute(sql)

        week = 0
        games = None

        update_sql = ""
        #updated_spreads = {}
        for row in cur:
            print row
            if row[1] != week:
                week = row[1]
                # get schedule and results for the week
                games = nflgame.games(self.season,week=int(week))
                scores = {}
                final = {}
                for g in games:
                    print g
                    scores[self.getNflgameName(g.away)] = g.score_away;
                    scores[self.getNflgameName(g.home)] = g.score_home;
                    final[self.getNflgameName(g.home)] = g.game_over();

            season = row[4]
            table_id = row[0]
            home_team = row[2]
            away_team = row[3]

            home_score = scores[home_team]
            away_score = scores[away_team]

            single_sql = "UPDATE games SET home_score = %d, away_score = %d, final = %d WHERE id=%s;" % (home_score, away_score, final[home_team], table_id)

            if final[home_team] == True:
                away_margin = away_score - home_score
                home_margin = home_score - away_score

                #updated_spreads[home_team] = home_margin
                #updated_spreads[away_team] = away_margin

                home_spread_sql = 'UPDATE spreads SET cover = CASE WHEN spread + %d > 0 THEN 1.0 WHEN spread + %d < 0 THEN 0.0 ELSE 0.5 END WHERE team=\'%s\' AND week=%d AND season=%d;' % (home_margin, home_margin, home_team, week, self.season)
                away_spread_sql = 'UPDATE spreads SET cover = CASE WHEN spread + %d > 0 THEN 1.0 WHEN spread + %d < 0 THEN 0.0 ELSE 0.5 END WHERE team=\'%s\' AND week=%d AND season=%d;' % (away_margin, away_margin, away_team, week, self.season)

                update_sql = update_sql + home_spread_sql + away_spread_sql


            update_sql = update_sql + single_sql


        print update_sql
        if update_sql:
            cur.execute(update_sql)
            cur.connection.commit()


        cur.close()
Exemplo n.º 48
0
def update_stats(host, port, year, kind, game_week):
  games = nflgame.games(year, week = game_week, kind = kind)

  for nfl_game in games:
    game = Game(nfl_game, game_week)
    for player in game.all_players():
      update_player_stats(host, port, player)
      
Exemplo n.º 49
0
    def updateGames(self):
        #cur = self.conn.cursor()
        week = 15

        games = nflgame.games(self.season,week=int(week))
        for g in games:
            print g
            self.addGame(week, g.home, g.away)
def build_weekly_stats(season=2015, week=1):
    errors = 0
    new_week, _ = Week.objects.get_or_create(season=season,
                                             number=week)
    print "..filling in data for {}".format(new_week)
    games = nflgame.games(season.year, week=week)
    players = nflgame.combine_game_stats(games)

    # qb stats
    for p in players.passing().sort('passing_yds').limit(30):
        try:
            db_player = Player.objects.get(playerid=p.playerid)
        except Player.DoesNotExist:
            errors += 1
            continue
        else:
            weekly_stat, _ = WeeklyStats.objects.get_or_create(player=db_player,
                                                               season=season,
                                                               week=new_week)
            # qb stats
            weekly_stat.passing_attempts = p.passing_attempts
            weekly_stat.passing_cmps = p.passing_cmp
            weekly_stat.passing_yds = p.passing_yds
            weekly_stat.passing_tds = p.passing_tds
            weekly_stat.passing_ints = p.passing_ints
            weekly_stat.save()
    # rushing stats
    for p in players.rushing().sort('rushing_yds').limit(100):
        try:
            db_player = Player.objects.get(playerid=p.playerid)
        except Player.DoesNotExist:
            errors += 1
            continue
        else:
            weekly_stat, _ = WeeklyStats.objects.get_or_create(player=db_player,
                                                               season=season,
                                                               week=new_week)
            weekly_stat.rushing_yds = p.rushing_yds
            weekly_stat.rushing_atts = p.rushing_att
            weekly_stat.rushing_tds = p.rushing_tds
            weekly_stat.save()

    for p in players.receiving().sort('receiving_yds').limit(200):
        try:
            db_player = Player.objects.get(playerid=p.playerid)
        except Player.DoesNotExist:
            errors += 1
            continue
        else:
            weekly_stat, _ = WeeklyStats.objects.get_or_create(player=db_player,
                                                               season=season,
                                                               week=new_week)
            # rec stats
            weekly_stat.receiving_rec = p.receiving_rec
            weekly_stat.receiving_yds = p.receiving_yrds
            weekly_stat.receiving_tds = p.receiving_tds
            weekly_stat.save()
Exemplo n.º 51
0
def gather_players(seasons, weeks):
	for season in seasons:
		for week in weeks:
			game = nflgame.games(season, week=week)
			filename = '../nfl_game_data/' + str(season) + '_' + str(week) + '.csv'
                        try:
                                nflgame.combine_game_stats(game).csv(filename)
                        except TypeError:
                                continue
Exemplo n.º 52
0
def scoreboard(request):
    current_week = schedule.current_week()
    year = date.today().year
    games = nflgame.games(year, week=current_week)
    scores = []
    for x in games:
        scores.append(x)
    weeks = []
    for x in range(0,current_week):
        weeks.append(x+1)
    return render(request, 'scoreboard.html', {'scores':scores,'week':current_week, 'past_weeks':weeks, 'current_week':True})
Exemplo n.º 53
0
    def update_player_stats(self):
        print('Updating player stats...')

        for year, phase, week in update_sched.year_phase_week(year=self.year):
            if phase != 'PRE':
                print('    {} year: {}, week: {}'.format(phase, year, week))
                try:
                    games = nflgame.games(year, week, kind=phase)
                    real_week = week + 17 if phase == 'POST' else week
                    if len(games):
                        players = nflgame.combine_game_stats(games)

                        for player in players:
                            if player.player:
                                try:
                                    playerObj = NflPlayer.objects.get(gsis_id=player.player.player_id, active=True)
                                except ObjectDoesNotExist:
                                    #print('        Did not find {}: {}'.format(player.player.player_id, player))
                                    continue

                                try:
                                    stat = NflStat.objects.get(week=real_week, player=playerObj)
                                    # if player.player.player_id == '00-0026138':
                                    # if phase == 'POST':
                                    #     print('        Updating {}'.format(stat))
                                    # update the stat data
                                    stat.td = player.tds
                                    stat.fg = player.kicking_fpm
                                    stat.two = player.twoptm
                                    stat.xp = player.kicking_xpmade
                                    stat.diff = 0
                                    # if player.player.player_id == '00-0026138':
                                    #     print('    updating {}'.format(stat))
                                    stat.save()
                                except ObjectDoesNotExist:
                                    # create the stat
                                    # if player.player.player_id == '00-0026138':
                                    # if phase == 'POST':
                                    #     print('    Creating stat for {} {}'.format(week, player.player.player_id))
                                    stat = NflStat.objects.create(
                                        week = real_week,
                                        td = player.tds,
                                        fg = player.kicking_fgm,
                                        xp = player.kicking_xpmade,
                                        two = player.twoptm,
                                        diff = 0,
                                        player = playerObj
                                    )
                                    # if player.player.player_id == '00-0026138':
                                    #     print('    creating {}'.format(stat))
                                    stat.save()
                except TypeError:
                    # needed for nflgame not pulling post season data correctly
                    pass
Exemplo n.º 54
0
def playerstats(message, player, year, details='no'):
	year = int(year)
	response = 'Here are the stats for %s in %s:\n' % (player, year)

	# calculate games and players variables
	games = nflgame.games(year)
	players = nflgame.combine(games)

	if details == 'detailed':
		# this works to calculate games but specifying the team is MUCH faster:
		# #games = nflgame.games(year, home="PIT", away="PIT")
		#games = nflgame.games(year)
		bigben = nflgame.find(player)[0]
		# bigben -> Ben Roethlisberger (QB, PIT)
		# bigben.gsis_name -> B.Roethlisberger
		# bigben.position -> QB
		# bigben.team -> PIT

		# #TODO: complete this if logic for position-based stats
		# if bigben.position == 'QB':
		# 	# QB stats
		# if bigben.position == 'RB':
		# 	# RB stats
		# if bigben.position == 'WR':
		# 	# WR stats
		# if bigben.position == 'K':
		# 	# K stats
		
		# right now this is QB stats (hence the passing nomenclature)
		for i, game in enumerate(games):
		    if game.players.name(bigben.gsis_name):
		        stats = game.players.name(bigben.gsis_name).passing_yds
		        tds = game.players.name(bigben.gsis_name).passing_tds
		        response += '*Week {:2}* - {:3} yds, {:2} TD\n'.format(game.schedule['week'], stats, tds)

		response += '-'*25
		#players = nflgame.combine(games)
		response += '\n*{:4} Season - {:4} yds, {:2} TD*'.format(year, players.name(bigben.gsis_name).passing_yds, players.name(bigben.gsis_name).passing_tds)

	# if detailed stats are not requested, provide overall stats for the season
	else:
		#games = nflgame.games(year)
		#players = nflgame.combine(games)
		my_player = nflgame.find(player)[0]
		brady = players.name(my_player.gsis_name)
		response += '%d total yds, %d total TD in %d' % (brady.passing_yds, brady.passing_tds, year)

		# ne = nflgame.games(2010, home="NE", away="NE")
		# players = nflgame.combine(ne)
		# brady = players.name("T.Brady")
		# response += '%d, %d' % (brady.passing_tds, brady.passing_yds)

	message.reply(response)
Exemplo n.º 55
0
def get_games(uptoweek):
    if uptoweek in week_to_games_cache.keys():
        return week_to_games_cache.get(uptoweek)
    weekstoget = []
    i = 1
    while i < uptoweek:
        weekstoget.append(i)
        i += 1
    games = []
    if len(weekstoget) > 0:
        games = nflgame.games(2015, weekstoget)
    week_to_games_cache[uptoweek] = games
    return games
Exemplo n.º 56
0
def k_stats(player_id, year, wk, team):
    # takes player's full name, year of game(s), week of game(s), player team
    # applies for all kickers
    stats = {'fgmade':0, 'fga':0, 'xpmade':0, 'xpa':0}
    games = nflgame.games(year, week=wk, home=team, away=team)
    gameplayers = nflgame.combine_game_stats(games)
    for p in gameplayers:
        if p.playerid == player_id:
            stats['fgmade']=p.kicking_fgm
            stats['fga']=p.kicking_fga
            stats['xpmade']=p.kicking_xpmade
            stats['xpa']=p.kicking_xpa
    return stats
Exemplo n.º 57
0
def rushingyards(playerid,team,year,week=None):
  try:
    rushing_yds_per_att = []
    current_year = 2016
    current_week = 17
    if week:
      weeks = [int(week)]
    else:
      current_year, current_week = nflgame.live.current_year_and_week()
      weeks = [x for x in range(1, current_week+1)] if int(year) == int(current_year) else [x for x in range(1, 18)]

    try:
      games = nflgame.games(int(year), week=weeks, home=team, away=team)
    except (ValueError, KeyError, TypeError):
      print "FAILED"
      return jsonify(result = rushing_yds_per_att)

    if games != []:
      allplays = nflgame.combine_plays(games)
      player_position = nflgame.players[playerid].position
      for p in allplays:
        if p.has_player(playerid):
          if (p.receiving_tar==1) or (p.rushing_att==1):
            if p.rushing_att==1:
              type = 'RUSH'
            elif p.receiving_rec==1:
              type = 'PASS'
            else:
              type = 'INCOMPLETE'
            if (player_position == 'QB') and (type == 'PASS' or type == 'INCOMPLETE'):
              pass
            else:
              play = {
                'type': type, 
                'yards': p.rushing_yds if p.rushing_att==1 else p.receiving_yds, 
                # 'desc': str(re.sub(r'\([^)]*\)', '', p.desc)), 
                'desc': str(p.desc), 
                'down': str(p.down) + ' and ' + str(p.yards_togo),
                'time': str(p.time),
                'position': str(p.yardline),
                'game': str(p.drive.game), 
                'week': p.drive.game.schedule['week']
              }
              rushing_yds_per_att.append(play)

    else:
      print "EMPTY"
    gc.collect()
    return jsonify(result = rushing_yds_per_att)
  except (ValueError, KeyError, TypeError):
    abort(400, 'custom error message to appear in body')
Exemplo n.º 58
0
    def tryToGetStats(self, year, week=None):
        # Try to fetch games
        try:
            stats = nflgame.games(year, week)
        except TypeError:
            # The nflgame api returns a TypeError when the year or week doesn't have data
            print 'Type Error: Invalid Year or Week passed to tryToGetStats'
            return False
        except:
            # Anything but a TypeError means something has gone terribly wrong
            print "Unexpected error:", sys.exc_info()[0]
            raise

        return stats