0

How can I calculate a moving average (or other technical indicators) in R using different length parameters in different periods?

require(quantmod)
library(chron)
library(caTools)

## rm(list = ls())

#  Get the data
from.dat <- as.Date("2015-01-01")
#to.dat <- as.Date("2000-01-01")

ES <- getSymbols("^GSPC" , from = from.dat,auto.assign = FALSE) # to today

data <- ES
rm(ES)
data<-data[,6]
names(data)<-c("ES")


# create vectore with dummy values
data$num <- rep(10,length(data$ES))
for(i in 2:length(data$num)){
        if (data$num[i-1] == 10) {data$num[i] <- 5}
}


# moving average with moving length
data$sma<-SMA(data$ES, data$num )
plot(data$ema)

The plot does not show even a moving average. How to use technical indicators with moving length parameters?

Cettt
  • 11,460
  • 7
  • 35
  • 58
gcats
  • 41
  • 6

1 Answers1

1

If i do understand you correcty you want data$sma to be a vector of alternating length-5 average and length-10 average.

l5sma <- SMA(data$ES, 5) 
l10sma <- SMA(data$ES, 10)

data$sma <- ifelse(data$num == 5, l5sma, l10sma)
plot(data$ES)
lines(data$sma, col = 3)

enter image description here

Rentrop
  • 20,979
  • 10
  • 72
  • 100
  • Thank you Floo0, but I was looking for some more general script. What if I have a vector with much more "length" elements that change over the time? – gcats Dec 02 '15 at 10:01