4

我使用 quantmod 的getSymbols函数下载多个代码的历史价格,并使用以下代码将它们转换为列表或多变量 XTS:

library(quantmod)

myenv <- new.env()
tickers <- c("^GSPC", "AAPL", "MSFT", "GOOG", "^RUT")
getSymbols(tickers, env=myenv)
ll <- eapply(myenv, function(x) x)        # Convert to list
ts <- do.call(merge, (eapply(myenv, Ad))) # Convert to multivariate XTS and extract only the adjusted price

我用这种方法遇到的问题是列表中代码的顺序和 XTS 与我在中指定的不同tickers

> names(ll)
[1] "AAPL" "GSPC" "GOOG" "RUT"  "MSFT"
> names(ts)
[1] "AAPL.Adjusted" "GSPC.Adjusted" "GOOG.Adjusted" "RUT.Adjusted" 
[5] "MSFT.Adjusted"

我认为这是因为eapply以随机顺序执行操作,如帮助页面中所述eapply

Note that the order of the components is arbitrary for hashed environments.

如何执行上述相同的操作,但输出的顺序与tickers向量中指定的顺序相同?即列表的第一项/XTS 的第一列应该对应于tickers向量的第一个元素,依此类推。

4

2 回答 2

4

您可以将结果子集eapply化为您想要的顺序。

library(quantmod)
tickers <- c("^GSPC", "AAPL", "MSFT", "GOOG", "^RUT")
myenv <- new.env()
symnames <- getSymbols(tickers, env=myenv)  # getSymbols returns adjusted names
ts <- do.call(merge, eapply(myenv, Ad)[symnames])
于 2013-03-21T12:37:04.103 回答
2

尝试mget代替eapply. 注意:需要使用从股票名称中删除gsub以获取.^objectmyenv

library(quantmod)

myenv <- new.env()
tickers <- c("^GSPC", "AAPL", "MSFT", "GOOG", "^RUT")
getSymbols(tickers, env = myenv)
## [1] "GSPC" "AAPL" "MSFT" "GOOG" "RUT" 

test <- mget(gsub("\\^", "", tickers), envir = myenv)
ts <- do.call(merge, lapply(test, Ad))
names(ts)
## [1] "GSPC.Adjusted" "AAPL.Adjusted" "MSFT.Adjusted" "GOOG.Adjusted" "RUT.Adjusted" 

tickers
## [1] "^GSPC" "AAPL"  "MSFT"  "GOOG"  "^RUT" 
于 2013-03-21T08:05:29.437 回答