In a previous post, we have provided an example of Rolling Regression in Python to get the market beta coefficient. We have also provided an example of pairs trading in R. In this post, we will provide an example of rolling regression in R working with the **rollRegres** package. We will provide an example of getting the beta coefficient between two co-integrated stocks in a rolling window of n observations.

## What is a Rolling Regression

The rolling regression is simply a dynamic regression within a rolling moving window. Assuming that we have 5 observations and a rolling window of 3 observations. Then we will run 3 regression models as we can see from my perfect picture below ðŸ™‚

## Rolling Regression with Co-Integrated Pairs

In the previous post, we found that the NFLX and AMZN stocks are co-integrated for the period of **2020-01-01** to **2021-01-03**. Let’s see how the beta coefficient evolves across time by considering a rolling window of 30 observations.

library(rollRegres) library(tidyverse) library(tseries) library(quantmod) mySymbols <- c('AMZN', 'NFLX') myStocks <-lapply(mySymbols, function(x) {getSymbols(x, from = "2020-01-01", to = "2021-01-03", periodicity = "daily", auto.assign=FALSE)} ) names(myStocks)<-mySymbols closePrices <- lapply(myStocks, Cl) closePrices <- do.call(merge, closePrices) names(closePrices)<-sub("\\.Close", "", names(closePrices)) # get the logarithm of the prices closePrices<-log(closePrices) head(closePrices)

Run the Rolling Regression with a moving window of 30 observations and get the intercept and the beta coefficient.

my_rollregression<-roll_regres(NFLX ~ AMZN, closePrices, width = 30, do_compute = c("sigmas", "r.squareds", "1_step_forecasts")) tail(my_rollregression$coefs)

## Get the Rolling Betas in Chart

Let’s have a look at the rolling betas.

my_coef<-as.data.frame(my_rollregression$coefs) my_coef<-rownames_to_column(my_coef, "Date")%>%na.omit() my_coef$Date<-as.Date(my_coef$Date) my_coef%>%ggplot(aes(x=Date, y=AMZN))+ geom_point()+geom_line()+ylab("Rolling Beta")+ ggtitle("Rolling Beta of NFLX vs AMZN")

## The Takeaway

When you want to do pairs trading, a good approach is to run rolling regressions so that to monitor dynamically the relationship of the pairs. Also, you can test if the pairs are indeed co-integrated in every rolling window.

## 4 thoughts on “Rolling Regression and Pairs Trading in R”

This is really nice. Sir I wanted to know if you have code on rolling window forecast, in particular out of sample forecasting.

Thank you, it is not so common to use rolling regression for predicting n observations ahead since you need to update the coefficients in every single step

There is no pair trading in this post. The title should be how to do rolling rehrgession in R.

It has applications in pairs trading.