【问题标题】:Storing the xts object returned by getSymbols存储 getSymbols 返回的 xts 对象
【发布时间】:2015-01-21 14:30:01
【问题描述】:

我正在尝试通过 quantmod 的开盘价和收盘价收集共同基金业绩数据。我已经抓取了 5000 支基金的清单,并试图循环并为每个基金获得一个开盘价和收盘价。我很难调用getSymbols() 产生的xts 对象,因为它被无形地调用到环境中。由于该对象存储为其股票代码名称,因此我尝试通过其股票代码名称来调用它。

到目前为止的代码:

## loop thru list and use quantmod to calculate performance from 1/2/14 to 12/31/14
for(i in 1:4881){
    ticker <- tickernames[i]
    getSymbols(ticker)
    Open <- ticker["2014-01-02",1]
    Close <- ticker["2014-12-31",4]

    performance2014[i] = (Open - Close)/Open
}

有没有办法可以使用ls() 调用对象?

【问题讨论】:

  • 试试help(getSymbols) 并寻找auto.assign

标签: r xts quantmod


【解决方案1】:

关键是将getSymbols中的auto.assign参数设置为FALSE。这样您就可以禁用 getSymbols 自动分配到全局环境。

下面是一个示例,可以逐步指导您完成:

require(quantmod)

#Vector of symbols to fetch prices for
symbols <- c('MSFT','SBUX','GOOGL')

#Initialize a list to store the fetched prices
myList <- list()

#Loop through symbols, fetch prices, and store in myList
myList <-lapply(symbols, function(x) {getSymbols(x,auto.assign=FALSE)} )

#Housekeeping
names(myList) <- symbols

#Access MSFT prices
myList[['MSFT']]

#Access SBUX prices
myList[['SBUX']]

#Access GOOGL prices
myList[['GOOGL']]

希望这回答了你的问题。

【讨论】:

    猜你喜欢
    • 2020-07-20
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-08
    • 2020-02-16
    • 1970-01-01
    相关资源
    最近更新 更多