Rolling Regression and Pairs Trading in R
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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 beta coefficient evolve 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.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.