0

I am trying to calculate RSI for lookback period of 14 days. There are three columns in my excel file - DATE,OPEN,CLOSE. But when I am checking dff>0 inside the if-statement, an error is raised - Error in if (dff > 0) { : argument is of length zero. Below is my code. Any suggestions why this is happening?

library(readxl)
data <- read_excel(address of file)
data <- data.frame(data)
rows <- nrow(data)
RSI <- rep(0,rows)
for(i in 14:rows){
  gain <- 0
  cnt_gain <- 0
  cnt_loss <- 0
  loss <- 0
  for(j in i-13:i){
    dff <- data[j,3]-data[j,2]
    if(dff > 0){
      gain <- gain + dff
      cnt_gain <- cnt_gain + 1
    }
    else{
      loss <- loss -dff
      cnt_loss <- cnt_loss + 1
    }
  }
  avg_gain <- gain/cnt_gain
  avg_loss <- loss/cnt_loss
  RSI[i] <- 100 - 100/(1+ avg_gain/avg_loss)
}
jd_sal
  • 11
  • 3

0 Answers0