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