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.