Predictive Hacks

Rolling Regression and Pairs Trading in R

rolling regression

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")
 
rolling regression

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.

Get 25$ in BTC for FREE

You can get $25 in Bitcoin by investing $100 in Nexo

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

5 thoughts on “Rolling Regression and Pairs Trading in R”

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

    Reply
    • 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

      Reply
  2. Hi ,
    I had earlier asked the question on the rolling window. So in that regards, I kind of used the code for rolling beta using the code from “Tidy Finance with R” for my own data. So i wished to know how to modify this code to obtain the coefficients for all the factors rather than a single coefficient as in this case.

    estimate_capm <- function(data, min_obs = 1) {
    if (nrow(data) < min_obs) {
    beta <- as.numeric(NA)

    } else {
    fit <- lm(excess_returns ~ mkt_excess + hml + smb , data = data)
    # note that we take into account the coefficient of mkt_excess
    beta <- as.numeric(coefficients(fit)[2])

    }
    return(beta)
    }

    # rolling capm estimation
    roll_capm_estimation <- function(data, months, min_obs) {
    data
    arrange(date)

    betas <- slide_period_vec(
    .x = data,
    .i = data$date,
    .period = "month",
    .f = ~ estimate_capm(., min_obs),
    .before = months – 1,
    .complete = FALSE
    )

    return(tibble(
    month = unique(data$date),
    beta = betas

    ))
    }

    Reply

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.