Home > other >  Quantmod in R - How to work on multiple symbols efficiently?
Quantmod in R - How to work on multiple symbols efficiently?

Time:01-27

I'm using quantmod to work on multiple symbols in R. My instinct is to combine the symbols into a list of xts objects, then use lapply do do what I need to do. However, some of the things that make quantmod convenient seem (to this neophyte) not to play nicely with lists. An example:

> symbols <- c("SPY","GLD")
> getSymbols(symbols)
> prices.list <- mget(symbols)
> names(prices.list) <- symbols
> returns.list <- lapply(prices.list, monthlyReturn, leading = FALSE)

This works. But it's unclear to me which column of prices it is using. If I try to specify adjusted close, it throws an error:

> returns.list <- lapply(Ad(prices.list), monthlyReturn, leading = FALSE)
Error in Ad(prices.list) :
  subscript out of bounds: no column name containing "Adjusted"

The help for Ad() confirms that it works on "a suitable OHLC object," not on a list of OHLC objects. In this particular case, how can I specify that lapply should apply the monthlyReturn function to the Adjusted column?

More generally, what is the best practice for working with multiple symbols in quantmod? Is it to use lists, or is another approach better suited?

CodePudding user response:

Answer monthlyReturn:

All the **Return functions are based on periodReturn. The default check of periodReturn is to make sure it is an xts objects and then takes the open price as the start value and the close price as the last value and calculates the return. If these are available at least. If these are not available it will calculate the return based on the first value of the timeseries and the last value of the timeseries, taking into account the needed time interval (month, day, year, etc).

Answer for lapply:

You want do 2 operations on a list object, so using an function inside the lapply should be used:

lapply(prices.list, function(x) monthlyReturn(Ad(x), leading = FALSE))

This will get what you want.

Answer for multiple symbols:

  1. Do what you are doing.

  2. run and lapply when getting the symbols: stock_prices <- lapply(symbols, getSymbols, auto.assign = FALSE)

  3. use packages tidyquant or BatchGetSymbols to get all the data in a big tibble.

  4. ... probably forgot a few. There are multiple SO answers about this.

  •  Tags:  
  • Related