Вы находитесь на странице: 1из 9

Title Author

Constrained Portfolio Optimisation using Matlab Page A fellow IE student

Portfolio Optimisation as a general optimisation problem

We will make use of Matlabs optimisation functions to help us in our portfolio selection problem. The rst question one may ask is why? What exactly is optimisation and why will it help us to nd the best portfolios given our constraints? Optimisation according to the an online dictionary is the act of nding the best compromise among several often conicting requirements. Concretely, in nance, as Professor Rivela has shown, one may seek to nd the best portfolio dened as a compromise between volatility p and expected return E(rp ) under certain requirements - such as no shorting, or a diversication requirement. The particular type of problems we are interested in solving are constrained optimisation problems and these are exactly the sort that Excels Solver solves. Excels Solver and all the optimisation algorithms in Matlab owe their existence to the subeld of applied mathematics concerned with optimisation. Conveniently for us, there is a common way that problems in mathematical optimisation are phrased that allows us, once we learn it, to express our real world problems in a manner that Excel and tools in Matlab can understand and help resolve.

1.1

Some denitions

A quick revision of the denition of a portfolio may be useful now: a portfolio is a set of weights, x1 , x2 , . . . , xn that represents the percentage of our wealth we should invest in the corresponding assets Asset1 , Asset2 , . . . , Assetn . If x1 = 0.1, it means that we invest 10% of our money in Asset1 . To paraphrase Wikipedia, all constrained optimisation problems start with a function f (x) that takes some inputs x from a set A and returns a real number (we also call these objective functions). We seek to nd the exact x0 that either minimises f (x0 ) or maximises f (x0 ). It is no accident that we used xi to denote the portfolio weights since our problems will almost always involve nding the weights that will return the best outcome to investors dened by the function f (x). In nance, f (~ ) could be: x For my own notational convenience, Ill 1. The expected return of the portfolio (we often want to maximise this) switch to matrix notation from here E(rp ) = ~ 0 E(r) x on out. ~ will be x the column vector 2. The risk of the portfolio (we may want to minimise volatility where S is the that represents a variance-covariance matrix), or equivalently, its variance: portfolio
2 p

~ = x0 S ~ x

Title Author

Constrained Portfolio Optimisation using Matlab Page A fellow IE student

3. The Sharpe Ratio (we want to maximise this too) (E(rp ) c) =p ~0 s ~ x x It should be clear that these f (~ ) all take the vector ~ and return a single number x x as required by our denition of valid objective functions. But there are important dierences between them which will aect the types of optimisers we can use with each: 1. The expected return E(rp ) is a linear function in terms of the xi weights. For example, with a hypothetical 2 asset portfolio, the portfolios expected return will be E(rp ) = x1 E(r1 ) + x2 E(r2 ) Linear objective functions can be optimised in Matlab using the linprog function that implements a technique called linear programming. 2. The variance is a quadratic function in the xi weights. For the same 2 asset portfolio, we had the following
2 p

Linear functions are those where the highest power is 1, quadratic functions are those where the highest power is 2. Nonlinear p functions are x1 or x1 x2

= x2 var(x1 ) + x2 var(x2 ) + 2 x1 x2 cov(x1 , x2 ) 1 2

Quadratic objective functions in Matlab can be optimised using the quadprog function. Unlike the linprog function, one has to provide the Hessian matrix which contains the second order partial derivatives of the objective. This looks like: 2 var(x1 ) 2 cov(x1 , x2 ) H(f ) = 2 cov(x1 , x2 ) 2 var(x2 ) 3. Finally, the Sharpe ratio is a non-linear, non-quadratic function of the xi because it involves taking the square root and other non-linear operations. For optimisation of such functions, we use Matlabs fmincon function.

1.2

How does this apply to what we saw in class?

In case this sounds confusing because its so abstract, lets look at Professor Rivelas lectures. First, consider the task of nding the General Minimum Variance Portfolio (GMVP). Lets forget the solution presented in class for a moment and reconsider what the GMVP really is. Geometrically, we saw that the GMVP was the portfolio that gives us the leftmost point of the mean-variance e cient frontier. How does this look algebraically? min f (~ ) = x
~ x 2 p

subject to

n X i=1

xi = 1

Title Author

Constrained Portfolio Optimisation using Matlab Page A fellow IE student

In matrix form, this is the same as saying min f (~ ) = x


~ x 2 p

subject to 11xn ~ = 1 x Remember that 11xn is a row vector of length n whose elements are all 1 which we call matrix Aeq. vectors are just a Constraints of this form are known as equality constraints since there is an equal special form of sign between the left and right hand sides of the equation. matrix. So the 11xn here is written as a 1.2.1 How do we solve this in Matlab? matrix that really We shall use the same function fmincon that Ive mentioned before for the GMVP is a column vector. problem even though quadprog would work just as well. The way to understand this is to think of a hierarchy of programs that begin with the most e cient but also most restricted (linprog) to the most general but least e cient (fmincon). For simplicity, I shall stick with fmincon since it will solve all the problems we will encounter even if it isnt the most e cient. According to the documentation in Matlab, fmincon nds the minimum of a problem specied by minx subject to f (x) c(x) 0 ceq (x) = 0 Ax b Aeq x = beq lb x ub (1) (2) (3) (4) (5) (6)

fmincon is then called with the following syntax: x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon) Of the fmincon denition above, only lines (1) and (5) are of concern to the GMVP problem since we only really care about the objective function and the equality constraints. This means that we only need to supply Matlab with the parameters fun, x0, Aeq, beq 1.2.2 How do we create the parameters for Matlab?

The parameter f un is a Matlab function that is dened in the usual way shown in class but it returns a single scalar value while taking only a vector as input. It really should correspond to our mathematical function for the variance of the portfolio. Here is an example which loads the variance-covariance matrix stored in a le called demodata.mat that Ill show you how to create later:

Title Author

Constrained Portfolio Optimisation using Matlab Page A fellow IE student

function [ variance ] = portvar_demo(x) demo_data = load('demodata.mat'); variance = x' * demo_data.s * x; end Now we need to tell Matlab what the Aeq and beq parameters are and pass our initial guess of what the answer would be as a vector x0. Matlab still needs place holders for the inequality matrices A and the vector B, but we shall simply assign them with empty objects using the [ ] symbol. Note that the current problem has a 5 asset portfolio. x0=[0.2,0.2,0.2,0.2,0.2]'; A = []; B = []'; Aeq = [1 1 1 1 1]; beq = 1; Finally, we shall tell Matlab to run fmincon and give us a solution using the command: fmincon(@portvar_demo, x0, A, B, Aeq, beq) Special note: We had to tell Matlab that the variable portvar demo should be treated as a function and we did this using the ampersand symbol @. The output for the portfolio using the particular s and inputs given should look like: ans = -0.3124 0.0398 0.4963 0.3184 0.4581

1.3

Introducing optimisation with inequality constraints


30 problem using

On to a more realistic problem, I shall discuss solving the 130 fmincon.

Our objective is dierent now, instead of looking for the lowest variance portfolio, we want to get the best portfolio in terms of its risk-return tradeo, that we measure using the Sharpe ratio, . Instead of minimising the Sharpe ratio, we want to maximise it. Logically, we just have to minimise the negative of to maximise , or to state this precisely for you, max f (x) min f (x) min min (E(r ) c) p p ~0 s ~ x x

Title Author

Constrained Portfolio Optimisation using Matlab Page A fellow IE student

Recall the denition in class, we are allowed to use leverage to buy up to 130% of our wealth in certain assets, and go short a maximum of 30% in any assets. The total wealth invested must still sum up to 100%. The leverage and shorting constraints are our inequality constraints and can be written algebraically as: 30% xi 130% for each of the 5 assets in our portfolio indexed by i Lets remind ourselves of the Matlab specication for a constraint minimisation problem solved by fmincon: minx subject to f (x) c(x) 0 ceq (x) = 0 Ax b Aeq x = beq lb x ub (1) (2) (3) (4) (5) (6)

We have a slight problem with the way that Matlab and indeed all optimisation problems are specied. They only allow for less than constraints of the form xi bi as you note in (4) of the equations above. Never fear, we just have to do a little bit more work and change the inequalities. In high school algebra (yes we learnt a lot in high school!) we were taught that if we want to ip the inequality 30% x

we need to multiply -1 on both sides and ip the inequality sign. Hence the following inequality is actually equivalent mathematically x 30% Therefore, we can take all our 130 30 constraints and re-express them for each xi as the pair of less than or equal constraints like so xi 130% xi 30% In matrix form, for a 2 asset case, the equation would look like 2 3 2 3 1 0 130% 60 6 7 17 6 7 x1 6 130% 7 4 1 05 4 30% 5 x2 0 1 30%

Title Author

Constrained Portfolio Optimisation using Matlab Page A fellow IE student

We can write it conveniently by calling matrix of 1s, -1s and 0s matrix A, and the ~ vectors ~ and B. x A~ B x ~ The same equality constraints in the GMVP problem still hold here so the entire 130 30 problem can be written as min f (~ ) = x
~ x

subject to 11xn ~ = 1 x A~ B x ~ 1.3.1 How do we create the parameters for Matlab in this case?

Objective function, f un here is the as we discussed before. To compute , we need more pieces of information than in the GMVP, namely, the risk free rate c, ~ and the expected returns vector for the assets E(r). Here is an example where I load the le demodata130.mat with the necessary variables, s the variance-covariance matrix, c, the risk free rate, and er, the expected returns vector: function [ negativesharpe ] = portSharpe_demo(x) demo_data = load('demodata130.mat'); erp = x'*demo_data.er; variance = x' * demo_data.s * x; negativesharpe = -(erp-demo_data.c)/sqrt(variance); end With the same 5 asset portfolio used in the earlier demonstration, we now create the necessary parameters representing our inequality and equality constraints as follows x0=[0.2,0.2,0.2,0.2,0.2]'; A = [ 1 0 0 0 0; ... 0 1 0 0 0; ... 0 0 1 0 0; ... 0 0 0 1 0; ... 0 0 0 0 1; ... -1 0 0 0 0; ... 0 -1 0 0 0; ... 0 0 -1 0 0; ... 0 0 0 -1 0; ... 0 0 0 0 -1];

B = [1.3 1.3 1.3 1.3 1.3 0.3 0.3 0.3 0.3 0.3]'; Aeq = [1 1 1 1 1];

Title Author

Constrained Portfolio Optimisation using Matlab Page A fellow IE student

Beq = 1; Finally, we shall tell Matlab to run fmincon and give us a solution using the commands to rst use a better algorithm than the default, and then to run it with the new options: options = optimset('fmincon'); options = optimset(options,'Algorithm','sqp'); fmincon(@portSharpe_demo, x0, A, B, Aeq, Beq,[],[],[],options) The output for the portfolio using the particular s and inputs given should look like: ans = -0.3000 -0.0106 0.7754 -0.0525 0.5877

1.4

Some shortcuts using other Matlab commands

Now that you are familiar with what the parameters look like, we can introduce some Matlab commands that will automate most of the generation of matrix A. Matrix A is nothing but the identity matrix Inn stacked on top of another identity matrix Inn 1. Matlab allows us to generate an n n identity matrix using the eye(n) command. To stack the two matrices, we use a semi-colon. Thus, to get the 5 asset inequality matrix, we issue the following command A=[eye(5);-1*eye(5)] This trick should save you time when the size of your portfolios start getting larger. Next, we look at the use of the repmat command to help us create the column vector B (the upper bounds of our inequalities). repmat(numeric constant, 1, number of repetitions)'

gives us a column vector of the numeric constant repeated the number of times required. An example is shown below. >> repmat(1.3,1,5)' ans = 1.3000 1.3000 1.3000 1.3000 1.3000

Title Author

Constrained Portfolio Optimisation using Matlab Page A fellow IE student

Putting everything together, if we were to run the fmincon command again to solve for the problem in section 1.3.1, we would do the following: x0=repmat(0.2,1,5)'; A = [eye(5);-1*eye(5)];

B = [repmat(1.3,1,5)';repmat(0.3,1,5)']; Aeq = repmat(1,1,5); Beq = 1; fmincon(@portSharpe_demo, x0, A, B, Aeq, Beq)

1.5

Creating, Saving and Loading data in Matlab

Earlier, I showed the creation of the function portvar demo(x) that loaded variancecovariance matrix s. How did we create this matrix, save it to a le and now, reload it? If you have the actual price data, Professor Rivelas notes already demonstrate how one can make a variance-covariance matrix from scratch. Ill explain what to do when you have the numbers already. 1. Creating a matrix is easy if the numbers are in Excel. Just highlight the cells in Excel, copy and paste into Notepad in Windows. Now, for the rst row, add the s = [ symbols. Next, at the end of each line of numbers, add except for the last row. Finally, in the last row, add the closing square bracket and the semi-colon ];. It should look like this (this is just an example with 5 assets taken from class): s = [ 0.1307 0.0774 0.0242 -0.0053 0.1142; ... 0.0774 0.1834 0.0501 -0.0014 0.0382; ... 0.0242 0.0501 0.0386 0.0186 0.0118; ... -0.0053 -0.0014 0.0186 0.0561 -0.0081; ... 0.1142 0.0382 0.0118 -0.0081 0.1217]; Select everything and copy and paste to Matlabs command window. 2. Saving any variable in Matlab is very simple, we just need to know where we want to store the variable and the name of the variable. I want to save my variance-covariance matrix s now to the le demodata.mat. My command would be: save('demodata.mat','s') 3. Anytime you want to load and use that variable, I can now use the command: load('demodata.mat')

Title Author

Constrained Portfolio Optimisation using Matlab Page A fellow IE student

If you wish to save more than one variable at a time, you can just save all the variables into the same le with the same save command but listing every variable in the parenthesis after the le name like so: save('demodata130.mat','s','c','er') Good luck, from Stanley Yong