capture log close
log using "s_cogs.txt", text replace
set more off
clear all

//the following part simply generate data (under folder xxx) for the t-test. 

//importing price deflators
// use file 2.Analysis/generate_aux_data.do


//merging with price deflators
clear
use "Data/COMPUSTAT 20180608.dta",clear
	replace datacqtr = subinstr(datacqtr, "Q", "",.) 
	destring datacqtr, replace
	gen naics1 = substr(naics,1,1)
	gen naics2 = substr(naics,1,2)
	gen naics3 = substr(naics,1,3)
	gen naics4 = substr(naics,1,4)
	gen naics5 = substr(naics,1,5)
	merge m:1 datacqtr naics5 using "price_deflators.dta", keepusing(pricedef) update
	drop if _merge==2
	drop _merge
	merge m:1 datacqtr naics4 using "price_deflators.dta", keepusing(pricedef) update
	drop if _merge==2
	drop _merge
	merge m:1 datacqtr naics3 using "price_deflators.dta", keepusing(pricedef) update
	drop if _merge==2
	drop _merge
	merge m:1 datacqtr naics2 using "price_deflators.dta", keepusing(pricedef) update
	drop if _merge==2
	drop _merge
	merge m:1 datacqtr naics1 using "price_deflators.dta", keepusing(pricedef) update
	drop if _merge==2
	drop _merge

* if naics1==4 and procedef is missing, we use deflator of naics1=="3&4"
	gen NAICS="3&4" if naics1=="4" & mi(pricedef)
	merge m:1 datacqtr NAICS using "price_deflators.dta", keepusing(pricedef) update
	drop if _merge==2
	drop _merge

** if ind_price_deflator is missing, we use GDP deflators
	replace naics1="GDP" if mi(pricedef)
	merge m:1 datacqtr naics1 using "price_deflators.dta", keepusing(pricedef) update
	drop if _merge==2
	drop _merge
	replace naics1 = substr(naics,1,1)

* Keep duration to correspond to the supply chain dataset (including pre- and post-customer time periods)
	drop if datacqtr<20012 |datacqtr>20174

	keep if naics1=="3" | naics1=="4"

	replace cogsq = cogsq*100/pricedef
	replace invtq = invtq*100/pricedef
	replace cusip=substr(cusip,1,8)

* generate production series
	gen dataabsqtr = floor(datacqtr/10)*4+mod(datacqtr,10)
	sort gvkey dataabsqtr
	destring gvkey, replace
	xtset gvkey dataabsqtr
	gen prodq = cogsq+invtq-l.invtq

	preserve
	keep gvkey cusip datacqtr cogsq prodq
	replace cusip=substr(cusip,1,6)
	duplicates drop cusip datacqtr,force
	ren cusip c_cusip
	ren cogsq cus_cogsq
	ren prodq cus_prodq
	**
	gen year=floor(datacqtr/10)
    gen qtr=datacqtr-year*10
    replace datacqtr = yq(year, qtr)
    format datacqtr %tq
	**
save "compustat_c", replace
	ren c_cusip s_cusip
	ren cus_cogsq sup_cogsq
	ren cus_prodq sup_prodq
save "naics_compustat_s", replace
save "compustat_s_naics3-4.dta",replace
	restore
save "compustat_0608", replace

log close
