Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
736 lines (615 sloc) 25.7 KB
---
title: "Mean-Variance Portfolio Optimization"
output:
ioslides_presentation:
highlight: tango
logo: misq.png
css: 5min_mod2.css
runtime: shiny
smaller: true
---
<!-- Much of this presentation was taken from here: https://github.com/Matt-Brigida/portfolio-theory/blob/master/chapter3/chapter3.Rmd -->
## Diversification
Diversification is an investment strategy which reduces portfolio risk without necessarily reducing portfolio return.
- It works because the expected return on a portfolio is the weighted-average of the expected returns of the assets in the portfolio, but the standard deviation of the portfolio is less than the weighted average of the individual standard deviations of the assets in the portfolio.
<div class="MIfooter"><img src="mi.png" style="height:50px;"></div>
## Diversification: The Math
Say we have two risky assets, A and B, in our portfolio. The expected return on our portfolio is:
$E(r_p) = w_AE(r_A) + w_BE(r_B)$
where $w$ denotes the weight of the asset in our portfolio. We see that the expected return on a portfolio is the weighted-average of the expected returns of the individual assets in the portfolio. However the variance of the portfolio is:
$\sigma_p^2 = w_A^2\sigma_A^2 + w_B^2\sigma_B^2 + 2w_Aw_B\sigma_A\sigma_B\rho_{A,B}$
Importantly, the portfolio variance is a function of the correlation coefficient between the assets in the portfolio, but the expected return is not.
<div class="MIfooter"><img src="mi.png" style="height:50px;"></div>
##
Now, assume that $\rho_{A,B} = 1$, then:
$\sigma_p^2 = (w_A\sigma_A + w_B\sigma_B)^2 \Rightarrow \sigma_p = w_A\sigma_A + w_B\sigma_B$
and the risk on a portfolio is the weighted-average of the risk of the individual assets in the portfolio.
- However, in practice $\rho_{A,B} < 1$ and so risk on a portfolio will be less than the weighted-average of the risk of the individual assets in the portfolio. This is the benefit of diversification. The ability to reduce risk (risk is decreasing with correlation) without necessarily reducing the expected return. The expected return is not a function of asset correlations.
<div class="MIfooter"><img src="mi.png" style="height:50px;"></div>
## Diversification: An Economic Argument
In economic terms, we can think of the risk on an assets as being decomposable into market and firm-specific induced risks.
- Market risks (such as the risk of a sudden increase in interest rates) are common across all assets, and are not diversifiable.
- Examples of firm-specific risks are a fire at a Ford factory or a drop in Facebook users.
As you add assets to your portfolio the good news from one company text to offset the bad news from another. Adding enough assets, eventually all the firm-specific risk is offset and you hold only market risk.
We are diversifying our portfolio if, given the portfolio has a set size, we split this amount across more and more assets.
- Note, diversification doesn't mean you add more money to your portfolio and invest it in a new asset.
<div class="MIfooter"><img src="mi.png" style="height:50px;"></div>
## Portfolio Frontier with Two Risky Assets and Varying Correlation
The following widget shows the efficient frontier for a portfolio of two risky assets. The first risky asset (call it 'Debt') has a 9\% expected return and 11\% standard deviation. The second portfolio (call it 'Equity') has a 12\% expected return and a 20\% standard deviation. You are free to change the correlation coefficient between Debt and Equity returns, and see the resulting effect on the efficient frontier.
What you should note, is that as you lower the correlation coefficient, you can receive the same expected return for less risk. That is, investors benefit form the lower correlation. If the correlation coefficient is -1, then you can construct a risk-free portfolio. See below for the calculation.
<div class="MIfooter"><img src="mi.png" style="height:50px;"></div>
##
```{r echo = FALSE, warning = FALSE}
### Efficient Frontier: 2 assets ------
#{{{
inputPanel({
sliderInput("correl", "Correlation Coefficient", min = -1, max = 1, step = 0.01, value = 0.5, animate = TRUE)
})
renderPlot({
## library(ggvis)
w.e <- seq(-.5,1.5, by=.01)
w.d <- 1 - w.e
r.e <- .12
r.d <- .09
E <- w.e*r.e+w.d*r.d
s.e <- .2
s.d <- .11
S <- sqrt((w.e^2)*s.e^2+(w.d^2)*s.d^2+2*w.d*w.e*s.e*s.d*input$correl)
dataEff <- data.frame(cbind(S,E,w.e))
## plot(S, E, type='l', xlim=c(0,.3), xlab='Portfolio Standard Deviation', ylab='Portfolio Expected Return', col = 'green')
S.ports <- c(dataEff[dataEff$w.e == 0, ]$S, dataEff[dataEff$w.e == 1, ]$S)
E.ports <- c(dataEff[dataEff$w.e == 0, ]$E, dataEff[dataEff$w.e == 1, ]$E)
dataPorts <- cbind(S.ports, E.ports)
plot(dataPorts, type='p', xlim=c(0,.3), xlab='Portfolio Standard Deviation', ylab='Portfolio Expected Return', col = 'black', ylim = c(.08, .13))
lines(S, E, col = "green", lwd = 1.5)
text(dataPorts, labels = c("Debt", "Equity"), cex = 1, pos = 2)
})
#}}}
```
## Correlations and Diversification
So we can see, holding expected returns constant, as we lower the correlation, we lower the portfolio risk without lowering the portfolio return.
- Often portfolio managers will look for assets with low or negative correlations with the other assets in their portfolio as a way of limiting risk.
- You can use the following app to investigate the correlation between assets.
<div class="MIfooter"><img src="mi.png" style="height:50px;"></div>
##
```{r echo = FALSE, warning=FALSE, error=FALSE, message = FALSE}
#{{{
devtools::install_github("joshuaulrich/quantmod", ref="157_yahoo_502")
library(highcharter)
library(quantmod)
inputPanel(
textInput("ticker1", "Stock Ticker", value = "XOM"),
textInput("ticker2", "Stock Ticker", value = "GLD"),
textInput("ticker3", "Stock Ticker", value = "TSLA"),
textInput("ticker4", "Stock Ticker", value = "TLT"),
textInput("ticker5", "Stock Ticker", value = "UNH")
)
renderHighchart({
stock1 <- getSymbols(input$ticker1, from = '2015-01-01', auto.assign = FALSE)
stock1 <- to.weekly(stock1)
stock1 <- Delt(Ad(stock1))[-1]
names(stock1) <- input$ticker1
stock2 <- getSymbols(input$ticker2, from = '2015-01-01', auto.assign = FALSE)
stock2 <- to.weekly(stock2)
stock2 <- Delt(Ad(stock2))[-1]
names(stock2) <- input$ticker2
stock3 <- getSymbols(input$ticker3, from = '2015-01-01', auto.assign = FALSE)
stock3 <- to.weekly(stock3)
stock3 <- Delt(Ad(stock3))[-1]
names(stock3) <- input$ticker3
stock4 <- getSymbols(input$ticker4, from = '2015-01-01', auto.assign = FALSE)
stock4 <- to.weekly(stock4)
stock4 <- Delt(Ad(stock4))[-1]
names(stock4) <- input$ticker4
stock5 <- getSymbols(input$ticker5, from = '2015-01-01', auto.assign = FALSE)
stock5 <- to.weekly(stock5)
stock5 <- Delt(Ad(stock5))[-1]
names(stock5) <- input$ticker5
M <- cor(data.frame(cbind(stock1, stock2, stock3, stock4, stock5)))
hchart(M)
})
#}}}
```
## *Optimal* Diversification and Markowitz
In 1952 Harry Markowitz published *[Portfolio Selection](https://scholar.google.com/scholar?cluster=5160592821225000015&hl=en&as_sdt=0,39)*, which introduced the idea of diversifying optimally.
- Fixing the portfolio expected return we find the weights on each asset in the portfolio such that risk (portfolio variance) is minimized.
- Note, here we assume either the investor ignores portfolio [skewness](https://en.wikipedia.org/wiki/Skewness) and [kurtosis](https://en.wikipedia.org/wiki/Kurtosis) in their utility function, or returns are distributed according to an elliptical distribution (such as the normal distribution).
- Doing this over all portfolio expected returns gives us a set of portfolios which have minimum risk. This portfolio is known as the *mean-variance fontier*.
<div class="MIfooter"><img src="mi.png" style="height:50px;"></div>
## Efficient Frontier
As you can see in the previous app the *mean-variance frontier* forms one side of a hyperbola.
- The section of the frontier from the minimum variance portfolio upwards is known as the *efficient frontier*---investors would hold one of these portfolios.
- The lower half offers the same portfolio variance offered on the efficient frontier, however with a lower expected return.
<div class="MIfooter"><img src="mi.png" style="height:50px;"></div>
## Optimal Portfolios
If we add a risk free asset we can find the unique *optimal risky portfolio* by choosing the risky portfolio which maximizes the slope of the line starting at the risk free rate and passing one of the set of risky portfolios (*capital allocation line*).
- Of great importance is that the optimal portfolio is *not* a function of investor risk preferences. In fact, two investors who consider the same set of stocks, and have the same estimates of the stock return parameters (expected returns and variance/covariances) will have the *same* optimal portfolio.
- The Capital Asset Pricing Model builds on Markowitz by assuming all investors hold the market portfolio.
<div class="MIfooter"><img src="mi.png" style="height:50px;"></div>
##
The app on the next slide allows you to enter 5 stocks, and see the mean-variance frontier, and the optimal portfolio with the capital allocation line passing through it. We allow short selling stocks in the app, which benefits the frontier. By better we mean the frontier portfolios have higher return per unit risk.
<div class="MIfooter"><img src="mi.png" style="height:50px;"></div>
##
```{r echo = FALSE, warning=FALSE, error=FALSE}
#{{{
library(quantmod)
inputPanel(
textInput("ticker1a", "Stock Ticker", value = "XOM"),
textInput("ticker2a", "Stock Ticker", value = "GE"),
textInput("ticker3a", "Stock Ticker", value = "RTN"),
textInput("ticker4a", "Stock Ticker", value = "AAPL"),
textInput("ticker5a", "Stock Ticker", value = "UNH")
)
renderPlot({
### Begin Zivot code from https://faculty.washington.edu/ezivot/econ424/portfolio.r
#{{{
# portfolio.r
#
# Functions for portfolio analysis
# to be used in Introduction to Computational Finance & Financial Econometrics
# last updated: November 7, 2000 by Eric Zivot
# Oct 15, 2003 by Tim Hesterberg
# November 18, 2003 by Eric Zivot
# November 9, 2004 by Eric Zivot
# November 9, 2008 by Eric Zivot
# August 11, 2011 by Eric Zivot
#
# Functions:
# 1. efficient.portfolio compute minimum variance portfolio
# subject to target return
# 2. globalMin.portfolio compute global minimum variance portfolio
# 3. tangency.portfolio compute tangency portfolio
# 4. efficient.frontier compute Markowitz bullet
# 5. getPortfolio create portfolio object
#
getPortfolio <-
function(er, cov.mat, weights)
{
# contruct portfolio object
#
# inputs:
# er N x 1 vector of expected returns
# cov.mat N x N covariance matrix of returns
# weights N x 1 vector of portfolio weights
#
# output is portfolio object with the following elements
# call original function call
# er portfolio expected return
# sd portfolio standard deviation
# weights N x 1 vector of portfolio weights
#
call <- match.call()
#
# check for valid inputs
#
asset.names <- names(er)
weights <- as.vector(weights)
names(weights) = names(er)
er <- as.vector(er) # assign names if none exist
if(length(er) != length(weights))
stop("dimensions of er and weights do not match")
cov.mat <- as.matrix(cov.mat)
if(length(er) != nrow(cov.mat))
stop("dimensions of er and cov.mat do not match")
if(any(diag(chol(cov.mat)) <= 0))
stop("Covariance matrix not positive definite")
#
# create portfolio
#
er.port <- crossprod(er,weights)
sd.port <- sqrt(weights %*% cov.mat %*% weights)
ans <- list("call" = call,
"er" = as.vector(er.port),
"sd" = as.vector(sd.port),
"weights" = weights)
class(ans) <- "portfolio"
ans
}
efficient.portfolio <-
function(er, cov.mat, target.return)
{
# compute minimum variance portfolio subject to target return
#
# inputs:
# er N x 1 vector of expected returns
# cov.mat N x N covariance matrix of returns
# target.return scalar, target expected return
#
# output is portfolio object with the following elements
# call original function call
# er portfolio expected return
# sd portfolio standard deviation
# weights N x 1 vector of portfolio weights
#
call <- match.call()
#
# check for valid inputs
#
asset.names <- names(er)
er <- as.vector(er) # assign names if none exist
cov.mat <- as.matrix(cov.mat)
if(length(er) != nrow(cov.mat))
stop("invalid inputs")
if(any(diag(chol(cov.mat)) <= 0))
stop("Covariance matrix not positive definite")
# remark: could use generalized inverse if cov.mat is positive semidefinite
#
# compute efficient portfolio
#
ones <- rep(1, length(er))
top <- cbind(2*cov.mat, er, ones)
bot <- cbind(rbind(er, ones), matrix(0,2,2))
A <- rbind(top, bot)
b.target <- as.matrix(c(rep(0, length(er)), target.return, 1))
x <- solve(A, b.target)
w <- x[1:length(er)]
names(w) <- asset.names
#
# compute portfolio expected returns and variance
#
er.port <- crossprod(er,w)
sd.port <- sqrt(w %*% cov.mat %*% w)
ans <- list("call" = call,
"er" = as.vector(er.port),
"sd" = as.vector(sd.port),
"weights" = w)
class(ans) <- "portfolio"
ans
}
globalMin.portfolio <-
function(er, cov.mat)
{
# Compute global minimum variance portfolio
#
# inputs:
# er N x 1 vector of expected returns
# cov.mat N x N return covariance matrix
#
# output is portfolio object with the following elements
# call original function call
# er portfolio expected return
# sd portfolio standard deviation
# weights N x 1 vector of portfolio weights
call <- match.call()
#
# check for valid inputs
#
asset.names <- names(er)
er <- as.vector(er) # assign names if none exist
cov.mat <- as.matrix(cov.mat)
if(length(er) != nrow(cov.mat))
stop("invalid inputs")
if(any(diag(chol(cov.mat)) <= 0))
stop("Covariance matrix not positive definite")
# remark: could use generalized inverse if cov.mat is positive semi-definite
#
# compute global minimum portfolio
#
cov.mat.inv <- solve(cov.mat)
one.vec <- rep(1,length(er))
# w.gmin <- cov.mat.inv %*% one.vec/as.vector(one.vec %*% cov.mat.inv %*% one.vec)
w.gmin <- rowSums(cov.mat.inv) / sum(cov.mat.inv)
w.gmin <- as.vector(w.gmin)
names(w.gmin) <- asset.names
er.gmin <- crossprod(w.gmin,er)
sd.gmin <- sqrt(t(w.gmin) %*% cov.mat %*% w.gmin)
gmin.port <- list("call" = call,
"er" = as.vector(er.gmin),
"sd" = as.vector(sd.gmin),
"weights" = w.gmin)
class(gmin.port) <- "portfolio"
gmin.port
}
tangency.portfolio <-
function(er,cov.mat,risk.free)
{
# compute tangency portfolio
#
# inputs:
# er N x 1 vector of expected returns
# cov.mat N x N return covariance matrix
# risk.free scalar, risk-free rate
#
# output is portfolio object with the following elements
# call captures function call
# er portfolio expected return
# sd portfolio standard deviation
# weights N x 1 vector of portfolio weights
call <- match.call()
#
# check for valid inputs
#
asset.names <- names(er)
if(risk.free < 0)
stop("Risk-free rate must be positive")
er <- as.vector(er)
cov.mat <- as.matrix(cov.mat)
if(length(er) != nrow(cov.mat))
stop("invalid inputs")
if(any(diag(chol(cov.mat)) <= 0))
stop("Covariance matrix not positive definite")
# remark: could use generalized inverse if cov.mat is positive semi-definite
#
# compute global minimum variance portfolio
#
gmin.port <- globalMin.portfolio(er,cov.mat)
if(gmin.port$er < risk.free)
stop("Risk-free rate greater than avg return on global minimum variance portfolio")
#
# compute tangency portfolio
#
cov.mat.inv <- solve(cov.mat)
w.t <- cov.mat.inv %*% (er - risk.free) # tangency portfolio
w.t <- as.vector(w.t/sum(w.t)) # normalize weights
names(w.t) <- asset.names
er.t <- crossprod(w.t,er)
sd.t <- sqrt(t(w.t) %*% cov.mat %*% w.t)
tan.port <- list("call" = call,
"er" = as.vector(er.t),
"sd" = as.vector(sd.t),
"weights" = w.t)
class(tan.port) <- "portfolio"
tan.port
}
efficient.frontier <-
function(er, cov.mat, nport=20, alpha.min=-0.5, alpha.max=1.5)
{
# Compute efficient frontier with no short-sales constraints
#
# inputs:
# er N x 1 vector of expected returns
# cov.mat N x N return covariance matrix
# nport scalar, number of efficient portfolios to compute
#
# output is a Markowitz object with the following elements
# call captures function call
# er nport x 1 vector of expected returns on efficient porfolios
# sd nport x 1 vector of std deviations on efficient portfolios
# weights nport x N matrix of weights on efficient portfolios
call <- match.call()
#
# check for valid inputs
#
asset.names <- names(er)
er <- as.vector(er)
cov.mat <- as.matrix(cov.mat)
if(length(er) != nrow(cov.mat))
stop("invalid inputs")
if(any(diag(chol(cov.mat)) <= 0))
stop("Covariance matrix not positive definite")
#
# create portfolio names
#
port.names <- rep("port",nport)
ns <- seq(1,nport)
port.names <- paste(port.names,ns)
#
# compute global minimum variance portfolio
#
cov.mat.inv <- solve(cov.mat)
one.vec <- rep(1,length(er))
port.gmin <- globalMin.portfolio(er,cov.mat)
w.gmin <- port.gmin$weights
#
# compute efficient frontier as convex combinations of two efficient portfolios
# 1st efficient port: global min var portfolio
# 2nd efficient port: min var port with ER = max of ER for all assets
#
er.max <- max(er)
port.max <- efficient.portfolio(er,cov.mat,er.max)
w.max <- port.max$weights
a <- seq(from=alpha.min,to=alpha.max,length=nport) # convex combinations
we.mat <- a %o% w.gmin + (1-a) %o% w.max # rows are efficient portfolios
er.e <- we.mat %*% er # expected returns of efficient portfolios
er.e <- as.vector(er.e)
names(er.e) <- port.names
cov.e <- we.mat %*% cov.mat %*% t(we.mat) # cov mat of efficient portfolios
sd.e <- sqrt(diag(cov.e)) # std devs of efficient portfolios
sd.e <- as.vector(sd.e)
names(sd.e) <- port.names
dimnames(we.mat) <- list(port.names,asset.names)
#
# summarize results
#
ans <- list("call" = call,
"er" = er.e,
"sd" = sd.e,
"weights" = we.mat)
class(ans) <- "Markowitz"
ans
}
#
# print method for portfolio object
print.portfolio <- function(x, ...)
{
cat("Call:\n")
print(x$call, ...)
cat("\nPortfolio expected return: ", format(x$er, ...), "\n")
cat("Portfolio standard deviation: ", format(x$sd, ...), "\n")
cat("Portfolio weights:\n")
print(round(x$weights,4), ...)
invisible(x)
}
#
# summary method for portfolio object
summary.portfolio <- function(object, risk.free=NULL, ...)
# risk.free risk-free rate. If not null then
# compute and print Sharpe ratio
#
{
cat("Call:\n")
print(object$call)
cat("\nPortfolio expected return: ", format(object$er, ...), "\n")
cat( "Portfolio standard deviation: ", format(object$sd, ...), "\n")
if(!is.null(risk.free)) {
SharpeRatio <- (object$er - risk.free)/object$sd
cat("Portfolio Sharpe Ratio: ", format(SharpeRatio), "\n")
}
cat("Portfolio weights:\n")
print(round(object$weights,4), ...)
invisible(object)
}
# hard-coded 4 digits; prefer to let user control, via ... or other argument
#
# plot method for portfolio object
plot.portfolio <- function(object, ...)
{
asset.names <- names(object$weights)
barplot(object$weights, names=asset.names,
xlab="Assets", ylab="Weight", main="Portfolio Weights", ...)
invisible()
}
#
# print method for Markowitz object
print.Markowitz <- function(x, ...)
{
cat("Call:\n")
print(x$call)
xx <- rbind(x$er,x$sd)
dimnames(xx)[[1]] <- c("ER","SD")
cat("\nFrontier portfolios' expected returns and standard deviations\n")
print(round(xx,4), ...)
invisible(x)
}
# hard-coded 4, should let user control
#
# summary method for Markowitz object
summary.Markowitz <- function(object, risk.free=NULL)
{
call <- object$call
asset.names <- colnames(object$weights)
port.names <- rownames(object$weights)
if(!is.null(risk.free)) {
# compute efficient portfolios with a risk-free asset
nport <- length(object$er)
sd.max <- object$sd[1]
sd.e <- seq(from=0,to=sd.max,length=nport)
names(sd.e) <- port.names
#
# get original er and cov.mat data from call
er <- eval(object$call$er)
cov.mat <- eval(object$call$cov.mat)
#
# compute tangency portfolio
tan.port <- tangency.portfolio(er,cov.mat,risk.free)
x.t <- sd.e/tan.port$sd # weights in tangency port
rf <- 1 - x.t # weights in t-bills
er.e <- risk.free + x.t*(tan.port$er - risk.free)
names(er.e) <- port.names
we.mat <- x.t %o% tan.port$weights # rows are efficient portfolios
dimnames(we.mat) <- list(port.names, asset.names)
we.mat <- cbind(rf,we.mat)
}
else {
er.e <- object$er
sd.e <- object$sd
we.mat <- object$weights
}
ans <- list("call" = call,
"er"=er.e,
"sd"=sd.e,
"weights"=we.mat)
class(ans) <- "summary.Markowitz"
ans
}
print.summary.Markowitz <- function(x, ...)
{
xx <- rbind(x$er,x$sd)
port.names <- names(x$er)
asset.names <- colnames(x$weights)
dimnames(xx)[[1]] <- c("ER","SD")
cat("Frontier portfolios' expected returns and standard deviations\n")
print(round(xx,4), ...)
cat("\nPortfolio weights:\n")
print(round(x$weights,4), ...)
invisible(x)
}
# hard-coded 4, should let user control
#
# plot efficient frontier
#
# things to add: plot original assets with names
# tangency portfolio
# global min portfolio
# risk free asset and line connecting rf to tangency portfolio
#
plot.Markowitz <- function(object, plot.assets=FALSE, ...)
# plot.assets logical. If true then plot asset sd and er
{
if (!plot.assets) {
y.lim=c(0,max(object$er))
x.lim=c(0,max(object$sd))
plot(object$sd,object$er,type="b",xlim=x.lim, ylim=y.lim,
xlab="Portfolio SD", ylab="Portfolio ER",
main="Efficient Frontier", ...)
}
else {
call = object$call
mu.vals = eval(call$er)
sd.vals = sqrt( diag( eval(call$cov.mat) ) )
y.lim = range(c(0,mu.vals,object$er))
x.lim = range(c(0,sd.vals,object$sd))
plot(object$sd,object$er,type="b", xlim=x.lim, ylim=y.lim,
xlab="Portfolio SD", ylab="Portfolio ER",
main="Efficient Frontier", ...)
text(sd.vals, mu.vals, labels=names(mu.vals))
}
invisible()
}
#}}}
### end Zivot code
data1 <- getSymbols(input$ticker1a, auto.assign = FALSE)
data2 <- getSymbols(input$ticker2a, auto.assign = FALSE)
data3 <- getSymbols(input$ticker3a, auto.assign = FALSE)
data4 <- getSymbols(input$ticker4a, auto.assign = FALSE)
data5 <- getSymbols(input$ticker5a, auto.assign = FALSE)
dataMarket <- getSymbols("SPY", auto.assign = FALSE)
data1ret <- Delt(Ad(data1))[-1]
data2ret <- Delt(Ad(data2))[-1]
data3ret <- Delt(Ad(data3))[-1]
data4ret <- Delt(Ad(data4))[-1]
data5ret <- Delt(Ad(data5))[-1]
dataMarketret <- Delt(Ad(dataMarket))[-1]
er <- c(mean(data1ret) * 252, mean(data2ret) * 252, mean(data3ret) * 252, mean(data4ret) * 252, mean(data5ret) * 252)
tickerNames <- c(input$ticker1a, input$ticker2a, input$ticker3a, input$ticker4a, input$ticker5a)
names(er) <- tickerNames
covmat <- 252 * cov(cbind(data1ret, data2ret, data3ret, data4ret, data5ret))
dimnames(covmat) <- list(tickerNames, tickerNames)
rk.free <- 0.00005 * 252
## global minimum variance portfolios
gmin.port <- globalMin.portfolio(er, covmat)
## tangency portfolio
tan.port <<- tangency.portfolio(er, covmat, rk.free)
## efficient frontier
ef <- efficient.frontier(er, covmat, alpha.min = -2, alpha.max = 1.5, nport = 50)
plot(ef, plot.assets = TRUE)
points(gmin.port$sd, gmin.port$er, col = "blue")
points(tan.port$sd, tan.port$er, col = "red")
sr.tan <- ( tan.port$er - rk.free ) / tan.port$sd
abline(a = rk.free, b = sr.tan)
### old
## sim <- stockModel(gR, model="SIM", index=6, shortSelling="y")
## simOP <- optimalPort(sim, Rf = 0)
## plot(simOP)
## portPossCurve(sim, add = TRUE)
## abline(coef = c(.01, ((simOP$R - .01) / simOP$risk)))
## legend('topright', c(paste0("Optimal Portfolio\n ", "Exp. Return = ", round(100 * simOP$R, 2)), paste0("Risk = ", round(100 * simOP$risk, 2))))
## })
})
### Would like to include the below, but it is not reactive for some reason -- doesn't update when you input a new stock
## renderUI({
## str1 <- paste0("Optimal Portfolio Expected Return ", round(tan.port$er * 100, 2), "%")
## str2 <- paste0("Optimal Portfolio Standard Deviation ", round(tan.port$sd * 100), "%")
## str4 <- paste("Asset Weights")
## HTML(paste(str1, str2, str4, sep = '<br/>'))
## })
## renderUI({
## str3 <- paste(tickerNames, round(tan.port$weights, 2) * 100, "%")
## HTML(paste(str3, sep = '<br/>'))
## })
```
<div class="MIfooter"><img src="mi.png" style="height:50px;"></div>
## Credits and Collaboration
Click the following links to see the [code](https://github.com/FinancialMarkets/5MinuteFinance/blob/master/Portfolio_Finance/markowitz_portfolio_optimization/markowitz.Rmd), [line-by-line contributions to this presentation](https://github.com/FinancialMarkets/5MinuteFinance/blame/master/Portfolio_Finance/markowitz_portfolio_optimization/markowitz.Rmd), and [all the collaborators who have contributed to 5-Minute Finance via GitHub](https://github.com/FinancialMarkets/5MinuteFinance/graphs/contributors).
Learn more about how to contribute [here](http://www.5minutefinance.org/how-to-contribute).
<div class="MIfooter"><img src="mi.png" style="height:50px;"></div>