How to do Regression with Statsmodels in Python

00Comment iconComment iconComment iconComment icon

Discover how to perform regression analysis with Statsmodels in Python. From data preparation to model tuning, learn step-by-step instructions to leverage this powerful statistical tool for robust predictive modeling.

Writer image

번역자Editorial

Writer image

개정자Editorial

Edit Article

Material to accompany this lesson

Download the spreadsheet found here on Google Sheetslink outside website. We will use this spreadsheet for the lesson. Download it as CSV, the most common method for storing a database that can be read by any language (Comma-Separated Values).

Create a python3 development environment or use ready-made online environments such as JupyterLab onlinelink outside website and import the database.

Statsmodels in Python

Start by downloading the data as CSV, renaming it to "dados-2.csv" to make it easier to work with. We will use the pandas, numpy, statsmodels, and matplotlib packages in Python. Below you can see how to import each one:

Importing packages in Python
Importing packages in Python

Time as an index

Notice that we are using decimal="," and thousands="." precisely because our data is in Portuguese. Now we will use time as the index of our data table. Below is the code to set time as the index and also create a "Days" column. The "Days" column will be used in the linear regression; with it, we will check when each stock is growing over time using the slope coefficient.

Transformation to use time as an index
Transformation to use time as an index

Correlation matrix

Before starting the regressions, let's move on to a very important analysis for investors: the correlation matrix. This matrix shows how each stock is correlated. If you want to create an investment portfolio in the future, remember to choose stocks that are negatively correlated with each other, as this reduces the portfolio's risk. Below is the code to calculate the correlation matrix:

Calculating correlations
Calculating correlations

The matrix should look like this at the end:

Correlation matrix between stocks
Correlation matrix between stocks

Below is what was printed by Python regarding the correlations. Most positive correlations:

Company 1Company 2Correlation
BradescoTim0.957497
TimBradesco0.957497
Domino's pizzaDays0.948813
DaysDomino's pizza0.948813
MastercardDomino's pizza0.921368
Domino's pizzaMastercard0.921368
SantanderAmerican Express Company0.888684
American Express CompanySantander0.888684
TimSantander0.888301
SantanderTim0.888301

Most negative correlations:

Company 1Company 2Correlation
DaysSantander-0.642465
SantanderDays-0.642465
Ford motorsBraskem-0.668737
BraskemFord motors-0.668737
Ford motorsMastercard-0.708027
MastercardFord motors-0.708027
Domino's pizzaFord motors-0.826345
Ford motorsDomino's pizza-0.826345

Simple Linear Regression

Now let's actually use Statsmodels. Below is the code to perform a simple linear regression between Gold and the number of Days.

Linear regression in Statsmodels
Linear regression in Statsmodels

Linear regression provides several results; see the table below and try to interpret each parameter:

OLS results
OLS results

Below are our forecast and the observed real-world points:

Forecast vs observed
Forecast vs observed

It's not one of the best regressions, right? Let's also look at the residuals.

The residuals show a trend and are not symmetrical
The residuals show a trend and are not symmetrical

ARIMA Regression

If our friend Linear Regression cannot forecast, we can look for other models. So let's try to run an ARIMA(1,1,1) regression between the value of Gold and Time.

Python code for ARIMA
Python code for ARIMA
ARIMA result
ARIMA result
Forecast vs Observed with ARIMA
Forecast vs Observed with ARIMA

Even though the forecast looks good, we must not forget to look at the residuals:

ARIMA residuals
ARIMA residuals

Training set vs test set

Even though ARIMA had a great result, it is good to check by dividing our sample into at least two sets: a training set and a test set. We will split it in half, train our model with the training set, and check whether it also has good results on the test set.

Creating the test and training sets and running a new regression
Creating the test and training sets and running a new regression
Training ARIMA results
Training ARIMA results

Final forecast:

Test, Training, and observed values
Test, Training, and observed values

Multivariate Regression

If you do not want to work with ARIMA, it is possible to perform a Multivariate Regression by choosing stocks correlated with yours to make forecasts. In the example below, I use Chevron's price and the number of Days to forecast the price of Vale do Rio Doce.

Python code for multivariate regression
Python code for multivariate regression
Multivariate Regression result
Multivariate Regression result
Forecast and observed values from the Multivariate Regression
Forecast and observed values from the Multivariate Regression

Exercises

Now you do it:

1) Import this dataset into pandas

2) Create the correlation matrix

3) Choose a stock and perform a linear regression between it and the days. It cannot be gold!

4) Choose a stock and run an ARIMA between it and time.

5) Choose a stock and train an ARIMA with half of the data, then test it with the other half.

6) Challenge: perform a multivariate regression that attempts to explain the value of a stock using time and the value of another stock as a reference.