views:

115

answers:

1

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.

+1  A: 

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.

Shane
Thanks for the quick response. You've got me going in the right direction. Muddling through the help files to get to the final solution.
Milktrader
I got the rollapply method from zoo to work. Checked it against the results I get from Excel and they match.One thing I did differently is to read in the file with the read.zoo method and knock out the zoo object issue right from the start.An important parameter to set is by.column=F. I didn't put it in at first and got garbage.
Milktrader
Yes. I set that in my example for good reason. by.column=F means that it doesn't do the rollapply on each column individually, but passes them all in at once. Also make sure that you use align="right".
Shane
Why is it important to use align="right"? Default is "center" and this only aligns the text in the column, right?
Milktrader
@Milktrader - No: it does not have to do with text alignment. My advice: *play with it yourself and see what happens*. It's important that you understand the implications of these different settings if you're going to use that function. Please accept this answer if it answers your question.
Shane
Thanks, I will play with it as the help file is a bit opaque. Funny thing happened though when rollapply() created a new object, it did not name the vectors and I can't isolate them with the new_roll_object$v3 (for example) technique
Milktrader
Shane, you have answered my question. Is there something I need to do to move this thread to the 'answered' category. <- new to this great forum.
Milktrader
read the faq and labeled this question 'answered' Thanks Shane.
Milktrader
You can assign names to the columns with `colnames(object) <- c("name1", "name2", etc.)`.
Shane
Thanks again Shane.
Milktrader