Baseball: Hot and Cold Streaks

Avatar
Posted on Apr 24, 2015
  1. Contributed by Malcolm Hess.
  2. Malcolm is part of the 12-Week Data Science Bootcamp with Vivian Zhang in the spring of 2015.
  3. This post is based on Malcolm's project investigating hot and cold streaks for hitters in baseball

 


Background
Baseball (America's pastime) is a unique sport and the first that truly embraced statistical analysis.  Baseball has by far the longest season in terms of games (162 games in a regular season) and also has one of the longest durations of play (from April to the end of September).  For lack of a better analogy, the regular season for baseball is sort of like a marathon, one or two days won't make a big difference, what really matters is the player's average at the end of the year.
 Most hitters are known to go through "hot streaks" and "cold  streaks" (also referred to as a slump).  There are also some hitters that are considered "streaky hitters", these are players that are thought to have a cyclical nature in their hot and cold streaks but should finish the year with their respective batting average.  Some base ideas to support streaks is that a player should have a 5 day cycle which corresponds to the opponent team's pitching rotation.  Since the best pitcher of a team pitches every 5 games, one would assume that a player to have consistently worse games against "number 1" pitchers and that cycle might be visible on a chart.  Some players are thought to "finish strong" or "start off slow" from year to year.  With these charts I can compare the same player's years to see if I can find evidence of a player being consistent in that regard.

Objective
  1. Set up a system where I can easily create my own database of baseball data.  I chose a website that has day by day data which has the needed granularity so that I can research hot and cold streaks.
    • Create a functions that can that will download the information and format it properly.  Then save it to my local computer.  This data should contain the career batting data for a specific player in a game by game bat log format.
    •  Create a function that will load in the data for that player. t.
  2. Create a visualization of hits across the year to visualization potential patterns in hot and cold streaks.


Implementation
Code Chunk 1: setting up the create a player function-
First I created the function which takes in three parameters.  The players first name, last name and key number.  I also included a small amount of checking to make sure the values entered make sense.  I also check to see if there is a directory called "Baseball" to save the data into that, if it does not exist the function will create the directory.
Code Chunk 2: create player identity and download from the website which career years this player has played in. 
This code chunk is dedicated to cleaning the user input and stringing it together into the proper player identity.  It also pulls from the website which career years the player has records in.  It puts all those years into a vector and re-orders them from earliest to latest year.  I remove the post-season statistics because I'm more interested in regular season analysis.
Code  Chunk 3: acquiring the batting log data and cleaning of one year data for  the specified player
This "getyeardata" is the longest code chunk as there was extensive work to be done on cleaning the data.  There were many obstacles I had to deal with in order to make it into a truly clean and usable format.  First i create the url and download the chart off of the website.  I remove extra rows which were originally included to separate different months.   I then created new columns which have the player identity and the year just in case I want to combine multiple players together, I can continue to differentiate them.  The dates have potential issues because double-headers (a day where two games are played) have special symbols which I needed to remove in order to turn the dates into a proper date class object.
For some players the chart would bring in an extra row with column names, so I removed those.  I also fixed the "home/away" column which at first has no name, I also include the symbol "H" for home games and leave the standard "@" for away games.  I created a new variable which I called "deltaavg" which is the change in batting average from one game to the next.  I do not utilize this variable right now but I believe it could be interesting to use in future analysis.
Code  Chunk 4: getting each year for a player and combining it into one data frame. Then saving that data to the local computer.
With the vector containing all years and my getyeardata function this was easy.  I run through the entire vector and rbind all the clean years together.
Code Chunk 5: creating a function to load in a specific player's data.
This code loads a specific player's file which is saved in the baseball directory created during "createaplayer" function.
Code Chunk 6: visualizing the data
This code uses a calendar heat map function I found online. After loading in the data for Josh Hamilton, I create a subset of 2013,  and then graphed it.   I made minor alterations to the original code by changing the color pallet.  The graph shows the number of hits on a given day.  Dark blue is a bad day and red are good days. The code for the calendar heat map can be found on my github here: Code

 

Results

 

bbhamilton

The chart is a new and interesting way to look at baseball data.  It gives you a better feel for the strength of a player in a given time frame.  I chose to highlight this year because it is one of this player's worst years in recent times.  I was hoping to see a cycle between hot and cold  across multiple days but such a cycle isn't really visible.  August and September were certainly better than the earlier months of the season but overall I think it is clear that the year is just a poor one for Josh Hamilton's standards.  I've looked at multiple players and multiple seasons and have found very little visual evidence to support the existence of a hot and cold cycle throughout the year.  I have also not found any evidence to support that certain players have a general and unique yearly cycle.  That cycle could be having a week first half of the year with a very strong second half.

 

I think we can gleam very interesting realizations from the fact that these cycles do not exist.  First of all there is no evidence to support that a player's success should cycle with the expected opponent's pitching rotation.  We can't assume that players from year to year will be consistent in when they get their hits, whether it is consistent hitting throughout the year or hits clustered together in one or two months.  By the end of the year we will still expect a player to have similar results as the previous year but how the player gets there seems to be incredibly random with no determinable cycle.

 


All code can also be found here: Code

Code 

Code Chunk 1: setting up the create a player function-

createplayer <- function(playerfirstname, playerlastname, key=1){

require(XML)

require(RCurl)

#check if key is valid entry

if (class(key)!= "numeric"){

stop("Invalid key: Requires number 1-9")

stop}

if (key > 9 | key < 1){

stop("Invalid key: Requires number 1-9")

stop}

#keys are always two digit, so if less than 10 it makes

#key to a string and adds a zero to the front

if (key < 10){

key <- substring(toString(key), 1, 1)

key <- paste("0", key, sep="")

}

#checks to see if Baseball directory exists, and if not creates it.

if(!file.exists("Baseball")){createwd("Baseball") }

setwd('Baseball')

 

 


Code Chunk 2: create player identity and download from the website which career years this player has played in. 

  playerfirstname <- as.character(playerfirstname)

playerlastname <- as.character(playerlastname)

#cleaning names and key to make player identity object

subfirst <- substring(playerfirstname, 1, 2)

sublast <- substring(playerlastname, 1, 5)

identity <- paste(sublast, subfirst, key, sep="")

identity <- tolower(identity)

#checks to see if player already exists in local database

filename <- paste0(identity, ".csv")

if(file.exists(filename)){

stop("Player already exists in database")

}

#making url to get to base page for the specified player

url <- paste0("http://www.baseball-reference.com/players/gl.cgi?id=", identity)

raw <- getURL(url)

data <- htmlParse(raw)

#making a list of all the years that this player has played in

xpath <- '//*[@id="stats_sub_index"]/ul/li[4]/ul/li/a'

nodes <- getNodeSet(data, xpath)

years <- sapply(nodes, xmlValue)

#cleaning up the list of years, need to remove postseason and turn characters to numbers

years <- years[!is.element(years, "Postseason")]

years <- as.numeric(years)

years<-sort(years)

amountofyears <- length(years)

 


 

Code  Chunk 3: acquiring the batting log data and cleaning of one year data for  the specified player

getyeardata <- function(ident = identity, year=2014){

#setting up URL to get data from a specific year

url1<- "http://www.baseball-reference.com/players/gl.cgi?id="

url2<- "&t=b&year="

urlyear <- paste(url1, identity, url2, year, sep="")

#downloading html site and taking out the table with the batting data

html <- htmlTreeParse(urlyear, useInternal=TRUE)

tables <- readHTMLTable(html)

batlog<- tables$batting_gamelogs

rows<- nrow(batlog)

i<-1

while(i<=rows){ #removes Month rows

if(batlog[i,1]=="April" | batlog[i,1]=="May" | batlog[i,1]=="June"|

batlog[i,1]=="July"| batlog[i,1]=="August"| batlog[i,1]=="September"|

batlog[i,1]=="October"){

batlog <- batlog[-i,]

i <- i - 1

rows <- nrow(batlog)

}

i <- i + 1

}

#adding a column to the front of the data that has identity and year on it

#remove first column which is just row number, imported from html table.

batlog <- batlog[,-1]

batlog <- transform(batlog, Player=identity)

batlog <- transform(batlog, Year=year)

temp<- batlog[,36:37]

batlog <- batlog[,-36:-37]

batlog <- cbind(temp,batlog)

#more data cleanup. Var.5 is currently the home/away column, away games signified with @

#Date variable transformed to character so I can clean up the dates and later and a year to it.

rows<- nrow(batlog)

batlog <- transform(batlog, Var.5= as.character(Var.5), Date=as.character(Date), Gtm = as.character(Gtm))

#double headers have extra symbols on them after the date, I need to

#remove (1) or (2) from them to properly transform it to a date class.

#Gtm will also have extra () based on amount of games a player missed

#I am also adding the year to the end of the date.

i <-1

while(i<=rows){

if(grepl(")", batlog$Date[i])) {

nc <- nchar(batlog$Date[i])

batlog$Date[i] <- substring(batlog$Date[i], 1, (nc-4))

}

if(gre)

batlog$Date[i] <- paste(batlog$Date[i], year, sep=", ")

i <- i +1 }

batlog<- subset(batlog, Gcar != "Tm")

batlog<- subset(batlog, H != "HR")

#more data cleaning

colnames(batlog)[7] <- "Home"

batlog <- transform(batlog, DELTAAVG= NA, BA = as.numeric(as.character(BA)), Home = as.character(Home))

#One K loop to do two things.  First, deal with issues of home/away, second create deltaavg.

#adds 'H' (symbolize home game) to blank entires, away games are '@' symbol

k<-1

while(k<=nrow(batlog)){

if(batlog[k,7]!= "@"){

batlog[k,7] <- "H"

}

##Makes new variable (deltaavg) that is the difference of Batting average from day to day

if((k+1) <= nrow(batlog)){

batlog$DELTAAVG[(k+1)] <- (batlog$BA[(k+1)] - batlog$BA[k])

}

k<-k+1

} #end of k while loop

batlog

}#end of getyeardata


Code  Chunk 4: getting each year for a player and combining it into one data frame. Then saving that data to the local computer. 

#initializing object (careerdata) which will become the main dataframe

careerdata <- NULL

j<-1

#Go through all years and rbind the data together into the careerdata object

while (j <= amountofyears){

b<- getyeardata(identity, year = years[j])

careerdata <- rbind(careerdata, b)

j<-j+1

}

filename <- paste0(identity, ".csv")

write.csv(careerdata, file= filename)

} #End of create player function!

 

 


 

Code Chunk 5: creating a function to load in a specific player's data.

 

loadplayer <- function (playerfirstname, playerlastname, key=1){

setwd("E:/Baseball")

if (key < 10){

key <- substring(toString(key), 1, 1)

key <- paste("0", key, sep="")

}

playerfirstname <- as.character(playerfirstname)

playerlastname <- as.character(playerlastname)

#cleaning names and key to make player identity object

subfirst <- substring(playerfirstname, 1, 2)

sublast <- substring(playerlastname, 1, 5)

identity <- paste(sublast, subfirst, key, sep="")

identity <- tolower(identity)

filename <- paste0(identity, ".csv")

dataframe <- read.csv(filename, header=TRUE)

dataframe

}

 


 

Code Chunk 6: visualizing the data

source('calendarheat.R')

currentplayer <- loadplayer("josh", "hamilton", 3)

simple <- transform(currentplayer, date = as.Date(Date, format = "%b %d, %Y"), h= as.numeric(H), Date=as.character(Date))

sub1 <- subset(simple, format(date, "%Y") %in% c("2013"))

calendarHeat(sub1$date, sub1$h, date.form = "%b %d, %Y")

About Author

Leave a Comment

No comments found.

View Posts by Categories


Our Recent Popular Posts


View Posts by Tags

#python #trainwithnycdsa 2019 airbnb Alex Baransky alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus API Application artist aws beautiful soup Best Bootcamp Best Data Science 2019 Best Data Science Bootcamp Best Data Science Bootcamp 2020 Best Ranked Big Data Book Launch Book-Signing bootcamp Bootcamp Alumni Bootcamp Prep Bundles California Cancer Research capstone Career Career Day citibike clustering Coding Course Demo Course Report D3.js data Data Analyst data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization Deep Learning Demo Day Discount dplyr employer networking feature engineering Finance Financial Data Science Flask gbm Get Hired ggplot2 googleVis Hadoop higgs boson Hiring hiring partner events Hiring Partners Industry Experts Instructor Blog Instructor Interview Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter lasso regression Lead Data Scienctist Lead Data Scientist leaflet linear regression Logistic Regression machine learning Maps matplotlib Medical Research Meet the team meetup Networking neural network Neural networks New Courses nlp NYC NYC Data Science nyc data science academy NYC Open Data NYCDSA NYCDSA Alumni Online Online Bootcamp Open Data painter pandas Part-time Portfolio Development prediction Prework Programming PwC python python machine learning python scrapy python web scraping python webscraping Python Workshop R R language R Programming R Shiny r studio R Visualization R Workshop R-bloggers random forest Ranking recommendation recommendation system regression Remote remote data science bootcamp Scrapy scrapy visualization seaborn Selenium sentiment analysis Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau team TensorFlow Testimonial tf-idf Top Data Science Bootcamp twitter visualization web scraping Weekend Course What to expect word cloud word2vec XGBoost yelp