5.10 Relative Strength Index (RSI)
The calculation of RSI requires several steps:
- Whether price has gone up or down each day
- Relative strength (RS): the ratio of the (simple or exponential) average numbers of up day to the average of down day
- Relative strength index (RSI): normalize RS to the scale from 0 to 100.
Step 1. Upward and downward indicators, \(U_t\) and \(D_t\), are
\[U_{t}=\left\{ \begin{array}{cl} 1, & P_t>P_{t-1} \\ 0, & P_t \leq P_{t-1} \end{array} \right. \] and \[ D_{t}=\left\{ \begin{array}{cl} 0, & P_t\geq P_{t-1} \\ 1, & P_t < P_{t-1} \end{array} \right. \]
Step 2. Then \(up_{t}(N)\) and \(down_{t}(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 \[up_{t}(n)=\frac{U_t+U_{t-1}+...+U_{t-n+1}}{n}\] and \[down_{t}(n)=\frac{D_t+D_{t-1}+...+D_{t-n+1}}{n}\]. 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=\frac{up_{t}(n)}{down_{t}(n)}\]
Step 3. Finally, an n-day RSI is given by
\[RSI_t(n) = 100\frac{RS_{t}(n)}{1+RS_{t}(n)}\] where RSI is normalized relative strength.
In calculation, we usually consider directly:
\[RSI_t(n) = 100\frac{up_{t}(n)}{up_{t}(n)+down_{t}(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