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!