3

I'm learning R this semester and this is my first assignment. I want to retrieve monthly Adjusted stock quotes within a set date range using a for loop. And once I am able to do that I want to merge all the data into a data frame.

My code so far retrieves daily stock quotes for 5 stock symbols within a set date range, it assigns the object to the environment specified, and places only the .Adjusted column in the list.

Could someone point me in a better direction in obtaining the monthly quotes and am I on the right track with my code.

Thanks.

#Packages
library(quantmod)

#Data structure that contains stock quote objects
ETF_Data <- new.env()

#Assign dates to set range for stock quotes
sDate <- as.Date("2007-08-31")
eDate <- as.Date("2014-09-04")

#Assign a vector of ticker symbols.
ticker_symbol <- c("IVW","JKE","QQQ","SPYG","VUG")

#Assign number of ticker symbols.
total_ticker_symbols <- length(ticker_symbol)

#Assign empty list to for each object contained in my environment. 
Temp_ETF_Data <- list()

#Assign integer value to counter.
counter <- 1L

#Loop and retrieve each ticker symbols quotes from Yahoo's API 
for(i in ticker_symbol)  
{  

  getSymbols(
    i, 
    env = ETF_Data, 
    reload.Symbols = FALSE, 
    from = sDate, 
    to = eDate,
    verbose = FALSE,
    warnings = TRUE,
    src = "yahoo",
    symbol.lookup = TRUE) 

  #Add only Adjusted Closing Prices for each stock or object into list. 
  Temp_ETF_Data[[i]] <- Ad(ETF_Data[[i]])  

  if (counter == length(ticker_symbol))
  { 
     #Merge all the objects of the list into one object. 
     ETF_Adj_Daily_Quotes   <- do.call(merge, Temp_ETF_Data)
     ETF_Adj_Monthly_Quotes <- ETF_Adj_Daily_Quotes[endpoints(ETF_Adj_Daily_Quotes,'months')]
  }
  else
  {
    counter <- counter + 1
  }

}

3 Answers3

3

I know that this is an old question but this answer might help potential future users seeking a better answer.

quantmod has now introduced an additional parameter to the getSymbols function called periodicity which can take the values of daily, weekly, monthly.

I tested out the following and it seems to work as desired:

getSymbols("EURGBP=X", from = starting, src = 'yahoo', periodicity = 'monthly')
David
  • 1,192
  • 5
  • 13
  • 30
2

There's no need for the for loop. You can loop over all the objects in the environment with eapply:

getSymbols(ticker_symbol, env=ETF_Data, from=sDate, to=eDate)
# Extract the Adjusted column from all objects,
# then merge all columns into one object
ETF_Adj_Data <- do.call(merge, eapply(ETF_Data, Ad))
# then extract the monthly endpoints
Monthly_ETF_Adj_Data <- ETF_Adj_Data[endpoints(ETF_Adj_Data,'months')]
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • Code does exactly what I need. The reason for the for loop is our Professor wanted us to use one. Nonetheless, great stuff. Thanks! –  Oct 31 '14 at 16:55
-1

just use

to.monthly(your_ticker)
Oktu
  • 187
  • 1
  • 4
  • 10