1

I'm trying to create a nested For Loop that does the following: the Outer Loop grabs 100 days of stock data and then iterates forward by 1 day each for each loop. The Inner Loop takes that 100 days and runs 100 regressions (i.e. Day1:100, Day2:100, Day3:100, etc.) It saves the R2's of each regression to a list. Hypothetically, each element of the list should contain 100 r2s. Being somewhat new to R, I'm not sure what I'm doing wrong, but the end result is a list where each element only has one value, not 100. Here is my code:

require(quantmod)

getSymbols("SPY", src = "google", from = "2016-10-15", to = "2017-08-14")
tmp <- SPY

tickerClose <- data.frame(tmp[,"SPY.Close"], Time = index(tmp))    

grab <- list()
for (j in 1:(nrow(tickerClose)-100)) {
        temp <- tickerClose[j:(99+j),]
                for (i in 1:100) {
                      tmpSet <- temp[(nrow(temp)-(100-i)):nrow(temp),]
                      colnames(tmpSet) <- c("Close","Time")
                      tickerQuad <- lm(Close ~ as.vector(Time), data = tmpSet)
                      grab[[i]] <- summary(tickerQuad)[8]
                } 
}

1 Answer 1

5

You can tweak your code as

grab <- list()
final_grab <- list()
for (j in 1:(nrow(tickerClose)-100)) {
  for (i in 1:100) {
    <your code>
    grab[[i]] <- summary(tickerQuad)[8]
  } 
  final_grab[[j]] <- grab
}

final_grab will have the resulting list which you are interested in.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.