I am trying to replicate the stock prediction case study from the Data Mining with R book, and am trying to place some of the code within a loop so I can deal with more than one stock. However, I cannot figure out how to get the specifyModel function to work within the loop. I want to calculate a number of technical indicators for each stock, and eventually use a random forest to select the most useful ones. Below is some example code.
library(quantmod)
# The list of stocks I want to investigate
stock.symbols = c("MMM", "IBM")
# Download daily stock prices to global environment
getSymbols(stock.symbols, src = "yahoo", quotes = c("Open", "High", "Low", "Close", "Volume", "Adjusted"), from = "2011-01-01", to = "2012-01-01")
# "Custom" indicator functions
myAroon = function(x) aroon(Cl(x))[,1]
myADX = function(x) ADX(HLC=x)[,4]
# Try to create quantmod model for each stock
for(i in stock.symbols)
{
my.model = specifyModel(Cl(MMM) ~ myAroon(MMM) + myADX(MMM)) # this line works - looks up MMM in global environment
# my.model = specifyModel(Cl(i) ~ myAroon(i) + myADX(i)) # I would like something like this
}
I understand that if you refer to the stock by its symbol, for example "MMM", specifyModel looks it up in the current workspace. I would like to know how to make this more general. At the minute I am getting the following error:
no applicable method for 'as.xts' applied to an object of class "character"
I have tried going through the documentation for specifyModel, but to no avail (it doesn't seem to be the most widely used function in the world). I have also tried using get() and as.name(). I realise I may be doing something completely wrong here, so apologies in advance! Any help at all would be greatly appreciated.
Using get
works for me.
my.model <- list()
for(i in stock.symbols)
{
stock <- get(i)
my.model = c(my.model, specifyModel(Cl(stock) ~ myAroon(stock) + myADX(stock)) )
}
lapply(my.model, function(x) head(x@model.data))