Search code examples
rfor-loopquantmod

Relative Performance loop in R


I'm not a programmer by any means and have been trying to learn R to code various trading strategies. I'm trying to calculate the relative performance of a list of stocks versus the S&P 500 and save it to a matrix. It appears that what I've written only goes through the first symbol and then stops. Below is the code that I've come up with. I appreciate any help, input and advice on how to proceed. Thank you.

library(quantmod)
library(PerformanceAnalytics)
Sys.setenv(TZ = "UTC")
symbols <- c('IBM', 'GE', '^GSPC')
getSymbols(symbols, src = "yahoo", from = "2010-12-31", to = Sys.Date())
symadj <- cbind(IBM[,6], GE[,6])
sp5adj <- GSPC[,6]
# Calculate Relative Performance vs S&P and save data
for (i in length(symadj)) {
  rp <- matrix(symadj[,1]/sp5adj, nrow = 1070, ncol = 3)
  print(tail(rp))
}

Solution

  • _You are not looping over an array but over a single number:

    for (i in length(symadj))
    

    Try (see the seq added, watch the parenthesis. Plus, be careful with length, the iteration is over ncol - i.e. the columns):

    for (i in seq(1,ncol(rp),1))
    

    _Also, you are going always through the same column:

      rp <- matrix(symadj[,1]/sp5adj, nrow = 1070, ncol = 3)
    

    _A thing I skipped: you should build your matrix before the loop:

    rp <- matrix(0,nrow=1071,ncol=2) 
    

    And then assign without overwritting your previous matrix - you have already build it (plus, look at the i where the 1 was, now you are iterating)

    rp[,i] <- symadj[,i]/sp5adj #This inside the loop
    

    _Your for loop should end up looking something like this:

    rp <- matrix(0,nrow=1071,ncol=2) 
    for (i in seq(1,ncol(rp),1)) {
        rp[,i] <- symadj[,i]/sp5adj #This inside the loop
      print(tail(rp))
    }
    

    \!/ Now there are 1071 days in that period, so the matrix should have one more row - that's why the 1071.