/*The code to prepare the results in "Can Trade Costs Explain Why*/
/*Exchange Rate Volatility Doesn't Feed Into Consumer Prices"*/

	use "C:/DATA/tcostxrvol.dta", clear
	log using "C:/DATA/tcostxrvol.log", text replace

	preserve

/*Telling Stata it is a panel data set*/
/*group variable represents an ordered country-pair*/

	tsset group year

/*Actual inflation measures*/
/*These will be used as the benchmarks for comparison purposes*/
/*Consumer price inflation*/

	gen lcpihome = ln(cpihome)
	gen inflationc = 100*d.lcpihome
	label variable inflationc "CPI inflation"
	drop lcpihome

	gen lcpifor = ln(cpifor)
	gen inflationcfor = 100*d.lcpifor
	drop lcpifor

/*GDP deflator inflation is needed for Table 1*/
/*Home GDP deflator inflation*/

	gen pgdphome = gdpchome/gdpkhome
	gen lpgdphome = ln(pgdphome)
	gen inflationg = 100*d.lpgdphome
	label variable inflationg "Home GDP deflator inflation"
	drop lpgdphome

/*Foreign GDP deflator inflation*/

	gen pgdpfor = gdpcfor/gdpkfor
	gen lpgdpfor =  ln(pgdpfor)
	gen inflationgfor = 100*d.lpgdpfor
	label variable inflationgfor "Foreign GDP deflator inflation"
	drop lpgdpfor

/*Rescaling imports and generating imports from self*/
/*Generating expenditure shares*/
/*g is the ratio of output to value added*/
/*to run the gross output version of the results, set g=2*/

	gen g = 1

	egen totimsample = sum(imp), by(homecode year)
	gen expsh = (imp/totimsample)*(imphome/((g*gdphome)+imphome-exphome))
	replace expsh = ((g*gdphome)-exphome)/((g*gdphome)+imphome-exphome) if homecode==forcode
	
	gen impreg = (imp/totim)*imphome
	replace impreg = (g*gdphome)-exphome if homecode==forcode

	egen totimsamplefor = sum(impf), by(forcode year)
	gen expshfor = (impf/totimsamplefor)*(impfor/((g*gdpfor)+impfor-expfor))
	replace expshfor = ((g*gdpfor)-expfor)/((g*gdpfor)+impfor-expfor) if homecode==forcode

	gen impregfor = (impf/totimfor)*imphome
	replace impregfor = (g*gdphome)-exphome if homecode==forcode

/*Inflation contributions*/
/*Inflation predictions will be weighted averages of these objects*/

	gen p = ln(x) + ln(gdpcfor/gdpkfor)
	gen dp = 100*d.p

	gen pfor = - ln(x) + ln(gdpchome/gdpkhome)
	gen dpfor = 100*d.pfor

/*First set of predictions - use measured within-sample expenditure or import shares*/
/*Consumer price inflation prediction with actual within-sample expenditure shares*/

	gen expshma = 0.5*(expsh + l1.expsh)
	gen wdp1 = expshma*dp
	egen pred1 = sum(wdp1), by(homecode year)
	label variable pred1 "Actual shares"

	gen expshmafor = 0.5*(expshfor + l1.expshfor)
	gen dpfor1 = expshmafor*dpfor
	egen predfor1 = sum(dpfor1), by(forcode year)

/*Second set of predictions - use within-sample GDP shares*/
/*GDP shares CPI inflation prediction*/

	egen gdpsample = sum(gdpfor), by(homecode year)
	gen gdpsh = gdpfor/gdpsample
	gen gdpshma = 0.5*(gdpsh + l1.gdpsh)
	gen wdp3 = gdpshma*dp
	egen pred3 = sum(wdp3), by(homecode year)
	label variable pred3 "GDP shares"

	egen gdpsamplefor = sum(gdphome), by(forcode year)
	gen gdpshfor = gdphome/gdpsamplefor
	gen gdpshmafor = 0.5*(gdpshfor + l1.gdpshfor)
	gen wdpfor3 = gdpshmafor*dpfor
	egen predfor3 = sum(wdpfor3), by(homecode year)

/*Preparing to estimate the gravity equation*/
/*log distance*/

	gen ldist = ln(1+dist)

/*reversing indicator variables for interpretation*/ 

	gen ncontig = 1
	replace ncontig = 0 if border==1
	gen ncomlang = 1
	replace ncomlang = 0 if comlang==1

/*this variable will be used to store predicted bilateral trade*/

	gen imphat1 = .

/*this variable will be used to store the predicted bilateral trade cost*/

	gen tcost1 = .
            
/*running the gravity regressions including fixed effects*/

	quietly xi: poisson impreg ldist ncontig ncomlang i.homecode i.forcode if year==1970, robust
	outreg ldist ncontig ncomlang using "C:\DATA\gravoutput1", se noparen nolabel addstat(Pseudo R-squared, e(r2_p)) replace
	predict temp if e(sample)
	replace imphat1 = temp if temp~=.
	replace tcost1 = (exp( (_b[ldist]*ldist) + (_b[ncontig]*ncontig) + (_b[ncomlang]*ncomlang) ))^(-1/4) if temp~=.
	drop temp

	local i = 1
	while `i' <= 33 {
		quietly xi: poisson impreg ldist ncontig ncomlang i.homecode i.forcode if year==1970 + `i', robust
		outreg ldist ncontig ncomlang using "C:\DATA\gravoutput1", se noparen nolabel addstat(Pseudo R-squared, e(r2_p)) append
		predict temp if e(sample)
		replace imphat1 = temp if temp~=.
		replace tcost1 = (exp( (_b[ldist]*ldist) + (_b[ncontig]*ncontig) + (_b[ncomlang]*ncomlang) ))^(-1/4) if temp~=.
		drop temp
		local ++i
	}

/*Constructing the gravity weights*/

	egen exphat1 = sum(imphat1), by(homecode year)
	gen expshhat1 = (imphat1/exphat1)
	drop exphat1

/*Third set of predictions - use shares from gravity equation*/
/*Gravity shares CPI inflation prediction*/

	gen expshhatma1 = 0.5*(expshhat1 + l1.expshhat1)
	gen wdp5 = expshhatma1*dp
	egen pred5 = sum(wdp5), by(homecode year)
	label variable pred5 "Gravity shares"

/*Doing the gravity thing the other way around*/
/*Need this to look at ratios of real exchange rate volatility*/
/*This variable stores the prediction*/

	gen imphatfor1 = .

	quietly xi: poisson impregfor ldist ncontig ncomlang i.homecode i.forcode if year==1970, robust
	predict temp if e(sample)
	replace imphatfor1 = temp if temp~=.
	drop temp

	local i = 1
	while `i' <= 33 {
		quietly xi: poisson impregfor ldist ncontig ncomlang i.homecode i.forcode if year==1970 + `i', robust
		predict temp if e(sample)
		replace imphatfor1 = temp if temp~=.
		drop temp
		local ++i
	}

/*Constructing the gravity weights the other way around*/

	egen exphatfor1 = sum(imphatfor1), by(forcode year)
	gen forshhatfor1 = (imphatfor1/exphatfor1)
	drop exphatfor1

/*The gravity prediction the other way around*/

	gen forshhatfor2 = 0.5*(forshhatfor1 + l1.forshhatfor1)
	gen dpfor5 = forshhatfor2*dpfor
	egen predfor5 = sum(dpfor5), by(forcode year)
	drop forshhatfor2


/*Stuff for the tables and figures,and results mentioned in the text*/

/*Import coverage in the data*/
/*mentioned in the data section*/

	gen imcoverage = totimsample/totim
	foreach i in AUS AUT BEL CAN DNK FIN FRA GER GRC IRL ITA JPN KOR MEX NLD NZL NOR PRT ESP SWE CHE TUR GBR USA {
		sum imcoverage if forcode==homecode & homecode=="`i'"
	}

/*Stuff for Table 1 - st.dev. of exchange rate changes and cpi inflation*/
/*Stylized facts on volatility of CPI inflation*/

	egen infcm = mean(inflationc), by(homecode forcode)
	gen dinfcm = (inflationc - infcm)^2
	egen varinfc = mean(dinfcm), by(homecode forcode)
	gen sdinfc = varinfc^0.5
	bysort homecode: sum sdinfc if year==2003 & homecode==forcode
	drop infcm dinfcm varinfc sdinfc

/*Stylized facts on volatility of GDP deflator inflation*/

	egen infgm = mean(inflationg), by(homecode forcode)
	gen dinfgm = (inflationg - infgm)^2
	egen varinfg = mean(dinfgm), by(homecode forcode)
	gen sdinfg = varinfg^0.5
	bysort homecode: sum sdinfg if year==2003 & homecode==forcode
	drop infgm dinfgm varinfg sdinfg

/*Stylized facts on volatility of bilateral nominal exchange rates*/

	tsset group year
	gen lx = ln(x)
	gen dlx = 100*d.lx

	egen dlxm = mean(dlx), by(homecode forcode)
	gen ddlx = (dlx - dlxm)^2
	egen vardlx = mean(ddlx), by(homecode forcode)
	gen sddlx = vardlx^0.5
	bysort homecode: sum sddlx if year==2003 & homecode~=forcode
	drop dlxm ddlx vardlx sddlx

/*Table 2 is the gravity equation estimates*/
/*They are recovered in "C:\DATA\gravoutput1"*/
/*Measures of fit*/

	bysort year: correlate impreg imphat1
	bysort year: correlate expshhat1 expsh

/*Stuff for Table 3*/
/*First and second moments of CPI inflation, and the predictions*/

	foreach i in AUS AUT BEL CAN DNK FIN FRA GER GRC IRL ITA JPN KOR MEX NLD NZL NOR PRT ESP SWE CHE TUR GBR USA {
		tabstat inflationc pred1 pred5 pred3 if year>1970 & forcode==homecode & homecode=="`i'", stats(mean sd)
	}

/*Figures*/

	foreach i in AUS AUT BEL CAN DNK FIN FRA GER GRC IRL ITA JPN KOR MEX NLD NZL NOR PRT ESP SWE CHE TUR GBR USA {
		#delimit ;
		twoway (line inflationc year, clwidth(medthick)) (line pred1 year, clwidth(medthick) clpattern(dash)) 
			(line pred5 year, clwidth(medthick) clpattern(shortdash)) 
			(line pred3 year, clwidth(medthick) clpattern(dash_dot)) 
			if year>1970 & forcode==homecode & homecode=="`i'", title(`i') 
			l1title(%) graphregion(fcolor(white)) saving("C:/DATA/`i'.gph",replace);
		#delimit cr
	}


/*Ratios of standard deviations of real exchange rates*/
/*Bilateral exchange rate volatility section*/
/*bilateral real exchange rate changes and predictions*/

	gen dlrer = inflationcfor + dlx - inflationc
	gen dlrerhat1 = predfor1 + dlx - pred1
	gen dlrerhat5 = predfor5 + dlx - pred5
	gen dlrerhat3 = predfor3 + dlx - pred3

/*variance and standard deviation of bilateral real exchange rate changes*/

	foreach i in dlrer dlrerhat1 dlrerhat3 dlrerhat5 {
		egen sd_`i'=sd(`i'), by(group)
		gen v_`i'=sd_`i'*sd_`i'
	}

/*ratios of standard deviations*/

	gen ratio1=sd_dlrerhat1/sd_dlrer
	gen ratio3=sd_dlrerhat3/sd_dlrer
	gen ratio5=sd_dlrerhat5/sd_dlrer
	
	sum  ratio1 ratio5 ratio3 if homecode~=forcode & year==2003

/*components of volatility of actual and predicted real exchange rate changes*/

	gen infc=inflationc
	gen infcfor=inflationcfor

/*variance components*/

	foreach i in dlx infc infcfor pred1 predfor1 pred3 predfor3 pred5 predfor5 {
		egen sd_`i'=sd(`i'), by(group)
		gen v_`i'=sd_`i'*sd_`i'
	}

/*covariance components*/

	foreach i in dlx infc infcfor pred1 predfor1 pred3 predfor3 pred5 predfor5 {
		egen m_`i'=mean(`i'), by(group)
	}

	gen p_dlx_infcfor=(dlx - m_dlx)*(inflationcfor - m_infcfor)
	gen p_dlx_infc=(dlx - m_dlx)*(inflationc - m_infc)
	gen p_infc_infcfor=(inflationc - m_infc)*(inflationcfor - m_infcfor)

	foreach i in dlx_infcfor dlx_infc infc_infcfor {
		egen c_`i'=mean(p_`i'), by(group)
	}

	foreach i in 1 3 5 {
		gen p_dlx_predfor`i'=(dlx - m_dlx)*(predfor`i' - m_predfor`i')
		egen c_dlx_predfor`i'=mean(p_dlx_predfor`i'), by(group)
		gen p_dlx_pred`i'=(dlx - m_dlx)*(pred`i' - m_pred`i')
		egen c_dlx_pred`i'=mean(p_dlx_pred`i'), by(group)
		gen p_pred`i'_predfor`i'=(pred`i' - m_pred`i')*(predfor`i' - m_predfor`i')
		egen c_pred`i'_predfor`i'=mean(p_pred`i'_predfor`i'), by(group)
	}

/*summary of variance and covariance components*/

	gen vh_dlrer = v_dlx + v_infcfor + v_infc + 2*(c_dlx_infcfor - c_dlx_infc - c_infc_infcfor)
	gen cv_dlrer_1 = v_dlx + v_infcfor + v_infc
	gen cv_dlrer_2 = 2*(c_dlx_infcfor - c_dlx_infc - c_infc_infcfor)

	foreach i in 1 3 5 {
		gen vh_dlrerhat`i' = v_dlx + v_predfor`i' + v_pred`i' + 2*(c_dlx_predfor`i' - c_dlx_pred`i' - c_pred`i'_predfor`i')
		gen cv_dlrerhat`i'_1 = v_dlx + v_predfor`i' + v_pred`i'
		gen cv_dlrerhat`i'_2 = 2*(c_dlx_predfor`i' - c_dlx_pred`i' - c_pred`i'_predfor`i')
	}

	drop infc infcfor

/*Stuff for Table 4 - decomposition into home and foreign components*/
/*only show the gravity shares case in the table, but results for actual and gdp shares are sketched in the text*/

	gen foreign = 1
	replace foreign = 0 if homecode==forcode
	gen home = 1
	replace home = 0 if homecode~=forcode

/*Actual shares*/

	gen expshmahome = expshma*home
	gen expshmaforg = expshma*foreign
	gen wdphome1 = expshmahome*dp
	gen wdpfor1 = expshmaforg*dp
	egen predhome1 = sum(wdphome1), by(homecode year)
	egen predforg1 = sum(wdpfor1), by(homecode year)
	label variable predhome1 "Inflation from domestic sources"
	label variable predforg1 "Inflation from foreign sources"
	drop expshmahome expshmaforg wdphome1 wdpfor1

/*GDP shares*/

	gen gdpshmahome = gdpshma*home
	gen gdpshmahfor = gdpshma*foreign
	gen wdphome3 = gdpshmahome*dp
	gen wdphfor3 = gdpshmahfor*dp
	egen predhome3 = sum(wdphome3), by(homecode year)
	egen predhfor3 = sum(wdphfor3), by(homecode year)
	label variable predhome3 "Inflation from domestic sources"
	label variable predhfor3 "Inflation from foreign sources"
	drop gdpshmahome gdpshmahfor wdphome3 wdphfor3

/*Gravity predicted shares*/

	gen expshhat1mah = expshhat1*home
	gen expshhat1maf = expshhat1*foreign
	gen wdphome5 = expshhat1mah*dp
	gen wdpfor5 = expshhat1maf*dp
	egen predhome5 = sum(wdphome5), by(homecode year)
	egen predforg5 = sum(wdpfor5), by(homecode year)
	label variable predhome5 "Inflation from domestic sources"
	label variable predforg5 "Inflation from foreign sources"
	drop expshhat1mah expshhat1maf wdphome5 wdpfor5

/*Decomposition of mean of CPI predictions into home and foreign components*/
/*Measured expenditure shares*/

	foreach i in AUS AUT BEL CAN DNK FIN FRA GER GRC IRL ITA JPN KOR MEX NLD NZL NOR PRT ESP SWE CHE TUR GBR USA {
		tabstat pred1 predhome1 predforg1 if year>1970 & forcode==homecode & homecode=="`i'", stats(mean)
	}

/*GDP shares*/

	foreach i in AUS AUT BEL CAN DNK FIN FRA GER GRC IRL ITA JPN KOR MEX NLD NZL NOR PRT ESP SWE CHE TUR GBR USA {
		tabstat pred3 predhome3 predhfor3 if year>1970 & forcode==homecode & homecode=="`i'", stats(mean)		
	}

/*Gravity shares*/

	foreach i in AUS AUT BEL CAN DNK FIN FRA GER GRC IRL ITA JPN KOR MEX NLD NZL NOR PRT ESP SWE CHE TUR GBR USA {
		tabstat pred5 predhome5 predforg5 if year>1970 & forcode==homecode & homecode=="`i'", stats(mean)
	}

/*Decomposition of variance of CPI predictions into home and foreign components*/
/*Measured expenditure shares*/
	
	foreach i in AUS AUT BEL CAN DNK FIN FRA GER GRC IRL ITA JPN KOR MEX NLD NZL NOR PRT ESP SWE CHE TUR GBR USA {
		correlate pred1 predhome1 predforg1 if year>1970 & forcode==homecode & homecode=="`i'", covariance
	}

/*GDP shares*/

	foreach i in AUS AUT BEL CAN DNK FIN FRA GER GRC IRL ITA JPN KOR MEX NLD NZL NOR PRT ESP SWE CHE TUR GBR USA {
		correlate pred3 predhome3 predhfor3 if year>1970 & forcode==homecode & homecode=="`i'", covariance
	}

/*Gravity shares*/

	foreach i in AUS AUT BEL CAN DNK FIN FRA GER GRC IRL ITA JPN KOR MEX NLD NZL NOR PRT ESP SWE CHE TUR GBR USA {
		correlate pred5 predhome5 predforg5 if year>1970 & forcode==homecode & homecode=="`i'", covariance
	}


/*Stuff for Table 5 - measured and predicted home share of expenditure*/

	bysort homecode: sum expsh if homecode==forcode
	bysort homecode: sum expshhat1 if homecode==forcode
	bysort homecode: sum gdpsh if homecode==forcode

/*Stuff for Broda-Romalis suggestion: components of predicted inflation volatility*/
/*Stylized facts on volatility of inflation contributions*/

	egen dpm = mean(dp), by(homecode forcode)
	gen ddp = (dp - dpm)^2
	egen vardp = mean(ddp), by(homecode forcode)
	gen sddp = vardp^0.5
	bysort homecode: sum sddp if year==2003 & homecode~=forcode
	drop vardp ddp dpm

/*Correlation of import shares and volatility of inflation contributions*/
/*Actual import shares*/

	egen expshm = mean(expsh), by(homecode forcode)
	bysort homecode: correlate sddp expshm if year==2003 & forcode~=homecode, covariance
	drop expshm

/*Predicted import shares*/

	egen expshhat1m = mean(expshhat1), by(homecode forcode)
	bysort homecode: correlate sddp expshhat1m if year==2003 & forcode~=homecode, covariance
	drop expshhat1m
	
/*GDP shares*/

	egen gdpshm = mean(gdpsh), by(homecode forcode)
	bysort homecode: correlate sddp gdpshm if year==2003 & forcode~=homecode, covariance
	drop gdpshm sddp


/*Robustness stuff*/

/*gross output stuff is obtained by re-running this file, but setting g=2*/

/*expanded import sample stuff is obtained by running a different do file on a different data set*/

/*Moments of expenditure deflator*/

	gen pe = (gdpchome - expchome + impchome)/(gdpkhome - expkhome + impkhome)
	gen lpe = ln(pe)
	tsset group year
	gen inflatione = 100*d.lpe

	foreach i in AUS AUT BEL CAN DNK FIN FRA GER GRC IRL ITA JPN KOR MEX NLD NZL NOR PRT ESP SWE CHE TUR GBR USA {
		sum inflatione if forcode~=homecode & homecode=="`i'"
	}

	restore, preserve

	capture log close
