I am trying to download some stock data from which I would like to automatically pick out the ones which satisfy certain conditions relating to moving averages. So far I have been able to download the data, but I am having difficulty trying to create the moving average data for every stock.
# Read csv as character list
ticker.list <- as.character(read.csv("shortftse250tickers.csv",header=F)$V1)
ftse250 <- new.env()
allData <- list()
# Get data
allData <- getSymbols(ticker.list, from='2017-01-03', src='google', env = ftse250)
# Extract Close data in correct order
tl <- mget(ticker.list, envir = ftse250)
closeData <- do.call(merge, eapply(ftse250, Cl)[allData])
# Calculate EMAs for each stock
for (i in ticker.list) {
ema3 <- EMA(closeData[i], 3)
ema7 <- EMA(closeData[i], 7)
}
Everything seems ok up until I reach the last for loop, where I receive the error:
Error in if (length(c(year, month, day, hour, min, sec)) == 6 && c(year, :
missing value where TRUE/FALSE needed
I have tried converting the closeData to a list using newData <- as.list(closeData)
, and received the error:
Error in EMA(newData[i], 3) : Invalid 'n'
I can manually calculate the EMA no problem with:
EMA(newData$ZPLA)
Any help would be much appreciated.
Two things: (1) the column names of closeData have .Close appended to them. (2) closeData is an xts object so you need to subset differently. Try this out for your loop:
# Calculate EMAs for each stock
for (i in paste0(ticker.list, ".Close")) {
ema3 <- EMA(closeData[, i], 3)
ema7 <- EMA(closeData[, i], 7)
}