如何使用getSymbols下载一组价格并按照请求的顺序存储它们?

时间:2013-03-21 07:38:20

标签: r quantmod

我使用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向量的第一个元素,依此类推。

2 个答案:

答案 0 :(得分: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])

答案 1 :(得分:2)

尝试使用mget代替eapply。注意:需要使用gsub从代码名称中删除^,以便在object中获取myenv个名称。

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"