5.2 Simple Moving Average (SMA)
A n-day simple moving avaerage (n-day SMA) is arithmetic average of prices of past n days:
\[ SMA_t(n) = \frac{P_t+\ldots+P_{t-n+1}}{n}\]
The following is an SMA function:
mySMA <- function (price,n){
sma <- c()
sma[1:(n-1)] <- NA
for (i in n:length(price)){
sma[i]<-mean(price[(i-n+1):i])
}
sma <- reclass(sma,price)
return(sma)
}
Let us apply our function:
## [,1]
## 2012-12-26 19.36046
## 2012-12-27 19.23925
## 2012-12-28 19.09680
5.2.1 TTR
In the TTR package, we can use SMA():
## SMA
## 2012-12-26 19.36046
## 2012-12-27 19.23925
## 2012-12-28 19.09680
We can see that our code gives the same result.
5.2.2 Trading signal
Buy signal arises when a short-run SMA crosses from below to above a long-run SMA.
Sell signal arrises when a short-run SMA crosses from above to above a long-run SMA.