Storing the xts object returned by getSymbols

馋奶兔 提交于 2019-12-13 01:09:01

问题


I'm trying to collect mutual fund performance data via open and close prices from quantmod. I have scraped a list of 5000 some funds and am trying to loop through and get one open and close price for each fund. I'm having difficulty calling the xts object yielded by getSymbols() as it is called invisibly into the environment. Since the object is stored as its ticker name, I tried calling it by its ticker name.

Code so far:

## 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
}

Is there a way I can call the object using ls()?


回答1:


The key is to set the auto.assign argument to FALSE in getSymbols. This way you deactivate getSymbols automatic assignment to the global environment.

Here's an example that should guide you through step by step:

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

Hope this answered your question.



来源:https://stackoverflow.com/questions/28069655/storing-the-xts-object-returned-by-getsymbols

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!