简体   繁体   中英

Loop Regression and Store Intercepts, Slopes, etc

I need to use a loop to regress each company's returns onto the index return: The company return is:

       AAPL         AXP          BA         CAT        CSCO         CVX          DD         DIS          GE          GS          HD 
 12.3360728 -13.9214932  22.5635983 -27.2829432  24.1013814 -20.3403951   0.4449273  28.1967333  20.3767961   3.9267703  30.2680724 
        IBM        INTC         JNJ         JPM          KO         MCD         MMM         MRK        MSFT         NKE         PFE 
 -7.8815087   8.0829670  -1.3179946  12.5467514   8.2271155  24.7729246   7.6478088  -0.5601629  21.9812572  39.4680023  19.9745312 
         PG         TRV         UNH         UTX           V          VZ         WMT         XOM 
 -6.7330018  16.4542731  27.3932024  -1.2581727  41.5225073  -1.2022588 -23.1585254  -9.7806252 

and the index return is:

    ^DJI 
4.910218 

I want to:

  1. print a table of intercepts, slopes (βi), and idiosyncratic standard deviations σRi (standard deviation of the residuals) for all companies i = 1, ..., 30,

  2. compute and print the variance of the index's return,

  3. compute the single-index approximation to the covariance matrix, Qsi, using the computed σ^2M, βi and σRi for all i Note: the diagonal entries of Ω are σ^2Ri, not σRi

Basically I just need to do a loop of different regressions and somehow store that information. Can someone help please?

This is a simple example you can use to develop your own code. This code loops over variables of the mtcars dataset and estimates linear models using mpg as a target variable:

ref_variable <- "mpg"
target_vars <- c("hp","wt","qsec")

# container results
res <- data.frame(matrix(NA,0,4), stringsAsFactors = FALSE)
names(res) <- c("variable", "intercept", "slope", "std_dev_resid")

for (var in target_vars){
  linear_model <- lm(as.formula(paste0(ref_variable,"~",var)), data = mtcars)
  res <- rbind(res, data.frame(variable=var,
                      intercept=linear_model$coefficients[[1]], # intercept
                      slope=linear_model$coefficients[[2]], # slope
                      std_dev_resid=sd(resid(linear_model)) # std dev of residuals
                      ))
}

Output

  variable intercept       slope std_dev_resid
1       hp 30.098861 -0.06822828     0.5262956
2       wt 37.285126 -5.34447157     0.6674783
3     qsec -5.114038  1.41212484     0.3654127

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM