【问题标题】:Difftime Error using Looping Regressions in R在 R 中使用循环回归的 Difftime 错误
【发布时间】:2015-01-13 20:52:21
【问题描述】:

使用下面的代码,我收到了错误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;
  }

【问题讨论】:

    标签: r loops regression


    【解决方案1】:

    好吧,我想通了。问题是 R 不喜欢为按时间索引的数据计算 R^2 值。通过将数据值与时间进行回归,difftime() 中会发生错误。我通过将索引从时间值更改为标准整数索引解决了这个问题,一切运行良好。

    【讨论】:

      猜你喜欢
      • 2017-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多