Reading Returns Data

Let us import the returns xts object we created.

library(quantmod)

returns <- read.csv("returns.csv", stringsAsFactors = F)
returns <- xts(returns, order.by=as.Date(returns$Index),"%d-%m-%Y")

returns <- returns[,2:1632]
returns <- returns[-1,]
mode(returns) <- "numeric"
dim(returns)
## [1] 2855 1631

Getting Mean, Stdev, Covariances of Stocks

We have the log returns data with us. Let us calculate the average returns, standard deviation of the individual staocks and covariances among the stocks. To do that, let us create a function called “findCovMat()”. This function will take the returns as an input and returns the mean, stdev and covariances. We will combine these three into a list.

findCovMat <- function(R, ...) {
  
  meanv        <- apply(R,2, FUN = function(x){mean(x, na.rm = T)})  # Average return of stocks
  cov_mat      <- cov(R, use = "pairwise.complete.obs")              # Covariance among stocks
  diag_cov_mat <- diag(cov_mat)                                      # Variances of Individual stocks
  sdevv        <- sqrt(diag(cov_mat))                                # Stdev of Stocks
  
  list(meanv,cov_mat,diag_cov_mat,sdevv)
}

Let us use this function on our returns and call it as “info”

info <- findCovMat(returns)

Access the Info

We can access the required data from info using list indexing.

mean   <- info[[1]]   # To get averages of individual stocks
covar  <- info[[2]]   # To get covariances among the stocks
var    <- info[[3]]   # To get variances of the individual stocks
stdev  <- info[[4]]   # To get standard deviations (Risk) of the individual stocks

Creating Portfolio

We have collected returns of various stocks and calculated their average daily log returns, standard deviations and covariances between them. Let us use this data to create an optimal portfolio.

Sharpe Ratio

There are around 1600 stocks in our dataframe. We need to identify only a few stocks which promise better returns at a given amount of risk. This is measured by Sharpe Ratio. Sharpe Ratio is the excess return provided by the asset when additional 1% risk is taken.

So we will calculate the Sharpe Ratio of all the stocks and shortlist the stocks which have better Sharpe Ratio.

sharpe <- function(mean, stdev, rf){

  mean.a  <- mean * 252
  stdev.a <- stdev * sqrt(252)
  logrf   <- log(1+rf)
  sharpe  <- (mean.a - logrf)/stdev.a
}


ratios <- sharpe(mean, stdev, 0.06)
ratios <- ratios[order(-ratios)]

We have calculated Sharpe Ratios as “ratios” as a list. We will take the 15 stocks with highest Sharpe Ratio to create our portfolio.

names(ratios[1:15])
##  [1] "URJA.NS.Close"       "BOROSIL.NS.Close"    "MASKINVEST.NS.Close"
##  [4] "BANDHANBNK.NS.Close" "KIOCL.NS.Close"      "OPTIEMUS.NS.Close"  
##  [7] "NBIFIN.NS.Close"     "MIDHANI.NS.Close"    "AVANTIFEED.NS.Close"
## [10] "TALWGYM.NS.Close"    "PSPPROJECT.NS.Close" "DMART.NS.Close"     
## [13] "SMSLIFE.NS.Close"    "NRAIL.NS.Close"      "TASTYBITE.NS.Close"

These stocks have high sharpe ratio. But one should be careful while selecting stocks while creating a portfolio. There may be some penny stocks, some bad stocks with no fundementals or some stocks which are traded very less. Make sure you avoid such stocks while selecting the stocks. SO to avoid such kind of stocks, I will skip, first few stocks from our list. Let us try with stocks from 40 to 90 ranks in our list.

stocks <- names(ratios[40:90])

Weights of Investments

We have selected our stocks to invest. But we are yet to calculate how much to invest in each of these stocks. In other words, what fraction of the total investment should be given to each stock?

We know that creating a portfolio helps us decrease our risks by diversification and at the same time increasing our returns. So we have to assign weights in such a way that the risk is minimized. This done by using minimizing program. We will do this by using “quadprog” package.

library(quadprog)

findWeights <- function(mean, cov, mean_port){
  
  Dmat    <- 2*cov
  dvec    <- rep(0, length(mean))
  Amat    <- cbind(rep(1,length(mean)),mean,diag(1,nrow=length(mean)))
  bvec    <- c(1,mean_port,rep(0,length(mean)))
  weights <- solve.QP(Dmat, dvec, Amat, bvec, meq = 2)
  weights
  
}

To calculate Weights let us use above function. Let us get the relevant data first and make them into seperate objects.

mean.n  <- mean[stocks]*252
cov.n   <- covar[stocks, stocks]*252

weights <- findWeights(mean.n, cov.n, .6)

Let us look at the weights and the solution (risk) of our portfolio

weights.n <- data.frame(stock = stocks, weight = round(weights$solution,3)) # To Get weights of stocks
final     <- subset(weights.n, weights.n$weight > 0)
final
##                stock weight
## 1  JSLHISAR.NS.Close  0.100
## 3      APEX.NS.Close  0.295
## 5   BIGBLOC.NS.Close  0.293
## 11 SHIVATEX.NS.Close  0.108
## 12  IBULISL.NS.Close  0.200
## 24   HITECH.NS.Close  0.004
risk      <- weights$value               # To know the risk value
risk
## [1] 0.1133738

2018-07-27