5.11 TTR
In the TTR package, we can use RSI() function:
rsi <- RSI(Cl(AAPL), SMA, n=14)
tail(rsi,n=3)
## rsi
## 2012-12-26 38.85768
## 2012-12-27 35.28446
## 2012-12-28 38.26622
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:
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] <- price[i]- Lprice[i]
} else{
D[i] <- Lprice[i]- price[i]
}
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)
}
Now we can see that we have the same result:
rsi <- myRSI(Cl(AAPL), n=14)
tail(rsi,n=3)
## [,1]
## 2012-12-26 38.85768
## 2012-12-27 35.28446
## 2012-12-28 38.26622
5.11.1 Trading signal
Buy signal arises when RSI is less than 30.
Sell signal arrises when RSI is higher than 30.
5.11.2 Charting
chartSeries(AAPL,
subset='2007-05::2009-01',
theme=chartTheme('white'))
addRSI(n=14,maType="EMA")