Hi Mr. Clyde Schechter
​​​​and all STATALIST expert,
I have an issue which i really appreciate the help, I'm trying to do the following :
I have 45 portfolios: 25 BEME portfolios and 20 RISK portfolios,
and I want to produce a table that shows the estimates of beta_cf and beta_dr for the 25 size BEME-sorted portfolios, and another table that shows the estimates of beta_cf and beta_dr for the 20 RISK-sorted portfolios as a (5*5 square matrix)!!

My raw data are:
* Example generated by -dataex-. To install: ssc install dataex
clear
input long Date double(R_Me TY PE VS EtR_Me N_dr N_cf Rrf FFS1BM1 FFS1BM2 FFS1BM3 FFS1BM4 FFS1BM5 FFS2BM1 FFS2BM2 FFS2BM3 FFS2BM4 FFS2BM5 FFS3BM1 FFS3BM2 FFS3BM3 FFS3BM4 FFS3BM5 FFS4BM1 FFS4BM2 FFS4BM3 FFS4BM4 FFS4BM5 FFS5BM1 FFS5BM2 FFS5BM3 FFS5BM4 FFS5BM5 RISK1 RISK2 RISK3 RISK4 RISK5 RISK6 RISK7 RISK8 RISK9 RISK10 RISK11 RISK12 RISK13 RISK14 RISK15 RISK16 RISK17 RISK18 RISK19 RISK20)
//////////////////////
/////////////////////
However, I reshaped the data to decompose beta and produce beta_cf and beta_dr as follows:


gen int mdate = ym(floor(Date/100), mod(Date, 100))
format mdate %tm
assert !missing(mdate)
order mdate, first
gen int year = year(dofm(mdate))
rename (FFS* RISK*) return=
reshape long return, i(mdate) j(portfolio) string

capture program drop betas
program define betas
tsset mdate
gen delta = N_cf - N_dr
summ delta
local denom = r(Var)
corr return N_cf, cov
local cf1 = r(cov_12)
corr return L1.N_cf, cov
local cf2 = r(cov_12)
gen beta_cf = (`cf1' + `cf2')/`denom'
corr return N_dr, cov
local dr1 = r(cov_12)
corr return L1.N_dr, cov
local dr2 = r(cov_12)
gen beta_dr = (`dr1' + `dr2')/`denom'
drop delta
gen beta = beta_dr + beta_cf
exit
end

runby betas, by(year portfolio)
duplicates drop beta_cf beta_dr, force

Please help me