/* (J,K) = (6,6) */
sort smth
gen rk6_0 = 1
forval i = 10(10)90 {
by smth: egen tmp = pctile(lnret6), p(`i')
replace rk6_0 = (`i'/10)+1 if lnret6 > tmp
drop tmp
}
replace rk6_0 = . if lnret6 == .
/* For each month, calculate the decile values for all stocks with non-missing returns over past J months
Then, rank stocks into 10 groups (1(lowest) to 10(highest)). */
tsset permno smth
forval i=1/5 {
gen rk6_`i' = L`i'.rk6_0
}
/* Generate ranking in past 5 months */
/* In each month, 6 portfolios are formed based on current and past 5 rankings */
forval i = 0/5 {
preserve
collapse (mean) ret_`i'=ret, by(date smth rk6_`i')
rename rk6_`i' rk6
save tmp`i', replace
restore
}
/* Calculate equally-weighted return for each of the decile-rank portfolio */
use tmp0.dta, clear
forval i = 1/5 {
merge 1:1 date smth rk6 using tmp`i'
drop _merge
save tmp.dta, replace
}
/* Merge all 6 portfolio returns together */