Step 1: Make sure required packages are loaded

This code requires the Quandl package and the xts time series package.

require(xts)
require(Quandl)

Step 2: Create a function

The function name is “stockret()”
Input: a list of ticker symbols for the arguments.
Output: A series of monthly stock returns.

  1. Set up an empty time series data set
  2. Convert the tickers into quandle time series ids “codelist”
  3. Loop through ids
    1. use quandle to grab data for each id
      A. Collapse to monthly observations
      B. Specify data to collect “adjusted close” C. Transform to percent change
    2. merge to a single data set
    3. set the name of each data series to the ticker symbol
  4. Returns the data set
stockret<- function(tickers){
  data=xts()
  codelist<-paste("YAHOO/",tickers,sep="")
  for(i in 1:length(tickers)) {
    d<-Quandl(codelist[i], type="xts", collapse="monthly", transform = "rdiff")$'Adjusted Close'
    data<-merge.xts(d,data)
  }
names(data)<-tickers
return(data)
}

Step 3: Try using the function

  1. Create a list of the tickers to look up in Quandl
    1. Note that this may require going to Quandl to do a little searching
    2. The Quandl database is set to YAHOO and cannot be changed without changing the funciton
  2. Call up the data object to view it
tickers <- c("FUND_DFUSX", "FUND_DFLVX", "FUND_DFSVX", "FUND_DFIVX")

returns<-stockret(tickers)

Step 4: Plot one of the xts objects

plot.xts(returns$FUND_DFIVX)