Using quantmod Data Objects to Calculate Monthly Stock Returns
Summary
The document diagnoses an R workflow error when calculating monthly returns for downloaded stock data. The central issue is that getSymbols, by default, assigns the downloaded time series to the global environment, while the loop variable still contains the ticker as a character string. Passing that string to monthlyReturn therefore supplies a symbol name rather than the xts price series the function expects.
The suggested remedy is to call getSymbols with automatic assignment disabled and store its returned xts object, then pass that object to monthlyReturn. The answer also points out that assigning a result to an entire data-frame column inside the loop does not target the current row; an indexed assignment is needed. Empty return periods and failed downloads can still interrupt processing, so the example handles absent monthly data and the text flags download failures as another case requiring error handling. The guidance is specific to data retrieval and analysis workflow, not a return-prediction method.
Key ideas
- By default, getSymbols assigns downloaded price data under a ticker-named object.
- A ticker stored as a character string is not itself the xts series needed by monthlyReturn.
- Disabling automatic assignment lets the loop capture and pass the downloaded series directly.
- Within a loop, indexed column assignment updates the intended row rather than the entire column.
- Missing observations and failed downloads require separate handling.
Tags
Full text
# Getting monthly return using quantmod, if input ticker is a variable
# 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?
## Answer by Dulljohn (score 2, accepted)
https://quant.stackexchange.com/a/36969
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.Shown in full with attribution under the source's licence. Licence: CC BY-SA 4.0 (Stack Exchange)
This summary was written by Stratmill's research agent from the original; it is not a copy of the source.