问题
I would like to loop through a list of stock symbols and print them with chartSeries
. It would be easier than always changing the argument. Unfortunatly I always get an error, when I want to loop or subset:
Error in try.xts(x, error = "chartSeries requires an xtsible object"):
chartSeries requires an xtsible object
Here the code that produces the error:
library(quantmod)
stocks <- c("FIS", "AXP", "AVB")
symbols <- (getSymbols(stocks, src='yahoo'))
for (i in symbols){
chartSeries(i, theme="white",
TA="addVo();addBBands();addCCI();addSMA(20, col='blue');
addSMA(5, col='red');addSMA(50, col='black')", subset='last 30 days')
}
or only:
chartSeries(symbols[1], theme="white",
TA="addVo();addBBands();addCCI();addSMA(20, col='blue');
addSMA(5, col='red');addSMA(50, col='black')", subset='last 30 days')
回答1:
symbols
is a character vector. It's not a list of xts objects. Calling chartSeries
on a character vector causes the error.
R> chartSeries("OOPS")
Error in try.xts(x, error = "chartSeries requires an xtsible object") :
chartSeries requires an xtsible object
One solution is to put all the downloaded data into one environment, then call chartSeries
on every object in the environment.
library(quantmod)
stocks <- c("FIS", "AXP", "AVB")
stockEnv <- new.env()
symbols <- getSymbols(stocks, src='yahoo', env=stockEnv)
for (stock in ls(stockEnv)){
chartSeries(stockEnv[[stock]], theme="white", name=stock,
TA="addVo();addBBands();addCCI();addSMA(20, col='blue');
addSMA(5, col='red');addSMA(50, col='black')", subset='last 30 days')
}
来源:https://stackoverflow.com/questions/36120961/xtsible-object-looping-in-quantmod