Wednesday, November 5, 2014

Portfolio Optimization, Tangency Portfolio, CML with shorts not allowed.

The functions in the previous post have been updated to put in the additional constraints that no portfolio weights can be negative, that is short selling is not allowed.

setwd("C:/Users/admin/Desktop/Data Analytics/QuantitativeFinance/QFLabs")


GetData20 <- function(CSVfile){
  baseData <- read.csv(CSVfile)
  N0 <- ncol(baseData)
  Close <- baseData[, 3:N0]
  logRet1 <- log(head(Close, -1) / tail(Close, -1))

PlotData20 <- function(logRet1){
  Retn <- colMeans(logRet1)
  Risk <- diag(var(logRet1))
  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")

rOptPort20 <- function(hRets,pRet, Shorts = TRUE){
  Dmat <- 2*cov(hRets)
  dvec <- rep(0,ncol(hRets))
  if (Shorts){
    ##message("Shorts : TRUE")    ## Shorts are allowed
    Amat <- cbind(rep(1,ncol(hRets)),colMeans(hRets))
    bvec <- c(1,pRet)
  } else {
    ##message("Shorts = FALSE")    ## Shorts are not allowed
    Amat <- cbind(rep(1,ncol(hRets)),colMeans(hRets),diag(1,nrow = ncol(hRets)))
    bvec <- c(1,pRet,rep(0,ncol(hRets)))
  result = tryCatch({
    solve.QP(Dmat = Dmat, dvec = dvec, Amat = Amat, bvec = bvec, meq =2)
  }, warning = function(w){
    message("warning : ",pRet)
  }, error = function(w){
    message("infeasible : ", pRet)
  }, finally = {
  if (!is.null(result)){
    wP <- result$solution
    varP <- result$value
    wP <- "error"
    varP <- "error"
  retList <- list(wP,varP)
  names(retList) <- c("wP","varP")

EFMinVar20 <- function(hRets, minRet, maxRet,Shorts = FALSE){
  smuP <- seq(minRet,maxRet,length=50)
  svarP <- sapply(smuP,function(x) rOptPort20(hRets,x,Shorts)$varP)
  EffF <-,svarP))
  EffF0 <-[EffF$svarP != "error",])
  EffF0 <-, 2, FUN = function(x) as.numeric(as.character(x))))
  minVar <- min(EffF0$svarP)
  L <- EffF0$svarP == minVar
  minRet <- EffF0[L,]$smuP
  minPoint <-,minVar))
  minVarwP <- rOptPort20(hRets,minRet,Shorts)$wP
  rList <-list(EffF0,minPoint,minVarwP)
  names(rList) <- c("EFF","minPoint","wP")

EFMinVar20Plot <- function(list1){
  ealred  <- "#7D110C"
  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")

EFSharpe20 <- function(hRets, minRet, maxRet,RF, Shorts = FALSE){
  smuP <- seq(minRet,maxRet,length=50)
  svarP <- sapply(smuP,function(x) rOptPort20(hRets,x,Shorts)$varP)
  EffF <-,svarP))
  EffF0 <-[EffF$svarP != "error",])
  EffF0 <-, 2, FUN = function(x) as.numeric(as.character(x))))
  sharpe <- (EffF0$smuP-RF)/EffF0$svarP
  EFF <-,sharpe,RF))
  L <- EFF$sharpe == max(EFF$sharpe)
  maxSharpe <- EFF[L,]
  wTP <- rOptPort20(hRets,maxSharpe$smuP,Shorts)$wP
  rList <-list(EFF,maxSharpe,wTP)
  names(rList) <- c("EFF","maxSharpe","wTP")

EFSharpe20Plot <- 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")


logRet <- GetData20("US5.csv")
##logRet <- GetData20("India5.csv")

## Shorts = FALSE

z10 <- EFMinVar20(logRet,-0.0005,0.0002, Shorts = FALSE)
cminRet <- (z10$minPoint)$minRet
z11 <- rOptPort20(logRet,cminRet,Shorts = FALSE)
cminRet <- (z10$minPoint)$minRet
maxR <- cminRet + max(0.001,cminRet+ 2*abs(cminRet))
z10a <- EFMinVar20(logRet,cminRet, maxR, Shorts = FALSE)

z12 <- EFSharpe20(logRet,cminRet,maxR,0.0001,Shorts = FALSE)
maxSharpeRet <- (z12$maxSharpe)$smuP

After the data is downloaded from the web and stored in  CSV file as explained in an earlier post. define the functions and test the program as follows :

> logRet <- GetData20("US5.csv")
> ##logRet <- GetData20("India5.csv")
> PlotData20(logRet)

Unlike the case were shorts are allowed, in this case, not every desired portfolio return is feasibile when shorts are not allowed. Here we search through a range of returns from -0.0005 to + 0.0002 and detect which return gives us the minimum variance. The means that are infeasible are flagged as sucn and ignored.
> z10 <- EFMinVar20(logRet,-0.0005,0.0002, Shorts = FALSE)
infeasible : -5e-04
infeasible : -0.000242857142857143

Dataframe z10 contains the range of feasible returns and the corresponding variance. The portofolio weights are printed out as follows. The first one though technically negative is very, very small.
> z10$wP
[1] -1.386988e-17  4.295438e-02  1.356919e-01  4.977252e-01  3.236285e-01

we note the return achieved at the point of minimum variance
> cminRet <- (z10$minPoint)$minRet
> cminRet
[1] 0.0001285714

> EFMinVar20Plot(z10)

The efficient frontier is plotted, but this is not very useful because the range of returns that we have taken are "below" the minvariance point.

So in the next few lines, we have defined a range of returns that goes above, or higher than, the return for minimum variance

> cminRet <- (z10$minPoint)$minRet
> maxR <- cminRet + max(0.001,cminRet+ 2*abs(cminRet))
> z10a <- EFMinVar20(logRet,cminRet, maxR, Shorts = FALSE)
infeasible : 0.000761224489795919
infeasible : 0.00112857142857143
> EFMinVar20Plot(z10a)

Next we identify the maximum Sharpe ratio, identify the tangency portfolio and draw the capital market line. Note that the risk free rate is 0.0001

> z12 <- EFSharpe20(logRet,cminRet,maxR,0.0001,Shorts = FALSE)
infeasible : 0.000761224489795919
infeasible : 0.00112857142857143
> z12$wTP
[1]  2.515328e-01  0.000000e+00 -1.456853e-17  7.484672e-01 -6.938894e-18
> sum(z12$wTP)
[1] 1
> (z12$maxSharpe)$smuP
[1] 0.0005163265
> (z12$maxSharpe)$svarP
[1] 0.0002621069
> maxSharpeRet <- (z12$maxSharpe)$smuP
> EFSharpe20Plot(z12)

Please note that by setting SHORTS = TRUE, this set of functions should be able to recreate the results given in the previous post.

These programs can be run on StatAce, the free hosted R environment and get the same result.


  1. How long should we hold this portfolio weightage to get the expected return?

  2. Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. SEO optimalisatie

  3. I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. Thanks... SEO

  4. This is a mind boggling stirring article.I am essentially happy with your incredible work.You put really outstandingly obliging information... SEO in New York

  5. These companies do not take any shortcuts, and usually have a team of professional content writers who will cater to the needs of the business in a comprehensive manner so that Search Engine Optimization does not become a headache for the company or client. business startup We have entered an era where business is no longer limited to where you are established.

  6. Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info.

  7. Hello I am so delighted I located your blog, I really located you by mistake, while I was watching on google for something else, Anyways I am here now and could just like to say thank for a tremendous post and a all round entertaining website. Please do keep up the great work.

  8. This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free. Niche Relevant

  9. Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained! Ethiopian Policus

  10. If you request that a SEO proficient mention to you what it will take to get you to page 1, and they give you the old "we don't have any acquaintance with, it is up to Google", we suggest finding different alternatives. SEO no cure no pay

  11. Both compensation per-snap and SEO are focused to get your site set as near the highest point of web index results as could really be expected. Showcasing and SEO are extraordinary, yet extremely, comparable. link

  12. The code optimization stage in a compiler starts with apportioning the successions of three-address directions into essential squares. These essential squares become the hubs of a stream diagram. Ebay SEO expert top3

  13. SEO hosting allows you to spread your domain names across multiple c class ips, making them look unique and separated. SEO hosting makes it all possible to manage these ips under one control panel. It would be a time consuming nightmare to have to login manually to each ip. web hosting

  14. Search engine optimization (SEO) is a mega-hot, high-paying field right now. Hence, job opportunities in SEO have grown significantly. This means the need for SEO training is growing by leaps and bounds. But, what type of SEO course is right for you, how much will it cost, is it online or off? Get answers to these questions, and more, here.

  15. Harrah's Philadelphia - MapyRO
    The Harrah's Philadelphia Hotel and Casino, 과천 출장샵 Philadelphia: 495 reviews, 12 photos 인천광역 출장안마 and 30 태백 출장마사지 tips. Leave 대전광역 출장안마 a rating. ☆ Harrah's Philadelphia Casino - See All. Rating: 3 · ‎Review by Ayden J. 경산 출장샵