Esempio n. 1
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})
Esempio n. 2
0
def show_season_table(db, player, stype, week_range=None, pos=None):
    if pos is None:
        pos = player.position
    _, cur_year, _ = nfldb.current(db)

    pstats = []
    for year in range(2009, cur_year+1):
        qgames = nflcmd.query_games(db, player, year, stype, week_range)
        games = qgames.as_games()
        if len(games) == 0:
            continue

        game_stats = map(partial(nflcmd.Game.make, db, player), games)
        agg = qgames.sort([]).as_aggregate()
        pstats.append(nflcmd.Games(db, year, game_stats, agg[0]))

    spec = prefix_season + nflcmd.columns['season'][nflcmd.pcolumns[pos]]
    rows = [nflcmd.header_row(spec)]
    rows += map(partial(nflcmd.pstat_to_row, spec), pstats)
    if len(pstats) > 1:
        summary = nfldb.aggregate(pstat._pstat for pstat in pstats)[0]
        allrows = nflcmd.Games(db, '-', [], summary)
        allrows._fgs = []
        for pstat in pstats:
            allrows._fgs += pstat.fgs
            allrows.games += pstat.games
        rows.append(nflcmd.pstat_to_row(spec, allrows))
    print(nflcmd.table(rows))
def prediction_feature_set(db, pipe, infoColumns, pred_year=None, pred_week=None, player_ids=None):
    pipe.set_params(pipe1__data__db=db)

    ### prediction data
    # get information we need to make predictions
    season_phase, cur_year, cur_week = nfldb.current(db)
    if(pred_year is None):
        pred_year = cur_year

    if(pred_week is None):
        pred_week = cur_week + 1

    pred_yr_wk = [(j, i) for j in range(2009,pred_year-1) for i in range(1,18)]
    pred_yr_wk += [(pred_year, i) for i in range(1,pred_week+1)]

    pipe.set_params(pipe1__data__yr_wk = pred_yr_wk)

    if(player_ids is None):
        player_ids = week_player_id_list(db, pred_year, pred_week, position='RB')

    pred_data = pipe.fit_transform(player_ids)
    pred_info = infoColumns.fit_transform(X=pred_data)

    # get extra info like team and opponent
    # should probably be put in to infoColumns transformer later
    extra_info = player_current_game_info(db, year=pred_year, week=pred_week, player_ids = list(pred_info['player_id']))
    join_on = ['player_id']
    add_on = ['team', 'opp_team', 'at_home']
    pred_info = pred_info.join(extra_info.set_index(join_on).loc[:,add_on], on=join_on)

    # predict for the last week
    pred_yr_wk_t = [pred_yr_wk[-1]]
    garbage_i, predict_i = split_by_year_week(pred_data, pred_yr_wk_t)

    return((pred_data, predict_i, pred_info, (pred_year, pred_week)))
Esempio n. 4
0
def schedule(bot, trigger):
    season_type, season_year, current_week = nfldb.current(db)
    if current_week is None:
        bot.reply('not currently in season')
        return
    name = trigger.group(2)
    team = nfldb.standard_team(name)
    p = None
    if team == 'UNK':
        results = nfldb.player_search2(db, name, limit=1000)
        if len(results) == 0:
            bot.reply("No player or team matching that name could be found")
            return
        else:
            p = results[0][0]
            team = p.team
    weeks = range(18)
    q = nfldb.Query(db).game(season_type=season_type,
                             season_year=season_year,
                             week=weeks[current_week:current_week + 5],
                             team=team)
    message = []
    if p is not None:
        message.append('Upcoming schedule for %s' % p)
    else:
        message.append('Upcoming schedule for %s' % team)
    for g in q.sort(('week', 'asc')).as_games():
        message.append(str(g))
    say_multiline(bot, '\n'.join(message))
Esempio n. 5
0
def schedule(bot, trigger):
    season_type, season_year, current_week = nfldb.current(db)
    if current_week is None:
        bot.reply("not currently in season")
        return
    name = trigger.group(2)
    team = nfldb.standard_team(name)
    p = None
    if team == "UNK":
        results = nfldb.player_search2(db, name, limit=1000)
        if len(results) == 0:
            bot.reply("No player or team matching that name could be found")
            return
        else:
            p = results[0][0]
            team = p.team
    weeks = range(18)
    q = nfldb.Query(db).game(
        season_type=season_type, season_year=season_year, week=weeks[current_week : current_week + 5], team=team
    )
    message = []
    if p is not None:
        message.append("Upcoming schedule for %s" % p)
    else:
        message.append("Upcoming schedule for %s" % team)
    for g in q.sort(("week", "asc")).as_games():
        message.append(str(g))
    say_multiline(bot, "\n".join(message))
Esempio n. 6
0
def v_home():
    phase, season, week = nfldb.current(db)
    params = { 'season': season, 'phase': phase, 'week': week }
    url = bottle.default_app().get_url('v_games', **params)
    bottle.response.status = 302
    bottle.response.set_header('Location', url)
    return ''
Esempio n. 7
0
def v_home():
    phase, season, week = nfldb.current(db)
    params = {'season': season, 'phase': phase, 'week': week}
    url = bottle.default_app().get_url('v_games', **params)
    bottle.response.status = 302
    bottle.response.set_header('Location', url)
    return ''
Esempio n. 8
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")
Esempio n. 9
0
def gameforecast(bot, trigger):
    """.gameforecast denver gives the forecast for the denver game this week"""
    week = None
    team = nfldb.standard_team(trigger.group(2))
    if team == 'UNK':
        bot.reply('I do not know that team')
        return

    season_type, season_year, current_week = nfldb.current(db)
    if week is None:
        if current_week is None:
            bot.reply('Not currently in season')
            return
        week = current_week

    q = nfldb.Query(db).game(season_type='Regular',
                             season_year=season_year,
                             week=week,
                             team=team)
    games = q.as_games()
    if len(games) == 0:
        bot.reply('%s is on BYE' % team)
        return

    g = games[0]
    start_time = g.start_time
    stadium = stadiums[g.home_team]
    lat, lon = stadium[2]
    output = []
    output.append('Kickoff forecast for %s at %s %s' %
                  (g.away_team, g.home_team,
                   g.start_time.strftime('%Y-%m-%d %I:%M:%S%p')))
    if stadium[3] == False:
        try:
            forecast = forecastio.load_forecast(forecastio_api_key,
                                                lat,
                                                lon,
                                                time=start_time,
                                                units='us')
            output.append(
                u'%s %s\u00B0F windspeed %smph from the %s chance of precip %s%%'
                % (forecast.currently().d['summary'],
                   forecast.currently().d['temperature'],
                   forecast.currently().d['windSpeed'],
                   windbearing(forecast.currently().d['windBearing']),
                   forecast.currently().d['precipProbability']))
        except:
            output.append('there was an error getting the forecast')
    else:
        output.append('Dome')

    say_multiline(bot, '\n'.join(output))
Esempio n. 10
0
def correct_years_pro(player_id, db):
    global players

    db_season = nfldb.current(db)[1]
    seasons = [s for s in players[player_id]['seasons']]
    last_season_played = max(seasons)

    for season in seasons:
        # player retired
        if int(db_season) - int(last_season_played) > 1:
            players[player_id]['seasons'][season]['years_pro'] -= int(last_season_played) - int(season)
        else:
            players[player_id]['seasons'][season]['years_pro'] -= int(db_season) - int(season)
Esempio n. 11
0
def update_current_week_schedule(db):
    update_nflgame_schedules()

    phase_map = nfldb.types.Enums._nflgame_season_phase
    phase, year, week = nfldb.current(db)
    log('Updating schedule for (%s, %d, %d)' % (phase, year, week))
    with nfldb.Tx(db) as cursor:
        for gsis_id, info in nflgame.sched.games.items():
            if year == info['year'] and week == info['week'] \
                    and phase == phase_map[info['season_type']]:
                g = game_from_id(cursor, gsis_id)
                for table, prim, vals in g._rows:
                    nfldb.db._upsert(cursor, table, vals, prim)
    log('done.')
Esempio n. 12
0
def update_current_week_schedule(db):
    update_nflgame_schedules()

    phase_map = nfldb.types.Enums._nflgame_season_phase
    phase, year, week = nfldb.current(db)
    log('Updating schedule for (%s, %d, %d)' % (phase, year, week))
    with nfldb.Tx(db) as cursor:
        for gsis_id, info in dict(nflgame.sched.games).items():
            if year == info['year'] and week == info['week'] \
                    and phase == phase_map[info['season_type']]:
                g = game_from_id(cursor, gsis_id)
                for table, prim, vals in g._rows:
                    nfldb.db._upsert(cursor, table, vals, prim)
    log('done.')
Esempio n. 13
0
def v_query():
    params = bottle.request.params
    args = {}
    if 'game_season_year' in params:
        args['season'] = params.get('game_season_year')
    if 'game_season_type' in params:
        args['phase'] = as_phase(params.get('game_season_type'))
    if 'game_week' in params:
        args['week'] = params.get('game_week')

    phase, season, week = nfldb.current(db)
    args.setdefault('season', season)
    args.setdefault('phase', phase)
    args.setdefault('week', week)
    return template('query', **args)
Esempio n. 14
0
def v_query():
    params = bottle.request.params
    args = {}
    if 'game_season_year' in params:
        args['season'] = params.get('game_season_year')
    if 'game_season_type' in params:
        args['phase'] = as_phase(params.get('game_season_type'))
    if 'game_week' in params:
        args['week'] = params.get('game_week')

    phase, season, week = nfldb.current(db)
    args.setdefault('season', season)
    args.setdefault('phase', phase)
    args.setdefault('week', week)
    return template('query', **args)
Esempio n. 15
0
def gameforecast(bot, trigger):
    """.gameforecast denver gives the forecast for the denver game this week"""
    week = None
    team = nfldb.standard_team(trigger.group(2))
    if team == "UNK":
        bot.reply("I do not know that team")
        return

    season_type, season_year, current_week = nfldb.current(db)
    if week is None:
        if current_week is None:
            bot.reply("Not currently in season")
            return
        week = current_week

    q = nfldb.Query(db).game(season_type="Regular", season_year=season_year, week=week, team=team)
    games = q.as_games()
    if len(games) == 0:
        bot.reply("%s is on BYE" % team)
        return

    g = games[0]
    start_time = g.start_time
    stadium = stadiums[g.home_team]
    lat, lon = stadium[2]
    output = []
    output.append(
        "Kickoff forecast for %s at %s %s" % (g.away_team, g.home_team, g.start_time.strftime("%Y-%m-%d %I:%M:%S%p"))
    )
    if stadium[3] == False:
        try:
            forecast = forecastio.load_forecast(forecastio_api_key, lat, lon, time=start_time, units="us")
            output.append(
                u"%s %s\u00B0F windspeed %smph from the %s chance of precip %s%%"
                % (
                    forecast.currently().d["summary"],
                    forecast.currently().d["temperature"],
                    forecast.currently().d["windSpeed"],
                    windbearing(forecast.currently().d["windBearing"]),
                    forecast.currently().d["precipProbability"],
                )
            )
        except:
            output.append("there was an error getting the forecast")
    else:
        output.append("Dome")

    say_multiline(bot, "\n".join(output))
Esempio n. 16
0
def get_player_stats_by_season(player_id, db):
    season_type, current_year, week = nfldb.current(db)
    player_seasons = []
    for year in range(2000, current_year):
        q = nfldb.Query(db).player(player_id=player_id)
        res = q.game(season_year=year).as_aggregate()
        if(len(res) == 1):
            agg = res[0]
            pass_avg, rushing_avg, receiving_avg = get_averages(agg)
            player_seasons.append({
                'player': agg,
                'season': year,
                'pass_avg': pass_avg,
                'rushing_avg': rushing_avg,
                'receiving_avg': receiving_avg})
    return player_seasons
Esempio n. 17
0
def schedule_week(bot, trigger):
    week = None
    if trigger.group(2) is not None:
        try:
            week = int(trigger.group(2))
        except:
            bot.reply("not a valid week")
            return
    season_type, season_year, current_week = nfldb.current(db)
    if season_year is None:
        bot.say("not currently in season")
        return
    if week is None:
        week = current_week
    q = nfldb.Query(db).game(season_type="Regular", season_year=season_year, week=week)
    message = [str(g) for g in q.sort(("start_time", "asc")).as_games()]
    say_multiline(bot, "\n".join(message))
Esempio n. 18
0
def schedule_week(bot, trigger):
    week = None
    if trigger.group(2) is not None:
        try:
            week = int(trigger.group(2))
        except:
            bot.reply('not a valid week')
            return
    season_type, season_year, current_week = nfldb.current(db)
    if season_year is None:
        bot.say('not currently in season')
        return
    if week is None:
        week = current_week
    q = nfldb.Query(db).game(season_type='Regular',
                             season_year=season_year,
                             week=week)
    message = [str(g) for g in q.sort(('start_time', 'asc')).as_games()]
    say_multiline(bot, '\n'.join(message))
Esempio n. 19
0
def get_player_stats_by_game(player_id, db):
    # Get the season typ, year, and week
    season_type, year, week = nfldb.current(db)
    q = nfldb.Query(db).player(player_id=player_id)
    games = q.game(
        season_year=year,
        season_type=season_type,
        week__le=week).sort(
        ('week',
         'asc')).as_games()
    player_games = []
    for game in games:
        agg = nfldb.Query(db).player(
            player_id=player_id).game(
            gsis_id=game.gsis_id).as_aggregate()[0]
        pass_avg, rushing_avg, receiving_avg = get_averages(agg)
        player_games.append({'player': agg,
                             'game': game,
                             'pass_avg': pass_avg,
                             'rushing_avg': rushing_avg,
                             'receiving_avg': receiving_avg})
    return player_games
Esempio n. 20
0
def run():
    """Runs the `nflstats` command."""
    db = nfldb.connect()
    _, cur_year, _ = nfldb.current(db)

    parser = argparse.ArgumentParser(
        description='Show NFL game stats for a player.')
    aa = parser.add_argument
    aa(dest='player_query', metavar='PLAYER', nargs='+')
    aa('--team', type=str, default=None,
       help='Specify the team of the player to help the search.')
    aa('--pos', type=str, default=None,
       help='Specify the position of the player to help the search.')
    aa('--soundex', action='store_true',
       help='When set, player names are compared using Soundex instead '
            'of Levenshtein.')
    aa('--year', type=str, default=cur_year,
       help='Show game logs for only this year. (Not applicable if '
            '--season is set.)')
    aa('--pre', action='store_true',
       help='When set, only games from the preseason will be used.')
    aa('--post', action='store_true',
       help='When set, only games from the postseason will be used.')
    aa('--weeks', type=str, default='',
       help='Show stats only for the inclusive range of weeks given,\n'
            'e.g., "4-8". Other valid examples: "4", "-8",\n'
            '"4-". Has no effect when --season is used.')
    aa('--season', action='store_true',
       help='When set, statistics are shown by season instead of by game.')
    aa('--show-as', type=str, default=None,
       help='Force display of player as a particular position. This may need '
            'to be set for inactive players.')
    args = parser.parse_args()

    args.player_query = ' '.join(args.player_query)
    player = nflcmd.search(db, args.player_query, args.team, args.pos,
                           args.soundex)
    if player is None:
        eprint("Could not find a player given the criteria.")
        sys.exit(1)
    print('Player matched: %s' % player)

    week_range = nflcmd.arg_range(args.weeks, 1, 17)
    stype = 'Regular'
    if args.pre:
        stype = 'Preseason'
    if args.post:
        stype = 'Postseason'


    pos = None
    if args.show_as is not None:
        pos = nfldb.Enums.player_pos[args.show_as]
    elif player.position == nfldb.Enums.player_pos.UNK:
        q = nfldb.Query(db)
        q.play_player(player_id=player.player_id)
        q.sort(('gsis_id', 'desc'))
        pos = nfldb.guess_position(q.as_play_players())
        if pos == nfldb.Enums.player_pos.UNK:
            eprint("The player matched is not active and I could not guess\n"
                   "his position. Specify it with the '--show-as' flag.")
            sys.exit(1)
        print("Guessed position: %s" % pos)

    if args.season:
        show_season_table(db, player, stype, week_range, pos)
    else:
        show_game_table(db, player, args.year, stype, week_range, pos)
Esempio n. 21
0
def rest_current():
    phase, season, week = nfldb.current(db)
    return {'phase': str(phase), 'season': season, 'week': week}
Esempio n. 22
0
def rest_current():
    phase, season, week = nfldb.current(db)
    return {'phase': str(phase), 'season': season, 'week': week}
Esempio n. 23
0
	        data.append(row)

	data = pd.DataFrame(data)
	return data

if False:

	players2dict(player_id2player(week_player_id_list(db, 2015, 6)))

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

	players2dict(player_id2player(week_player_id_list(db, 2015, 6)))

	# get current season phase, year, week
	season_phase, cur_year, cur_week = nfldb.current(db)

	pred_week = cur_week

	# master list of teams - all teams play in week 1
	all_teams = week_team_list(db, cur_year, week=1)

	# master list of players
	all_players = players2dict(nfldb.Query(db).player(team=all_teams).as_players())

	# list of teams playing for a week
	week_teams = week_team_list(db, cur_year, week=pred_week)

	# list of all players on those teams
	week_players = [plyr for plyr in all_players if plyr['team'] in week_teams]
Esempio n. 24
0
def run():
    """Runs the `nflrank` command."""
    db = nfldb.connect()
    _, cur_year, _ = nfldb.current(db)

    parser = argparse.ArgumentParser(
        description='Show NFL player rankings for statistical categories.')
    aa = parser.add_argument
    aa(dest='categories', metavar='CATEGORY', nargs='+')
    aa('--years', type=str, default=str(cur_year),
       help='Show rankings only for the inclusive range of years given,\n'
            'e.g., "2010-2011". Other valid examples: "2010", "-2010",\n'
            '"2010-".')
    aa('--weeks', type=str, default='',
       help='Show rankings only for the inclusive range of weeks given,\n'
            'e.g., "4-8". Other valid examples: "4", "-8",\n'
            '"4-".')
    aa('--pre', action='store_true',
       help='When set, only data from the preseason will be used.')
    aa('--post', action='store_true',
       help='When set, only data from the postseason will be used.')
    aa('--pos', type=str, default=[], nargs='+',
       help='When set, only show players in the given positions.')
    aa('--teams', type=str, default=[], nargs='+',
       help='When set, only show players currently on the given teams.')
    aa('--limit', type=int, default=10,
       help='Restrict the number of results shown.')
    args = parser.parse_args()

    for cat in args.categories:
        if cat not in nfldb.stat_categories:
            eprint("%s is not a valid statistical category.", cat)
            sys.exit(1)

    stype = 'Regular'
    if args.pre:
        stype = 'Preseason'
    if args.post:
        stype = 'Postseason'

    years = nflcmd.arg_range(args.years, 2009, cur_year)
    weeks = nflcmd.arg_range(args.weeks, 1, 17)

    def to_games(agg):
        syrs = years[0] if len(years) == 1 else '%d-%d' % (years[0], years[-1])
        qgames = nflcmd.query_games(db, agg.player, years, stype, weeks)
        return nflcmd.Games(db, syrs, qgames.as_games(), agg)

    catq = nfldb.QueryOR(db)
    for cat in args.categories:
        k = cat + '__ne'
        catq.play_player(**{k: 0})

    q = nfldb.Query(db)
    q.game(season_year=years, season_type=stype, week=weeks)
    q.andalso(catq)
    if len(args.pos) > 0:
        posq = nfldb.QueryOR(db)
        for pos in args.pos:
            posq.player(position=nfldb.Enums.player_pos[pos])
        q.andalso(posq)
    if len(args.teams) > 0:
        q.player(team=args.teams)
    q.sort([(cat, 'desc') for cat in args.categories])
    q.limit(args.limit)
    pstats = map(to_games, q.as_aggregate())

    spec = ['name', 'team', 'game_count'] + args.categories
    rows = [nflcmd.header_row(spec)]
    rows += map(partial(nflcmd.pstat_to_row, spec), pstats)
    print(nflcmd.table(rows))
Esempio n. 25
0
            print format(field + ':', '8s') + '  ' + format(
                str(field_val), '8s') + ' * ' + format(str(getattr(
                    pp, field)), '8s') + ' = ' + format(
                        str(getattr(pp, field) * field_val), '8s')


def playerGames(player, game, cur_player):
    if (cur_player.full_name == player):
        print player + ' - week ' + str(
            game.week) + ': ' + game.home_team + ' VS ' + game.away_team


#get a DB connection
db = nfldb.connect()
#get current status of the season
db_season_phase = nfldb.current(db)[
    0]  #can be preseacon, regular, or postseason
db_season_year = nfldb.current(db)[1]  #current season year
db_current_week = nfldb.current(db)[2]  #current week of this season phase

#positions_sort is used later to figure out the best position player out of a group
positions_sort = {
    'QB': 'passing_yds',
    'RB': 'rushing_yds',
    'WR': 'receiving_yds',
    'TE': 'receiving_yds',
    'K': 'kicking_fgm'
}
#take the RealDictRows returned from the DB query and convert them to dictionaries
#with extra attributes for each player category we can work with
positions = ['QB', 'RB', 'WR', 'TE', 'K']