SlideShare a Scribd company logo
1 of 8
Download to read offline
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

What's hot

What's hot (20)

Farewell to #define private public
Farewell to #define private publicFarewell to #define private public
Farewell to #define private public
 
Let us C (by yashvant Kanetkar) chapter 3 Solution
Let us C   (by yashvant Kanetkar) chapter 3 SolutionLet us C   (by yashvant Kanetkar) chapter 3 Solution
Let us C (by yashvant Kanetkar) chapter 3 Solution
 
Essence of the iterator pattern
Essence of the iterator patternEssence of the iterator pattern
Essence of the iterator pattern
 
4 Type conversion functions
4 Type conversion functions4 Type conversion functions
4 Type conversion functions
 
Array
ArrayArray
Array
 
Code optimization
Code optimization Code optimization
Code optimization
 
C programming
C programmingC programming
C programming
 
Introduction to F# for the C# developer
Introduction to F# for the C# developerIntroduction to F# for the C# developer
Introduction to F# for the C# developer
 
MIMO Capacity and Duality Between MAC and BC
MIMO Capacity and Duality Between MAC and BCMIMO Capacity and Duality Between MAC and BC
MIMO Capacity and Duality Between MAC and BC
 
Amortized complexity
Amortized complexityAmortized complexity
Amortized complexity
 
Uts
UtsUts
Uts
 
String Manipulation Function and Header File Functions
String Manipulation Function and Header File FunctionsString Manipulation Function and Header File Functions
String Manipulation Function and Header File Functions
 
Amortized complexity
Amortized complexityAmortized complexity
Amortized complexity
 
C- Programs - Harsh
C- Programs - HarshC- Programs - Harsh
C- Programs - Harsh
 
Amortized complexity
Amortized complexityAmortized complexity
Amortized complexity
 
Program uts
Program utsProgram uts
Program uts
 
Lessons learned from functional programming
Lessons learned from functional programmingLessons learned from functional programming
Lessons learned from functional programming
 
Implementation of c string functions
Implementation of c string functionsImplementation of c string functions
Implementation of c string functions
 
15 2. arguement passing to main
15 2. arguement passing to main15 2. arguement passing to main
15 2. arguement passing to main
 
Hexagonal architecture & Elixir
Hexagonal architecture & ElixirHexagonal architecture & Elixir
Hexagonal architecture & Elixir
 

Viewers also liked

JVM responde a Peña Nieto: "Exijo respeto como mujer y como su par en la con...
JVM responde a Peña Nieto:  "Exijo respeto como mujer y como su par en la con...JVM responde a Peña Nieto:  "Exijo respeto como mujer y como su par en la con...
JVM responde a Peña Nieto: "Exijo respeto como mujer y como su par en la con...Súmate a la Diferencia
 
10598 formato de_evaluación_-_alumno
10598 formato de_evaluación_-_alumno10598 formato de_evaluación_-_alumno
10598 formato de_evaluación_-_alumnoPriscila Bustamante
 
Найти по следам. Теория и практика ретаргетинга
Найти по следам. Теория и практика ретаргетингаНайти по следам. Теория и практика ретаргетинга
Найти по следам. Теория и практика ретаргетингаСтудия Атвинта
 
Insegnare e progettare per competenze
Insegnare e progettare per competenzeInsegnare e progettare per competenze
Insegnare e progettare per competenzeMaria pia Dell'Erba
 
Orbital Hemorrhage Following Trivial Trauma
Orbital Hemorrhage Following Trivial TraumaOrbital Hemorrhage Following Trivial Trauma
Orbital Hemorrhage Following Trivial TraumaDr. Jagannath Boramani
 
Insights del Mil-oficios Peruano: ¿qué piensan y sienten los maestros?
Insights del Mil-oficios Peruano: ¿qué piensan y sienten los maestros?Insights del Mil-oficios Peruano: ¿qué piensan y sienten los maestros?
Insights del Mil-oficios Peruano: ¿qué piensan y sienten los maestros?Consumer Truth - Insights & Planning
 
II-SDV 2016 Nils Newman - Sentiment Analysis: What your Choice of Words Says ...
II-SDV 2016 Nils Newman - Sentiment Analysis: What your Choice of Words Says ...II-SDV 2016 Nils Newman - Sentiment Analysis: What your Choice of Words Says ...
II-SDV 2016 Nils Newman - Sentiment Analysis: What your Choice of Words Says ...Dr. Haxel Consult
 
Oculus Company Presentation
Oculus Company PresentationOculus Company Presentation
Oculus Company PresentationKenneth Sandera
 
Imagenesrenacimiento
ImagenesrenacimientoImagenesrenacimiento
ImagenesrenacimientoJAIMECASTS
 
Desarrollo endogeno
Desarrollo endogenoDesarrollo endogeno
Desarrollo endogenoRosa Toicen
 

Viewers also liked (17)

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

Similar to Efficient equity portfolios using mean variance optimisation in R

Pumps, Compressors and Turbine Fault Frequency Analysis
Pumps, Compressors and Turbine Fault Frequency AnalysisPumps, Compressors and Turbine Fault Frequency Analysis
Pumps, Compressors and Turbine Fault Frequency AnalysisUniversity of Illinois,Chicago
 
Pumps, Compressors and Turbine Fault Frequency Analysis
Pumps, Compressors and Turbine Fault Frequency AnalysisPumps, Compressors and Turbine Fault Frequency Analysis
Pumps, Compressors and Turbine Fault Frequency AnalysisUniversity of Illinois,Chicago
 
The ProblemUsing C programming language write a program that simul.pdf
The ProblemUsing C programming language write a program that simul.pdfThe ProblemUsing C programming language write a program that simul.pdf
The ProblemUsing C programming language write a program that simul.pdffederaleyecare
 
R/Finance 2009 Chicago
R/Finance 2009 ChicagoR/Finance 2009 Chicago
R/Finance 2009 Chicagogyollin
 
Kaggle Winning Solution Xgboost algorithm -- Let us learn from its author
Kaggle Winning Solution Xgboost algorithm -- Let us learn from its authorKaggle Winning Solution Xgboost algorithm -- Let us learn from its author
Kaggle Winning Solution Xgboost algorithm -- Let us learn from its authorVivian S. Zhang
 
Leveraging R in Big Data of Mobile Ads (R在行動廣告大數據的應用)
Leveraging R in Big Data of Mobile Ads (R在行動廣告大數據的應用)Leveraging R in Big Data of Mobile Ads (R在行動廣告大數據的應用)
Leveraging R in Big Data of Mobile Ads (R在行動廣告大數據的應用)Craig Chao
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2goMoriyoshi Koizumi
 
RDataMining slides-r-programming
RDataMining slides-r-programmingRDataMining slides-r-programming
RDataMining slides-r-programmingYanchang Zhao
 
Introduction to programming c and data structures
Introduction to programming c and data structuresIntroduction to programming c and data structures
Introduction to programming c and data structuresPradipta Mishra
 
Introduction to programming c and data-structures
Introduction to programming c and data-structures Introduction to programming c and data-structures
Introduction to programming c and data-structures Pradipta Mishra
 
Python 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptxPython 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptxTseChris
 
Regression and Classification with R
Regression and Classification with RRegression and Classification with R
Regression and Classification with RYanchang Zhao
 
Georgy Nosenko - An introduction to the use SMT solvers for software security
Georgy Nosenko - An introduction to the use SMT solvers for software securityGeorgy Nosenko - An introduction to the use SMT solvers for software security
Georgy Nosenko - An introduction to the use SMT solvers for software securityDefconRussia
 
An Interactive Introduction To R (Programming Language For Statistics)
An Interactive Introduction To R (Programming Language For Statistics)An Interactive Introduction To R (Programming Language For Statistics)
An Interactive Introduction To R (Programming Language For Statistics)Dataspora
 

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

Pumps, Compressors and Turbine Fault Frequency Analysis
Pumps, Compressors and Turbine Fault Frequency AnalysisPumps, Compressors and Turbine Fault Frequency Analysis
Pumps, Compressors and Turbine Fault Frequency Analysis
 
Pumps, Compressors and Turbine Fault Frequency Analysis
Pumps, Compressors and Turbine Fault Frequency AnalysisPumps, Compressors and Turbine Fault Frequency Analysis
Pumps, Compressors and Turbine Fault Frequency Analysis
 
The ProblemUsing C programming language write a program that simul.pdf
The ProblemUsing C programming language write a program that simul.pdfThe ProblemUsing C programming language write a program that simul.pdf
The ProblemUsing C programming language write a program that simul.pdf
 
R/Finance 2009 Chicago
R/Finance 2009 ChicagoR/Finance 2009 Chicago
R/Finance 2009 Chicago
 
Final project kijtorntham n
Final project kijtorntham nFinal project kijtorntham n
Final project kijtorntham n
 
Kaggle Winning Solution Xgboost algorithm -- Let us learn from its author
Kaggle Winning Solution Xgboost algorithm -- Let us learn from its authorKaggle Winning Solution Xgboost algorithm -- Let us learn from its author
Kaggle Winning Solution Xgboost algorithm -- Let us learn from its author
 
Leveraging R in Big Data of Mobile Ads (R在行動廣告大數據的應用)
Leveraging R in Big Data of Mobile Ads (R在行動廣告大數據的應用)Leveraging R in Big Data of Mobile Ads (R在行動廣告大數據的應用)
Leveraging R in Big Data of Mobile Ads (R在行動廣告大數據的應用)
 
week-3x
week-3xweek-3x
week-3x
 
QMC: Undergraduate Workshop, Tutorial on 'R' Software - Yawen Guan, Feb 26, 2...
QMC: Undergraduate Workshop, Tutorial on 'R' Software - Yawen Guan, Feb 26, 2...QMC: Undergraduate Workshop, Tutorial on 'R' Software - Yawen Guan, Feb 26, 2...
QMC: Undergraduate Workshop, Tutorial on 'R' Software - Yawen Guan, Feb 26, 2...
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 
RDataMining slides-r-programming
RDataMining slides-r-programmingRDataMining slides-r-programming
RDataMining slides-r-programming
 
Introduction to programming c and data structures
Introduction to programming c and data structuresIntroduction to programming c and data structures
Introduction to programming c and data structures
 
Introduction to programming c and data-structures
Introduction to programming c and data-structures Introduction to programming c and data-structures
Introduction to programming c and data-structures
 
Python 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptxPython 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptx
 
Regression and Classification with R
Regression and Classification with RRegression and Classification with R
Regression and Classification with R
 
cluster(python)
cluster(python)cluster(python)
cluster(python)
 
Georgy Nosenko - An introduction to the use SMT solvers for software security
Georgy Nosenko - An introduction to the use SMT solvers for software securityGeorgy Nosenko - An introduction to the use SMT solvers for software security
Georgy Nosenko - An introduction to the use SMT solvers for software security
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
CppTutorial.ppt
CppTutorial.pptCppTutorial.ppt
CppTutorial.ppt
 
An Interactive Introduction To R (Programming Language For Statistics)
An Interactive Introduction To R (Programming Language For Statistics)An Interactive Introduction To R (Programming Language For Statistics)
An Interactive Introduction To R (Programming Language For Statistics)
 

More from Gregg Barrett

Cirrus: Africa's AI initiative, Proposal 2018
Cirrus: Africa's AI initiative, Proposal 2018Cirrus: Africa's AI initiative, Proposal 2018
Cirrus: Africa's AI initiative, Proposal 2018Gregg Barrett
 
Cirrus: Africa's AI initiative
Cirrus: Africa's AI initiativeCirrus: Africa's AI initiative
Cirrus: Africa's AI initiativeGregg Barrett
 
Applied machine learning: Insurance
Applied machine learning: InsuranceApplied machine learning: Insurance
Applied machine learning: InsuranceGregg Barrett
 
Road and Track Vehicle - Project Document
Road and Track Vehicle - Project DocumentRoad and Track Vehicle - Project Document
Road and Track Vehicle - Project DocumentGregg Barrett
 
Modelling the expected loss of bodily injury claims using gradient boosting
Modelling the expected loss of bodily injury claims using gradient boostingModelling the expected loss of bodily injury claims using gradient boosting
Modelling the expected loss of bodily injury claims using gradient boostingGregg Barrett
 
Data Science Introduction - Data Science: What Art Thou?
Data Science Introduction - Data Science: What Art Thou?Data Science Introduction - Data Science: What Art Thou?
Data Science Introduction - Data Science: What Art Thou?Gregg Barrett
 
Revenue Generation Ideas for Tesla Motors
Revenue Generation Ideas for Tesla MotorsRevenue Generation Ideas for Tesla Motors
Revenue Generation Ideas for Tesla MotorsGregg Barrett
 
Data science unit introduction
Data science unit introductionData science unit introduction
Data science unit introductionGregg Barrett
 
Social networking brings power
Social networking brings powerSocial networking brings power
Social networking brings powerGregg Barrett
 
Procurement can be exciting
Procurement can be excitingProcurement can be exciting
Procurement can be excitingGregg Barrett
 
Machine Learning Approaches to Brewing Beer
Machine Learning Approaches to Brewing BeerMachine Learning Approaches to Brewing Beer
Machine Learning Approaches to Brewing BeerGregg Barrett
 
A note to Data Science and Machine Learning managers
A note to Data Science and Machine Learning managersA note to Data Science and Machine Learning managers
A note to Data Science and Machine Learning managersGregg Barrett
 
Quick Introduction: To run a SQL query on the Chicago Employee Data, using Cl...
Quick Introduction: To run a SQL query on the Chicago Employee Data, using Cl...Quick Introduction: To run a SQL query on the Chicago Employee Data, using Cl...
Quick Introduction: To run a SQL query on the Chicago Employee Data, using Cl...Gregg Barrett
 
Variable selection for classification and regression using R
Variable selection for classification and regression using RVariable selection for classification and regression using R
Variable selection for classification and regression using RGregg Barrett
 
Diabetes data - model assessment using R
Diabetes data - model assessment using RDiabetes data - model assessment using R
Diabetes data - model assessment using RGregg Barrett
 
Introduction to Microsoft R Services
Introduction to Microsoft R ServicesIntroduction to Microsoft R Services
Introduction to Microsoft R ServicesGregg Barrett
 
Insurance metrics overview
Insurance metrics overviewInsurance metrics overview
Insurance metrics overviewGregg Barrett
 
Review of mit sloan management review case study on analytics at Intermountain
Review of mit sloan management review case study on analytics at IntermountainReview of mit sloan management review case study on analytics at Intermountain
Review of mit sloan management review case study on analytics at IntermountainGregg Barrett
 
Example: movielens data with mahout
Example: movielens data with mahoutExample: movielens data with mahout
Example: movielens data with mahoutGregg Barrett
 

More from Gregg Barrett (20)

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

Recently uploaded

定制英国白金汉大学毕业证(UCB毕业证书) 成绩单原版一比一
定制英国白金汉大学毕业证(UCB毕业证书)																			成绩单原版一比一定制英国白金汉大学毕业证(UCB毕业证书)																			成绩单原版一比一
定制英国白金汉大学毕业证(UCB毕业证书) 成绩单原版一比一ffjhghh
 
Brighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingBrighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingNeil Barnes
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfSocial Samosa
 
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130Suhani Kapoor
 
RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998YohFuh
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfLars Albertsson
 
Invezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz1
 
Unveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystUnveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystSamantha Rae Coolbeth
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxolyaivanovalion
 
Call Girls In Mahipalpur O9654467111 Escorts Service
Call Girls In Mahipalpur O9654467111  Escorts ServiceCall Girls In Mahipalpur O9654467111  Escorts Service
Call Girls In Mahipalpur O9654467111 Escorts ServiceSapana Sha
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfMarinCaroMartnezBerg
 
Week-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionWeek-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionfulawalesam
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxolyaivanovalion
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxolyaivanovalion
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Callshivangimorya083
 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfRachmat Ramadhan H
 
(ISHITA) Call Girls Service Hyderabad Call Now 8617697112 Hyderabad Escorts
(ISHITA) Call Girls Service Hyderabad Call Now 8617697112 Hyderabad Escorts(ISHITA) Call Girls Service Hyderabad Call Now 8617697112 Hyderabad Escorts
(ISHITA) Call Girls Service Hyderabad Call Now 8617697112 Hyderabad EscortsCall girls in Ahmedabad High profile
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...Suhani Kapoor
 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfLars Albertsson
 

Recently uploaded (20)

定制英国白金汉大学毕业证(UCB毕业证书) 成绩单原版一比一
定制英国白金汉大学毕业证(UCB毕业证书)																			成绩单原版一比一定制英国白金汉大学毕业证(UCB毕业证书)																			成绩单原版一比一
定制英国白金汉大学毕业证(UCB毕业证书) 成绩单原版一比一
 
Brighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingBrighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data Storytelling
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
 
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
 
RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdf
 
Invezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signals
 
Unveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystUnveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data Analyst
 
CebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptxCebaBaby dropshipping via API with DroFX.pptx
CebaBaby dropshipping via API with DroFX.pptx
 
Call Girls In Mahipalpur O9654467111 Escorts Service
Call Girls In Mahipalpur O9654467111  Escorts ServiceCall Girls In Mahipalpur O9654467111  Escorts Service
Call Girls In Mahipalpur O9654467111 Escorts Service
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
 
Week-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionWeek-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interaction
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptx
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptx
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
 
(ISHITA) Call Girls Service Hyderabad Call Now 8617697112 Hyderabad Escorts
(ISHITA) Call Girls Service Hyderabad Call Now 8617697112 Hyderabad Escorts(ISHITA) Call Girls Service Hyderabad Call Now 8617697112 Hyderabad Escorts
(ISHITA) Call Girls Service Hyderabad Call Now 8617697112 Hyderabad Escorts
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdf
 

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: 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)
  • 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)