xtsible对象,在quantmod中循环

时间:2016-03-20 23:34:35

标签: r quantmod stocks

我想循环查看股票代码列表并使用chartSeries打印它们。比总是改变论点容易。不幸的是,当我想要循环或子集时,我总是会收到错误:

Error in try.xts(x, error = "chartSeries requires an xtsible object"):
  chartSeries requires an xtsible object

这里产生错误的代码:

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')     
}

或仅限:

  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 个答案:

答案 0 :(得分:0)

symbols是一个字符向量。它不是xts对象的列表。在字符向量上调用chartSeries会导致错误。

R> chartSeries("OOPS")
Error in try.xts(x, error = "chartSeries requires an xtsible object") : 
  chartSeries requires an xtsible object

一种解决方案是将所有下载的数据放入一个环境中,然后在环境中的每个对象上调用chartSeries

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')     
}