Rollapply在R中倒退时间序列

时间:2015-11-26 13:09:13

标签: r xts rollapply

我需要知道回报(在真实情况下他们被模拟)的倒退历史价格。 到目前为止,我有这段代码:

library(quantmod)
getSymbols("AAPL")
df = AAPL["2014-01-01/2015-01-01", "AAPL.Close"]
df_ret = diff(log(df),1)
# imagine the half of the past prices are missing
df["2014-01-01/2014-07-01"] = NA
df_tot = cbind(df, df_ret)

fillBackwards = function(data, range_to_fill){
  index_array = index(data[range_to_fill,])
  data_out = data
  for (i in (length(index_array)-1):1){
    inx = index_array[i]
    inx_0 = index_array[i+1]
    data_out[inx,1] = exp(-(data_out[inx_0,2]))*(data_out[inx_0,1])
  }
  return (data_out)
}

df_filled = fillBackwards(df_tot,"2014-01-01/2014-07-02")

sum(AAPL["2014-01-01/2015-01-01", "AAPL.Close"] - df_filled[,1]) # zero up to computation error, i.e. identical

这很完美,但有点慢。你能否使用内置rollapply()

来推荐一些东西
# i want something like this 
df_filled = rollapply(df_tot["2014-07-02/2014-01-01",], by=-1, function(x) {....})

1 个答案:

答案 0 :(得分:1)

您不需要rollapply或循环。您可以在退货时使用cumprod。这是使用fillBackwards的{​​{1}}版本:

cumprod