Hi I'm struggling to learn how to use the parallel package. I have (a sample) unbalanced panel data of 7 stocks from 2011m7 to 2023m9. I want to run regressions for each stock in each month using the stock's past data. Ideally, I want to run these regressions in parallel. The following code is my attempt at running these regressions in parallel using the parallel package. To check whether it is running correctly, I run it in series afterward. I find that sometimes, the resulting outcomes (Beta`n'_JK is parallel results, JKBeta`n'_JK is series results) are sometimes the same, but they differ in most of the instances. I would really appreciate it if you may be able to advise me on what I'm doing wrong with these codes.. Thank you very much!
Code:
use "FinalFinal Stock Level Dataset (1)", clear
keep stockid calmt yvar_* xvar_*
sort stockid calmt
keep if _n<=901
********************************************************************************
local sources "JK"
foreach source of local sources {
foreach n of numlist 1 3 6 {
qui gen Beta`n'_`source' = .
qui gen JKBeta`n'_`source' = .
}
}
********************************************************************************
prog def parfor
args l tmin tmax source
forv m = `tmin'(1)`tmax' {
cap reg yvar_`source' xvar_ if stockid=="`l'"&calmt<`m'
if _rc==0 {
qui replace Beta1_`source' = _b[xvar_] if stockid=="`l'"&calmt==`m'
}
}
end
********************************************************************************
timer on 1
parallel initialize 16
qui levelsof stockid, local(levels)
foreach l of local levels {
qui su calmt if stockid=="`l'"
parallel, prog(parfor): parfor `l' `r(min)' `r(max)' JK
}
timer off 1
********************************************************************************
timer on 2
qui levelsof stockid, local(levels)
foreach l of local levels {
qui su calmt if stockid=="`l'"
forv m = `r(min)'(1)`r(max)' {
local source = "JK"
cap reg yvar_`source' xvar_ if stockid=="`l'"&calmt<`m'
if _rc==0 {
qui replace JKBeta1_`source' = _b[xvar_] if stockid=="`l'"&calmt==`m'
}
}
}
timer off 2
********************************************************************************
