# Expected Shortfall Portfolio Optimization in R using nloptr

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
I have previously done examples of QP optimization in for financial portfolios.  I am not a huge fan of variance optimization in finance.  Return distributions are not normal, are often skewed, and are usually leptokurtic.  In plain speak, the distributions have fat tails and while the mean may be 0, the median is shifted to one side or the other.

Because of the shape of return distributions, variance optimization fails to capture the true risk of a portfolio. The risk measure I prefer to use is Expected Shortfall.  Expected Shortfall is defined as the mean of the left tail of the distribution, below some given alpha.

Beyond VaR:

We call the value at the apha Value-at-Risk (VaR).  VaR has been much maligned over the last few years — not always for the right reasons.  Some people confuse all VaR measures as assuming a normal distribution. Not so.  The definition is that is it some left tail alpha value of the expected P/L distribution.  No where does it assume a normal distribution — people just wrongly use a normal distribution when calculating VaR.

Jorion’s definition of VaR fromValue at Risk: The New Benchmark for Managing Financial Risk, 3rd Edition says (I’m paraphrasing) VaR is the maximum expected loss at a given level of certainty during normal market conditions.  That often is misinterpreted by management as THE number of the maximum loss.  Jorion’s definition has a positive spin that pushes the misinterpretation.

I prefer to but a negative spin on it.  VaR is the minimum expected loss when you have a bad day.  If I have a day that is, at least, in the alpha percential of crappy-ness, then I will lose MORE than VaR.

VaR is the floor, not the ceiling.  That’s where it has been misused.

So why not optimize on VaR?  Short answer is that VaR is highly nonlinear.  Add nonlinear instruments to your portfolio and you can no longer guarantee the concavity of the objective function.

Enter ES:
Expected Shortfall (ES) is the average of the values above the VaR value.  That is, when I’m having a really bad day, what is my expected loss.  If I say a 1 in 20 day is bad (alpha=.05) then I should have 12-13 bad days a year.  If my portfolio was static and the return distributions unchanging (not likely), then the average of those 12-13 days should center on ES.

ES is still not perfect because you don’t know how far to the left you can go.  But it does factor in the fat, skewed tail that we see.  It is a good starting point for risk analysis.

Because ES is a mean, it is guaranteed to be a concave function (I’m still looking for the reference — I’ve seen it before and will update the post if I find it).  So ES is a better measure of risk than VaR and we can trust optimization results from it.  So let’s build an optimization routine for ES.

nloptr:
nloptr is a nonlinear optimization library in R wrapping the GNU NLopt library.  ES, while well behaved, is nonlinear.  nloptr provides a number of nonlinear solvers.  It’s what we want.

For our test case, we will simulate a 4 variable normal distribution with 10,000 draws (correlation given below).  We will build the ES function and a gradient function for ES.  We will constrain portfolio weights to be between [0,1].  We will impose an equality constraint that the sum of the weights = 1.
require(MASS)< o:p>
require(nloptr)< o:p>

#Covariance structure for the simulation< o:p>
#give everything a std=.1< o:p>
n = 4< o:p>
corr = c(1, .7.5.1,< o:p>
.71.4, .1,< o:p>
.5, .4,   1.6,< o:p>
.1, .1, .61)< o:p>

corr = matrix(corr,n,n)< o:p>

std = matrix(0,n,n)< o:p>
for(i in 1:n){       < o:p>
std[i,i] = .1< o:p>
}< o:p>

cov = std %*% corr %*% std< o:p>

#Simulate 10,000 draws< o:p>
sim = mvrnorm(n=10000,rep(0,n),cov)< o:p>

#feasible starting values of equal weights< o:p>
w = rep(1/n,n)< o:p>

#ES function.  Mean of values above alpha< o:p>
es = function(w,sim=NA,alpha=.05){< o:p>
ret = sort(sim %*% w)< o:p>
< o:p>
n = length(ret)< o:p>
i = alpha * n< o:p>
< o:p>
es = mean(ret[1:i])< o:p>
< o:p>
return(es)   < o:p>
}< o:p>

#linear equality constraint< o:p>
#note: nloptr requires all functions to have the same signature< o:p>
eval_g0 <- function(w,sim=NA,alpha=NA) {< o:p>
return( sum(w) 1 )< o:p>
}< o:p>

#numerical approximation of the gradient< o:p>
des = function(w,sim=NA,alpha=.05){< o:p>
n = length(w)< o:p>
out = w;< o:p>
for (i in 0:n){< o:p>
up = w;< o:p>
dn = w;< o:p>
up[i] = up[i]+.0001< o:p>
dn[i] = dn[i].0001< o:p>
out[i] = (es(up,sim=sim,alpha=alpha) es(dn,sim=sim,alpha=alpha))/.0002< o:p>
}< o:p>
return(out)< o:p>
}< o:p>

#use nloptr to check out gradient< o:p>
check.derivatives(w,es,des,sim=sim, alpha=.05)< o:p>

#function to optimize — a list of objective and gradient < o:p>
toOpt = function(w,sim=NA,alpha=.05){< o:p>
}< o:p>

#equality constraint function.  The jacobian is 1 for all variables< o:p>
eqCon = function(w,sim=NA,alpha=.05){< o:p>
list(constraints=eval_g0(w,sim=NA,alpha=.05),jacobian=rep(1,4))      < o:p>
}< o:p>

#optimization options< o:p>
opts <- list( “algorithm” = “NLOPT_LD_SLSQP”,< o:p>
“xtol_rel” = 1.0e-7,< o:p>
“maxeval” = 1000)< o:p>

#run optimization and print results< o:p>
nl = nloptr(w,toOpt,< o:p>
lb = rep(0,4), < o:p>
ub = rep(1,4),< o:p>
eval_g_eq=eqCon,< o:p>
opts=opts,< o:p>
sim=sim,alpha=.05)< o:p>

print(nl)< o:p>

s = nl\$solution< o:p>
obj = nl\$objective< o:p>
To confirm the results, I ran this 100 times and averaged the resulting weights and objective value.  I did the same in SAS IML.  UPDATE: SAS code located here.

From R we get
> apply(s,2,mean)< o:p>
[1] 0.101697131193604 0.420428046895474 0.000000000004212 0.477874821906712< o:p>
> mean(obj)< o:p>
[1] 0.1371< o:p>
In SAS we get
wgt< o:p>
0.1015076 0.4218076 -4.75E-20 0.4766848< o:p>
obj< o:p>
0.1375891
I am comfortable with the results.

Final Thoughts:
I was only able to get the SLSQP routine to converge.  This routine uses a local quadratic approximation of the function, runs a QP to update the variables, and then iterates.  I am not sure why the others failed.

The number of routines available for problems with equality constraints are limited.  On top of that, the NLopt documentation gives a number of other routines that should accept linear constraints but the R implementation throws an error.  A number of augmented LM routines are available for equality constraints, but again the only one that worked used SLSQP as the sub-optimizer and produced the same result as SLSQP (in about 5x the time).

The time to run the optimization in R is high.  During the 100 iteration sample it took from 1.5-10 seconds per loop depending on the internal iterations needed by nloptr.  In all it took about 10 minutes.  The SAS code ran in 45 seconds.  I see the following as reasons:

1. SLSQP is not as efficient as other routines.  It has to approximate a hessian matrix numerically.  Finding another routine that reliably converges could be a big help.
2. My gradient function is numeric.  Each time the gradient is computed it takes a large number of FLOPs.  This is the same in SAS where the IML optimizer calculates numeric derivatives.
3. As previously discussed, the linear algebra matrix multiplication in R is slow.  This code relies heavily on it.  SAS IML is optimized for matrix math.
If anyone has ideas on how to speed up the R processing, I would love to hear them.  Maybe there are other, more efficient, nonlinear optimization libraries in R.  I’m sure there are parts of my code that can be sped up as well.