NYC Data Science Academy| Blog
Bootcamps
Lifetime Job Support Available Financing Available
Bootcamps
Data Science with Machine Learning Flagship ๐Ÿ† Data Analytics Bootcamp Artificial Intelligence Bootcamp New Release ๐ŸŽ‰
Free Lesson
Intro to Data Science New Release ๐ŸŽ‰
Find Inspiration
Find Alumni with Similar Background
Job Outlook
Occupational Outlook Graduate Outcomes Must See ๐Ÿ”ฅ
Alumni
Success Stories Testimonials Alumni Directory Alumni Exclusive Study Program
Courses
View Bundled Courses
Financing Available
Bootcamp Prep Popular ๐Ÿ”ฅ Data Science Mastery Data Science Launchpad with Python View AI Courses Generative AI for Everyone New ๐ŸŽ‰ Generative AI for Finance New ๐ŸŽ‰ Generative AI for Marketing New ๐ŸŽ‰
Bundle Up
Learn More and Save More
Combination of data science courses.
View Data Science Courses
Beginner
Introductory Python
Intermediate
Data Science Python: Data Analysis and Visualization Popular ๐Ÿ”ฅ Data Science R: Data Analysis and Visualization
Advanced
Data Science Python: Machine Learning Popular ๐Ÿ”ฅ Data Science R: Machine Learning Designing and Implementing Production MLOps New ๐ŸŽ‰ Natural Language Processing for Production (NLP) New ๐ŸŽ‰
Find Inspiration
Get Course Recommendation Must Try ๐Ÿ’Ž An Ultimate Guide to Become a Data Scientist
For Companies
For Companies
Corporate Offerings Hiring Partners Candidate Portfolio Hire Our Graduates
Students Work
Students Work
All Posts Capstone Data Visualization Machine Learning Python Projects R Projects
Tutorials
About
About
About Us Accreditation Contact Us Join Us FAQ Webinars Subscription An Ultimate Guide to
Become a Data Scientist
    Login
NYC Data Science Acedemy
Bootcamps
Courses
Students Work
About
Bootcamps
Bootcamps
Data Science with Machine Learning Flagship
Data Analytics Bootcamp
Artificial Intelligence Bootcamp New Release ๐ŸŽ‰
Free Lessons
Intro to Data Science New Release ๐ŸŽ‰
Find Inspiration
Find Alumni with Similar Background
Job Outlook
Occupational Outlook
Graduate Outcomes Must See ๐Ÿ”ฅ
Alumni
Success Stories
Testimonials
Alumni Directory
Alumni Exclusive Study Program
Courses
Bundles
financing available
View All Bundles
Bootcamp Prep
Data Science Mastery
Data Science Launchpad with Python NEW!
View AI Courses
Generative AI for Everyone
Generative AI for Finance
Generative AI for Marketing
View Data Science Courses
View All Professional Development Courses
Beginner
Introductory Python
Intermediate
Python: Data Analysis and Visualization
R: Data Analysis and Visualization
Advanced
Python: Machine Learning
R: Machine Learning
Designing and Implementing Production MLOps
Natural Language Processing for Production (NLP)
For Companies
Corporate Offerings
Hiring Partners
Candidate Portfolio
Hire Our Graduates
Students Work
All Posts
Capstone
Data Visualization
Machine Learning
Python Projects
R Projects
About
Accreditation
About Us
Contact Us
Join Us
FAQ
Webinars
Subscription
An Ultimate Guide to Become a Data Scientist
Tutorials
Data Analytics
  • Learn Pandas
  • Learn NumPy
  • Learn SciPy
  • Learn Matplotlib
Machine Learning
  • Boosting
  • Random Forest
  • Linear Regression
  • Decision Tree
  • PCA
Interview by Companies
  • JPMC
  • Google
  • Facebook
Artificial Intelligence
  • Learn Generative AI
  • Learn ChatGPT-3.5
  • Learn ChatGPT-4
  • Learn Google Bard
Coding
  • Learn Python
  • Learn SQL
  • Learn MySQL
  • Learn NoSQL
  • Learn PySpark
  • Learn PyTorch
Interview Questions
  • Python Hard
  • R Easy
  • R Hard
  • SQL Easy
  • SQL Hard
  • Python Easy
Data Science Blog > Student Works > Baseball: Hot and Cold Streaks

Baseball: Hot and Cold Streaks

malcolmhess
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

malcolmhess

View all posts by malcolmhess >

Leave a Comment

Cancel reply

You must be logged in to post a comment.

No comments found.

View Posts by Categories

All Posts 2399 posts
AI 7 posts
AI Agent 2 posts
AI-based hotel recommendation 1 posts
AIForGood 1 posts
Alumni 60 posts
Animated Maps 1 posts
APIs 41 posts
Artificial Intelligence 2 posts
Artificial Intelligence 2 posts
AWS 13 posts
Banking 1 posts
Big Data 50 posts
Branch Analysis 1 posts
Capstone 206 posts
Career Education 7 posts
CLIP 1 posts
Community 72 posts
Congestion Zone 1 posts
Content Recommendation 1 posts
Cosine SImilarity 1 posts
Data Analysis 5 posts
Data Engineering 1 posts
Data Engineering 3 posts
Data Science 7 posts
Data Science News and Sharing 73 posts
Data Visualization 324 posts
Events 5 posts
Featured 37 posts
Function calling 1 posts
FutureTech 1 posts
Generative AI 5 posts
Hadoop 13 posts
Image Classification 1 posts
Innovation 2 posts
Kmeans Cluster 1 posts
LLM 6 posts
Machine Learning 364 posts
Marketing 1 posts
Meetup 144 posts
MLOPs 1 posts
Model Deployment 1 posts
Nagamas69 1 posts
NLP 1 posts
OpenAI 5 posts
OpenNYC Data 1 posts
pySpark 1 posts
Python 16 posts
Python 458 posts
Python data analysis 4 posts
Python Shiny 2 posts
R 404 posts
R Data Analysis 1 posts
R Shiny 560 posts
R Visualization 445 posts
RAG 1 posts
RoBERTa 1 posts
semantic rearch 2 posts
Spark 17 posts
SQL 1 posts
Streamlit 2 posts
Student Works 1687 posts
Tableau 12 posts
TensorFlow 3 posts
Traffic 1 posts
User Preference Modeling 1 posts
Vector database 2 posts
Web Scraping 483 posts
wukong138 1 posts

Our Recent Popular Posts

AI 4 AI: ChatGPT Unifies My Blog Posts
by Vinod Chugani
Dec 18, 2022
Meet Your Machine Learning Mentors: Kyle Gallatin
by Vivian Zhang
Nov 4, 2020
NICU Admissions and CCHD: Predicting Based on Data Analysis
by Paul Lee, Aron Berke, Bee Kim, Bettina Meier and Ira Villar
Jan 7, 2020

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 ChatGPT 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 football 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 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

NYC Data Science Academy

NYC Data Science Academy teaches data science, trains companies and their employees to better profit from data, excels at big data project consulting, and connects trained Data Scientists to our industry.

NYC Data Science Academy is licensed by New York State Education Department.

Get detailed curriculum information about our
amazing bootcamp!

Please enter a valid email address
Sign up completed. Thank you!

Offerings

  • HOME
  • DATA SCIENCE BOOTCAMP
  • ONLINE DATA SCIENCE BOOTCAMP
  • Professional Development Courses
  • CORPORATE OFFERINGS
  • HIRING PARTNERS
  • About

  • About Us
  • Alumni
  • Blog
  • FAQ
  • Contact Us
  • Refund Policy
  • Join Us
  • SOCIAL MEDIA

    ยฉ 2025 NYC Data Science Academy
    All rights reserved. | Site Map
    Privacy Policy | Terms of Service
    Bootcamp Application