Technical Analysis using R, Dr. Arunachalam Rajagopal


Technical Analysis using R

Dr.Arunachalam Rajagopal Ph.D., Former Professor and HOD


1.1 Fundamental Analysis & Technical Analysis - Introduction
Analysts and investors make use of stock analysis for decision making on whether to buy or sell a stock. The investors and traders analyse the past and current data on the price and other performance indices of a firm to take a decision on trading a particular company's stock. Investors and analysts make use of two types of analysis with respect to stock trading:
            1. Fundamental analysis
            2. Technical analysis
Fundamental analysis attempts to evaluate the intrinsic value of a stock. While technical analysis focuses on price movements, trading signals, and other charts for taking decision to buy or sell a stock.

1.2 Technical analysis tools
The often used technical tools for buy & sell decisions by investors are:
1. Simple Moving Average (SMA)
2. Exponential Moving Average (EMA)
3. Bollinger Bands
4. Moving Average Convergence Divergence (MACD)
5. Relative Strength Index (RSI)

1.2.1 SMA
Simple Moving Average (SMA) is a popular technical analysis tool. SMA is available in Technical Trading Rules (TTR) package. SMA calculates the arithmetic mean of the series over the past n observations. TTR package can be downloaded and installed from R-CRAN website. SMA can be used to identify trend direction and can be used to make buy/sell decisions.
Usage:  SMA(x, n=20)
Where,
x          is a numeric vector to be averaged
N          is period to be considered for SMA

If, say, the closing prices are: 23, 26, 25, 27, 29, 31, ...
SMA = (23+26+25+27+29)/5 = 26             # moving average for period 5

The SMA for 6th day is calculated as follows:
The first day price '23' is left out and the 6th day price '31' is included for the next SMA calculation.

Next SMA = (26+25+27+29+31)/5 = 27.6      # moving average for period 6
This roll-on calculation will continue till the end of the dataset.


Figure 1 Simple Moving Average SMA (n=20)

The Figure 1 shows the SMA20 for period from 01-01-2019 to 01-04-2020 for a leading FMCG company in India.

Moving averages are used as support and resistances of a stock price. When these levels are broken there will be significant change in the price of stocks.

1.2.2 EMA
Exponential Moving Average (EMA) gives more weightage to recent values and less weightage to older values in the series. Hence, EMA is more responsive to changes in price of the scrip or any other security. EMA is exponentially weighted SMA. EMA weights will be exponentially decreasing, giving more weight to recent values and lesser weight to old values of the scrip price.
Usage: EMA(x, n=10, wilder=FALSE)
where, x                      Vector to be averaged
            n                      Number of periods to average over
            wilder              logical; if TRUE, a Welles Wilder type EMA will be calculated




Figure 2 Exponential Moving Average, EMA (n=20)

The Figure 2 shows the EMA20 for period from 01-01-2019 to 01-04-2020 for a leading FMCG company in India.

Note: For EMA, wilder=FALSE (the default) uses an exponential smoothing ratio of 2/(n+1), while wilder=TRUE uses Welles Wilder’s exponential smoothing ratio of 1/n. The EMA with n-period sample, will be initialized at period 'n'.

1.2.3 BBands
Bollinger Bands are made use of for trading decisions in stocks, futures, and currencies. The BBands consists of a centre line which is simple moving average (n=20). The bands further comprise of an upper band line and a lower band line. The upper band line is EMA + 2*Sigma, where Sigma is the standard deviation of market place. The lower line of the band is EMA - 2*Sigma. The Bollinger Bands are expected to reflect the volatality in the price movement of an instrument, as standard deviation (Sigma) is a measure of volatality. The bands expand and contract to reflect the market activity of an instrument and attempts to reflect the volatality. Generally 20 days Bollinger Band is drawn for carrying out technical analysis. Bollinger bands (BBands) is a combination of Rolling Range and SMA indicators.

Usage: BBands(x, n = 20, maType, sd = 2)

where,
x                      numeric vector like 'Close Price' of security. If HLC (High, Low, Close) prices are given as matrix or data frame, the typical price will be used for analysis.
Typical price = (H+L+C)/3
n                      Number of periods for moving average.
maType           A function or a string naming the function to be called.
sd                     The number of standard deviations to use.


The output will contain the following values:
dn                    The lower Bollinger Band.
mavg               The middle Moving Average (see notes).
up                    The upper Bollinger Band.
pctB                 The %B calculation.

Default maType=SMA, In case any other moving average is used then there will be inconsistencies in the standard deviation calculation as the rolling calculation for standard deviation uses SMA as the moving average method.

The following key points with respect to BBands may be noted:
When the stock price continually touches upper Bollinger Band, it indicates overbought situation.
When the price of the instrument continually touches the lower Bollinger Band, it indicates oversold situation. It is a 'buy' signal for the investors.

It may be noted that when there is strong uptrend in the price of an instrument, the price fluctuates between the upper band and the centre line (20 day moving average line). When the price line, which is in the upper band of the BB channel, crosses the centreline (20 days moving average) and goes into the lower band, it indicates a trend reversal of the price towards downside.


The Figure 3 shows the BBands for period from 01-01-2019 to 01-04-2020 for a leading FMCG company in India.

  Figure 3 Bollinger Bands (SMA, n=20)


1.2.4 MACD
Moving Average Convergence Divergence (MACD) is a convergence divergence indicator as the name indicates.
MACD Line = (12 day EMA - 26 day EMA)
Signal Line = 9 day EMA of MACD Line
Usage: MACD(x, nFast=12, nSlow=26, nSig=9, maType=SMA)

MACD line & Signal line are drawn in a separate graph plot, just below the graph plot of Price of the scrip.

The Figure 4 shows the MACD for period from 01-01-2019 to 01-04-2020 for a leading FMCG company in India.

Key point to note regarding BBands analysis:
MACD line crosses over a signal line, it is entry signal.
Signal line crosses over the MACD line, it is an exit signal



Figure 4 Moving Average Convergence Divergence (MACD)


Stock price is making higher highs in an uptrend & MACD line is making lower highs ... Bearish divergence (trend could change)
Stock price is making lower highs in a downtrend & MACD line is making higher highs .... Bullish divergence (trend could change)

1.2.7 RSI
Relative Strength Index aka RSI. RSI measures velocity or magnitude of directional price movements. RSI is a measure of stocks overbought and oversold position. Commonly used is 14 day RSI.

Usage: RSI(x, n=14)
where,
x          is numeric vector of stock price
n          window size or number of periods


RSI = 100 - 100/(1+RS)
where,
RS is the smoothed ratio of the average gains or average losses. The averages are not true averages, since they divided by the value of 'n' and not the number of periods in which there are gains / losses.



Figure 5 Relative Strength Index, RSI

The Figure 5 shows the RSI for period from 01-01-2019 to 01-04-2020 for a leading FMCG company in India.

RSI output values:
The output is an object of the same class as the price or a vector containing RSI values.
RSI is measured on a scale of 0-100. The following key points are to be noted.

RSI 70 or above indicates that the stock is overbought or overvalued (there is likely trend reversal or corrective pull back)
RSI 30 or below indicates a oversold undervalued condition.



The RSI chart could be made use of for taking decision on entry and exit points for trading.
Over sold & at support level      ....... Entry point
Over bought & at resistance level ....... Exit point


2.0 R in action:
The  R code running the technical analysis has been given in modules:
module A: Data Input
module A1: SMA
module A2: EMA
module A3: Bollinger Bands
module A4: MACD
module A5: RSI

Select and run the R code module wise in R Studio. The BSE stock price historical data could be downloaded for a major FMCG company in India with BSE Code 500696.


3.0 Annexure: R code is given below:


# Technical Analysis: MACD (Moving Average Convergence Divergence)
#---------------------------------------------------------------------------------
# Title: Technical Analysis Using R
# Author: Dr. Arunachalam Rajagopal Ph.D., Former Professor and HOD   
# contact the author: arg1962@gmail.com   mobile: 9488361726

# Google "bse stock price historical data" 
# Download the stock price data for, say, BSE stock code: 500510
# copy and paste '500510.csv' from 'downloads' to any convenient directory

# R code available at: 
# https://arg1962.blogspot.com/2020/04/technicalanalysis-using-r-dr.html

# first running module A is compulsory before running A1, A2, A3, A4, A5

#---------------------------------------------------------------------------------

# module A: Data Input

#select the BSE stock price csv file
input<-read.csv(file.choose(), sep=",", header=T)    
head(input)

datadf<-data.frame(TrDate=as.Date(input$Date,format="%d-%b-%Y"), 
        OpenPrice=input$Open.Price, HighPrice=input$High.Price, 
        LowPrice=input$Low.Price, ClosePrice=input$Close.Price,
        volume=input$No.of.Shares, spCloseOpen=input$Spread.Close.Open)

abc<-datadf[order(datadf$TrDate, decreasing=F),]
rownames(abc)<-c(1:nrow(datadf))
str(abc)
head(abc)

abc$TrDate<-as.character(abc$TrDate, format="%d-%b-%y")

head(abc)
tail(abc)
nrow(abc)

# module A: Data Input End

#---------------------------------------------------------------------------------

# module A1
# Technical Analysis: SMA

library(TTR)
sma<-SMA(abc$ClosePrice, n=20)
xyz<-data.frame(TrDate=abc$TrDate, ClosePrice=abc$ClosePrice, 
                volume=abc$volume, sma)
head(xyz, 24)
layout(matrix(c(1,1,1,2,2), nrow=5, ncol=1))

plot(abc$ClosePrice, xaxt="n", type="l", col=2, xlab="Date", 
     ylim=c(min(abc$ClosePrice)*0.95, max(abc$ClosePrice)*1.05), 
     ylab= "Close Price", main="SMA20", lwd=2)

axis(1, at=1:nrow(abc), labels=abc$TrDate)
axis(2, tck=1, col.ticks="lightgray")
for (i in 0:10){
abline(v=i*nrow(abc)/10, lty=2, col="lightgray")
}

lines(xyz$sma, type="l", col='blue')
legend("topleft", lty=c(1,1), col=c('red', 'blue'), 
       legend=c("Close Price", "SMA20"), 
       bty="n", cex=0.6, lwd=c(2,1))

plot(abc$volume, type="h", xaxt="n", col="green", xlab="", 
     main="", sub="", ylab="volume")

axis(1, at=1:nrow(abc), labels=abc$TrDate)
axis(2, tck=1, col.ticks="lightgray")
for (i in 0:10){
abline(v=i*nrow(abc)/10, lty=2, col="lightgray")
}

#---SMA20 and volume plot---

# module A1 End

#---------------------------------------------------------------------------------

# module A2
# Technical Analysis: EMA

library(TTR)
ema<-EMA(abc$ClosePrice, n=20)
xyz<-data.frame(TrDate=abc$TrDate, ClosePrice=abc$ClosePrice, 
                volume=abc$volume, ema)
head(xyz,24)
layout(matrix(c(1,1,1,2,2), nrow=5, ncol=1))

plot(abc$ClosePrice, xaxt="n", type="l", col=2, xlab="Date", 
     ylim=c(min(abc$ClosePrice)*0.95, max(abc$ClosePrice)*1.05), 
     ylab="Close Price", main="EMA20", lwd=2)

axis(1, at=1:nrow(abc), labels=abc$TrDate)
axis(2, tck=1, col.ticks="lightgray")
for (i in 0:10){
abline(v=i*nrow(abc)/10, lty=2, col="lightgray")
}

lines(xyz$ema, type="l", col='blue')
legend("topleft", lty=c(1,1), col=c('red', 'blue'), 
       legend=c("Close Price", "SMA"), bty="n", 
       cex=0.6, lwd=c(2,1))

plot(abc$volume, type="h", xaxt="n", col="green", 
     xlab="", main="", sub="", ylab="volume")

axis(1, at=1:nrow(abc), labels=abc$TrDate)
axis(2, tck=1, col.ticks="lightgray")
for (i in 0:10){
abline(v=i*nrow(abc)/10, lty=2, col="lightgray")
}

#---EMA20 and volume plot---

# module A2 End

#---------------------------------------------------------------------------------

# module A3
# Technical Analysis: Bollinger Bands

library(TTR)
bb20<-BBands(abc$ClosePrice, sd=2)
xyz<-data.frame(TrDate=abc$TrDate, ClosePrice=abc$ClosePrice, 
                volume=abc$volume, bb20)
head(xyz,24)
layout(matrix(c(1,1,1,2,2), nrow=5, ncol=1))

plot(abc$ClosePrice, xaxt="n", type="l", col=2, 
     ylim=c(min(abc$ClosePrice)*0.95, max(abc$ClosePrice)*1.05), xlab="Date", 
     main="", sub="", ylab="Close Price", cex=0.6, lwd=2)

axis(1, at=1:nrow(abc), labels=abc$TrDate)
axis(2, tck=1, col.ticks="lightgray")
for (i in 0:10){
abline(v=i*nrow(abc)/10, lty=2, col="lightgray")
}

lines(xyz$up, type="l", col='green')
lines(xyz$dn, type="l", col='green')
lines(xyz$mavg, type="l", col='blue')
legend("topleft", col=c('red', 'green', 'green', 'blue'), lty=c(1,1,1,1), 
       legend=c('Close Price', 'up', 'dn', 'mavg'), 
       bty="n", cex=0.6, lwd=c(2,1,1,1))

plot(abc$volume, type="h", xaxt="n", col="green", 
     xlab="", main="", sub="", ylab="volume")

axis(1, at=1:nrow(abc), labels=abc$TrDate)
axis(2, tck=1, col.ticks="lightgray")
for (i in 0:10){
abline(v=i*nrow(abc)/10, lty=2, col="lightgray")
}

#---Bollinger bands plot---

# module A3 End

#---------------------------------------------------------------------------------

# module A4
#Technical Analysis: MACD

library(TTR)

sma<-SMA(abc$ClosePrice, n=20)

# Let us calculate standard(12,26,9) MACD
macd<-MACD(abc$ClosePrice, nFast=12, nSlow=26, nSig=9, maType=SMA)
xyz<-data.frame(TrDate=abc$TrDate, ClosePrice=abc$ClosePrice, 
                volume=abc$volume, macd, sma)
head(xyz,40)
layout(matrix(c(1,1,1,2,2), nrow=5, ncol=1))

plot(abc$ClosePrice, xaxt="n", type="l", col=2, xlab="Date", 
     ylim=c(min(abc$ClosePrice)*0.95, max(abc$ClosePrice)*1.05), 
     ylab="Close Price", mai=c(0.1,0.5,0.1,0.1), main=NA, sub=NA, lwd=2)

axis(1, at=1:nrow(abc), labels=abc$TrDate)
axis(2, tck=1, col.ticks="lightgray")
for (i in 0:10){
abline(v=i*nrow(abc)/10, lty=2, col="lightgray")
}

lines(xyz$sma, type="l", col='blue')
legend("topleft", lty=c(1,1), col=c('red', 'blue'), 
       legend=c("Close Price", "SMA20"), bty="n", 
       cex=0.6, lwd=c(2,1))
plot(xyz$macd, xaxt="n", type="l", col="green", ylab="MACD/Signal", 
     mai=c(0.1,0.5,0.1,0.1), xlab=NA, main=NA, sub=NA)
axis(1, at=1:nrow(abc), labels=abc$TrDate)
axis(2, tck=1, col.ticks="lightgray")
for (i in 0:10){
abline(v=i*nrow(abc)/10, lty=2, col="lightgray")
}

lines(xyz$signal, type="l", col='brown')
abline(h=0, col='purple')
legend("topleft", col=c('green', 'brown'), lty=c(1,1), 
       legend=c('macd', 'signal'), bty="n", cex=0.6)


#---MACD plot---

# module A4 End

#---------------------------------------------------------------------------------

# module A5
# Technical Analysis: RSI, Relative Strength Index

library(TTR)

sma<-SMA(abc$ClosePrice, n=20)

rsi14<-RSI(abc$ClosePrice, n=14)
xyz<-data.frame(TrDate=abc$TrDate, ClosePrice=abc$ClosePrice, 
                volume=abc$volume, rsi14, sma)
head(xyz,20)
tail(xyz,20)
layout(matrix(c(1,1,1,2,2), nrow=5, ncol=1))
plot(abc$ClosePrice, xaxt="n", type="l", col=2, xlab="Date", main="", 
     sub="", ylim=c(min(abc$ClosePrice)*0.95, max(abc$ClosePrice)*1.05), 
     ylab="Close Price", mai=c(0.1,1,0.1,0.5), lwd=2)
axis(1, at=1:nrow(abc), labels=abc$TrDate)
axis(2, tck=1, col.ticks="lightgray")
for (i in 0:10){
abline(v=i*nrow(abc)/10, lty=2, col="lightgray")
}

lines(xyz$sma, type="l", col='blue')
legend("topleft", lty=c(1,1), col=c('red', 'blue'), 
       legend=c("Close Price", "SMA20"), bty="n", cex=0.6, lwd=c(2,1))

plot(xyz$rsi14, xaxt="n", type="l", col="blue", 
     ylim=c(0,100), xlab="", main="", sub="",  
     ylab="RSI", mai=c(0.1,1,0.1,0.5))
axis(1, at=1:nrow(abc), labels=abc$TrDate)
axis(2, tck=1, col.ticks="lightgray")
for (i in 0:10){
abline(v=i*nrow(abc)/10, lty=2, col="lightgray")
}

abline(h=30, lty=2, col="red")
abline(h=70, lty=2, col="red")
text(5,40, "RSI=30", col="blue")
text(5,80, "RSI=70", col="blue")

#---RSI plot---

# module A5 End

#----------------------------------------------------------------------------------------------

Sample data link: 500510.csv



Author can be reached at:

arg1962@gmail.com          

mobile:  9488361726


Comments

  1. Hello Rajagopal Sir,

    Thanks for writing this blog and it has helped to learn more on how to use R for technical analysis. Can you please help me how to write the code for EMA 50 days for which the data is in Excel or R table without plotting graphs or with plotting.

    Please note I am self learner when it comes to coding.

    Regards,
    Shiva

    ReplyDelete

Post a Comment

Popular posts from this blog

Neural Network – IRIS data Classification Model, Dr. Arunachalam Rajagopal

Electricity Generation Forecast using ANN with R, Dr. Arunachalam Rajagopal