Search code examples
rdataframemergextsquantmod

Merge output from quantmod::getSymbols


I looked many entries on merging R data frames, however they are not clear to me, they talk about merging/joining using a common column, but in my case its missed or may I don't know how to extract. Here is what I am doing.

library(quantmod)
library(xts)
start = '2001-01-01'
end = '2015-08-14'
ticker = 'AAPL'
f = getSymbols(ticker, src = 'yahoo', from = start, to = end, auto.assign=F)
rsi14 <- RSI(f$AAPL.Adjusted,14)

The output I am expecting is all the columns of f and rsi14 match by date, however 'date' is not available as column, so not sure how do I join. I have to join few Moving Average columns as well.


Solution

  • The premise of your question is wrong. getSymbols returns an xts object, not a data.frame:

    R> library(quantmod)
    R> f <- getSymbols("AAPL", auto.assign=FALSE)
    R> str(f)
    An ‘xts’ object on 2007-01-03/2015-08-14 containing:
      Data: num [1:2170, 1:6] 86.3 84 85.8 86 86.5 ...
     - attr(*, "dimnames")=List of 2
      ..$ : NULL
      ..$ : chr [1:6] "AAPL.Open" "AAPL.High" "AAPL.Low" "AAPL.Close" ...
      Indexed by objects of class: [Date] TZ: UTC
      xts Attributes:  
    List of 2
     $ src    : chr "yahoo"
     $ updated: POSIXct[1:1], format: "2015-08-15 00:46:49"
    

    xts objects do not have a "Date" column. They have an index attribute that holds the datetime. xts extends zoo, so please see the zoo vignettes as well as the xts vignette and FAQ for information about how to use the classes.

    Merging xts objects is as simple as:

    R> f <- merge(f, rsi14=RSI(Ad(f), 14))
    

    Or you could just use $<- to add/merge a column to an existing xts object:

    R> f$rsi14 <- RSI(Ad(f), 14)