rstockautocorrelation

R: subset a stock price history every two months


I need to calculate return autocorrelation every two months based on daily observations. I could not figure out how to subset a stock's daily price history every two months. My dataset has multiple stocks and the history is different across stocks.

An example for one stock is below

data = data.frame(date = c("2000-01-27", "2000-01-28", "2000-01-29", "2000-01-30", "2000-02-27", 
                           "2000-02-28", "2000-03-27", "2000-03-28", "2000-03-29", "2000-03-30", 
                           "2000-04-27", "2000-04-28", "2000-04-29", "2000-04-30", "2000-05-27", 
                           "2000-05-28", "2000-05-29", "2000-05-30"), return = sample(-3:15, 18, replace = T))

In the MWE above, the outcome should include 3 autocorrelation coefficient: the first one using month 1 and 2 observations, the second one using month 3 and 4 observations, the third one using one month 5. Of course, for some stocks the number of months might be divisible by 2. The autocorrelation is below

autocorr = function(x,k){ # x is the return vector, k is the autocorrelation order (assumed 1)
  x = x - mean(x)
  n = length(x)
  var = x %*% x / (n-1)
  gamk = x[1:(n-k)] %*% x[(k+1):n] / (n-k-1)
  rho = gamk/var
  return(rho[1,1])
}

Solution

  • Use cut to partition the dates into 2 month segments and then use tapply to apply autocorr to the returns of each segment.

    with(data, tapply(return, cut(as.Date(date), "2 months"), autocorr, 1))