在RStudio中批量绘制ETF行情图表报错:chartSeries需xtsible对象
解决chartSeries批量绘图的xtsible对象错误
你用getSymbols获取ETF数据后,单个调用chartSeries(VGWD.DE)能正常绘图,但循环里用chartSeries(i)就触发报错:
Error in try.xts(x, error = "chartSeries requires an xtsible object") : chartSeries requires an xtsible object
错误原因
getSymbols默认会把获取的xts格式数据,以标的代码(比如VGWD.DE)作为变量名存入全局环境;而循环中的i只是字符串(比如"VGWD.DE"),chartSeries需要的是xts对象而非字符串,因此触发类型不匹配错误。
解决方法
方法1:用get()将字符串转为对应对象
直接修改循环代码,用get()从全局环境中取出字符串对应的xts对象:
for (i in ETF_list){ chartSeries(get(i), theme = chartTheme("white"), name = i, bar.type = "hlc", up.col = "green", dn.col = "red", TA = list("addVo()", "addEMA(n = 200, on = 1, col = 'blue')", "addEMA(n = 50, on =1, col = 'red')")) }
方法2:将数据存入列表(更规范的写法)
避免全局环境中散落变量,直接把getSymbols获取的数据存入列表,后续循环列表元素即可:
library(ggplot2) library(quantmod) library(magrittr) start_date <- as.Date("2020-01-02") end_date <- as.Date("2023-04-12") ETF_list <- c("WTEE.DE", "VGWD.DE") # 把所有ETF数据存入列表 etf_data <- lapply(ETF_list, function(code) { getSymbols(code, from = start_date, to = end_date, src = "yahoo", auto.assign = FALSE) }) names(etf_data) <- ETF_list # 给列表元素命名,方便识别 # 循环绘制所有标的图表 for (code in names(etf_data)){ chartSeries(etf_data[[code]], theme = chartTheme("white"), name = code, bar.type = "hlc", up.col = "green", dn.col = "red", TA = list("addVo()", "addEMA(n = 200, on = 1, col = 'blue')", "addEMA(n = 50, on =1, col = 'red')")) }
这里关键是给getSymbols加上auto.assign = FALSE参数,让它直接返回xts对象而非自动存入全局环境,再用lapply统一收集数据到列表,后续管理和操作更清晰。
内容的提问来源于stack exchange,提问作者BehSci
相关产品推荐
相关产品推荐

