5.11 TTR
In the TTR package, we can use RSI() function:
RSI(Cl(AAPL), SMA, n=14)
rsi <-tail(rsi,n=3)
## rsi
## 2012-12-26 38.85768
## 2012-12-27 35.28442
## 2012-12-28 38.26621
Note that the third input is a function. You may use SMA or EMA.
Further notice that this is different from what we have above. It is because their upward and downward indicators use numerical values instead:
Ut={Pt−Pt−1,Pt>Pt−10,Pt≤Pt−1 and Dt={0,Pt≥Pt−1Pt−1−Pt,Pt<Pt−1
Hence, we need to modify our code:
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]){
price[i]- Lprice[i]
U[i] <-else{
} Lprice[i]- price[i]
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)
}
Now we can see that we have the same result:
myRSI(Cl(AAPL), n=14)
rsi <-tail(rsi,n=3)
## [,1]
## 2012-12-26 38.85768
## 2012-12-27 35.28442
## 2012-12-28 38.26621