I have a data table that contains return data of a company looking like this:
df=structure(list(Date = structure(c(13236, 13237, 13238, 13239,
13240, 13241, 13242, 13243, 13244, 13245, 13246, 13247, 13248,
13249, 13250, 13251), class = "Date"), IBES = c("@O5G", "@O5G",
"@O5G", "@O5G", "@O5G", "@O5G", "@O5G", "@O5G", "@O5G", "@O5G",
"@O5G", "@O5G", "@O5G", "@O5G", "@O5G", "@O5G"), MktAdjReturn = c(-0.00381466643441897,
-0.00834070809256926, -0.0193226301897589, NA, NA, -0.00885564092195712,
-0.051612619547402, -0.0065292323057804, 0.042244140103735, 0.003100395243401,
NA, NA, -0.00486229222347689, -0.0184708840023963, 0.00273824763632391,
-0.00510010246255499)), .Names = c("Date", "IBES", "MktAdjReturn"
), class = c("data.table", "data.frame"), row.names = c(NA, -16L
))
I want to calculate the moving average of the following 5 days excluding the current day. Therefore, the code should skip the NA and take the next available returns.
E.g. For the for the first Date 2006-03-29 the 5 days moving average should contain: -0.008340708 ; -0.019322630 ; -0.008855641 ; -0.051612620 ; -0,006529232
.
I tried:
rollapply(MktAdjReturn,width = 5,FUN=mean,align = "left",fill = NA,na.rm=T), by=c("IBES")
But, it includes the current date as well and I am not sure what it exactly does with fill = NA
.