-
Notifications
You must be signed in to change notification settings - Fork 1
/
win-probability.R
380 lines (345 loc) · 9.93 KB
/
win-probability.R
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# Load libraries
# install.packages("nflfastR", "ggimage", "devtools")
# devtools::install_github("topfunky/gghighcontrast")
library(nflfastR)
library(tidyverse)
library(gghighcontrast)
library(scales)
library(ggimage)
# Don't display numbers in scientific notation
options(scipen = 9999)
# Colors
dayglo_orange = "#ff6700"
light_blue = "#0098ff"
red = "#ff0000"
grey = "#808080"
kiwi_green = "#8ee53f"
dark_olive_green = "#556b2f"
dark_raspberry = "#872657"
rich_black = "#010203"
if (!dir.exists("data")) {
dir.create("data")
}
load_data <- function(start_year, end_year, logos) {
# For each year, load data
data <- data.frame()
for (year in seq(start_year, end_year, by = 1)) {
# Download file to cache if not present
url = str_interp(
"https://raw.githubusercontent.com/guga31bb/nflfastR-data/master/data/play_by_play_${year}.rds"
)
local_filename = str_interp("data/play_by_play_${year}.rds")
if (!file.exists(local_filename)) {
download.file(url, local_filename)
}
pbp_single_year <-
readRDS(str_interp('data/play_by_play_${year}.rds'))
data <- bind_rows(data, pbp_single_year)
}
data <-
data %>% inner_join(logos, by = c("posteam" = "team_abbr"))
return(data)
}
# Be nice to the ESPN CDN by storing team logo images locally.
cache_logo_image <- function(logo) {
local_filename = str_interp("data/${logo[['team_abbr']]}.png")
if (!file.exists(local_filename)) {
download.file(logo[['team_logo_espn']], local_filename)
}
return(local_filename)
}
load_logos <- function() {
logos <- teams_colors_logos
logos <- logos %>%
select(team_abbr, team_logo_espn) %>%
mutate(team_logo_local = apply(logos, 1, cache_logo_image))
return(logos)
}
is_scoring_team <-
function(posteam,
play_type,
td_team,
safety,
this_team,
that_team) {
(td_team == this_team) |
(posteam == this_team &
(play_type == "extra_point" |
play_type == "field_goal")) |
(posteam == that_team & safety == 1)
}
load_data_and_train_model <- function(start_year, end_year, logos) {
pbp <- load_data(start_year, end_year, logos) %>%
filter(
!is.na(score_differential),!is.na(play_type),!is.na(down),!is.na(yardline_100),!is.na(defteam_timeouts_remaining),!is.na(posteam_timeouts_remaining),
qtr <= 4
) %>%
mutate(
winner = if_else(
home_score > away_score,
home_team,
if_else(home_score < away_score, away_team, "TIE")
),
# Record winner on each row
poswins = ifelse(posteam == winner, 1, 0),
is_home_team = ifelse(posteam == home_team, 1, 0),
# Build a column with all scoring plays for display on chart
home_scoring_play = is_scoring_team(posteam, play_type, td_team, safety, home_team, away_team),
away_scoring_play = is_scoring_team(posteam, play_type, td_team, safety, away_team, home_team),
) %>%
filter(winner != "TIE", !is.na(poswins)) %>%
select(
game_id,
game_date,
posteam,
poswins,
home_team,
away_team,
winner,
qtr,
down,
ydstogo,
game_seconds_remaining,
yardline_100,
score_differential,
defteam_timeouts_remaining,
posteam_timeouts_remaining,
home_scoring_play,
away_scoring_play,
home_wp_post,
wp,
is_home_team,
team_logo_local
)
win_prediction_model <- build_win_prediction_model(pbp)
pbp <- pbp %>%
mutate(
wp_custom =
predict(win_prediction_model, pbp[row_number(), ], type = "response"),
# Recalculate win probabilities relative to home team
home_wp_custom = ifelse(posteam == home_team, wp_custom, 1 - wp_custom),
)
return(pbp)
}
build_win_prediction_model <- function(data) {
# Sample 80% of rows
set.seed(123)
indexes = sample(1:nrow(data),
round(nrow(data) * 0.8),
replace = FALSE)
train <- data[indexes, ]
win_prediction_model = glm(
poswins ~
qtr +
down +
ydstogo +
game_seconds_remaining +
yardline_100 +
score_differential +
defteam_timeouts_remaining +
posteam_timeouts_remaining +
is_home_team,
train,
family = "binomial"
)
return(win_prediction_model)
}
# Plot
plot_for_data <-
function(data,
logos,
foreground_color,
background_color) {
# NOTE: Doesn't work well with facet_wrap()...need to specify
# team logos more dynamically based on the data being charted.
single_game_id <- data[1, ]$game_id
game_title_pieces <- strsplit(single_game_id, "_")[[1]]
game_year <- game_title_pieces[1]
game_week <- game_title_pieces[2]
# Get home_team and away_team and annotate on chart
home_team_abbr <- data[1, ]$home_team
away_team_abbr <- data[1, ]$away_team
# Build a data frame with coordinates of team logo to place on chart
logo_placement_data <- data.frame(
x = c(3600, 3600),
y = c(0.875, 0.125),
team_abbr = c(home_team_abbr, away_team_abbr),
stringsAsFactors = FALSE
) %>% inner_join(logos, by = "team_abbr")
plot <- ggplot(data,
aes(x = game_seconds_remaining, y = home_wp_custom)) +
# 50% reference line
geom_hline(yintercept = 0.5,
color = grey,
size = 1) +
# Reference line for each quarter (and halftime)
geom_vline(xintercept = 15 * 60, color = grey) +
geom_vline(xintercept = 30 * 60, color = grey) +
geom_vline(xintercept = 45 * 60, color = grey) +
annotate(
"text",
x = 58 * 60,
y = 0.95,
label = "Q1",
family = "InputMono",
color = grey,
size = 2
) +
annotate(
"text",
x = 43 * 60,
y = 0.95,
label = "Q2",
family = "InputMono",
color = grey,
size = 2
) +
annotate(
"text",
x = 28 * 60,
y = 0.95,
label = "Q3",
family = "InputMono",
color = grey,
size = 2
) +
annotate(
"text",
x = 13 * 60,
y = 0.95,
label = "Q4",
family = "InputMono",
color = grey,
size = 2
) +
# Win Probability
geom_line(aes(y = home_wp_post), color = grey) +
geom_line(size = 0.8) +
# Scoring events
geom_rug(
data = filter(data, away_scoring_play == 1),
color = foreground_color,
sides = "b",
size = 1.5
) +
geom_rug(
data = filter(data, home_scoring_play == 1),
color = foreground_color,
sides = "t",
size = 1.5
) +
# Draw home and away team logo
geom_image(
data = logo_placement_data,
aes(x = x, y = y, image = team_logo_local),
size = 0.08,
asp = 16 / 9
) +
# Formatting
scale_x_reverse() +
scale_y_continuous(labels = percent, limits = c(0, 1)) +
theme_high_contrast(
base_family = "InputMono",
background_color = background_color,
foreground_color = foreground_color
) +
theme(axis.text.x = element_blank(),
axis.ticks.x = element_blank()) +
labs(
title = str_interp(
"${game_year} Week ${game_week}: ${away_team_abbr} at ${home_team_abbr}"
),
subtitle = "Custom win probability model compared to nflfastR WP (grey)",
caption = "Data from nflfastR",
x = "Quarters",
y = "Home Win Probability"
)
}
plot_accuracy <-
function(data, foreground_color, background_color) {
# data <- data %>%
# mutate(home_wp_custom_rounded = round(home_wp_custom * 0.05) / 0.05) %>%
# group_by(home_wp_custom_rounded) %>%
# mutate(actual_wp = sum(poswins) / length(poswins)) %>%
# ungroup()
# From nflfastR
data <- data %>%
mutate(bin_pred_prob = round(wp_custom / 0.05) * 0.05) %>%
group_by(qtr, bin_pred_prob) %>%
# Calculate the calibration results:
summarize(
n_plays = n(),
n_wins = length(which(poswins == 1)),
bin_actual_prob = n_wins / n_plays
)
plot <- data %>%
ungroup() %>%
mutate(qtr = fct_recode(
factor(qtr),
"Q1" = "1",
"Q2" = "2",
"Q3" = "3",
"Q4" = "4"
)) %>%
ggplot() +
geom_point(aes(x = bin_pred_prob, y = bin_actual_prob, size = n_plays)) +
geom_smooth(aes(x = bin_pred_prob, y = bin_actual_prob), method = "loess") +
geom_abline(
slope = 1,
intercept = 0,
color = "black",
lty = 2
) +
scale_x_continuous(labels = percent, limits = c(0, 1)) +
scale_y_continuous(labels = percent, limits = c(0, 1)) +
theme_high_contrast(
base_family = "InputMono",
background_color = background_color,
foreground_color = foreground_color
) +
theme(legend.position = "none") +
labs(
title = "Model Accuracy",
subtitle = "Custom prediction vs actual win percentage",
caption = "Data from nflfastR",
x = "Predicted",
y = "Actual"
) +
facet_wrap( ~ qtr)
}
foreground_color = rich_black
background_color = "white"
# Load 2009 through 2016 or maybe all the way to 2019
logos <- load_logos()
pbp_data <- load_data_and_train_model(2009, 2020, logos)
# Plot a few games
game_ids <- c(
"2019_10_SEA_SF",
"2019_17_SF_SEA",
"2016_01_CAR_DEN",
"2020_16_MIA_LV",
"2020_16_LA_SEA",
"2020_16_TB_DET",
"2020_17_WAS_PHI",
"2018_11_KC_LA"
)
for (single_game_id in game_ids) {
plot <-
plot_for_data(
filter(pbp_data, game_id == single_game_id),
logos,
foreground_color,
background_color
)
ggsave(
str_interp("wp-${single_game_id}.png"),
plot = plot,
width = 6,
height = 4
)
}
plot <- plot_accuracy(pbp_data, foreground_color, background_color)
ggsave("accuracy.png",
plot = plot,
width = 6,
height = 4)