Search code examples
rmoving-averagequantitative-financeweighted-averagerolling-computation

Apply sum product on columns of a dataframe in rolling windows


I have a set of defined weights and I want to calculate the weighted sum of returns in rolling windows on a time series dataframe. I believe we would use rollapplyr here, but I am unsure how to perform rolling window function across each row of the dataframe.

Find below dput output of a sample of the data:

tempVar <- structure(c(NA, -0.0081833512947922, 0.00508150903899551, -0.0072202479734873, 
0.00345258369231161, NA, 0, -0.00847462699097257, -0.00794638265247283, 
0.00445091892889238, NA, NA, NA, NA, NA, NA, 0, -0.0136462286616492, 
-0.00638979809877149, -0.00109950533341685), class = c("xts", 
"zoo"), .indexCLASS = "Date", .indexTZ = "UTC", tclass = "Date", tzone = "UTC", index = structure(c(946598400, 
946857600, 946944000, 947030400, 947116800), tzone = "UTC", tclass = "Date"), .Dim = 5:4, .Dimnames = list(
    NULL, c("TY00.USA", "CGB00.MOD", "G10L00.IFEU", "RLI00.IFEU"
    ))) 

And simplicity, lets consider weights to be:

tempWeights <- c(1.09,0.89,0)

Note: the weights suggest that as of the date of evaluation, returns of that date have no weighting.These weights do not sum to 1 by design

I would like the output to be:

tempRRI <- structure(c(NA, NA, NA, -0.00439731, -0.0008871759, NA, NA, NA, 
-0.00754241803, -0.0163096243, NA, NA, NA, NA, NA, NA, NA, NA, 
-0.01214514381, -0.02056130983), .Dim = 5:4, .Dimnames = list(
    NULL, c("TY00.USA", "CGB00.MOD", "G10L00.IFEU", "RLI00.IFEU"
    )), index = structure(c(946598400, 946857600, 946944000, 
947030400, 947116800), tzone = "UTC", tclass = "Date"), .indexTZ = "UTC", class = c("xts", 
"zoo"), .indexCLASS = "Date", tclass = "Date", tzone = "UTC")

Hopefully something similar to weighted.mean() but for sum, or if someone can please advise how I can can take sum product of each column (on rolling basis) with tempWeights.The weighted.sum() does not do the same thing.

tempRRI <- rollapplyr(tempVar, width = 3, function(x) {weighted.mean(x,tempWeights)}, by.column = TRUE) 

Solution

  • You adjust the formula by multiplying weighted.mean() with the sum of weights:

    tempRRI <- rollapplyr(tempVar, width = 3, function(x) {weighted.mean(x,tempWeights)*sum(tempWeights)}, by.column = TRUE)