[R-SIG-Finance] SMA & large n

Dirk Eddelbuettel edd at debian.org
Tue Sep 27 15:02:08 CEST 2011


On 27 September 2011 at 14:42, Anna Dunietz wrote:
| I would like to calculate the 377-day simple moving average on closing
| prices using the SMA function, but an error is always returned:
| 
| 
| 
| SMA(Cl(SPY),n=377)Error in runSum(x, n) : Invalid 'n'
| 
| 
| 
| Here is some code in order for you to quickly reproduce what I am doing:
| 
| 
| 
| getSymbols("SPY", from='1995-01-01', to='2010-01-01',
| index.class=c("POSIXt","POSIXct"))
| 
| SPY = to.monthly(SPY, indexAt='endof')
| 
| mysma<-SMA(Cl(SPY),n=377)

Monthly data from Jan 1995 to Jan 2010 covers 181 months:

   R> mm <- seq(as.Date("1995-01-01"), as.Date("2010-01-01"), by="month")
   R> head(mm)
   [1] "1995-01-01" "1995-02-01" "1995-03-01" "1995-04-01" "1995-05-01" "1995-06-01"
   R> length(mm)
   [1] 181
   R> 

You cannot run a moving average of length 377 over 181 observations.  

Maybe the magic number 377 came from daily data and you now want something
like 377 / 21 or about 18?

Dirk

-- 
New Rcpp master class for R and C++ integration is scheduled for 
San Francisco (Oct 8), more details / reg.info available at
http://www.revolutionanalytics.com/products/training/public/rcpp-master-class.php



More information about the R-SIG-Finance mailing list