๐Ÿ“ฆ BurntSushi / nflgame

๐Ÿ“„ compare-with-yahoo ยท 348 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348#!/usr/bin/env python2

# The purpose of this script is to test the aggregate accuracy of statistics
# reported by nflgame. This is done by assuming a ground truth, which we take
# from Yahoo for each position: http://sports.yahoo.com/nfl/stats/byposition.
# The output of the test is a mirror of the input: a new csv file for each
# input csv file where the data represents the difference between nflgame's
# statistics and Yahoo's statistics. They are reported in terms of the ground
# truth. e.g., "5" means nflgame reports a number 5 more than Yahoo and
# "-5" means nflgame reports a number 5 fewer than Yahoo. Consequently, "0"
# means they agree exactly.
#
# Note that I've had to do some manual post-processing to the Yahoo data.
# In particular, the column names are not unique. So for example, in the
# QB data, there are two "Yds" columns. The first refers to passing yards
# while the second refers to rushing yards. I renamed the second to "RYds".
# I did something similar for other columns and other positions. See the
# "statmap" dictionary below for the correct names.
#
# The secondary purpose of this script is to facilitate debugging. Namely, it
# should provide command line parameters to alter the way nflgame computes
# statistics (play-by-play, game-level or heuristically combined), and provide
# a means to drill down into the relevant statistics of a particular player on
# a game-by-game basis.
#
# Finally, this program makes a few assumptions about the input data:
#
#   - That each file has the suffix `{POSITION}.csv`, where position is
#     one of the 12 positions offered by Yahoo (e.g., DE, DT, QB, etc.).
#   - That the columns in the data correspond exactly to the columns on
#     the Yahoo page. The order does not matter, but the names must match.
#   - The names of players match those on NFL.com.
#     (I might be able to relax this assumption with fuzzy matching. Dunno.)

# N.B. As of now, this script is an atrocious mess. I plan to upend it once
# nfldb rounds out. I'll test nflgame by proxy with nfldb (it'll be much
# much quicker). The player name matching crap below will be built into
# nfldb too.

import argparse
from collections import OrderedDict
import csv
import heapq
import os
import os.path as path
import sys

import Levenshtein

import nflgame

parser = argparse.ArgumentParser(
    description='Test the aggregate accuracy of nflgame\'s statistics.',
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)
aa = parser.add_argument
aa('output_dir', type=str,
   help='The output directory to store the differences of each statistic '
        'at all positions given.')
aa('season', type=int, help='The year of the season to test.')
aa('yahoo_data_files', type=str, nargs='+',
   help='The yahoo data files to use to test nflgame with. '
        'They should each have a suffix like {POSITION}.tsv.')
aa('--which-stats', type=str, choices=['max', 'game', 'play'], default='max',
   help='The type of statistical combination to use. Max is the default '
        'and tries to use both game and play statistics. Game uses only '
        'game level statistics, which is not as detailed. Play uses only '
        'play-by-play statistics in the aggregate.')
args = parser.parse_args()

args.output_dir += '-%s' % args.which_stats
if not os.access(args.output_dir, os.R_OK):
    os.makedirs(args.output_dir)

def standard_position(pos):
    pos = pos.upper()
    if pos in ('QB', 'RB', 'WR', 'K', 'P'):
        return pos
    if pos == 'FB':
        return 'RB'
    if pos == 'TE':
        return 'WR'
    return 'DEF'

def standard_name(player):
    if player.player is not None:
        return player.player.name.lower()
    else:
        return player.name.lower()

def shrink_name(name):
    first, rest = name.split(' ', 1)
    return '%s.%s' % (first[0], rest)

def ratio(n1, n2):
    return Levenshtein.ratio(unicode(n1.lower()), unicode(n2.lower()))

def edit_name(p, name):
    if p.player is not None:
        return ratio(p.player.name, name)
    else:
        name = shrink_name(name)
        if p.name[0].lower() != name[0].lower():
            return 0.0
        return ratio(p.name, name)

if args.which_stats == 'game':
    players = nflgame.combine_game_stats(nflgame.games_gen(args.season))
elif args.which_stats == 'play':
    players = nflgame.combine_play_stats(nflgame.games_gen(args.season))
else:
    players = nflgame.combine_max_stats(nflgame.games_gen(args.season))
indexed = {}
for p in players:
    indexed[p.playerid] = p

def find(name, team=None, pos=None):
    if pos is not None:
        pos = standard_position(pos)

    result = []
    for pid, p in indexed.iteritems():
        if pos is not None and pos != standard_position(p.guess_position):
            continue

        r = edit_name(p, name)
        if r >= 0.8:
            result.append((r, pid))
    if len(result) == 0:
        return None, 0.0

    result = heapq.nlargest(1, result)
    if team is not None and result[0][0] < 0.85:
        sameteam = lambda (r, pid): \
            nflgame.standard_team(team) == indexed[pid].team
        result = filter(sameteam, result)
        if len(result) == 0:
            return None, 0.0
    return indexed[result[0][1]], result[0][0]

# Create a mapping between fields in the Yahoo CSV file and statistical
# categories in nflgame.
# Anything not in the mapping is skipped.
negatives = ['passing_sk_yds', 'defense_sk_yds']
statmap = {
    'QB': OrderedDict([
        ('G', 'games'),
        ('Comp', 'passing_cmp'),
        ('Att', 'passing_att'),
        ('Yds', 'passing_yds'),
        ('TD', 'passing_tds'),
        ('Int', 'passing_int'),
        ('Rush', 'rushing_att'),
        ('RYds', 'rushing_yds'),
        ('RTD', 'rushing_tds'),
        ('Sack', 'passing_sk'),
        ('YdsL', 'passing_sk_yds'),
        ('Fum', 'fumbles_tot'),
        ('FumL', 'fumbles_lost'),
    ]),
    'RB': OrderedDict([
        ('G', 'games'),
        ('Rush', 'rushing_att'),
        ('Yds', 'rushing_yds'),
        ('TD', 'rushing_tds'),
        ('Rec', 'receiving_rec'),
        ('Tgt', 'receiving_tar'),
        ('RcYds', 'receiving_yds'),
        # ('YAC', 'receiving_yac_yds'), # this is an average? wtf?
        ('RcTD', 'receiving_tds'),
        ('Fum', 'fumbles_tot'),
        ('FumL', 'fumbles_lost'),
    ]),
    'WR': OrderedDict([
        ('G', 'games'),
        ('Rec', 'receiving_rec'),
        ('Tgt', 'receiving_tar'),
        ('Yds', 'receiving_yds'),
        # ('YAC', 'receiving_yac_yds'), # this is an average? wtf?
        ('TD', 'receiving_tds'),
        ('Fum', 'fumbles_tot'),
        ('FumL', 'fumbles_lost'),
    ]),
    'TE': OrderedDict([
        ('G', 'games'),
        ('Rec', 'receiving_rec'),
        ('Tgt', 'receiving_tar'),
        ('Yds', 'receiving_yds'),
        # ('YAC', 'receiving_yac_yds'), # this is an average? wtf?
        ('TD', 'receiving_tds'),
        ('Rush', 'rushing_att'),
        ('RYds', 'rushing_yds'),
        ('RTD', 'rushing_tds'),
        ('Fum', 'fumbles_tot'),
        ('FumL', 'fumbles_lost'),
    ]),
    'K': OrderedDict([
        ('G', 'games'),
        # Lame. Want to test field goal ranges too.
        # Can do it, but it isn't included in the aggregate data.
        # Maybe in nfldb?
        ('FGM', 'kicking_fgm'),
        ('FGA', 'kicking_fga'),
        ('XPM', 'kicking_xpmade'),
        ('XPA', 'kicking_xpa'),
    ]),
    'P': OrderedDict([
        ('G', 'games'),
        ('Punt', 'punting_tot'),
        ('Yds', 'punting_yds'),
        ('In20', 'punting_i20'),
        # No aggregate stats for "inside 10" :-(
        # No aggregate stats for fair catches either (for punters).
        ('TB', 'punting_touchback'),
        ('Blk', 'punting_blk'),
    ]),
    'CB': OrderedDict([
        ('G', 'games'),
        ('Solo', 'defense_tkl'),
        ('Ast', 'defense_ast'),
        ('Sack', 'defense_sk'),
        ('YdsL', 'defense_sk_yds'),
        ('Int', 'defense_int'),
        ('Yds', 'defense_int_yds'),
        ('IntTD', 'defense_int_tds'),
        ('DefTD', 'defense_tds'),
        ('FFum', 'defense_ffum'),
        ('PD', 'defense_pass_def'),
        ('Sfty', 'defense_safe'),
    ]),
    'S': OrderedDict([
        ('G', 'games'),
        ('Solo', 'defense_tkl'),
        ('Ast', 'defense_ast'),
        ('Sack', 'defense_sk'),
        ('YdsL', 'defense_sk_yds'),
        ('Int', 'defense_int'),
        ('Yds', 'defense_int_yds'),
        ('IntTD', 'defense_int_tds'),
        ('DefTD', 'defense_tds'),
        ('FFum', 'defense_ffum'),
        ('PD', 'defense_pass_def'),
        ('Sfty', 'defense_safe'),
    ]),
    'LB': OrderedDict([
        ('G', 'games'),
        ('Solo', 'defense_tkl'),
        ('Ast', 'defense_ast'),
        ('Sack', 'defense_sk'),
        ('YdsL', 'defense_sk_yds'),
        ('Int', 'defense_int'),
        ('Yds', 'defense_int_yds'),
        ('IntTD', 'defense_int_tds'),
        ('DefTD', 'defense_tds'),
        ('FFum', 'defense_ffum'),
        ('PD', 'defense_pass_def'),
        ('Sfty', 'defense_safe'),
    ]),
    'DE': OrderedDict([
        ('G', 'games'),
        ('Solo', 'defense_tkl'),
        ('Ast', 'defense_ast'),
        ('Sack', 'defense_sk'),
        ('YdsL', 'defense_sk_yds'),
        ('Int', 'defense_int'),
        ('Yds', 'defense_int_yds'),
        ('IntTD', 'defense_int_tds'),
        ('DefTD', 'defense_tds'),
        ('FFum', 'defense_ffum'),
        ('PD', 'defense_pass_def'),
        ('Sfty', 'defense_safe'),
    ]),
    'DT': OrderedDict([
        ('G', 'games'),
        ('Solo', 'defense_tkl'),
        ('Ast', 'defense_ast'),
        ('Sack', 'defense_sk'),
        ('YdsL', 'defense_sk_yds'),
        ('Int', 'defense_int'),
        ('Yds', 'defense_int_yds'),
        ('IntTD', 'defense_int_tds'),
        ('DefTD', 'defense_tds'),
        ('FFum', 'defense_ffum'),
        ('PD', 'defense_pass_def'),
        ('Sfty', 'defense_safe'),
    ]),
    'NT': OrderedDict([
        ('G', 'games'),
        ('Solo', 'defense_tkl'),
        ('Ast', 'defense_ast'),
        ('Sack', 'defense_sk'),
        ('YdsL', 'defense_sk_yds'),
        ('Int', 'defense_int'),
        ('Yds', 'defense_int_yds'),
        ('IntTD', 'defense_int_tds'),
        ('DefTD', 'defense_tds'),
        ('FFum', 'defense_ffum'),
        ('PD', 'defense_pass_def'),
        ('Sfty', 'defense_safe'),
    ]),
}

def number(s):
    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except ValueError:
            return 0

def player_cmp(pos, yahoo_row, pobj):
    assert pos in statmap

    result = {
        'Name': yahoo_row['Name'],
        'Team': yahoo_row['Team'],
    }
    for yahoo_field, nflgame_field in statmap[pos].iteritems():
        truth = number(yahoo_row[yahoo_field])
        test = 0
        if hasattr(pobj, nflgame_field):
            test = getattr(pobj, nflgame_field)
        if nflgame_field in negatives:
            result[yahoo_field] = test + truth
        else:
            result[yahoo_field] = test - truth
    return result

for f in args.yahoo_data_files:
    pos = os.path.basename(f)[0:-4].upper()
    if pos not in statmap:
        continue

    tsvf = open(path.join(args.output_dir, '%s.tsv' % pos.lower()), 'w+')
    fieldnames = ['Name', 'Team'] + statmap[pos].keys()
    out = csv.DictWriter(tsvf, fieldnames=fieldnames, delimiter='\t')
    out.writerow({ k: k for k in fieldnames })
    rows = csv.DictReader(open(f), delimiter='\t')
    for row in rows:
        n, t = row['Name'], row['Team']
        m, r = find(n, t, pos)
        if m is None:
            print >> sys.stderr, 'NO MATCH (skipping): %s %s %s' % (n, t, pos)
            continue
        out.writerow(player_cmp(pos, row, m))
    tsvf.flush()