Storing the xts object returned by getSymbols
I am trying to collect data on the performance of a mutual fund via open and close prices from quantmod. I have cleared the 5000 funds list and I am trying to go through one open and close price for each fund. I am having a hard time calling the xts object provided getSymbols()
as it appears invisibly in the environment. Since the object is stored as its tick name, I tried calling it ticker.
The 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 it possible to call an object using ls()
?
source to share
The key is to set the argument auto.assign
to FALSE
in getSymbols
. This will disable automatic assignment getSymbols
for the global environment.
Here's an example to guide you 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']]
I hope this is the answer to your question.
source to share