Intruduction to Portfolio Theory:

A portfolio is set of financial assets:

library(quantmod)
## Loading required package: xts
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
getSymbols(Symbols = c("TSLA", "WMT") , from="2018-01-01", periodicity="monthly")
## 'getSymbols' currently uses auto.assign=TRUE by default, but will
## use auto.assign=FALSE in 0.5-0. You will still be able to use
## 'loadSymbols' to automatically load data. getOption("getSymbols.env")
## and getOption("getSymbols.auto.assign") will still be checked for
## alternate defaults.
## 
## This message is shown once per session and may be disabled by setting 
## options("getSymbols.warning4.0"=FALSE). See ?getSymbols for details.
## [1] "TSLA" "WMT"

I merge both dataset and extract only adjusted prices

prices = merge(Ad(TSLA),Ad(WMT))

I calculate historical cc returns

r = na.omit(diff(log(prices)))

I calculate the Geometric average of historical returns:

# We start calculating the arithmetic average of cc returns: 

avgccr =colMeans(r)

# The cc returns are ADITIVE; we can add them and taking its arithmetic average;
# But for simple historical returns (R), we CANNOT add them not take its arithmetic mean.

avgccr
## TSLA.Adjusted  WMT.Adjusted 
##   0.053599540   0.008834128
# The Geometric mean will be the Expected return of the stock: 
# I get the simple return from cc return: 
ER = exp(avgccr) - 1
ER
## TSLA.Adjusted  WMT.Adjusted 
##   0.055062008   0.008873264

I can calculate the expected return a portfolio as follows

If I assign 70% to TSLA and 30% to WMT

w1 = 0.7
w2 = 0.3
ERP1 = w1 * ER[1] + w2 *ER[2]
names(ERP1)=c("ExpRet Por1")
ERP1
## ExpRet Por1 
##  0.04120538

We can also get the expected return of the portfolio using Matrix Algebra. Matrix Algebra is very effective to SUM OF PRODUCTS:

I define a matrix for the weigths:

W = c(w1,w2)
W
## [1] 0.7 0.3

I have 2 vectors, W and ER, wich are matrices of 1 column. I multiply both vectors:

ERP1_2 = t(W) %% ER
ERP1_2
##            [,1]        [,2]
## [1,] 0.03925591 0.007182294

Now, How can I estimate the Expected Risk of the portfolio?

This was respond by Harry Markowitz in 1953 in his Ph.D. Dissertation Finanacial Markets had existed in the US since early 1800`s

Before Markowitz, the risk measures for portfolio did not consider the correlations between pair of assets returns!!

The right way to estimate the RISK of a portfolio is applying Probability Theory to the Portfolio equiation:

Let´s start with the VARIANCE of the PORTFOLIO Equation, and at the end, take the SQUARE ROOT to get the Std. Dev or volatility of the portfolios:

\(VAR[P] = VAR[w1*R1 + w2*R2 + w3*R3 + ... + wN*R4]\)

For a portfolio of 2 assets, the result fot he Expected Portfolio Variance is:

\(VAR[P] = w1^2 * VAR(R1) + w2^2 * VAR(R2) + 2*w1*w2*COV(R1,R2)]\)

THEN THE CONCLUTION :

\(SD[P] = sqrt(VAR[P])\)

SINCE THIS PART THE CODE EVEN IF THERE ARE TOO MANY ASSETS WILL WORK

We can calculate the exp. risk of our 2-asset portfolio with matrix algebra as follows:

COV = cov(r)
COV
##               TSLA.Adjusted WMT.Adjusted
## TSLA.Adjusted   0.039947094  0.002796124
## WMT.Adjusted    0.002796124  0.002880296
ERISKP = t(W) %*% COV %*% W
#This is the expected risk for the portfolio monthly 
ERISKP
##            [,1]
## [1,] 0.02100767

Our portfolio expected MONTHLY risk/volatility is 2.12%

EVOLT = sqrt(ERISKP)
EVOLT
##           [,1]
## [1,] 0.1449402

Portfolio Optimization Applications

Lets calculate the Global Minimum Variance Portfolio

Install the IntroCompFinR package.

Load the package and download stock data

library(IntroCompFinR)
library(quantmod)
# I select 5 assets 
tickers = c("MSFT","AAPL", "SPCE", "WMT", "FB")
getSymbols(Symbols = tickers, from="2018-01-01", periodicity="monthly")
## [1] "MSFT" "AAPL" "SPCE" "WMT"  "FB"

Calculating cc monthly returns

# Merge the datasets into one 
prices <- Ad(merge(AAPL,FB,MSFT,SPCE,WMT))
returns <- na.omit(diff(log(prices)))

Now I calculate the expectef return for each assets:

# This is the simple return expected. 
ER = exp(colMeans(returns)) -1 
ER
## AAPL.Adjusted   FB.Adjusted MSFT.Adjusted SPCE.Adjusted  WMT.Adjusted 
##   0.029142449   0.014145438   0.025802634   0.023615392   0.008873264

Before doing portfolio optimization, I need to calculate the VAR - COV matrix:

I can get descriptive statistics of the asset return

library(psych)
describe(returns)
##               vars  n mean   sd median trimmed  mad   min  max range  skew
## AAPL.Adjusted    1 40 0.03 0.09   0.05    0.03 0.09 -0.20 0.19  0.40 -0.42
## FB.Adjusted      2 40 0.01 0.09   0.01    0.01 0.10 -0.14 0.24  0.38  0.45
## MSFT.Adjusted    3 40 0.03 0.05   0.03    0.03 0.04 -0.08 0.13  0.21 -0.25
## SPCE.Adjusted    4 40 0.02 0.22   0.00    0.01 0.05 -0.51 0.62  1.13  0.58
## WMT.Adjusted     5 40 0.01 0.05   0.01    0.01 0.04 -0.17 0.10  0.27 -0.81
##               kurtosis   se
## AAPL.Adjusted    -0.61 0.01
## FB.Adjusted      -0.46 0.01
## MSFT.Adjusted    -0.54 0.01
## SPCE.Adjusted     1.03 0.03
## WMT.Adjusted      1.10 0.01
library(PerformanceAnalytics)
## 
## Attaching package: 'PerformanceAnalytics'
## The following object is masked _by_ '.GlobalEnv':
## 
##     prices
## The following object is masked from 'package:graphics':
## 
##     legend
charts.PerformanceSummary(returns, 
                          main = "Performance of $1.00 over time",
                          wealth.index = TRUE)

# regresar a ver el video del porfe 

COV = var(returns)
COV 
##               AAPL.Adjusted   FB.Adjusted MSFT.Adjusted SPCE.Adjusted
## AAPL.Adjusted  0.0089127006  0.0052453049  0.0033715846  0.0006706595
## FB.Adjusted    0.0052453049  0.0082549697  0.0025286527 -0.0004790925
## MSFT.Adjusted  0.0033715846  0.0025286527  0.0025608460  0.0005204921
## SPCE.Adjusted  0.0006706595 -0.0004790925  0.0005204921  0.0462644315
## WMT.Adjusted   0.0015497142  0.0015795725  0.0007742004 -0.0004671065
##                WMT.Adjusted
## AAPL.Adjusted  0.0015497142
## FB.Adjusted    0.0015795725
## MSFT.Adjusted  0.0007742004
## SPCE.Adjusted -0.0004671065
## WMT.Adjusted   0.0028802955

Now I get the correlation matrix to have an idea about how each pair of asset will contribute to the portfolio risk:

CORR = cor(returns)
# Es bueno y raro encontra runa correlación negativa ya que reduce la volatilidad del portfolio. 
CORR
##               AAPL.Adjusted FB.Adjusted MSFT.Adjusted SPCE.Adjusted
## AAPL.Adjusted    1.00000000  0.61151672    0.70572854    0.03302736
## FB.Adjusted      0.61151672  1.00000000    0.54997090   -0.02451534
## MSFT.Adjusted    0.70572854  0.54997090    1.00000000    0.04781881
## SPCE.Adjusted    0.03302736 -0.02451534    0.04781881    1.00000000
## WMT.Adjusted     0.30586406  0.32393904    0.28506451   -0.04046446
##               WMT.Adjusted
## AAPL.Adjusted   0.30586406
## FB.Adjusted     0.32393904
## MSFT.Adjusted   0.28506451
## SPCE.Adjusted  -0.04046446
## WMT.Adjusted    1.00000000

Calculating the Global Minimum Variance Portfolio

gmv = globalMin.portfolio(ER, COV, )
# EL tipo de clase es unico, 
gmv
## Call:
## globalMin.portfolio(er = ER, cov.mat = COV)
## 
## Portfolio expected return:     0.01755801 
## Portfolio standard deviation:  0.03944491 
## Portfolio weights:
## AAPL.Adjusted   FB.Adjusted MSFT.Adjusted SPCE.Adjusted  WMT.Adjusted 
##       -0.1633       -0.0004        0.6800        0.0329        0.4508

Efficient Frontier

efrontier = efficient.frontier(ER,COV,nport = 100, 
                               alpha.min = -0.5,
                               alpha.max = 1.5, shorts = TRUE)
plot(efrontier, plot.assets = TRUE, col= "green")

plot(efrontier, col= "green")

### The optimal/tangent portfolio

rf = 0.0
optport = tangency.portfolio(ER,COV,rf, )
optport
## Call:
## tangency.portfolio(er = ER, cov.mat = COV, risk.free = rf)
## 
## Portfolio expected return:     0.02586915 
## Portfolio standard deviation:  0.04787893 
## Portfolio weights:
## AAPL.Adjusted   FB.Adjusted MSFT.Adjusted SPCE.Adjusted  WMT.Adjusted 
##       -0.0341       -0.1720        1.0697        0.0330        0.1035
opweights = getPortfolio(ER,COV,weights = optport$weights)
opweights
## Call:
## getPortfolio(er = ER, cov.mat = COV, weights = optport$weights)
## 
## Portfolio expected return:     0.02586915 
## Portfolio standard deviation:  0.04787893 
## Portfolio weights:
## AAPL.Adjusted   FB.Adjusted MSFT.Adjusted SPCE.Adjusted  WMT.Adjusted 
##       -0.0341       -0.1720        1.0697        0.0330        0.1035
plot(opweights)

Capital market line:

The slope of the capital market line is the sharpe ratio

plot(efrontier)
# primero se pone el eje x
points(gmv$sd, col="green")
# ahora va el tangete portafolio 
points(optport$er, col="red", pch = 16 )

sharper = (optport$er - rf) / optport$sd
# que tantos premium returns te da un punto de riesgo 

abline(a=rf, b=sharper, col="blue")