HT create a new vector in data frame that takes correlation of existing vectors
-
20-09-2019 - |
Question
I have a time series of two indexes, with each row representing the closing price on the same day. I'd like to go to row 30 and lookback over the last 30 'days' and calculate the pearson correlation. And then store that value in a new vector. Then, repeat the calculation for the entire time series.
It is a trivial task in Excel, so I'm convinced it can be done in R. I don't know the method to use though.
Solution
There are many ways to do this (as with everything in R). I always recommend using a time series when working with time series data.
The zoo
package is probably the most popular time series package (although you can also look at others such as xts, timeSeries, its, fts):
library(zoo)
z <- zoo(data.frame(a=1:50, b=3:52), as.Date(1:50))
rollapply(z, 30, cor, by.column=F, align = "right")
You may also find the chart.RollingCorrelation
function in the PerformanceAnalytics
package useful.