clear
set more off
global PATH1 "E:\Research\GVCs\data\annual_industrial_firm\database"
cd $PATH1

use 2002-2007_ais.dta

gen lnva=ln(in_valueadded)
gen lnL=ln(employment)

destring yea,gen(y) force
destring f_year,gen(f_y) force
gen age=y-f_y
drop y f_y


gen lnage=ln(age)
replace fix_asset_1=fix_inves     if yea=="2003"
replace fix_asset_2=fix_asset_j   if yea=="2003"
gen lnK=ln(fix_asset_2)
gen lnm=ln(intermediate)


//  ----- OP method for workhouse ----  //
// ----generate exit--- // 

destring yea,gen(y) force
drop yea
drop year
rename y year

egen id=group(legal_person_code)
sort id year
duplicates drop id year,force
xtset id year

sort id year
by id: gen count = _N
gen survivor = count == 7
gen has02 = 1 if year == 2007
sort id has02
by id: replace has02 = 1 if has02[_n-1] == 1
replace has02 = 0 if has02 == .
sort id year
by id: gen has_gaps = 1 if year[_n-1] != year-1 & _n != 1
sort id has_gaps
by id: replace has_gaps = 1 if has_gaps[_n-1] == 1
replace has_gaps = 0 if has_gaps == .
by id: generate exit = survivor == 0 & has02 == 0 & has_gaps != 1 & _n == _N
replace exit = 0 if exit == 1 & year == 2007

// dummy of industray  //
xi i.indu_code, prefix(I_)
xi i.year, prefix(Y_)

drop if age==.
drop if lnva==.
drop if lnm==.
drop if lnL==.
drop if lnK==.

set matsize 11000

//   opreg  //
opreg lnva, exit(exit) state(age lnK) proxy(lnm) ///
              free(lnL I_indu_code_* Y_year_*)       ///
              cvars(year)                             ///
              vce(bootstrap, seed(1357) rep(5)) 
est store OP_all

cap drop tfp_op
gen tfp_op = lnva - _b[lnL]*lnL - _b[lnK]*lnK
label var tfp_op "OP法估计的TFP"

//   lpreg  //
levpet lnva, free(lnL lnage) proxy(lnm) capital(lnK) reps(20)
gen tfp_lp = lnva - _b[lnL]*lnL - _b[lnK]*lnK
label var tfp_lp "LP法估计的TFP"

save "2002-2007_ais.dta", replace



	  
	  
