Hi, I'm currently writing my bachelor thesis and I'm new to Stata. I have monthly data and I want to sort the data monthly in 5 portfolios according to their leverage change. To sort the data I have used the following code:
Code:
bys year month: astile change5 = lvchange_abs, nq(5)
A sample of my data is:

Code:
* Example generated by -dataex-. For more info, type help dataex
clear
input str12 isin int year byte month float lvchange_abs double(ri change5)
"GB0004052071" 1988  7 .003303988   9.566951 2
"GB0001826634" 1988  8 .001834629  -8.154499 1
"GB0009223206" 1988  8 .016871154  -11.46245 3
"GB0030913577" 1988  8 .003004034  -5.144036 1
"GB0007188757" 1988  8  .03863934  -2.752304 4
"GB0033195214" 1988  8   .0211871 -14.440441 4
"GB00B61TVQ02" 1988  8 .009517585 -2.8571427 2
"GB00B1WY2338" 1988  8  .04266421 -10.276688 5
"GB0004052071" 1988  8 .003303988 -3.2786906 2
"GB00B1WY2338" 1988  9  .04266421  14.096916 5
"GB0004052071" 1988  9 .003303988  7.3446393 2
"GB0001826634" 1988  9 .001834629   1.869154 1
"GB0030913577" 1988  9 .003004034  5.2060723 1
"GB0033195214" 1988  9   .0211871  6.4669967 4
"GB00B61TVQ02" 1988  9 .009517585  3.9215684 2
"GB0009223206" 1988  9 .016871154  11.160719 3
"GB0007188757" 1988  9  .03863934   7.679951 4
"GB0001826634" 1988 10 .001834629 -1.8348575 1
"GB00B1WY2338" 1988 10  .04266421   1.544416 5
"GB0030913577" 1988 10 .003004034  1.2371182 1
"GB0033195214" 1988 10   .0211871  2.0080209 4
end
I want to calculate the average return (ri) of the each portfolio per month, but I don't know how to do this. It will be something like the mean for each month for each year for each portfolio (ranging from 1 to 5). Is there an easy way to do this? And I would also like to implement an if function to only calculate the mean if a portfolio has more than 5 companies in it.

Thanks