Skip to content

Instantly share code, notes, and snippets.

@z-feldman
z-feldman / power_ratings.R
Last active June 29, 2021 01:35
Create simple SRS/Opponent Adjusted Point Differential using NFL data in R
# SRS, simple rating system, is a way to control point differential for opponent and location
# this is a great primer: https://www.pro-football-reference.com/blog/index4837.html?p=37
# To do this, we create a matrix with one row for each game, and columns of the 32 teams, plus a 33rd column for location
# We then solve the matrix/system of equations with the right hand side being the result of the game (scoring margin)
# Our matrix is populated with 1's, -1's, and 0's. 1 for home team, -1 for away team, 0 for teams not playing in the game
# In the location column 1 for home, 0 for neutral
# The equation for margin of victory for a single game is mov = home_field + home_team_rating - away_team_rating
# Our 1's and -1's are identifiers for the teams, and then solving the matrix will give us the ratings for each team
# that minimizes the error
# Since schedules are inbalanced (each team doesn't play each team the same number of times), we cannot fully solve the matrix,
library(nflscrapR)
library(tidyverse)
# assumes your data is called pbp
pbp <- pbp %>%
calculate_expected_points("half_seconds_remaining",
"yardline_100",
"down",
"ydstogo",
"goal_to_go")