Baseball: Hot and Cold Streaks

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 2020 Revenue 3-points agriculture air quality airbnb airline alcohol Alex Baransky algorithm alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus ames dataset ames housing dataset apartment rent API Application artist aws bank loans 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 boston safety Bundles cake recipe California Cancer Research capstone car price Career Career Day citibike classic cars classpass clustering Coding Course Demo Course Report covid 19 credit credit card crime frequency crops D3.js data data analysis Data Analyst data analytics data for tripadvisor reviews data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization database Deep Learning Demo Day Discount disney dplyr drug data e-commerce economy employee employee burnout employer networking environment feature engineering Finance Financial Data Science fitness studio Flask flight delay gbm Get Hired ggplot2 googleVis H20 Hadoop hallmark holiday movie happiness healthcare frauds higgs boson Hiring hiring partner events Hiring Partners hotels housing housing data housing predictions housing price hy-vee Income Industry Experts Injuries Instructor Blog Instructor Interview insurance italki Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter las vegas airport lasso regression Lead Data Scienctist Lead Data Scientist leaflet league linear regression Logistic Regression machine learning Maps market matplotlib Medical Research Meet the team meetup methal health miami beach movie music Napoli NBA netflix Networking neural network Neural networks New Courses NHL nlp NYC NYC Data Science nyc data science academy NYC Open Data nyc property NYCDSA NYCDSA Alumni Online Online Bootcamp Online Training Open Data painter pandas Part-time performance phoenix pollutants Portfolio Development precision measurement prediction Prework Programming public safety PwC python Python Data Analysis python machine learning python scrapy python web scraping python webscraping Python Workshop R R Data Analysis 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 seafood type Selenium sentiment analysis sentiment classification Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau teachers team team performance TensorFlow Testimonial tf-idf Top Data Science Bootcamp Top manufacturing companies Transfers tweets twitter videos visualization wallstreet wallstreetbets web scraping Weekend Course What to expect whiskey whiskeyadvocate wildfire word cloud word2vec XGBoost yelp youtube trending ZORI