【问题标题】:Rollapply backwards time series in R在R中向后滚动时间序列
【发布时间】:2016-02-29 14:30:30
【问题描述】:

我需要在知道回报的情况下反向填写历史价格(在真实情况下它们是模拟的)。 到目前为止,我有这个代码:

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) {....})

【问题讨论】:

  • 你可以通过zoo:::rollapply.zoo学习源代码rollapply。它相当长,但它可能只是mapply 的包装?但是在他们使用seq_along(...) 的地方你想要rev(seq_along(...))(这是评论,不是答案,因为我没有时间确认这个猜测。)

标签: r xts rollapply


【解决方案1】:

您不需要rollapply 或循环。您可以在退货时使用cumprod。这是使用cumprodfillBackwards 版本:

fillBackwards <- function(data, range_to_fill) {
  data_range <- data[range_to_fill,]

  returns <- rev(coredata(data_range[-1L, 2L]))
  last_price <- drop(coredata(last(data_range[, 1L])))

  new_prices <- rev(last_price * cumprod(exp(-returns)))
  data[range_to_fill, 1L] <- c(last_price, new_prices)

  return(data)
}

【讨论】:

    猜你喜欢
    • 2011-05-07
    • 1970-01-01
    • 2017-12-08
    • 2019-08-17
    • 2012-01-12
    • 2016-12-28
    • 2012-10-25
    • 1970-01-01
    • 2017-07-14
    相关资源
    最近更新 更多