使用同一图上环境中的数据绘制多个时间序列

时间:2018-07-07 17:15:41

标签: r quantmod

我正在使用以下字符:

myTixsectors <- c("APD", "ALB", "AVY", "BLL", "CF", "DWDP", "EMN", "ECL", "FMC", 
"FCX", "IP", "IFF", "LYB", "MLM", "MOS", "NEM", "NUE", "PKG", 
"PPG", "PX", "SEE", "SHW", "VMC", "WRK")

并且我有以下代码可以下载财务数据:

data <- new.env()

library(quantmod)

getSymbols(myTixsectors, src = 'yahoo', from = "2018-01-01", to = "2018-06-01", env = data)

normalise_series <- function(xdat) xdat / coredata(xdat)[1]
window <- "2018/"
getSymbols("SPY")

mytheme <- chart_theme()
mytheme$col$line.col <- "blue"
chart_Series(normalise_series(Cl(SPY)[window]) - 1, theme = mytheme, col = "blue")

我想做的是在SPY500上绘制时间序列。我可以使用以下方法做到这一点;

mytheme <- chart_theme()
mytheme$col$line.col <- "blue"
chart_Series(normalise_series(Cl(SPY)[window]) - 1, theme = mytheme, col = "blue")
add_TA(normalise_series(Cl(data$ALB)[window]) - 1, on = 1, col = "red", lty = 3)
add_TA(normalise_series(Cl(data$AVY)[window]) - 1, on = 1, col = "red", lty = 3)
add_TA(normalise_series(Cl(data$BLL)[window]) - 1, on = 1, col = "red", lty = 3)
add_TA(normalise_series(Cl(data$CF)[window]) - 1, on = 1, col = "red", lty = 3)
add_TA(normalise_series(Cl(data$DWDP)[window]) - 1, on = 1, col = "red", lty = 3)

但是这比较耗时,我无法将其重复到新数据上,因为每次我都必须手动更改data$DWDPdata$CF等。

我试图创建一个for循环以添加时间序列;

for(tick in myTixsectors){
  add_TA(normalise_series(Cl(data[[tick]])[window]) - 1, on = 1, col = "yellow", lty = 3)
}

但是,这不起作用。有没有一种方法可以调用环境中的所有数据框并绘制它们?

注意:这是跟我之前发布的here问题有关的后续问题。目标是相似的,但是我觉得这更是解决问题的正确方法。

编辑:我也正在尝试eapply,但是没有运气。

eapply(data, function(x) add_TA(normalise_series(Cl(x))))

1 个答案:

答案 0 :(得分:1)

要回答我自己的问题,我使用了以下内容:

mytheme <- chart_theme()
mytheme$col$line.col <- "blue"
chart_Series(ROC(Cl(SPY))[window], theme = mytheme, col = "blue")
eapply(data, function(x) add_TA(ROC(Cl(x))[window], on = 1, col = "grey", lty = 3))

使用eapply函数并以蓝色绘制SPY收益,从而绘制列表中所有交易品种的收盘价收益。