In order to do any kind of basketball analysis, we need data. But with many different data sources, it can sometimes be difficult to find the optimal, least stressful way to obtain it.
In data analytics, it is said that more than 80% of the time is spent on data collection, cleaning and modification. Relatively small amounts of time are spent actually analyzing the data, be it visually or with machine learning algorithms.
In this article we will try to explain the necessary steps for data processing, including database setup, installation of programming languages and required packages. We also give additional tricks on how to modify the data for efficient future use.
Setting up a database
The easiest way to store NBA data is to put it into a database. Compared to files, this allows for faster querying, easier cross-platform access and safer updates.
I have chosen here to go with MySQL, a database system that uses Structured Query Language (SQL). We need to install the following:
Windows users1 first need the Visual C++ Redistributable:
Windows and Mac users then need to download and install the server, called MySQL Community Server on this page:
Workbench is a separate GUI application for working with the MySQL server: One can use it to run SQL queries, filter the results and sort them in a user-friendly way.
When starting Workbench, we want to create a database, using
create database nba;
create user ‘nba’@’localhost’ identified by ‘password’;On Windows, setup may also ask for .NET Framework 4.5.
Setting up Python
Why Python? Many in the sports analytics space use the statistics language “R” instead. My personal view is that — because R’s syntax can often hide a lot of the underlying complexity — people don’t always gain a decent understanding of what is actually happening underneath.
As a concrete example, almost all of the articles I’ve seen on how to do (R)APM in R have produced incorrect results.
Python is a well-maintained, modern scripting language that has a variety of easy-to-install libraries that are specifically aimed at machine learning and visualization.
For either platform, Python can be obtained here.
Since there are several versions of Python — which can get tangled up — it is good practice to create a virtual environment which contains the libraries and packages without influencing the rest of the system.
Creating and activating such an environment, and installing the necessary packages, looks like this:
macOS
mkdir ~/nba-data
cd ~/nba-data
python3 -m venv .venv
source .venv/bin/activate
python -m pip install nba_api pandas sqlalchemy pymysqlWindows
mkdir %USERPROFILE%\nba-data
cd %USERPROFILE%\nba-data
py -m venv .venv
.venv\Scripts\activate
python -m pip install nba_api pandas sqlalchemy pymysqlNote that the activation step has to be executed in that specific folder, each time a new terminal/console is opened.
A simple test
Once the above steps appear to be done, we can test whether everything is working correctly by creating a new Python file, with the following contents:
import pandas as pd
from nba_api.stats.static import teams
from sqlalchemy import create_engine
engine = create_engine(”mysql+pymysql://nba:password@localhost/nba”)
df = pd.DataFrame(teams.get_teams())
df.to_sql(”test_teams”, engine, if_exists=”replace”, index=False)
print(f”Wrote {len(df)} rows to test_teams”)Run the file in a terminal
python api_test.pyThen, in Workbench,
SELECT * FROM nba.test_teams;should show all 30 teams and their IDs.
As a general rule of thumb — and in the example above — data returned from the API gets converted into a DataFrame, which is a concept from the Python library pandas. Put simply, DataFrames work like database tables, allowing for filtering etc. The library Polars is a significantly faster, though less widely used, alternative to pandas.
Obtaining data through the NBA’s API
The open-source Python library “nba_api” — originally created by Swar Patel, and maintained by various contributors — gives us simple access to the data found on nba.com/stats. It returns the data in Python-native formats.
This NBA API has a large number of so-called endpoints, which return a specific dataset when called. Usually, an endpoint call contains specific parameters, which act as a filter. For example, we might want data for only a specific date, game, team or player.
Each endpoint is also connected to a specific dataset. The “BoxScoreHustleV2” endpoint returns hustle-related data, the “PlayByPlayV3” endpoint will return play-by-play data — you get the point.
The general practice is to import the necessary endpoints into the Python script, then call the endpoint with the desired parameters, then shovel the returned data into our database, using pandas.
Note: The NBA doesn’t love its API being hammered with a lot of requests. Adding “sleeps” between requests is often necessary to avoid being temporarily blocked.
Machines in the cloud — Amazon’s AWS and the like — are also blocked from access.
My suggestion would be to grab only those tables that are relevant to your research.
Depending on the project, people will want to access different datasets, which can be accessed through these endpoints. The full list of all stats endpoints is here, though several of the listed ones might have already been retired by the NBA.
Here are two more examples on how to grab some of the more important data.
Grabbing, and saving, team box scores:
from nba_api.stats.endpoints import leaguegamelog
from sqlalchemy import create_engine
engine = create_engine(”mysql+pymysql://nba:password@localhost/nba”)
log = leaguegamelog.LeagueGameLog(season=”2026-27”)
df = log.get_data_frames()[0]
df.to_sql(”team_game_log”, engine, if_exists=”replace”, index=False)
print(f”Wrote {len(df)} rows to team_game_log”)Note that the above grabs all available data for the 2026-27 regular season.
Since there are endpoints that return significantly more data — e.g. the PlayByPlayV3 endpoint we use below — we sometimes need to grab the data on a game-by-game (or day-by-day) basis.
To avoid the problem of duplicates, and in order to grab only the data we don’t already have, the code might look like this:
import pandas as pd, time
from nba_api.stats.endpoints import playbyplayv3
from sqlalchemy import create_engine, inspect
engine = create_engine(”mysql+pymysql://nba:password@localhost/nba”)
game_ids = pd.read_sql(”SELECT DISTINCT GAME_ID FROM team_game_log”, engine)[”GAME_ID”]
if inspect(engine).has_table(”play_by_play”):
existing = pd.read_sql(”SELECT DISTINCT gameId FROM play_by_play”, engine)[”gameId”]
game_ids = game_ids[~game_ids.isin(existing)]
for game_id in game_ids:
df = playbyplayv3.PlayByPlayV3(game_id=game_id).play_by_play.get_data_frame()
df.to_sql(”play_by_play”, engine, if_exists=”append”, index=False)
print(f”Wrote {len(df)} rows for game {game_id}”)
time.sleep(2)The most important tables for metric building
Below is a list of basic endpoints that cover a good chunk of the most important available data.
For lineup-based metrics, such as Adjusted Plus-Minus, data from the PlayByPlayV3 endpoint still has to be parsed in order to extract information about which 5-man lineups were facing each other during each possession. The GameRotation endpoint can be of additional help when it comes to lineups.
Further data manipulation in the DB
To quickly access the data inside the database with SELECT statements, here is a quick, crucial tip to speed up database access.
The larger a database table gets, the slower the requests tend to be. This can be even more of an issue when filters are used in the query.
For example, we might want to grab the rotation data for only a specific game with:
select * from game_rotation where game_id = ‘0022600280’To speed up requests we want to make sure that each column has the minimally needed data format: meaning, when a table is first created, pandas can sometimes incorrectly assume a specific data type. A column containing only integers might be instantiated as a text field, which takes up significantly more space.
To deal with this, we can specify column types in the initial pd.to_sql call, like this
from sqlalchemy.types import CHAR, INTEGER, VARCHAR
df.to_sql(”game_rotation”, engine, if_exists=”replace”, index=False,
dtype={ “GAME_ID”: CHAR(10), “TEAM_ID”: INTEGER, “TEAM_CITY”: VARCHAR(50),
“TEAM_NAME”: VARCHAR(50), “PERSON_ID”: INTEGER, ..})Or we can take a look at the currently existing columns with
show columns from game_rotationand modify them with a command like
alter table game_rotation modify column game_id char(10)Another method to speed up requests is to use indexes in the database tables.
For example, many of our tables might contain 31 seasons or more of NBA data.
If we know that many of our requests are aimed at grabbing 2026-27 data only
select * from matchups where season = 2027indexing the “season” column can increase execution speed of the query by a large factor.
An index can be created like this:
create index season_index on matchups(season)Note that if tables get replaced, indexes get lost.
Lots of different analyses have already been done in the basketball analytics space. But, with a dash of creativity, the possibilities of analyzing the data are practically endless.
Have fun!
Our free series of technical articles:
Assuming that most Linux users are probably already familiar with some of the concepts below, we will focus on macOS and Windows.










