Let us learn Stock Analysis using R

List of packages required

library(quantmod)
## Loading required package: xts
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(xts)
library(rvest)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter()         masks stats::filter()
## ✖ dplyr::first()          masks xts::first()
## ✖ readr::guess_encoding() masks rvest::guess_encoding()
## ✖ dplyr::lag()            masks stats::lag()
## ✖ dplyr::last()           masks xts::last()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(stringr)
library(forcats)
library(lubridate)
library(plotly)
## 
## Attaching package: 'plotly'
## 
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## 
## The following object is masked from 'package:stats':
## 
##     filter
## 
## The following object is masked from 'package:graphics':
## 
##     layout
library(dplyr)
library(PerformanceAnalytics)
## 
## Attaching package: 'PerformanceAnalytics'
## 
## The following object is masked from 'package:graphics':
## 
##     legend

Let us set the start and end date for the data extraction from the yahoo finance website

start <- as.Date("2022-01-01")
end <- as.Date("2023-11-23")
getSymbols("TATASTEEL.NS",src = "yahoo", from=start, to=end)
## [1] "TATASTEEL.NS"

Exploring the dataset

head(TATASTEEL.NS)
##            TATASTEEL.NS.Open TATASTEEL.NS.High TATASTEEL.NS.Low
## 2022-01-03            111.50            115.10          111.500
## 2022-01-04            115.30            115.97          113.650
## 2022-01-05            114.70            118.08          114.125
## 2022-01-06            117.20            118.30          115.555
## 2022-01-07            116.52            117.40          114.785
## 2022-01-10            116.50            117.34          115.385
##            TATASTEEL.NS.Close TATASTEEL.NS.Volume TATASTEEL.NS.Adjusted
## 2022-01-03            114.245            38658030              104.9700
## 2022-01-04            114.880            59757310              105.5534
## 2022-01-05            117.760            61861760              108.1996
## 2022-01-06            116.325            53354000              106.8811
## 2022-01-07            116.035            39738570              106.6146
## 2022-01-10            116.905            38225000              107.4140
tail(TATASTEEL.NS)
##            TATASTEEL.NS.Open TATASTEEL.NS.High TATASTEEL.NS.Low
## 2023-11-15            121.70            124.40           121.50
## 2023-11-16            124.00            125.25           123.00
## 2023-11-17            124.70            125.75           124.30
## 2023-11-20            125.05            125.65           124.05
## 2023-11-21            125.05            126.40           124.95
## 2023-11-22            126.40            126.90           125.50
##            TATASTEEL.NS.Close TATASTEEL.NS.Volume TATASTEEL.NS.Adjusted
## 2023-11-15             124.05            38344393                124.05
## 2023-11-16             124.70            30836413                124.70
## 2023-11-17             125.20            23319439                125.20
## 2023-11-20             124.35            18780290                124.35
## 2023-11-21             126.25            29643312                126.25
## 2023-11-22             126.10            19588063                126.10
plot(TATASTEEL.NS[,"TATASTEEL.NS.Close"],main = "SBIN.NS")

candleChart(TATASTEEL.NS, up.col="green", dn.col="red", theme = "white")

getSymbols(c("TATASTEEL.NS","JSWSTEEL.NS", "JINDALSTEL.NS"), src = "yahoo", from=start, to=end)
## [1] "TATASTEEL.NS"  "JSWSTEEL.NS"   "JINDALSTEL.NS"

Let us now get the multiple stocks into our study

stocks<- as.xts(data.frame(TATASTEEL.NS=TATASTEEL.NS[,"TATASTEEL.NS.Close"],JSWSTEEL.NS=JSWSTEEL.NS[,"JSWSTEEL.NS.Close"], JINDALSTEL.NS=JINDALSTEL.NS[,"JINDALSTEL.NS.Close"]))
head(stocks)
##            TATASTEEL.NS.Close JSWSTEEL.NS.Close JINDALSTEL.NS.Close
## 2022-01-03            114.245            667.05              385.85
## 2022-01-04            114.880            670.40              388.20
## 2022-01-05            117.760            694.50              406.40
## 2022-01-06            116.325            673.95              402.90
## 2022-01-07            116.035            672.85              406.60
## 2022-01-10            116.905            672.10              404.30
plot(as.zoo(stocks), screens=1, lty=1:3, xlab="Date", ylab="Price")

legend("right", c("TATASTEEL.NS", "JSWSTEEL.NS", "JINDALSTEL.NS"),lty=1:3, cex=0.5)

Let us now calculate the retruns

library(magrittr)
## 
## Attaching package: 'magrittr'
## The following object is masked from 'package:purrr':
## 
##     set_names
## The following object is masked from 'package:tidyr':
## 
##     extract
stock_return <- apply(stocks, 1, function(x) {x / stocks[1,]}) %>% t %>% as.xts
head(stock_return)
##            TATASTEEL.NS.Close JSWSTEEL.NS.Close JINDALSTEL.NS.Close
## 2022-01-03           1.000000          1.000000            1.000000
## 2022-01-04           1.005558          1.005022            1.006090
## 2022-01-05           1.030767          1.041151            1.053259
## 2022-01-06           1.018206          1.010344            1.044188
## 2022-01-07           1.015668          1.008695            1.053777
## 2022-01-10           1.023283          1.007571            1.047816
plot(as.zoo(stock_return), screens = 1, lty = 1:3, xlab = "Date", ylab = "Return" )
legend("topleft", c("TATASTEEL.NS", "JSWSTEEL.NS", "JINDALSTEL.NS"),lty=1:3, cex = 0.5)

Making our returns more accurate and insightful perspective on investment returns.

#By using log returns, investors can make more informed decisions about their investments, # based on a clearer understanding of the true impact of changes in value over time.

stock_change <- stocks%>% log%>% diff
head(stock_change)
##            TATASTEEL.NS.Close JSWSTEEL.NS.Close JINDALSTEL.NS.Close
## 2022-01-03                 NA                NA                  NA
## 2022-01-04        0.005542792       0.005009598         0.006071993
## 2022-01-05        0.024760592       0.035317577         0.045817179
## 2022-01-06       -0.012260702      -0.030036220        -0.008649504
## 2022-01-07       -0.002496070      -0.001633556         0.009141539
## 2022-01-10        0.007469727      -0.001115283        -0.005672770
plot(as.zoo(stock_change),screens=1, lty=1:3, xlab = "Date", ylab = "Log Difference")
legend("topleft", c("TATASTEEL.NS", "JSWSTEEL.NS", "JINDALSTEL.NS"), lty = 1:3, cex = 0.5)

Why don’t we check the correlation while interpreting the stocks performance?

Using cor() you can check the correlation

Simple Moving Average

cor(stocks)
##                     TATASTEEL.NS.Close JSWSTEEL.NS.Close JINDALSTEL.NS.Close
## TATASTEEL.NS.Close           1.0000000         0.6353199           0.5968716
## JSWSTEEL.NS.Close            0.6353199         1.0000000           0.9056154
## JINDALSTEL.NS.Close          0.5968716         0.9056154           1.0000000
candleChart(TATASTEEL.NS, up.col="green", dn.col="red", theme = "white")

addSMA(n=20)

candleChart(TATASTEEL.NS, up.col="green", dn.col="red", theme = "white", subset ="2023-10-01/" )

addSMA(n=20)

# SMA for 20, 50, and 200 days

candleChart(TATASTEEL.NS, up.col="green", dn.col="red", theme = "white", subset ="2022-10-01/" )

addSMA(n=c(20,50,200), col = c("blue", "green", "red"))

Interpret the results