# Getting monthly return using quantmod, if input ticker is a variable

I am new to package quantmod and quandl. I encountered a problem while I was trying to fetch period return data. Below is my source code:

require(TTR)
require(quantmod)
SYMs <- TTR::stockSymbols()
filtered = SYMs[!is.na(SYMs$Sector) & !is.na(SYMs$Industry),]
selected = filtered[,c("Symbol", "Sector", "Industry")]
for(i in 1:nrow(selected)){
ticker = selected$Symbol[i] getSymbols(ticker) selected$MonthyReturn <- monthlyReturn(ticker, subset='2017-11-10')
}


The problem of this code is that the monthlyReturn will not operate, giving an error of Error in try.xts(x) : Error in UseMethod("as.xts") : no applicable method for 'as.xts' applied to an object of class "character".

This error does not seem very intuitive to me. I tried an actual ticker and noticed that the monthlyReturn(ticker, subset='2017-11-10') will only work if the ticker is not of type character (e.g. AAPL instead of 'AAPL' will work fine).

Can I know what is the reason?

When writing getSymbols(ticker) the function is creating an xts object in the global env named by the ticker. In the first iteration, when i = 1, ticker is a character, "AAMC".

Next, when you are trying to get the monthly returns for that newly created xts object, monthlyReturn(ticker, subset='2017-11-10') you are referencing the character, not the newly created xts object, named AAMC as well.

To fix this, you could xtsTicker <- getSymbols(ticker, auto.assign = FALSE) then monthlyReturn(xtsTicker, subset='2017-11-10')

One thing to note as well, selected$MonthyReturn <- is referencing all rows within that column. This should be changed to selected$MonthyReturn[i].

While this answers your question as why the monthlyReturn() function will not work, this may not make your for loop work. This loop is bound to run into errors, which will break upon. For some tickers, there will not be an monthly returns to give. In that case, you could add an if statement to take care of that. One option would be:

for(i in 1:nrow(selected)){
ticker = selected$Symbol[i] xtsTicker <- getSymbols(ticker, auto.assign = FALSE) if(nrow(monthlyReturn(xtsTicker, subset='2017-11-17')) == 0){ selected$MonthyReturn[i] <- NA
}else{
selected\$MonthyReturn[i] <- monthlyReturn(xtsTicker, subset='2017-11-17')
}
}


There will also be times where a ticker is unable to be downloaded, hence another error.