R中使用循环回归的Difftime错误

时间:2015-01-13 20:52:21

标签: r loops regression

使用以下代码我收到错误Error in Ops.difftime((f - mean(f)), 2) : '^' not defined for "difftime" objects

此错误仅在包含位于循环末尾的r_sq[[counter-lookback]] <- summary(temp_lm)$r.squared;时发生。我在网上找不到任何类似的错误解决方案。谢谢您的帮助。

#Import necessary packages
require(quantmod)
require(ggplot2)

#Measure time used in processing
ptm <- proc.time()

#########
#Write in the ticker symbols of the pair
tickers <- c("GS","JPM")
########

#Pull data down for symbols
A <- getSymbols(tickers[1],auto.assign=FALSE)
B <- getSymbols(tickers[2],auto.assign=FALSE)

#Strip data such as high and low prices
A <- A[,4]
B <- B[,4]

#Create data frame of both price series
AB_DF <- data.frame(A,B)

#Create a time series of the spread & rename header
S <- A-B
colnames(S) <- "Spread.Close"

#Separate the index of times from the spread data for regression
TS <- index(S)
SP <- coredata(S)

#Perform regressions of past 'lookback' days of the spread, incrementing by 1, beginning at T = lookback+1

######## 
# Change below variable to alter length of data in regression
lookback <- 250
#######

#Initialize a counter, and lists to hold data from the spread regressions
counter <- lookback+1
res_store <- list()
spread_coef <- list()
r_sq <- list()
while (counter<length(SP)) {
    temp_lm <- lm(TS[(counter-lookback):counter]~SP[(counter-lookback):counter]);
    res_store[[counter-lookback]] <- residuals(temp_lm);
    spread_coef[[counter-lookback]] <- coefficients(temp_lm)[[2]];
    r_sq[[counter-lookback]] <- summary(temp_lm)$r.squared;
    counter <- counter+1;
  }

1 个答案:

答案 0 :(得分:0)

好的,我已经弄清楚了。问题是R不喜欢为按时间索引的数据计算R ^ 2值。通过对数据值随时间回归,发生difftime()中的错误。我通过将索引从时间值更改为标准整数索引来解决这个问题,一切运行正常。