2

I am new to the R language and as you will most likely notice I have some experience in C. I am working on making my program run faster and thus be more efficient.

The code below is just calculating a simple moving average from the data set:

library(quantmod)
StockData1 <- getSymbols("AAPL", auto.assign=FALSE, from="1984-01-01")

As far as I could find there is no quick pre-made function that will just do it for me so I made my own.

moving_avg <- function(StockData, MA, CurrentDay){

  #MA = Days long the MA is
  #CurrentDay = What day we are currently on

  MAValue <- NULL
  n <- 0
  total <- 0
  start <- CurrentDay - MA
  repeat {
    total <- total + StockData[[start, 4]]
    start <- start + 1
    n <- n + 1
    if(n == MA){
      break
    }
  }
  MAValue <- total/MA
  return(MAValue)
}

I tested it using microbenchmark:

library(microbenchmark)
microbenchmark(print(moving_avg(StockData1, 256, 300)))

My results were around 1000 microseconds which I find pretty slow for such a simple function.

rawr
  • 20,481
  • 4
  • 44
  • 78
LBD
  • 53
  • 4
  • 3
    There are many quick, pre-made functions: http://stackoverflow.com/q/743812/903061 – Gregor Thomas Apr 21 '15 at 16:34
  • Existing code for moving averages: [R Cookbook](http://www.cookbook-r.com/Manipulating_data/Calculating_a_moving_average), and [this answer](http://stackoverflow.com/a/743846/3005513). – Alex A. Apr 21 '15 at 16:34
  • 1
    If you are familiar with C then maybe try [Rcpp](http://cran.r-project.org/web/packages/Rcpp/index.html)? – zx8754 Apr 21 '15 at 16:35
  • 1
    You know, you didn't need to change your user name. +1 for making your code simple and reproducible; see the first comment for answers. – BrodieG Apr 21 '15 at 16:37
  • all your function does for me is `sum(StockData1[(300 - 256):(300 - 1), 4]) / 256` not a moving average – rawr Apr 21 '15 at 16:43

0 Answers0