Search code examples
rtime-seriesapplyxtsquantile-regression

Run regression for each month of a timeseries - apply.monthly does not work


I want to apply a quantile regression (with one dependent and one independent variable) to each month of a one-year time series , so that I will receive 12 coefficients as a result. My data set is given by return_2000_xts and rq() is a function for quantile regression. My dataset is in xts format and includes daily returns of bank stocks.

I tried using apply.monthly():

apply.monthly(return_2000_xts, 
    rq(esb.eu ~ hsbc.uk, data = return_2000_xts, tau = 0.95))

Unfortunately, I get the following error message:

Error in get(as.character(FUN), mode = "function", envir = envir) : object 'FUN' of mode 'function' was not found

What could be the problem with my code?


Solution

  • I'm not entirely sure what's going wrong, maybe apply.monthly() is stripping some attributes, but going back to basics seems to work.

    library(xts)
    library(quantreg)
    
    data(sample_matrix)
    xt <- as.xts(sample_matrix)
    
    f <- as.character(index(xt), format="%Y-%m")
    xt.ym <- split(xt, f)
    lapply(xt.ym, FUN=function(x) rq(Open ~ Close, data=x, tau=0.95))
    

    For reference, this is what didn't work, but feels like it should

    apply.monthly(xt, FUN=function(x) rq(Open ~ Close, data=x))
    

    Error in coredata.xts(x) : currently unsupported data type


    I've realised why apply.monthly() doesn't work. It wants to return an xts object, but there is no way a list of regression objects can be coerced to xts, so it throws an error. It will work, however, if we limit the regression output to something that can be coerced, f.ex.

    apply.monthly(xt, FUN=function(x) rq(Open ~ Close, data=x)$coef)
    #            (Intercept)     Close
    # 2007-01-31   12.224046 0.7564106
    # 2007-02-28   -6.326472 1.1242798
    # 2007-03-31   -2.108973 1.0432247
    # 2007-04-30    5.739395 0.8840677
    # 2007-05-31    2.453616 0.9495129
    # 2007-06-30   17.380465 0.6342055