Difftime Error using Looping Regressions in R

2019-09-02 03:12发布

问题:

With the below code I am getting the error Error in Ops.difftime((f - mean(f)), 2) : '^' not defined for "difftime" objects.

This error only occurs with the inclusion of r_sq[[counter-lookback]] <- summary(temp_lm)$r.squared; which is located towards the end of the loop. I cannot find any similar error solutions online. Thank you for your help.

#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:

Ok all, I have figured it out. The issue is that R does not like to compute R^2 values for data indexed by time. By regressing the data values against time, an error in difftime() occurs. I solved this by changing the index from time values to a standard integer index, and everything ran fine.