R:Quantmod 在股票代码前用 ^ 符号拉取标准普尔指数

R: Quantmod to pull S&P Index with ^ symbol before ticker

我在使用 quantmod 包获取标准普尔 (ticker = ^GSPC) 信息时遇到问题。

对于普通库存(例如:DFS),我可以 运行 下面的代码:

start <- as.Date("2020-01-01")
end <- as.Date("2020-05-06")
getSymbols("DFS", src = "yahoo", from = start, to = end)
DFS <-  data.frame(date=index(DFS), coredata(DFS))
head(DFS)

标准普尔的问题是名称中的 ^ 符号。

start <- as.Date("2020-01-01")
end <- as.Date("2020-05-06")
getSymbols("^GSPC", src = "yahoo", from = start, to = end)
SP500 <-  data.frame(date=index(^GSPC), coredata(^GSPC))

此代码给出以下错误:
错误:"SP500 <- data.frame(date=index(^"

中出现意外的“^”

有人知道解决这个问题的好方法吗?

使用auto.assign = FALSE。这允许您使用更合适的名称将您的值分配给您自己的 data.frame

start <- as.Date("2020-01-01")
end <- as.Date("2020-05-06")
df <- quantmod::getSymbols("^GSPC", src = "yahoo", from = start, to = end, auto.assign = FALSE)

附带说明一下,这也将是 quantmod 未来更新中的默认行为。