Data Scraping NBA 3 Point Shooting Statistics

Posted on Apr 6, 2017
The skills the author demoed here can be learned through taking Data Science with Machine Learning bootcamp with NYC Data Science Academy.


Previously, I wrote about the 3-point shooting trend in NBA in recent years, and showed statistical data analysis on the seasonal behavior of the 3-point shooting data. I wanted go get more detailed data, such as game log, and to explore more on the game by game basis. After searching for some time, I could not find a very good resource of properly organized NBA game log data set publicly, so I decided to scrape the data myself.


Library and tools:

I chose Scrapy as my main library for scraping because it is simple and straightforward to define the spider, and it uses a Python generator to loop through the crawled data. The scrapy.Request is quite easy to define, and we can pass a self-defined call back function to crawl through multiple pages (which I will describe later).


The Data

When I am referring about the game log data, I am referring to the box score of both teams, such as this image below:

Data Scraping NBA 3 Point Shooting Statistics

Box Score

This box score section is the must to go place for all basketball fans. So I decided to scrape this box score for every single game since the 2010 season. In order to do so, I need to go up one level higher to this page:

Data Scraping NBA 3 Point Shooting Statistics


On this page, there is a RECAP button for all the game played on that day. And what we need to do is to loop through all the days during the NBA season, and for each day, crawl the RECAP button, and extract the box score inside the RECAP button. Here is the Python code for what I just described:

Data Scraping NBA 3 Point Shooting Statistics

The 3 for loops above is loop through year 2010 to 2016, loop through October to April (NBA season), and loop through all the days in one month. Note that this is the Spider class in Scrapy, where I define how to crawl the website.


Pasre Method

Inside the Spider class, Scrapy has a default ```parse``` function, which is usually used to define the data table to be parsed, such as this simple example. In my case, I used the parse function to crawl through the links of the RECAP buttons instead of the box score.



Notice the if else statement is for the 2 different architectures for year 2010~2015 and year 2016, respectively.  In addition to the default parse function, I defined a ```parse_item``` function, which will crawl the boxscore inside the links of the RECAP buttons. This ```parse_item``` function is called in the callback argument of the Request object (line 44 in the above image). Here is what the ```parse_item``` looks like:



We have 17 fields in total, this corresponds to the fields defined in ```Item``` class in the `````` script:



Lastly, I need to define the pipeline, which stores the data scraped into ```NBA_stat.txt```. In this case, I had to use ```utf-8``` encoding because of the string from player's name field:



Here is what the scraped data looks like:



Data Analysis

Now that we have the data, we can do some statistical analysis on the game log data. As an extension from my previous post, I want to revisit the goal:

  • Are winning teams attempting/making more 3 point shots?
  • Is 3 point shot just a media hype?

If we take a look at the annual 3-point shooting attempt / made from both team that won and lost the game, we see a general trend going upwards.

Annual Average of 3 Point AttemptAnnual Average of 3 Point Made

The teams that won the game seem to be shooting more in general than the teams that lost the game. This is expected, but the difference is not big in terms of 3-point attempt. Let's take a look at the histogram to confirm:

Histogram of 3 Point AttemptHistogram of 3 Point Made

We do see the same pattern here that: winning teams made more 3-point shot, and both winning team and losing team attempted about the same amount of 3-point shot. Since the 3-point attempt is unclear which team attempted more, I conducted a 2-sample t-test to confirm. The null hypothesis is:

  • winning team and losing team attempts the same amount 3-point shots

The alternative hypothesis is:

  • winning team and losing team did not attempt the same amount 3-point shots

2-sample t-test equation

As a reminder, here is the 2-sample t-test equation:


The result is:

  • p-value = 0.01566 (which is < 0.05)

This means that it passed the 95% confidence interval, and we should reject the null hypothesis and accept the alternative hypothesis. And our conclusion for this test is:

  • Teams that won the game took more attempt than the teams that lost the game

Series Plot of 3-point attempts

Next, I wanted to make good use of the game log data, so I made a time series plot of 3-point attempt on daily basis since the first game in 2010:

Average Daily 3 Point Shot Time Series



We do see a general increasing trend of 3-point attempt, however the slope of this line is only 0.0031. So the question is, is this trend really going upward? Once again, we use 2-sample t-test to confirm this fact. I compared this year vs. last year, and the null hypothesis is this:

  • this year and last year attempted the same amount of  3-point

While the alternative hypothesis is:

  • this year and last year did not make the same amount 3-point attempt

And I conducted the t-test year by year since 2010, so:

Year p-value pass 95% confidence interval
2011 vs. 2010 0.2327 No
2012 vs. 2011 5.23 e-8 Yes
2013 vs. 2012 2.2 e-16 Yes
2014 vs. 2013 2.2 e-16 Yes
2015 vs. 2014 2.2 e-16 Yes
2016 vs. 2015 4.16 e-7 Yes

Only year 2011 vs. 2010 failed the test, while all other years indicate that the years have different amount of 3-point attempt shots. With this result, and the upward slope we observed earlier, we can confidently say

  • All teams are attempting / made more 3-point shots than before, with an increasing trend year-by-year

The code of this project can be found in this github link.


About Author

Werner Chao

Werner has been the lead data analyst for KaJin Health (, an online mental health company in Shanghai, and data analyst at SNC-Lavalin, a 7.8 billion dollar public company. He helped KaJin Health analyze web traffic, consumer insights,...
View all posts by Werner Chao >

Related Articles

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