SlideShare a Scribd company logo
Efficient Equity Portfolios using Mean
Variance Optimization
Gregg Barrett
======================== Efficient Equity Portfolios ========================
Data
setwd("~/R/datasets")
dat = read.csv("Stock_Bond.csv", header = T)
prices = cbind(dat$GM_AC, dat$F_AC, dat$CAT_AC, dat$UTX_AC,
dat$MRK_AC, dat$IBM_AC)
n = dim(prices)[1]
returns = 100 * (prices[2:n, ] / prices[1:(n-1), ] - 1)
pairs(returns)
mean_vect = colMeans(returns)
cov_mat = cov(returns)
sd_vect = sqrt(diag(cov_mat))
Function
library(quadprog)
## Warning: package 'quadprog' was built under R version 3.2.3
eff_front_fn = function(returns, muP, mu_free, lower_limit_weight = -Inf, up
per_limit_weight = +Inf){
n_stocks = dim(returns)[2]
mean_vect = apply(returns, 2, mean)
cov_mat = cov(returns)
sd_vect = sqrt(diag(cov_mat))
Amat = cbind(rep(1,n_stocks),mean_vect)
bvec = c(1,NaN)
if( is.finite(lower_limit_weight) ){
Amat = cbind(Amat, diag(1, nrow = n_stocks))
bvec = c(bvec, lower_limit_weight * rep(1, n_stocks))
}
if( is.finite(upper_limit_weight) ){
Amat = cbind(Amat, -diag(1, nrow = n_stocks))
bvec = c(bvec, -upper_limit_weight * rep(1, n_stocks))
}
sdP = muP
weights = matrix(0, nrow = length(muP), ncol = n_stocks)
for( i in 1:length(muP) ){
bvec[2] = +muP[i]
result = solve.QP(Dmat = 2*cov_mat, dvec = rep(0, n_stocks), Amat = Ama
t, bvec = bvec, meq=2)
sdP[i] = sqrt(result$value)
weights[i,] = result$solution
}
sharpe = ( muP - mu_free ) / sdP
ind_ms = (sharpe == max(sharpe))
ind_mv = (sdP == min(sdP))
list( muP = muP, sdP = sdP, weights = weights, sharpe = sharpe, max_sharp
e = ind_ms, min_variance = ind_mv )
}
Setting the risk free rate, the target
porfolio return and constraints
mu_free = 3.0/365
muP = seq(min(mean_vect), max(mean_vect), length.out=300)
mvo = eff_front_fn(returns, muP, mu_free = mu_free, lower_limit_weight = -0.
1, upper_limit_weight = 0.5)
sdP = mvo$sdP
Plot
plot(sdP, muP, type = "l",
xlim = c(0, 1.1 * max(sd_vect)),
ylim = c(0, 1.1 * max(mean_vect)),
lty=3)
points(0, mu_free, cex = 4, pch = "*")
sharpe = ( muP - mu_free ) / sdP
ind_ms = (sharpe == max(sharpe))
print(mvo$weights[ind_ms,] )
## [1] -0.091164544 -0.002905131 0.335298962 0.383700258 0.319482622
## [6] 0.055587833
lines(c(0, 2), mu_free + c(0, 2) * (muP[ind_ms] - mu_free) / sdP[ind_ms],
lwd = 4, lty = 1, col = "blue")
points(sdP[ind_ms], muP[ind_ms], cex = 4, pch = "*")
ind_mv = (sdP == min(sdP))
points(sdP[ind_mv], muP[ind_mv], cex = 2, pch = "+")
ind3 = (muP > muP[ind_mv])
lines(sdP[ind3], muP[ind3], type = "l", xlim = c(0, 0.25),
ylim = c(0, 0.3), lwd = 3, col = "red")
text(sd_vect[1], mean_vect[1], "GM", cex = 1.15)
text(sd_vect[2], mean_vect[2], "F", cex = 1.15)
text(sd_vect[3], mean_vect[3], "CAT", cex = 1.15)
text(sd_vect[4], mean_vect[4], "UTX", cex = 1.15)
text(sd_vect[5], mean_vect[5], "MRK", cex = 1.15)
text(sd_vect[6], mean_vect[6], "IBM", cex = 1.15)
======== Efficient Equity Portfolios using the package “fPortfolio” from Rmetrics ========
Data
library(fPortfolio)
## Warning: package 'fPortfolio' was built under R version 3.2.3
## Loading required package: timeDate
## Warning: package 'timeDate' was built under R version 3.2.3
## Loading required package: timeSeries
## Warning: package 'timeSeries' was built under R version 3.2.3
## Loading required package: fBasics
## Warning: package 'fBasics' was built under R version 3.2.3
##
##
## Rmetrics Package fBasics
## Analysing Markets and calculating Basic Statistics
## Copyright (C) 2005-2014 Rmetrics Association Zurich
## Educational Software for Financial Engineering and Computational Science
## Rmetrics is free software and comes with ABSOLUTELY NO WARRANTY.
## https://www.rmetrics.org --- Mail to: info@rmetrics.org
## Loading required package: fAssets
## Warning: package 'fAssets' was built under R version 3.2.3
##
##
## Rmetrics Package fAssets
## Analysing and Modeling Financial Assets
## Copyright (C) 2005-2014 Rmetrics Association Zurich
## Educational Software for Financial Engineering and Computational Science
## Rmetrics is free software and comes with ABSOLUTELY NO WARRANTY.
## https://www.rmetrics.org --- Mail to: info@rmetrics.org
##
##
## Rmetrics Package fPortfolio
## Portfolio Optimization
## Copyright (C) 2005-2014 Rmetrics Association Zurich
## Educational Software for Financial Engineering and Computational Science
## Rmetrics is free software and comes with ABSOLUTELY NO WARRANTY.
## https://www.rmetrics.org --- Mail to: info@rmetrics.org
setwd("~/R/datasets")
dat = read.csv("Stock_Bond.csv", header = T)
prices = cbind(dat$GM_AC, dat$F_AC, dat$CAT_AC, dat$UTX_AC,
dat$MRK_AC, dat$IBM_AC)
n = dim(prices)[1]
returns = 100 * (prices[2:n, ] / prices[1:(n-1), ] - 1)
pairs(returns)
mean_vect = colMeans(returns)
cov_mat = cov(returns)
sd_vect = sqrt(diag(cov_mat))
Constraints
returns3 = as.timeSeries(returns)
names(returns3) = c("GM", "F", "CAT", "UTX", "MRK", "IBM")
Constraints = c(
"minW[1:nAssets] = rep(-0.10, times = nAssets)",
"maxW[1:nAssets] = rep(0.50, times = nAssets)")
Spec
spec1 = portfolioSpec()
setRiskFreeRate(spec1) = 0.0082192
Model and plot
mvo2 = portfolioFrontier(returns3, spec1, Constraints)
frontierPlot(mvo2, frontier = c("both"),
col = c("black", "grey"), labels = TRUE,
return = c("mean"), risk = c("Sigma"))
minvariancePoints(mvo2, col = "red")
tangencyPoints(mvo2, col = "green")
tangencyLines(mvo2, col = "purple")
Examination of weights
weightsSlider(mvo2)
Efficient equity portfolios using mean variance optimisation in R

More Related Content

DOC
Virtual inheritance
DOCX
BIometrics- plotting DET and EER curve using Matlab
DOCX
Write a program to print out all armstrong numbers between 1 and 500
PDF
Assignment3
PPTX
Function presentation
PPSX
C programming pointer
PPTX
(Full MatLab Code) Image compression DCT
Virtual inheritance
BIometrics- plotting DET and EER curve using Matlab
Write a program to print out all armstrong numbers between 1 and 500
Assignment3
Function presentation
C programming pointer
(Full MatLab Code) Image compression DCT

What's hot (20)

PDF
Farewell to #define private public
DOCX
Let us C (by yashvant Kanetkar) chapter 3 Solution
PDF
Essence of the iterator pattern
PPT
4 Type conversion functions
PPT
PPTX
C programming
PPTX
Introduction to F# for the C# developer
PDF
MIMO Capacity and Duality Between MAC and BC
RTF
Amortized complexity
DOCX
RTF
Amortized complexity
PPTX
C- Programs - Harsh
RTF
Amortized complexity
DOCX
Program uts
PPTX
Lessons learned from functional programming
PDF
Implementation of c string functions
PDF
15 2. arguement passing to main
PDF
Hexagonal architecture & Elixir
Farewell to #define private public
Let us C (by yashvant Kanetkar) chapter 3 Solution
Essence of the iterator pattern
4 Type conversion functions
C programming
Introduction to F# for the C# developer
MIMO Capacity and Duality Between MAC and BC
Amortized complexity
Amortized complexity
C- Programs - Harsh
Amortized complexity
Program uts
Lessons learned from functional programming
Implementation of c string functions
15 2. arguement passing to main
Hexagonal architecture & Elixir
Ad

Viewers also liked (17)

PPTX
Algebra de boole
PDF
JVM responde a Peña Nieto: "Exijo respeto como mujer y como su par en la con...
DOC
10598 formato de_evaluación_-_alumno
PDF
Найти по следам. Теория и практика ретаргетинга
PPT
Insegnare e progettare per competenze
PPT
Ragusa ibla itinerario
PPT
Orbital Hemorrhage Following Trivial Trauma
PPTX
Insights del Mil-oficios Peruano: ¿qué piensan y sienten los maestros?
PDF
II-SDV 2016 Nils Newman - Sentiment Analysis: What your Choice of Words Says ...
PDF
Insights del Futbol: Psicología del Deporte Rey
PPTX
A2 Media Studies Preproduction
POT
A2 Meida Studies Minor tasks
PDF
Oculus Company Presentation
PPT
Imagenesrenacimiento
PPT
Desarrollo endogeno
PPTX
Teaser schreiben
Algebra de boole
JVM responde a Peña Nieto: "Exijo respeto como mujer y como su par en la con...
10598 formato de_evaluación_-_alumno
Найти по следам. Теория и практика ретаргетинга
Insegnare e progettare per competenze
Ragusa ibla itinerario
Orbital Hemorrhage Following Trivial Trauma
Insights del Mil-oficios Peruano: ¿qué piensan y sienten los maestros?
II-SDV 2016 Nils Newman - Sentiment Analysis: What your Choice of Words Says ...
Insights del Futbol: Psicología del Deporte Rey
A2 Media Studies Preproduction
A2 Meida Studies Minor tasks
Oculus Company Presentation
Imagenesrenacimiento
Desarrollo endogeno
Teaser schreiben
Ad

Similar to Efficient equity portfolios using mean variance optimisation in R (20)

PDF
Pumps, Compressors and Turbine Fault Frequency Analysis
DOCX
Pumps, Compressors and Turbine Fault Frequency Analysis
PDF
The ProblemUsing C programming language write a program that simul.pdf
PPT
R/Finance 2009 Chicago
PDF
Final project kijtorntham n
PDF
Kaggle Winning Solution Xgboost algorithm -- Let us learn from its author
PPTX
Leveraging R in Big Data of Mobile Ads (R在行動廣告大數據的應用)
PDF
QMC: Undergraduate Workshop, Tutorial on 'R' Software - Yawen Guan, Feb 26, 2...
PDF
All I know about rsc.io/c2go
PDF
RDataMining slides-r-programming
PDF
Introduction to programming c and data structures
PDF
Introduction to programming c and data-structures
PPTX
Python 03-parameters-graphics.pptx
PDF
Regression and Classification with R
PDF
cluster(python)
PDF
AI & ML Lab Manual1_BCE.pdf artificial intelligence
PPT
Georgy Nosenko - An introduction to the use SMT solvers for software security
PPTX
CPP Homework Help
PPT
CppTutorial.ppt
Pumps, Compressors and Turbine Fault Frequency Analysis
Pumps, Compressors and Turbine Fault Frequency Analysis
The ProblemUsing C programming language write a program that simul.pdf
R/Finance 2009 Chicago
Final project kijtorntham n
Kaggle Winning Solution Xgboost algorithm -- Let us learn from its author
Leveraging R in Big Data of Mobile Ads (R在行動廣告大數據的應用)
QMC: Undergraduate Workshop, Tutorial on 'R' Software - Yawen Guan, Feb 26, 2...
All I know about rsc.io/c2go
RDataMining slides-r-programming
Introduction to programming c and data structures
Introduction to programming c and data-structures
Python 03-parameters-graphics.pptx
Regression and Classification with R
cluster(python)
AI & ML Lab Manual1_BCE.pdf artificial intelligence
Georgy Nosenko - An introduction to the use SMT solvers for software security
CPP Homework Help
CppTutorial.ppt

More from Gregg Barrett (20)

PDF
Cirrus: Africa's AI initiative, Proposal 2018
PDF
Cirrus: Africa's AI initiative
PDF
Applied machine learning: Insurance
DOCX
Road and Track Vehicle - Project Document
PDF
Modelling the expected loss of bodily injury claims using gradient boosting
PDF
Data Science Introduction - Data Science: What Art Thou?
PDF
Revenue Generation Ideas for Tesla Motors
PDF
Data science unit introduction
PDF
Social networking brings power
PDF
Procurement can be exciting
PDF
Machine Learning Approaches to Brewing Beer
PDF
A note to Data Science and Machine Learning managers
PDF
Quick Introduction: To run a SQL query on the Chicago Employee Data, using Cl...
PDF
Hadoop Overview
PDF
Variable selection for classification and regression using R
PDF
Diabetes data - model assessment using R
PDF
Introduction to Microsoft R Services
PDF
Insurance metrics overview
PDF
Review of mit sloan management review case study on analytics at Intermountain
PDF
Example: movielens data with mahout
Cirrus: Africa's AI initiative, Proposal 2018
Cirrus: Africa's AI initiative
Applied machine learning: Insurance
Road and Track Vehicle - Project Document
Modelling the expected loss of bodily injury claims using gradient boosting
Data Science Introduction - Data Science: What Art Thou?
Revenue Generation Ideas for Tesla Motors
Data science unit introduction
Social networking brings power
Procurement can be exciting
Machine Learning Approaches to Brewing Beer
A note to Data Science and Machine Learning managers
Quick Introduction: To run a SQL query on the Chicago Employee Data, using Cl...
Hadoop Overview
Variable selection for classification and regression using R
Diabetes data - model assessment using R
Introduction to Microsoft R Services
Insurance metrics overview
Review of mit sloan management review case study on analytics at Intermountain
Example: movielens data with mahout

Recently uploaded (20)

PPT
DATA COLLECTION METHODS-ppt for nursing research
PPTX
Microsoft-Fabric-Unifying-Analytics-for-the-Modern-Enterprise Solution.pptx
PDF
Galatica Smart Energy Infrastructure Startup Pitch Deck
PPT
Predictive modeling basics in data cleaning process
PPTX
CEE 2 REPORT G7.pptxbdbshjdgsgjgsjfiuhsd
PPTX
Market Analysis -202507- Wind-Solar+Hybrid+Street+Lights+for+the+North+Amer...
PPTX
QUANTUM_COMPUTING_AND_ITS_POTENTIAL_APPLICATIONS[2].pptx
PDF
Mega Projects Data Mega Projects Data
PDF
Optimise Shopper Experiences with a Strong Data Estate.pdf
PPTX
01_intro xxxxxxxxxxfffffffffffaaaaaaaaaaafg
PDF
Lecture1 pattern recognition............
PDF
Introduction to the R Programming Language
PPTX
Managing Community Partner Relationships
PDF
How to run a consulting project- client discovery
PPTX
A Complete Guide to Streamlining Business Processes
PPTX
Acceptance and paychological effects of mandatory extra coach I classes.pptx
PPTX
Leprosy and NLEP programme community medicine
PDF
22.Patil - Early prediction of Alzheimer’s disease using convolutional neural...
PPTX
Pilar Kemerdekaan dan Identi Bangsa.pptx
PPTX
Database Infoormation System (DBIS).pptx
DATA COLLECTION METHODS-ppt for nursing research
Microsoft-Fabric-Unifying-Analytics-for-the-Modern-Enterprise Solution.pptx
Galatica Smart Energy Infrastructure Startup Pitch Deck
Predictive modeling basics in data cleaning process
CEE 2 REPORT G7.pptxbdbshjdgsgjgsjfiuhsd
Market Analysis -202507- Wind-Solar+Hybrid+Street+Lights+for+the+North+Amer...
QUANTUM_COMPUTING_AND_ITS_POTENTIAL_APPLICATIONS[2].pptx
Mega Projects Data Mega Projects Data
Optimise Shopper Experiences with a Strong Data Estate.pdf
01_intro xxxxxxxxxxfffffffffffaaaaaaaaaaafg
Lecture1 pattern recognition............
Introduction to the R Programming Language
Managing Community Partner Relationships
How to run a consulting project- client discovery
A Complete Guide to Streamlining Business Processes
Acceptance and paychological effects of mandatory extra coach I classes.pptx
Leprosy and NLEP programme community medicine
22.Patil - Early prediction of Alzheimer’s disease using convolutional neural...
Pilar Kemerdekaan dan Identi Bangsa.pptx
Database Infoormation System (DBIS).pptx

Efficient equity portfolios using mean variance optimisation in R

  • 1. Efficient Equity Portfolios using Mean Variance Optimization Gregg Barrett ======================== Efficient Equity Portfolios ======================== Data setwd("~/R/datasets") dat = read.csv("Stock_Bond.csv", header = T) prices = cbind(dat$GM_AC, dat$F_AC, dat$CAT_AC, dat$UTX_AC, dat$MRK_AC, dat$IBM_AC) n = dim(prices)[1] returns = 100 * (prices[2:n, ] / prices[1:(n-1), ] - 1) pairs(returns) mean_vect = colMeans(returns) cov_mat = cov(returns) sd_vect = sqrt(diag(cov_mat))
  • 2. Function library(quadprog) ## Warning: package 'quadprog' was built under R version 3.2.3 eff_front_fn = function(returns, muP, mu_free, lower_limit_weight = -Inf, up per_limit_weight = +Inf){ n_stocks = dim(returns)[2] mean_vect = apply(returns, 2, mean) cov_mat = cov(returns) sd_vect = sqrt(diag(cov_mat)) Amat = cbind(rep(1,n_stocks),mean_vect) bvec = c(1,NaN) if( is.finite(lower_limit_weight) ){ Amat = cbind(Amat, diag(1, nrow = n_stocks)) bvec = c(bvec, lower_limit_weight * rep(1, n_stocks)) } if( is.finite(upper_limit_weight) ){ Amat = cbind(Amat, -diag(1, nrow = n_stocks)) bvec = c(bvec, -upper_limit_weight * rep(1, n_stocks)) } sdP = muP weights = matrix(0, nrow = length(muP), ncol = n_stocks) for( i in 1:length(muP) ){ bvec[2] = +muP[i] result = solve.QP(Dmat = 2*cov_mat, dvec = rep(0, n_stocks), Amat = Ama t, bvec = bvec, meq=2) sdP[i] = sqrt(result$value) weights[i,] = result$solution } sharpe = ( muP - mu_free ) / sdP ind_ms = (sharpe == max(sharpe)) ind_mv = (sdP == min(sdP)) list( muP = muP, sdP = sdP, weights = weights, sharpe = sharpe, max_sharp e = ind_ms, min_variance = ind_mv ) }
  • 3. Setting the risk free rate, the target porfolio return and constraints mu_free = 3.0/365 muP = seq(min(mean_vect), max(mean_vect), length.out=300) mvo = eff_front_fn(returns, muP, mu_free = mu_free, lower_limit_weight = -0. 1, upper_limit_weight = 0.5) sdP = mvo$sdP Plot plot(sdP, muP, type = "l", xlim = c(0, 1.1 * max(sd_vect)), ylim = c(0, 1.1 * max(mean_vect)), lty=3) points(0, mu_free, cex = 4, pch = "*") sharpe = ( muP - mu_free ) / sdP ind_ms = (sharpe == max(sharpe)) print(mvo$weights[ind_ms,] ) ## [1] -0.091164544 -0.002905131 0.335298962 0.383700258 0.319482622 ## [6] 0.055587833 lines(c(0, 2), mu_free + c(0, 2) * (muP[ind_ms] - mu_free) / sdP[ind_ms], lwd = 4, lty = 1, col = "blue") points(sdP[ind_ms], muP[ind_ms], cex = 4, pch = "*") ind_mv = (sdP == min(sdP)) points(sdP[ind_mv], muP[ind_mv], cex = 2, pch = "+") ind3 = (muP > muP[ind_mv]) lines(sdP[ind3], muP[ind3], type = "l", xlim = c(0, 0.25), ylim = c(0, 0.3), lwd = 3, col = "red") text(sd_vect[1], mean_vect[1], "GM", cex = 1.15) text(sd_vect[2], mean_vect[2], "F", cex = 1.15) text(sd_vect[3], mean_vect[3], "CAT", cex = 1.15) text(sd_vect[4], mean_vect[4], "UTX", cex = 1.15) text(sd_vect[5], mean_vect[5], "MRK", cex = 1.15) text(sd_vect[6], mean_vect[6], "IBM", cex = 1.15)
  • 4. ======== Efficient Equity Portfolios using the package “fPortfolio” from Rmetrics ======== Data library(fPortfolio) ## Warning: package 'fPortfolio' was built under R version 3.2.3 ## Loading required package: timeDate ## Warning: package 'timeDate' was built under R version 3.2.3 ## Loading required package: timeSeries ## Warning: package 'timeSeries' was built under R version 3.2.3 ## Loading required package: fBasics ## Warning: package 'fBasics' was built under R version 3.2.3
  • 5. ## ## ## Rmetrics Package fBasics ## Analysing Markets and calculating Basic Statistics ## Copyright (C) 2005-2014 Rmetrics Association Zurich ## Educational Software for Financial Engineering and Computational Science ## Rmetrics is free software and comes with ABSOLUTELY NO WARRANTY. ## https://www.rmetrics.org --- Mail to: [email protected] ## Loading required package: fAssets ## Warning: package 'fAssets' was built under R version 3.2.3 ## ## ## Rmetrics Package fAssets ## Analysing and Modeling Financial Assets ## Copyright (C) 2005-2014 Rmetrics Association Zurich ## Educational Software for Financial Engineering and Computational Science ## Rmetrics is free software and comes with ABSOLUTELY NO WARRANTY. ## https://www.rmetrics.org --- Mail to: [email protected] ## ## ## Rmetrics Package fPortfolio ## Portfolio Optimization ## Copyright (C) 2005-2014 Rmetrics Association Zurich ## Educational Software for Financial Engineering and Computational Science ## Rmetrics is free software and comes with ABSOLUTELY NO WARRANTY. ## https://www.rmetrics.org --- Mail to: [email protected] setwd("~/R/datasets") dat = read.csv("Stock_Bond.csv", header = T) prices = cbind(dat$GM_AC, dat$F_AC, dat$CAT_AC, dat$UTX_AC, dat$MRK_AC, dat$IBM_AC) n = dim(prices)[1] returns = 100 * (prices[2:n, ] / prices[1:(n-1), ] - 1) pairs(returns)
  • 6. mean_vect = colMeans(returns) cov_mat = cov(returns) sd_vect = sqrt(diag(cov_mat)) Constraints returns3 = as.timeSeries(returns) names(returns3) = c("GM", "F", "CAT", "UTX", "MRK", "IBM") Constraints = c( "minW[1:nAssets] = rep(-0.10, times = nAssets)", "maxW[1:nAssets] = rep(0.50, times = nAssets)") Spec spec1 = portfolioSpec() setRiskFreeRate(spec1) = 0.0082192
  • 7. Model and plot mvo2 = portfolioFrontier(returns3, spec1, Constraints) frontierPlot(mvo2, frontier = c("both"), col = c("black", "grey"), labels = TRUE, return = c("mean"), risk = c("Sigma")) minvariancePoints(mvo2, col = "red") tangencyPoints(mvo2, col = "green") tangencyLines(mvo2, col = "purple") Examination of weights weightsSlider(mvo2)