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, Ut and Dt, are
Ut={1,Pt>Pt−10,Pt≤Pt−1 and Dt={0,Pt≥Pt−11,Pt<Pt−1
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+Ut−1+...+Ut−n+1n and downt(n)=Dt+Dt−1+...+Dt−n+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:
function (price,n){
myRSI <- length(price)
N <- rep(0,N)
U <- rep(0,N)
D <- rep(NA,N)
rsi <- Lag(price,1)
Lprice <-for (i in 2:N){
if (price[i]>=Lprice[i]){
1
U[i] <-else {
} 1
D[i] <-
}if (i>n){
mean(U[(i-n+1):i])
AvgUp <- mean(D[(i-n+1):i])
AvgDn <- AvgUp/(AvgUp+AvgDn)*100
rsi[i] <-
}
} reclass(rsi, price)
rsi <-return(rsi)
}
myRSI(Cl(AAPL), n=14)
rsi <-tail(rsi,n=3)
## [,1]
## 2012-12-26 35.71429
## 2012-12-27 35.71429
## 2012-12-28 35.71429