I'm trying to calculate multiple EMA for S&P 500 with different underlying periods.
#get stock data
library(quantmod)
getSymbols("^GSPC", src="yahoo", from="2020-01-01", to="2020-09-30")
SP500 <- GSPC[,"GSPC.Close"]
I know how to do it manually, but this is no satisfying solution.
#Calculate different EMA with different periods
EMA1 <- EMA(SP500, n=1, wilder=F)
EMA2 <- EMA(SP500, n=2, wilder=F)
EMA3 <- EMA(SP500, n=3, wilder=F)
data.frame(SP500, EMA1, EMA2, EMA3)
GSPC.Close EMA EMA.1 EMA.2
2020-01-02 3257.85 3257.85 NA NA
2020-01-03 3234.85 3234.85 3246.350 NA
2020-01-06 3246.28 3246.28 3246.303 3246.327
2020-01-07 3237.18 3237.18 3240.221 3241.753
2020-01-08 3253.05 3253.05 3248.774 3247.402
Is it possible to count n up while creating a new column for each new EMA? How could that be done?
Additionally, how would you create correct labels for these columns? In the example above EMA.1 corresponds to "EMA2" and so on, which could be confusing. Manually I would do this:
EMA1 <- EMA(SP500, n=1, wilder=F)
EMA2 <- EMA(SP500, n=2, wilder=F)
EMA3 <- EMA(SP500, n=3, wilder=F)
mydata <- data.frame(SP500, EMA1, EMA2, EMA3)
colnames(mydata) <- c("GSPC Close","EMA1","EMA2","EMA3")
mydata
GSPC Close EMA1 EMA2 EMA3
2020-01-02 3257.85 3257.85 NA NA
2020-01-03 3234.85 3234.85 3246.350 NA
2020-01-06 3246.28 3246.28 3246.303 3246.327
2020-01-07 3237.18 3237.18 3240.221 3241.753
Thanks everyone!
You can use a for loop and merge everything in the loop. Advantage is that you merge xts objects. Afterwards you can transform this into a data.frame if you want to.
n = c(1:3, 5) # choose the number of EMA periods
for(i in n) {
var <- EMA(SP500$GSPC.Close, n = i, wilder = FALSE) # create the EMA
var <- setNames(var, paste0("EMA", i)) # rename the variable
SP500 <- merge(SP500, var) # merge with original
}
head(SP500) # SP500 is still an xts object
GSPC.Close EMA1 EMA2 EMA3 EMA5
2020-01-02 3257.85 3257.85 NA NA NA
2020-01-03 3234.85 3234.85 3246.350 NA NA
2020-01-06 3246.28 3246.28 3246.303 3246.327 NA
2020-01-07 3237.18 3237.18 3240.221 3241.753 NA
2020-01-08 3253.05 3253.05 3248.774 3247.402 3245.842
2020-01-09 3274.70 3274.70 3266.058 3261.051 3255.461