Dani
Dani

Reputation: 2375

R: Calculate Quartely Returns from Monthly Returns

I have dataframe (return.monthly) of the form

Date         Return
2001-09-1    0.0404775
2001-10-1   -0.01771575
2001-11-1   -0.03304925
etc.

i.e. monthly returns over a period of time (2 years). I would like to calculate quarterly returns, i.e just take 3 observations and calculate the sum.

I tried

return.quarterly <- xts(return.monthly[, -1], return.monthly[,1])
function <- function(x) sum(x)
time <- 3
return.quarterly$return_q <- rollapply(return.quarterly$Return, FUN=function, 
width=time, align="left", na.pad=T)

Obviously this formula calculates returns over a rolling window, i.e. it takes observation 1-3 and calculates the sum, then 2-4 and calculates the sum, etc. What I want is however 1-3, 4-6, 7-9...

How could I do that?

Thanks in advance, Dani

Upvotes: 1

Views: 4949

Answers (1)

teucer
teucer

Reputation: 6238

You can use apply.quarterly from xts to compute the mean over a quarter:

apply.quarterly(return.quarterly,mean) #Jan-Feb-Mar first quarter etc.

BTW: shouldn't you consider instead of the mean the sum, for quarterly returns?

Upvotes: 4

Related Questions