Search code examples
rquantmod

Using lapply with a list of stock symbols


I'm trying to use lapply, to apply a function to all the symbols I have in a list. The symbols are stock price data of the form:

Date Open High Low Close

I have been able to do it using this format:

require(TTR)
require(quantmod)

symbols <- c("XLF", "XLK", "XLU")

StartDate = '2015-01-01'
Stocks = lapply(symbols, function(sym, column) {
  SMA(na.omit(getSymbols(sym, from=StartDate, auto.assign=FALSE))[,4],20)
})

However I can't workout how to simply use lapply to apply a function to a list of symbols that I already have data for. I don't want to download the data using getSymbols, I want to use my own data for those same symbols.

In the below example I'm just downloading it for the sake of producing a reproducible example, however in reality I have the data for the symbols stored as XTS objects.

I can't understand why this won't work, or how it differs to the first example:

require(TTR)
require(quantmod)

symbols <- c("XLF", "XLK", "XLU")
getSymbols(symbols, src='yahoo', from = '2015-01-01')

SMA_Symbols <- lapply(symbols, function(sym, column) {
SMA(sym[,4],20)
})

I get the error:

Error in sym[, 4] : incorrect number of dimensions Called from: inherits(x, "xts")


Solution

  • The reason your second approach is not working is that getSymbol loads the data corresponding to the symbol to the global environment and symbols are still a vector of character type. Thus the sym is just a character doesn't really contain data.

    You can use get function to access the data attached with the name of the corresponding symbol. Something like this:

    require(TTR)
    require(quantmod)
    
    symbols <- c("XLF", "XLK", "XLU")
    getSymbols(symbols, src='yahoo', from = '2015-01-01')
    
    SMA_Symbols <- lapply(symbols, function(sym, column) {
        SMA(na.omit(get(sym))[,4],20)
    })
    
    head(SMA_Symbols[[1]][-(1:19)])
                   SMA
    2015-01-30 23.7580
    2015-02-02 23.6905
    2015-02-03 23.6685
    2015-02-04 23.6620
    2015-02-05 23.6550
    2015-02-06 23.6395