r - 动态时间序列预测和rollapply

标签 r time-series

我正在尝试在 R 中获得动态时间序列的滚动预测(然后计算出预测的平方误差)。我的大部分代码都基于 this StackOverflow question ,但我对 R 很陌生,所以我很挣扎。任何帮助将非常感激。

require(zoo)
require(dynlm)

set.seed(12345)
#create variables
x<-rnorm(mean=3,sd=2,100)
y<-rep(NA,100)
y[1]<-x[1]
for(i in 2:100) y[i]=1+x[i-1]+0.5*y[i-1]+rnorm(1,0,0.5)
int<-1:100
dummydata<-data.frame(int=int,x=x,y=y)

zoodata<-as.zoo(dummydata)

prediction<-function(series)
  {
  mod<-dynlm(formula = y ~ L(y) + L(x), data = series) #get model
   nextOb<-nrow(series)+1
   #make forecast
   predicted<-coef(mod)[1]+coef(mod)[2]*zoodata$y[nextOb-1]+coef(mod)[3]*zoodata$x[nextOb-1]

   #strip timeseries information
   attributes(predicted)<-NULL

   return(predicted)
  }                

rolling<-rollapply(zoodata,width=40,FUN=prediction,by.column=FALSE)

这将返回:

20          21      .....      80
10.18676  10.18676          10.18676

其中有两个我没有预料到的问题:

  1. 从 20->80 运行,而不是我期望的 40->100(因为宽度为 40)
  2. 它给出的预测是恒定的:10.18676

我做错了什么?有没有比把它全部写出来更简单的方法来进行预测呢?谢谢!

最佳答案

您的函数的主要问题是 dynlmdata 参数。如果您查看?dynlm,您会发现data参数必须是data.framezoo目的。不幸的是,我刚刚了解到 rollapply 将您的 zoo 对象拆分为 array 对象。这意味着 dynlm 在注意到您的 data 参数的形式不正确后,搜索了 xy > 在您的全局环境中,这当然是在代码顶部定义的。解决方案是将 series 转换为 zoo 对象。您的代码还有一些其他问题,我在这里发布了更正的版本:

prediction<-function(series) {
   mod <- dynlm(formula = y ~ L(y) + L(x), data = as.zoo(series)) # get model
   # nextOb <- nrow(series)+1 # This will always be 21. I think you mean:
   nextOb <- max(series[,'int'])+1 # To get the first row that follows the window
   if (nextOb<=nrow(zoodata)) {   # You won't predict the last one
     # make forecast
     # predicted<-coef(mod)[1]+coef(mod)[2]*zoodata$y[nextOb-1]+coef(mod)[3]*zoodata$x[nextOb-1]
     # That would work, but there is a very nice function called predict
     predicted=predict(mod,newdata=data.frame(x=zoodata[nextOb,'x'],y=zoodata[nextOb,'y']))
     # I'm not sure why you used nextOb-1  
     attributes(predicted)<-NULL
     # I added the square error as well as the prediction.
     c(predicted=predicted,square.res=(predicted-zoodata[nextOb,'y'])^2)
   }
}    

rollapply(zoodata,width=20,FUN=prediction,by.column=F,align='right')

您的第二个问题是关于结果的编号,可以通过 align 参数控制 rollapplyleft 将为您提供 1..60center(默认)将为您提供 20..80正确为您提供40..100

关于r - 动态时间序列预测和rollapply,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11583177/

相关文章:

python - 如何读取时间序列数据文件并将其绘制为烛台图?

python - 使用 pandas 组合日期和时间列

从R中的字符串中删除表情符号

r - pennyPerShare Quantstrat 不工作

静态时间序列数据的数据库解决方案

java - 使用 JTransforms 库使用 FFT 计算自相关

python - 如何为具有清晰时间戳的时间序列数据构建数据框?

从 .RMD 中的代码块中删除空白(将 knit 编译为 Beamer pdf)

r - R 中水平线上的位置字母

用它的序号替换向量中的所有元素