Search code examples
rvolume

R: Faster Rolling VWAP


Given the following data

N<-1000;
Px<-runif(N, min = 100, max = 120);
Vol<-runif(N, min = 1, max = 20)

I generate a VWAP series rolling from index =1 with

VWAP<-unlist(lapply(seq(1,length(Px)),function(x) sum(Px[1:x]*Vol[1:x])/sum(Vol[1:x])))

This works well for N<10000 but as N approaches 1M the efficiency dramatically decreases. Any suggestions for a faster implementation?


Solution

  • You can use this syntax which doesn't recalculate sums of previous elements at each iteration:

      N<-1000000;
      Px<-runif(N, min = 100, max = 120);
      Vol<-runif(N, min = 1, max = 20)
      PxVol <- Px*Vol
      SPxVol <- cumsum(PxVol)
      SVol <- cumsum(Vol)
      VWAP <- SPxVol/SVol