Search code examples
rxtsquandl

Create an xts object in R from multiple Quandl codes


I am trying to pull multiple Quandl codes at the same time into R, and want to end up with a single xts object with [i] columns (plus the date column) containing the data.

The function I created to call the data from Quandl seems okay, but I need help with the syntax to create a xts object. Here is what I have so far:

# Build vector of model holdings
holdings <- c("VTI","VEA","VWO","LQD","BND","TLT","VNQ","GLD","VGSH")

# Function to fetch each holding as an xts object, adjusted close returns
getQholdings <- function(ticker){
  codes <- paste("EOD/",ticker,".11",sep="")
  for(i in 1:length(ticker)){
      ???? <- Quandl(codes[i],type="xts",transformation="rdiff",
                     start_date="2013-12-31",collapse="monthly",
                     force_irregular=TRUE)
    }}

I need help where the question marks are, which I assume should be some kind of function to build a xts object progressively with each iteration of the "for" function.


Solution

  • You don't need to build the xts object - Quandl function does it for you.

    Example with 2 codes:

    codes <- c("EOD/VTI.11", "EOD/VEA.11")
    x1 <- Quandl(codes,type="xts",transformation="rdiff",
           start_date="2013-12-31",collapse="monthly",
           force_irregular=TRUE)
    
    head(x1)
    

    Result:

               EOD.VTI - Adj_Close EOD.VEA - Adj_Close
    2014-01-31        -0.031693078        -0.052063340
    2014-02-28         0.048664944         0.059478613
    2014-03-31         0.005078150        -0.003653885
    2014-04-30         0.000615574         0.015749939
    2014-05-31         0.021019174         0.017652672
    2014-06-30         0.026241859         0.010426937
    

    Merge time series

    But if you already have two time series then use merge:

    x1 <- Quandl("EOD/VTI.11", type="xts", ......
    x2 <- Quandl("EOD/VEA.11", type="xts", ......
    
    x <- merge(x1, x2)
    

    merge on xts is based on time series' time index.