# Matlab code for equally weighted portfolio

I have daily returns of 10 stocks. I need to construct an equally weighted portfolio that goes long in the 3 highest returns and short in the 3 lowest returns. The portfolio needs to be re-balanced every month. How to tell Matlab about this constraint? I started like following:

2) port=Portfolio(); # create the portfolio

3) port=port.estimateAssetMoments(R);# calculate the average return for each index

4) I ignore the command that tell Matlab to be short in the 3 lowest returns and long in the 3 long returns. I just find the default command : port=port.setDefaultConstraints();

• if you can edit your post and show us what you have done so far it'll be easier for us to help you. – Malick Feb 1 '16 at 19:33

Your question is not clear enough. Go long on 3 highest returns... since when? During the past month? If so, at the end of each month you need to compute the average return on each index, and then find the minimum and maximum returns.

As simple dummy example, I will generate a matrix of 10 stocks and 30 daily returns. Then I will average those and find the 3 lowest and 3 largest.

rng(0,'twister');
a = -1;
b = 1;
r = (b-a).*rand(1000,10,30) + a; %Generate a 10x30 matrix of returns
average = mean(r,2);
[~,index] = sort(average);


Then you should be short 1/3 on the stocks which index is (1,2,3) and long 1/3 on the stocks in which index is (8,9,10).

• Thanks so much for your reply, if I understand correctly, the code gives me the positions (long and short) for one month.. How to make a loop for n=1 to t months to repeat the calculation every month? – Nourhaine Nefzi Feb 3 '16 at 13:29
• That depends on how your data is sorted. You just need to have a vector with the month and year and select the data bit by bit. – phdstudent Feb 4 '16 at 9:06
• The code that I found calculates the weights for one month from a vector (1*10). The vector presents monthly returns that sorted from the lowest return to the highest return.. – Nourhaine Nefzi Feb 4 '16 at 9:16