如何使用 getSymbols 下载一组价格并按照请求的顺序存储它们? [英] How can I download a set of prices with getSymbols and store them in the order it was requested?

查看:46
本文介绍了如何使用 getSymbols 下载一组价格并按照请求的顺序存储它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I download historical prices with quantmod's getSymbols function for multiple tickers and convert them into either a list or a multivariate XTS with the following code:

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 中指定的不同:

The problem I have with this approach is that the order of the tickers in the list and the XTS are not the same as what I specified in 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 的帮助页面所述:

I think this is because eapply performs the operations in a random order, as explained in the help pages of eapply:

请注意,对于散列环境,组件的顺序是任意的.

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

How can I perform the same operations above but have an output that is in the same order as specified in my tickers vector? I.e. first item of the list / first column of XTS should correspond to first element of the tickers vector and so on.

推荐答案

您可以将 eapply 的结果子集到您想要的顺序.

You could just subset the results of eapply into the order you want.

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])

这篇关于如何使用 getSymbols 下载一组价格并按照请求的顺序存储它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆