Skip to content
Prev 353 / 15274 Next

Price Smoothing

Dear ManojW,

There is a function EWMA in the RMetrics package.

You can also write a script such as the following:

expma <- function(alpha,price.vec) {
  if(missing(alpha)) stop("alpha argument missing")
  if( alpha < 0 || alpha > 1 ) stop("alpha must be between 0 and 1 inclusive")
  if(missing(price.vec)) stop("price vector argument missing")
  n <- length(price.vec)
  x <- rep(0,n)
  x[1] <- price.vec[1]
  if( n > 1 )
  {
    for( i in 2:n )
      x[i] <- alpha*price.vec[i-1] + (1-alpha)*x[i-1]
  }
  xed
}

Since loops are slow in R, it will take some time to calculate all moving averages.  But if you save them, they are easily updated via the baxic formula.  

If you really need speed, however, you should write a function in C/C++ and use in inside or outside R.

Best,

Steve Moffit




---------- Original Message ----------------------------------
From: "ManojW" <manojsw@gmail.com>
Date:  Tue, 10 May 2005 20:57:23 +0900