1

While I can manually use quantmod to collect volatilities on a stock-by-stock basis, such as:

library(quantmod)
library(TTR)
getSymbols("SPY",from="2010-01-02", to="2020-01-02")
vol=volatility(SPY,n=252,N=252,calc="close"),

This requires me to manually copy the symbol, (in the case above it is SPY), to the volatility function.

I have been trying to generate volatilities for a vector of symbols, but have unable to get this working without having to manually enter each symbol into the volatility function.

How can I pass the xts zoo output from getsymbols into the volatility function?

M--
  • 25,431
  • 8
  • 61
  • 93
mellose
  • 11
  • 1

1 Answers1

0

Create a new environment where the downloaded stock data will be saved. Loop through the objects in that environment, then run the volatility function on each object. Save the result in a list so that you don't overwrite the values. Then unlist.

stockEnv <- new.env()

stocks <- c("AAPL", "AMZN", "FB", "GOOG", "JNJ")

getSymbols(stocks, src='yahoo', env=stockEnv)

vol <- vector("list", length = length(stocks))
names(vol) <- stocks

for (stock in ls(stockEnv)){
  x <- get(stock, envir = stockEnv)
  if(is.xts(x)) vol[[stock]] <- volatility(x,n=252,N=252,calc="close")     
}

vol <- do.call(cbind, vol)

tail(vol)
                AAPL      AMZN        FB      GOOG       JNJ
2020-04-02 0.3942074 0.2847975 0.3764976 0.3471883 0.2944110
2020-04-03 0.3944644 0.2847008 0.3773450 0.3477343 0.2944769
2020-04-06 0.4028379 0.2884106 0.3840943 0.3564780 0.2973116
2020-04-07 0.4030194 0.2883778 0.3843052 0.3564362 0.2977434
2020-04-08 0.4037249 0.2887164 0.3856355 0.3569687 0.3005816
2020-04-09 0.4036574 0.2887087 0.3856682 0.3569642 0.3009180
Mr.Rlover
  • 2,523
  • 3
  • 14
  • 32