xtsible object, looping in quantmod

自闭症网瘾萝莉.ら 提交于 2021-01-29 01:49:34

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!