Hi Luca,
I understand that you want to create five portfolios, where each portfolio holds 20% of the stocks according to their market capitalization. The portfolio should be recalculated every year, such that the portfolio with the biggest 20% of the stocks should include the biggest 20% for each year.
This can be achieved by following these steps:
- Create a for loop where the loop index goes from start year to the end year.
- For each loop, filter the table such that the table only contains rows corresponding to the loop index year.
Here is the sample MATLAB code for filtering the table inside the loop assuming the loop variable is “year”:
yearFilteredTable = subset2(subset2{:, 2} == year, :);
- Please refer to the following documentation for more information about logical indexing in MATLAB: https://in.mathworks.com/help/matlab/matlab_prog/access-data-in-a-table.html#mw_77d04ebd-b6f7-4ee9-93ac-1cc1fd7bc735
- After filtering the table, sort the table of stocks in ascending order based on their market capitalization.
- Use linear indexing to index the table and split it into five equal sets. Please refer to this link for the detailed MATLAB code for sorting and linearly indexing the table to split it into five equal sets: https://in.mathworks.com/matlabcentral/answers/812650-how-to-sort-a-table-into-five-subsets#answer_684200
In this way, five portfolios can be created for a year, where each portfolio holds 20% of the stocks according to their market capitalization for that particular year.
I hope this helps.