Friday 18 August 2017

How to Calculate Beta of a Stock using R Programming?

R is a powerful tool. Apart from using it for data science, it can be used an excel spreadsheet. The last couple of years I showed you how to calculate beta of a stock on excel, now I take an opportunity to calculate beta of a stock. Click Here to know how to calculate beta of a stock on excel.

To get beta you do not need any fancy library to load. Your base package will work fine.

The process is simple and as follows:

  1. Import data to R
  2. calculate returns (arithmetic, logarithmic)
  3.  apply linear regression
  4. select slop as beta.
The codes are as follows:

Importing Data

We will import the data in the name of nifty and ril. which are in the forms of OHLC data collected from nseindia.com. Where I used nifty and Reliance Ltd data.

nifty<-read.csv(choose.files(),header = TRUE)
ril<-read.csv(choose.files(),header = TRUE)

Renaming the values

This is not necessary as specifing the complete data is hectic. I like to cut it short.

NC<-nifty$Close
RC<-ril$Close.Price

Plotting the Closing Price

plot(NC,type = "l",main="Nifty",col="Red")
plot(RC,type="l",main="RIL",col="green")

Calculating the closing price

I tried to calcualte the returns using Arthamatic menthod and even log menthod can be better and most desireable than this.

indexR<-(NC[1:(length(NC)-1)]-NC[2:length(NC)])/NC[2:length(NC)]
stockR<-(RC[1:(length(RC)-1)]-RC[2:length(RC)])/RC[2:length(RC)]

Finding the regression of x and y

result<-lm(stockR~indexR)
beta<-result$coefficients[2,1]
print(beta)

No comments:

Post a Comment