December 2017
Beginner to intermediate
470 pages
12h 29m
English
There are times when simple logic shows us that there are parts of our implementations that are unnecessary. In this particular case, the accumulation of period_prices can be avoided by setting sma to 0 initially instead of NA, and adding to it each price. However, when doing so, we lose track of the number of elements in the vector, so the mean() function doesn't make sense any more, and we proceed to simply divide the sum by period as we were doing earlier:
sma_slow_5 <- function(period, symbol, data) { result <- NULL for(end in 1:nrow(data)) { position <- end sma <- 0 n_accumulated <- 0 if (data[end, "symbol"] == symbol) { while(n_accumulated < period & position >= 1) { if (data[position, "symbol"] == symbol) ...