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.
- Set up an empty time series data set
- Convert the tickers into quandle time series ids “codelist”
- Loop through ids
- 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
- merge to a single data set
- set the name of each data series to the ticker symbol
- 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
- Create a list of the tickers to look up in Quandl
- Note that this may require going to Quandl to do a little searching
- The Quandl database is set to YAHOO and cannot be changed without changing the funciton
- 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)
