Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get expected goals from probabilities
# library(implied)
#
# dta <- read.csv('E0.csv')
#
# # Convert bookmaker odds to probabilities.
# imp <- implied_probabilities(dta[,c('B365H', 'B365D', 'B365A')], method='power')
# prob_mat <- imp$probabilities
#
# # Convert probabilities to expected goals.
# expg_res <- expg_from_probabilities(prob_mat)
lambda_sq_error <- function(lambda_pars, trgt_probs, maxgoals=25){
lambda_pars <- exp(lambda_pars) # trick to avoid negaive lambda parameters.
hda_probs <- numeric(3)
probmat <- dpois(0:maxgoals, lambda=lambda_pars[1]) %o% dpois(0:maxgoals, lambda=lambda_pars[2])
hda_probs[2] <- sum(diag(probmat))
hda_probs[1] <- sum(probmat[lower.tri(probmat)])
hda_probs[3] <- 1 - sum(hda_probs[1:2])
sum((hda_probs - trgt_probs)^2)
}
# Estimate the expected goals from win-draw-lose probabilities.
expg_from_probabilities <- function(probabilities){
if (!is.matrix(probabilities)){
probabilities <- matrix(probabilities, nrow=1,
dimnames = list(NULL, names(probabilities)))
}
stopifnot(ncol(probabilities) == 3)
expg <- matrix(ncol=2, nrow=nrow(probabilities))
sq_errors <- numeric(nrow(probabilities))
for (ii in 1:nrow(probabilities)){
optim_res <- optim(c(0, 0), fn=lambda_sq_error, trgt_prob=probabilities[ii,])
expg[ii,] <- exp(optim_res$par)
sq_errors[ii] <- optim_res$value
}
out <- list(expg = expg, sq_errors=sq_errors)
return(out)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment