5.10 Relative Strength Index (RSI)

The calculation of RSI requires several steps:

  1. Whether price has gone up or down each day
  2. Relative strength (RS): the ratio of the (simple or exponential) average numbers of up day to the average of down day
  3. Relative strength index (RSI): normalize RS to the scale from 0 to 100.

Step 1. Upward and downward indicators, Ut and Dt, are

Ut={1,Pt>Pt10,PtPt1 and Dt={0,PtPt11,Pt<Pt1

Step 2. Then upt(N) and downt(N) are average numbers of upward moves and downward moves of closing price of past n days:

If we use simple average, then we have upt(n)=Ut+Ut1+...+Utn+1n and downt(n)=Dt+Dt1+...+Dtn+1n. Instead, We may use exponential moving average.

Relative strength (RS) is relative ratio of days with upward moves and downward moves during last n days. Formally, it si RS=upt(n)downt(n)

Step 3. Finally, an n-day RSI is given by

RSIt(n)=100RSt(n)1+RSt(n) where RSI is normalized relative strength.

In calculation, we usually consider directly:

RSIt(n)=100upt(n)upt(n)+downt(n)

Below is our RSI function:

myRSI <- function (price,n){
  N <- length(price)
  U <- rep(0,N)
  D <- rep(0,N)
  rsi <- rep(NA,N)
  Lprice <- Lag(price,1)
  for (i in 2:N){
    if (price[i]>=Lprice[i]){
      U[i] <- 1
    } else {
      D[i] <- 1
    }
    if (i>n){
      AvgUp <- mean(U[(i-n+1):i])
      AvgDn <- mean(D[(i-n+1):i])
      rsi[i] <- AvgUp/(AvgUp+AvgDn)*100 
      }
    }
  rsi <- reclass(rsi, price)
  return(rsi)
}
rsi <- myRSI(Cl(AAPL), n=14)
tail(rsi,n=3)
##                [,1]
## 2012-12-26 35.71429
## 2012-12-27 35.71429
## 2012-12-28 35.71429