时间序列的R -循环线性回归结果

uoifb46i  于 2023-01-15  发布在  其他
关注(0)|答案(1)|浏览(122)

我想对新西兰元和一些证券进行线性回归
我有一些代码来运行回归,但不是将其应用于每个证券,我更喜欢在证券列表中运行一个循环,以给予一个包含每个线性回归的r^2结果的文件
我的dep变量叫做:恩兹杜什德
我想循环使用的自变量是spx,adxy,vix
代码:与spx当前的代码相同(喜欢使用相同的代码循环遍历变量adxy和vix)

library(tseries)
library(lmtest)
library(dplyr)
library(lubridate)

# 3 month regression, change variable here to get number of days
# e.g. 3 months sd = 60

# inputs
# 3 month regression
sd <- 60

# loading my market data from a saved location (variables nzdusd,spx, adxy, vix)
my_path <- file.path ("K:","X,"bbg_daily.Rdata")

load(file = my_path)

# Transform NZD into percentage change
pct.nzdusd <- nzdusd %>%
              select(date, PX_LAST) %>%
              mutate(lag = lag(PX_LAST),
              pct_chg = (PX_LAST - lag) * 100 / lag) %>%
          select(date, pct_chg)

# SPX(S&P 500)

myfun <-  function(x) {
  deparse(substitute(x))
}
# ^=^=^=^=^=^=^=^=^=^=^=^=^=^=
mysec_str <- myfun(spx)

mysec <- spx

z <- 5          # Series ID
# ^=^=^=^=^=^=^=^=^=^=^=^=^=^=

# Transform into percentage change

      mypct <- mysec %>%
              select(date, PX_LAST) %>%
              mutate(lag = lag(PX_LAST),
              pct_chg = (PX_LAST - lag) * 100 / lag) %>%
          select(date, pct_chg)
                    
                    
      assign(paste("pct.", mysec_str, sep = ""),mypct)

# join times series
ts <- paste("ts_", z, sep ="")
ts <- (inner_join(x = pct.nzdusd, y = mypct, by = "date"))
# get last row
last_row <- ts %>% slice(n())
end_dt <- last_row [1,1]

# start date declared above depending on regression
start_dt <- ts[((nrow (ts))-sd),1]

# getting subset of time series
ts_sub <- subset(ts,
                 date >= as.POSIXct(start_dt) &
                   date <= as.POSIXct(end_dt))

# regression 
reg.ts = lm(pct_chg.x~pct_chg.y, ts_sub)

r2 <- summary(reg.ts)$r.squared
assign(paste(mysec_str, ".r2", sep = ""),r2)

stderr <- sqrt(deviance(reg.ts)/df.residual(reg.ts))
assign(paste(mysec_str, ".stderr", sep = ""),stderr)

#===================================================

r2 <- c(spx.r2, *adxy.r2, vix.r2*)

my_path2 <- file.path ("K:","x")
save (r2, file = my_path2 )

我的代码是通过简单的复制和粘贴,然后用其他变量名替换spx来完成的,但是我知道使用循环可以使代码更加流畅,特别是当我想添加更多的独立变量时

zzlelutf

zzlelutf1#

如果没有reprex数据,很难知道这一点,但要运行多个模型,我发现透视时间更长,通过自变量嵌套,然后通过这些变量进行变异效果很好。如果您的数据只包含因变量和自变量,您可以:

library(tidyverse)
ts_sub %>%
   # Keep independent variable outside nested data
   pivot_longer(- nzdusd, names_to = "dependent_vars", values_to = "values") %>%
   nest_by(dependent_vars) %>%
   mutate(model = list(lm(nzdusd ~ values, data = data)))

参见:https://dplyr.tidyverse.org/reference/nest_by.html

相关问题