I'm wondering what is the best way to apply dplyr/tidyr functions to time series data like stock prices.
The most widespread format is xts/zoo as per the below example using the tseries::get.hist.quote function:
library(tseries)
spy <- get.hist.quote(instrument="spy",start="2015-01-01",quote="AdjClose",compression="d")
agg <-get.hist.quote(instrument="agg",start="2015-01-01",quote="AdjClose",compression="d")
port <-as.xts(merge(spy,agg))
colnames(port) <-c("spy","agg")
As dplyr/tidyr functions works on dataframes we cannot run directly something like:
> gather(port, stock, price, 1:2)
Error in UseMethod("gather_") :
no applicable method for 'gather_' applied to an object of class "c('xts', 'zoo')"
but must convert "port" to a data.frame first:
gather(data.frame(Date=index(port), coredata(port)), stock, price, -Date)
Now my question is whether there is a better way to use dplyr/tidyr functions without going back and forth between xts/zoo and data.frame format.
Ideally a solution converting "port" into a tbl object on the fly would be perfect:
> gather(as.tbl(port), stock, price, -Date)
Error in UseMethod("as.tbl") :
no applicable method for 'as.tbl' applied to an object of class "c('xts', 'zoo')"
but unfortunately as.tbl() does not support xts/zoo objects...maybe it could be enhanced to support them too.