Tuesday, November 4, 2014

Portfolio Optimisation, Tangency Portfolio and CML -- shorts allowed

I wish I could document this better, but let me get the code out first. The data used by the program shown in this post is available in a CSV file that can be created in the manner shown in an earlier post.

setwd("C:/Users/admin/Desktop/Data Analytics/QuantitativeFinance/QFLabs")
##baseData <- read.csv("US5.csv")
baseData <- read.csv("India5.csv")
N0 <- ncol(baseData)
Close <- baseData[, 3:N0]
logRet <- log(head(Close, -1) / tail(Close, -1))
Retn <- colMeans(logRet)
Risk <- diag(var(logRet))
RiskReturn <-,Risk)))


plot1 <- ggplot(data = RiskReturn,aes(x = Risk, y = Retn) )
plot1 <- plot1 + geom_point()
plot1 <- plot1 + xlab("Risk / Variance") + ylab("Daily Returns") + ggtitle("Risk/Returns")

# using portfolio.optim 
w0 <- portfolio.optim(as.matrix(logRet),pm = 0.005,shorts = TRUE,riskless= FALSE)

# understanding the code


# the basic function that calculates the min variance portfolio with NO SHORTS

rOptPort10 <- function(hRets,pRet){
  Dmat <- 2*cov(hRets)
  dvec <- rep(0,ncol(hRets))
  Amat <- cbind(rep(1,ncol(hRets)),colMeans(hRets))
  bvec <- c(1,pRet)
  result <- solve.QP(Dmat = Dmat, dvec = dvec, Amat = Amat, bvec = bvec, meq =2)
  wP <- result$solution
  varP <- result$value
  retList <- list(wP,varP)
  names(retList) <- c("wP","varP")

# testing out the function with expected return

z <- rOptPort10(logRet,0.005)


# here we create the Efficient Frontier for a given range of returns

EFMinVar10 <- function(hRets, minRet, maxRet){
  smuP <- seq(minRet,maxRet,length=50)
  svarP <- sapply(smuP,function(x) rOptPort10(hRets,x)$varP)
  EffF <-,svarP))  
  minVar <- min(EffF$svarP)
  L <- EffF$svarP == minVar
  minRet <- EffF[L,]$smuP
  minPoint <-,minVar))
  minVarwP <- rOptPort10(hRets,minRet)$wP
  rList <-list(EffF,minPoint,minVarwP)
  names(rList) <- c("EFF","minPoint","wP")

# We use the above function to get the points of the Efficient Frontier
# and numerically detect the point of minimum variance

z10 <- EFMinVar10(logRet,-0.005,.005)
cminRet <- (z10$minPoint)$minRet
z11 <- rOptPort10(logRet,cminRet)

# This function plots the Efficient Frontier and showing the point of minimum variance

EFMinVar10Plot <- function(list1){
  plot2 <- ggplot(data = list1$EFF,aes(x = svarP, y = smuP) )
  plot2 <- plot2 + geom_point()
  plot2 <- plot2 + geom_point(data = list1$minPoint, aes(x = minVar,y = minRet),color = "red", size=3)
  plot2 <- plot2 + xlab("Variance") + ylab("Returns") + ggtitle("Efficient Frontier - MinVar")

cminRet <- (z10$minPoint)$minRet 

z10a <- EFMinVar10(logRet,min(0,cminRet),0.001)

# This function calculates the Max Sharpe Ratio
# and the Tangency Portfolio weights

EFSharpe10 <- function(hRets, minRet, maxRet,RF){
  smuP <- seq(minRet,maxRet,length=50)
  svarP <- sapply(smuP,function(x) rOptPort10(hRets,x)$varP)
  sharpe <- (smuP-RF)/svarP
  EFF <-,svarP,sharpe,RF))
  L <- EFF$sharpe == max(EFF$sharpe)
  maxSharpe <- EFF[L,]
  wTP <- rOptPort10(hRets,maxSharpe$smuP)$wP
  rList <-list(EFF,maxSharpe,wTP)
  names(rList) <- c("EFF","maxSharpe","wTP")

z11 <- EFSharpe10(logRet,min(0,cminRet),0.001,0.0001)
maxSharpeRet <- (z11$maxSharpe)$smuP

# This function plots the Efficient Fronter and shows
# The Tangency Point and the Capital Market Line

EFSharpe10Plot <- function(list1){
  plot2 <- ggplot(data = list1$EFF,aes(x = svarP, y = smuP) )
  plot2 <- plot2 + geom_point()
  plot2 <- plot2 + geom_point(data = list1$maxSharpe, aes(x = svarP,y = smuP),colour = "red", pch =24, size=3)
  plot2 <- plot2 + geom_point(data = list1$maxSharpe, aes(x = 0,y = RF),color = "red", pch =24, size=3)
  plot2 <- plot2 + xlab("Variance") + ylab("Returns") + ggtitle("Efficient Frontier - Sharpe")
  plot2 <- plot2 + geom_abline(intercept = (list1$maxSharpe)$RF, slope = (list1$maxSharpe)$sharpe, colour = "red")


DONT PANIC ! This 20 minute video will explain what this code is doing

What does negative weights mean ? It means short selling. So what is short selling ? Let us explain.

If you have a Rs 100 you can invest Rs 80 in Stock A and Rs 20 in Stock B and so the weights are (0.8, 0.2). Note that the weights add up to 1.

 But through a process known as short selling, you could sell Rs 80 worth of Stock B [ that you do not have, at the moment ] get Rs 80. To this you add the Rs 100 that you have and invest Rs 180 [ Rs 100 + Rs 80 ] in Stock A. In this case your weights are (180,-80) or (1.8 and -0.8) and you would note that weights add up to 1 again.

Why would you do short selling ? There are many reasons. For example, you may believe that Stock A will give you very high returns. Also if you sell "short", that is sell shares that you do not have, you will have to, at some point in future, or in the next "period" buy the shares from the market and deliver it to the person to whom you had sold the shares.


  1. This comment has been removed by the author.

  2. Doing small business portfolio is usually rough although on account of businessportfolio. online services. There're featuring a variety of account publishing services. When i likewise appreciate these individuals for their low cost selling price.

  3. The human body is the tool through which somebody experiences life and his surroundings as well as interacts and communicates with others. To some people, however, the body is another piece of canvas through which they could express themselves, their beliefs and their traditions.
    Online Accredited Financial Portfolio management advisor

  4. Project ranking is at the heart of project portfolio management (PPM). A good project portfolio ranking system should not only make the job much easier and faster but also yield a superior result over doing it manually or with simple spreadsheets.Portfolio management advisor

  5. One of the challenges of project portfolio management is planning and maintaining an optimized portfolio of projects over the long term as you launch new projects, finish successful projects, and kill unsuccessful projects. Consider that for a portfolio of 20 projects, there are over 1 million possible sub-sets of projects to choose from.portfolio Management tampa

  6. A majority of individuals have made the decision to increase their opportunities to discovering financial stability by taking advantage of investment possibilities. Best portfolio management tampa

  7. This pattern was first made acclaimed by Calvin Klein who publicized utilizing models wearing free pants and their plain white boxer shorts. boxer shorts

  8. I am all that much satisfied with the substance you have specified. I needed to thank you for this extraordinary article.  make your own custom fight shorts

  9. The preference of a customer to go online for selecting a company and ultimately buying a product has evidently boosted the need to have a proper digital marketing strategy. SEO Quotes Given below are a few tips that can help you choose the right digital marketing agency.

  10. If your website is optimized and people have started talking about it, this means that you are developing a connection with them view publisher site SEO is the abbreviation of Search Engine Optimisation.

  11. Today the Wii happens to be one of the top sellers out there, and there are many different games for you to choose from. Whether you're trying to find this year's Christmas gifts, a birthday gift for someone, or you just want some new great games for your Wii, here is a look at some of the best Wii games you'll want to consider and maybe even try yourself.

  12. How do I make money from playing games and earning
    These are kadangpintar the three most poormansguidetocasinogambling popular forms of gambling, and are งานออนไลน์ explained in a very concise and concise manner. The most common forms of gambling are: