5

我一直在尝试通过实施滚动窗口回归并计算和记录过去每一天的估计与最后可用日期之间的差异来回测回归的可预测性(试图提前一步预测) ,在一列中。

我试图在滚动回归返回多个对象时应用 Christoph_J 的答案

代码中没有语法错误。但是,我不确定是否存在语义错误。“预测”列的行中的值是该列的行值的i事前预测吗?iOpCl

library(zoo) 
library(dynlm)
library(quantmod)
sp <- getSymbols("^GSPC", auto.assign=FALSE)
sp$GSPC.Adjusted <- NULL
colnames(sp) <- gsub("^GSPC\\.","",colnames(sp))

sp$Number<-NA
sp$Number<-1:nrow(sp)

sp$OpCl <- OpCl(sp) 
sp$ClHi <- HiCl(sp) 
sp$LoCl <- LoCl(sp) 
sp$LoHi <- LoHi(sp) 

#### LAG

spLag <- lag(sp)
colnames(spLag) <- paste(colnames(sp),"lag",sep="")
sp <- na.omit(merge(sp, spLag))

### REGRESSION

f <- OpCl ~ Openlag + Highlag + OpCllag + ClHilag 

OpClLM <- lm(f, data=sp)

#sp$OpClForecast <- NA
#sp$OpClForecast <- tail(fitted(OpClLM),1)

#####################################################

rolling.regression <- function(series) {
mod <- dynlm(formula = OpCl ~ L(Open) + L(High) + L(OpCl) + L(ClHi), 
data = as.zoo(series))    

nextOb <- min(series[,6])+1 # To get the first row that follows the window
if (nextOb<=nrow(sp)) {   # You won't predict the last one

# 1) Make Predictions
predicted=predict(mod,newdata=data.frame(OpCl=sp[nextOb,'OpCl'],
Open=sp[nextOb,'Open'],High=sp[nextOb,'High'],


OpCl=sp[nextOb,'OpCl'], ClHi=sp[nextOb,'ClHi']))
attributes(predicted)<-NULL

#Solution ; Get column names right
c(predicted=predicted, 
AdjR = summary(mod)$adj.r.squared)
}
}

rolling.window <- 300
results.sp <-  rollapply(sp, width=rolling.window, 
FUN=rolling.regression,  by.column=F, align='right')
sp<-cbind(sp,results.sp)

View(sp)
4

0 回答 0