Optimize calculation of moving averages - is it possible?

Is it possible to optimize (make it much faster) this piece of code:

out <- do.call(rbind, lapply(split(Cl(cumulativeBars), "days"), function(x) { previousFullBars <- barsEndptCl[as.Date(index(barsEndptCl), tz=indexTZ(barsEndptCl)) < as.Date(last(index(x)), tz=indexTZ(x)), ] if (NROW(previousFullBars) >= 4) { last(SMA(last(rbind(previousFullBars, x), n=6), n=5)) } else { xts(NA, order.by=index(x)) } })) 

Below you can find my original question with all the sample code that works, but slows down my needs a bit.

ORIGINAL QUESTION:

After I was able to convert xts to a lower frequency in a cumulative way How to convert xts to a lower frequency in a cumulative way thanks to the people reading this list.

Now I'm trying to calculate the "evolution" of moving averages using the code below. That should slow me down. Can the tis code (from # TODO: how to calculate the moving average?), The Part starting with out <- do.call (rbind, lapply (split (Cl (cumulativeBars) ...) is optimized in some way?

 to.weekly.cumulative <- function(xts.obj, name="") { out <- do.call(rbind, lapply(split(xts.obj, 'weeks'), function(x) cbind(rep(first(x[,1]), NROW(x[,1])), cummax(x[,2]), cummin(x[,3]), x[,4]))) colnames(out) <- paste(name, c("Open", "High", "Low", "Close"), sep=".") out } library(quantmod) data(sample_matrix) myxts <- as.xts(sample_matrix) head(to.weekly.cumulative(myxts), 15) # TODO: How to compute moving average? # This SMA(Cl(to.weekly.cumulative(myxts)), n=5) would obviously be wrong cumulativeBars <- to.weekly.cumulative(myxts) barsEndptCl <- Cl(cumulativeBars[endpoints(cumulativeBars, 'weeks')]) barsEndptCl <- Cl(to.weekly(myxts)) #all.equal(cumulativeBars[endpoints(cumulativeBars, 'weeks')], to.weekly(myxts)) out <- do.call(rbind, lapply(split(Cl(cumulativeBars), "days"), function(x) { previousFullBars <- barsEndptCl[as.Date(index(barsEndptCl), tz=indexTZ(barsEndptCl)) < as.Date(last(index(x)), tz=indexTZ(x)), ] if (NROW(previousFullBars) >= 4) { last(SMA(last(rbind(previousFullBars, x), n=6), n=5)) } else { xts(NA, order.by=index(x)) } })) colnames(out) <- "SMA5" out <- lag.xts(out, k=7) chart_Series(to.weekly(myxts)) add_TA(SMA(to.weekly(myxts), 5), on=1, col="red") add_TA(out, on=1, col="green") 
+2
source share
1 answer

Moving averages do not exactly “evolve”, as you might be trying to figure out. Being an indicator of Momentum, it is more about cycles than about long-term evolution.

You can jump along the lines of the Moving Average, because you see that the trend is going in a certain way. The 200-day trend took place before the 190-day trend, and before that - the 180-day trend. It may be a more manageable concept to try to build a trading system around.

0
source

Source: https://habr.com/ru/post/1389168/


All Articles