clear
set more off

*Local assignment
local fignum = 8

/*****************/
/*** Draw Data ***/
/*****************/

use "$dtadir/state_taxes_analysis.dta", clear
keep if year >= 1980 & year <= 2010
drop if fips_state == 0 | fips_state == 11 | fips_state > 56

bysort fips_state: egen mean_GDP = mean(GDP)


/***********************/
/*** Manipulate Data ***/
/***********************/

** Gen main variables 
gen log_rev = log( rev_corp)
gen log_corp = log( 1-corporate_rate/100 ) /* Actually log keep rate */
gen log_rev_gdp = log(rev_corp/GDP)
gen r_g = rev_corptax/GDP
gen log_gdp = log(GDP)

** Center base components around state+year FE 
local base "sales_wgt Losscarryback Losscarryforward FranchiseTax FedIncomeTaxDeductible FederalIncomeasStateTaxBase AllowFedAccDep ACRSDepreciation FederalBonusDepreciation throwback combined investment_credit" 
foreach var in `base' { 
	reg `var' i.fips i.year 
	predict temp, res 
	replace `var' = temp 
	drop temp 
}


/******************************/
/*** Get Joint Interactions ***/
/******************************/

foreach xvar of varlist rec_val sales_wgt Losscarryback Losscarryforward FranchiseTax FedIncomeTaxDeductible FederalIncomeasStateTaxBase AllowFedAccDep ACRSDepreciation FederalBonusDepreciation throwback combined investment_credit incr_ma incr_fixed {
	 sum `xvar' [aw=mean_GDP] , d
	 replace `xvar'=(`xvar'-r(mean))/r(sd)

}

local i = 1 
foreach var of varlist rec_val sales_wgt Losscarryback Losscarryforward FranchiseTax FedIncomeTaxDeductible FederalIncomeasStateTaxBase AllowFedAccDep ACRSDepreciation FederalBonusDepreciation throwback combined investment_credit incr_ma incr_fixed  {
	gen s`i' = `var'
	local ++i
}


local base  "c.rec_val c.sales_wgt c.Losscarryback c.Losscarryforward c.FranchiseTax c.FedIncomeTaxDeductible c.FederalIncomeasStateTaxBase c.AllowFedAccDep c.ACRSDepreciation c.FederalBonusDepreciation c.throwback c.combined c.investment_credit c.incr_ma c.incr_fixed"


*Standard anova looped over r/gdp, r, and gdp (with no breaks); these data will be utilized in a separate file to create a combined figure
foreach var in r_g log_rev log_gdp {
preserve

reg `var' c.log_corp i.fips i.year ///
	`base' c.log_corp#(c.s1 c.s2 c.s3 c.s4 c.s5 c.s6 c.s7 c.s8 c.s9 c.s10 c.s11 c.s12 c.s13 c.s14 c.s15) [aw=mean_GDP]
	
gen index2_`var' = (_b[c.log_corp#c.s1]*s1 ///
			 +_b[c.log_corp#c.s2]*s2+_b[c.log_corp#c.s3]*s3 ///   
			 +_b[c.log_corp#c.s4]*s4+_b[c.log_corp#c.s5]*s5 ///
			 +_b[c.log_corp#c.s6]*s6+_b[c.log_corp#c.s7]*s7 ///
			 +_b[c.log_corp#c.s8]*s8+_b[c.log_corp#c.s9]*s9 ///
			 +_b[c.log_corp#c.s10]*s10+_b[c.log_corp#c.s11]*s11 ///
			 +_b[c.log_corp#c.s12]*s12+_b[c.log_corp#c.s13]*s13 ///
			 +_b[c.log_corp#c.s14]*s14+_b[c.log_corp#c.s15]*s15 ///
			 ) if e(sample)

anova index2_`var'  `base' ///
	[aw = mean_GDP]	
	

local tss = e(mss) + e(rss) /* Total ss */
gen res = e(rss)/`tss' /* Residual */
gen model = e(mss)/`tss'
gen ss_rec_val = e(ss_1)/`tss'
gen ss_saleswgt = e(ss_2)/`tss'
gen ss_losscarryback = e(ss_3)/`tss'
gen ss_losscarryforward = e(ss_4)/`tss'
gen ss_franchise = e(ss_5)/`tss'
gen ss_fedincded = e(ss_6)/`tss'
gen ss_fedincbase = e(ss_7)/`tss'
gen ss_allowfedaccdep = e(ss_8)/`tss'
gen ss_acrsdep = e(ss_9)/`tss'
gen ss_fedbonusdep = e(ss_10)/`tss'
gen ss_throwback = e(ss_11)/`tss'
gen ss_combined = e(ss_12)/`tss'
gen ss_investment_credit = e(ss_13)/`tss'
gen ss_incr_ma = e(ss_14)/`tss'
gen ss_incr_fixed  = e(ss_15)/`tss'

egen sum_base = rowtotal(ss_*)

drop res model 
ds ss_*
foreach ss in `r(varlist)' {
	qui replace `ss' = `ss'/sum_base
}
drop sum_base

keep ss*
keep if _n == 1

gen var = "`var'"

tempfile ts_vardecomp_data_`var'
save `ts_vardecomp_data_`var''

restore
}

/******************/
/*** Data/Clean ***/
/******************/

clear

use `ts_vardecomp_data_r_g'
append using `ts_vardecomp_data_log_rev'
append using `ts_vardecomp_data_log_gdp'

order var
g order = _n

rename ss_rec_val share_s1
rename ss_saleswgt share_s2
rename ss_losscarryback share_s3
rename ss_losscarryforward share_s4
rename ss_franchise share_s5
rename ss_fedincded share_s6
rename ss_fedincbase share_s7
rename ss_allowfedaccdep share_s8
rename ss_acrsdep share_s9
rename ss_fedbonusdep share_s10
rename ss_throwback share_s11
rename ss_combined share_s12
rename ss_investment_credit share_s13
rename ss_incr_ma share_s14
rename ss_incr_fixed share_s15

reshape long share_s, i(var) j(s)
sort order s
g share_s2 = share_s[_n+15]
g share_s3 = share_s[_n+30]
drop if _n > 15

*Get proper labels
g s_string = "R&D Tax Credit" in 1
replace s_string = "Sales Apportionment Weight" in 2
replace s_string = "Loss Carryback" in 3
replace s_string = "Loss Carryforward" in 4
replace s_string = "Franchise Tax" in 5
replace s_string = "Fed Income Tax Deductible" in 6
replace s_string = "Fed Income as State Tax Base" in 7
replace s_string = "Allow Fed Accelerated Dep" in 8
replace s_string = "ACRS Depreciation" in 9
replace s_string = "Federal Bonus Depreciation" in 10
replace s_string = "Throwback Rule" in 11
replace s_string = "Combined Reporting" in 12
replace s_string = "Investment Credit" in 13
replace s_string = "R&D Incremental Mov Avg" in 14
replace s_string = "R&D Incremental Fixed" in 15

*Output
graph hbar share_s share_s2 share_s3, over(s_string) ///
	nolabel ytitle("% Explained") ///
	graphregion(fcolor(white)) graphregion(color(white)) ///
	bar(1, color(dknavy)) bar(2, color(maroon*.7)) bar(3, color(forest_green)) ///
	legend(row(1) label(1 "Rev/GDP") label(2 "Corp Rev") label(3 "GDP"))
	
graph display, ysize(3)
graph export "$figdir/figure`fignum'a.pdf", replace 


/*****************/
/*** Draw Data ***/
/*****************/

use "$dtadir/state_taxes_analysis.dta", clear
keep if year >= 1980 & year <= 2010
drop if fips_state == 0 | fips_state == 11 | fips_state > 56

bysort fips_state: egen mean_GDP = mean(GDP)


** Gen main variables 
gen log_rev = log( rev_corp)
gen log_corp = log( 1-corporate_rate/100 ) /* Actually log keep rate */
gen log_rev_gdp = log(rev_corp/GDP) //Updated 02/08/2018
gen r_g = rev_corptax/GDP
gen r_gos = rev_corptax/GOS_s
gen log_rev_gos = log(rev_corp/GOS_s)
gen log_gos = log(GOS_s)
gen log_gdp = log(GDP)
gen gos = GOS_s/100000

** Center base components around state+year FE 
local base "sales_wgt Losscarryback Losscarryforward FranchiseTax FedIncomeTaxDeductible FederalIncomeasStateTaxBase AllowFedAccDep ACRSDepreciation FederalBonusDepreciation throwback combined investment_credit" 
foreach var in `base' { 
	reg `var' i.fips i.year 
	predict temp, res 
	replace `var' = temp 
	drop temp 
}

/******************************/
/*** Get Joint Interactions ***/
/******************************/

foreach xvar of varlist rec_val sales_wgt Losscarryback Losscarryforward FranchiseTax FedIncomeTaxDeductible FederalIncomeasStateTaxBase AllowFedAccDep ACRSDepreciation FederalBonusDepreciation throwback combined investment_credit incr_ma incr_fixed {
	 sum `xvar' [aw=mean_GDP] , d
	 replace `xvar'=(`xvar'-r(mean))/r(sd)

}

local i = 1 
foreach var of varlist rec_val sales_wgt Losscarryback Losscarryforward FranchiseTax FedIncomeTaxDeductible FederalIncomeasStateTaxBase AllowFedAccDep ACRSDepreciation FederalBonusDepreciation throwback combined investment_credit incr_ma incr_fixed  {
	gen s`i' = `var'
	local ++i
}


local base  "c.rec_val c.sales_wgt c.Losscarryback c.Losscarryforward c.FranchiseTax c.FedIncomeTaxDeductible c.FederalIncomeasStateTaxBase c.AllowFedAccDep c.ACRSDepreciation c.FederalBonusDepreciation c.throwback c.combined c.investment_credit c.incr_ma c.incr_fixed"


*Standard anova looped over r/gdp, r, and gdp (with no breaks); these data will be utilized in a separate file to create a combined figure
foreach var in r_g log_rev log_gdp {
preserve

reg `var' c.log_corp i.fips i.year ///
	`base' c.log_corp#(c.s1 c.s2 c.s3 c.s4 c.s5 c.s6 c.s7 c.s8 c.s9 c.s10 c.s11 c.s12 c.s13 c.s14 c.s15) [aw=mean_GDP]
	
gen index2_`var' = (_b[c.log_corp#c.s1]*s1 ///
			 +_b[c.log_corp#c.s2]*s2+_b[c.log_corp#c.s3]*s3 ///   
			 +_b[c.log_corp#c.s4]*s4+_b[c.log_corp#c.s5]*s5 ///
			 +_b[c.log_corp#c.s6]*s6+_b[c.log_corp#c.s7]*s7 ///
			 +_b[c.log_corp#c.s8]*s8+_b[c.log_corp#c.s9]*s9 ///
			 +_b[c.log_corp#c.s10]*s10+_b[c.log_corp#c.s11]*s11 ///
			 +_b[c.log_corp#c.s12]*s12+_b[c.log_corp#c.s13]*s13 ///
			 +_b[c.log_corp#c.s14]*s14+_b[c.log_corp#c.s15]*s15 ///
			 ) if e(sample)

anova index2_`var'  `base' ///
	[aw = mean_GDP]	
	

local tss = e(mss) + e(rss) /* Total ss */
gen res = e(rss)/`tss' /* Residual */
gen model = e(mss)/`tss'
gen ss_rec_val = e(ss_1)/`tss'
gen ss_saleswgt = e(ss_2)/`tss'
gen ss_losscarryback = e(ss_3)/`tss'
gen ss_losscarryforward = e(ss_4)/`tss'
gen ss_franchise = e(ss_5)/`tss'
gen ss_fedincded = e(ss_6)/`tss'
gen ss_fedincbase = e(ss_7)/`tss'
gen ss_allowfedaccdep = e(ss_8)/`tss'
gen ss_acrsdep = e(ss_9)/`tss'
gen ss_fedbonusdep = e(ss_10)/`tss'
gen ss_throwback = e(ss_11)/`tss'
gen ss_combined = e(ss_12)/`tss'
gen ss_investment_credit = e(ss_13)/`tss'
gen ss_incr_ma = e(ss_14)/`tss'
gen ss_incr_fixed  = e(ss_15)/`tss'

egen sum_base = rowtotal(ss_*)

drop res model 
ds ss_*
foreach ss in `r(varlist)' {
	qui replace `ss' = `ss'/sum_base
}
drop sum_base

keep ss*
keep if _n == 1

gen var = "`var'"

tempfile ts_vardecomp_data_`var'
save `ts_vardecomp_data_`var''

restore
}

replace log_corp = corporate_rate

*Now continue with our regular shit (prepping for break); note that index2_r_g is the same as generated above (in the preservation)
reg r_g c.log_corp i.fips i.year ///
	`base' c.log_corp#(c.s1 c.s2 c.s3 c.s4 c.s5 c.s6 c.s7 c.s8 c.s9 c.s10 c.s11 c.s12 c.s13 c.s14 c.s15) [aw=mean_GDP]
	
gen index2_r_g = (_b[c.log_corp#c.s1]*s1 ///
			 +_b[c.log_corp#c.s2]*s2+_b[c.log_corp#c.s3]*s3 ///   
			 +_b[c.log_corp#c.s4]*s4+_b[c.log_corp#c.s5]*s5 ///
			 +_b[c.log_corp#c.s6]*s6+_b[c.log_corp#c.s7]*s7 ///
			 +_b[c.log_corp#c.s8]*s8+_b[c.log_corp#c.s9]*s9 ///
			 +_b[c.log_corp#c.s10]*s10+_b[c.log_corp#c.s11]*s11 ///
			 +_b[c.log_corp#c.s12]*s12+_b[c.log_corp#c.s13]*s13 ///
			 +_b[c.log_corp#c.s14]*s14+_b[c.log_corp#c.s15]*s15 ///
			 ) if e(sample)
			 
sum index2_r_g [aw=mean_GDP], d 			 
replace index2_r_g=(index2_r_g)/r(sd)

anova index2_r_g  `base' ///
	[aw = mean_GDP]	


*Tempfile that is re-called throughout (simple preservation also works)
tempfile data
save `data', replace

/*********************/
/*** Breaking Base ***/
/*********************/

local i = 1 /* initialize tempfile count */
foreach break in break1 break2 break3 break4 break5 break6 {

use `data', clear

if "`break'" == "break1" {
	keep if year >= 1980 & year <= 1985
}
if "`break'" == "break2" {
	keep if year >= 1986 & year <= 1990
}
if "`break'" == "break3" {
	keep if year >= 1991 & year <= 1995
}
if "`break'" == "break4" {
	keep if year >= 1996 & year <= 2000
}
if "`break'" == "break5" {
	keep if year >= 2001 & year <= 2005
}
if "`break'" == "break6" {
	keep if year >= 2006 & year <= 2010
}

#delimit ;
local base = " rec_val sales_wgt Losscarryback Losscarryforward FranchiseTax 
	FedIncomeTaxDed FederalIncomeas AllowFedAcc ACRSDep FederalBonus throwback combined 
	investment_credit incr_ma incr_fixed";
#delimit cr
	
reg index2_r_g `base'	[aw = mean_GDP]	
	
foreach rule in  `base'{
	local beta=_b[`rule']
	qui summ `rule'
	local var=(r(sd))^2

	g bsqXx`rule' = (`beta')^2 *`var'
}	

egen sum_base = rowtotal(bsqX*)

foreach rule in  `base'{
	g ss_`rule' = bsqXx`rule'/sum_base
}	

keep ss* /*res model*/
keep if _n == 1



tempfile data`i'
save `data`i'', replace

local ++i /* Increment */

}

use `data1', clear
append using `data2'
append using `data3'
append using `data4'
append using `data5'
append using `data6'

local new_obs = _N + 1
set obs `new_obs' /* Add one observation such that 1980 == 1985 */
gen id = _n
replace id = 0 if id == `new_obs'
sort id

ds id, not
foreach var in `r(varlist)' {
	replace `var' = `var'[2] if id == 0
}
replace ss_incr_f = 0 if ss_incr_f==.

*Finish prep for figure
ds id ss_*, not
foreach var in `r(varlist)' {
	replace `var' = `var' * 100
}
label define id_fig 0 "1980" 1 "1985" 2 "1990" 3 "1995" 4 "2000" 5 "2005" 6 "2010"
label values id id_fig

g fedincbase = ss_FederalIncomeas
g fedincded=fedincbase+ss_FedIncomeTaxDed
g throwback=fedincded + ss_throwback
g saleswgt=throwback + ss_sales_wgt
g losscarryforward=saleswgt + ss_Losscarryforward
g losscarryback=ss_Losscarryback + losscarryforward
g combined=losscarryback + ss_combined
g investmentcredit=combined + ss_investment_credit
g recval=investmentcredit + ss_rec_val
g acrsdep=recval + ss_ACRSDep
g allowfedaccdep=acrsdep + ss_AllowFedAcc
g fedbonusdep=allowfedaccdep + ss_FederalBonus
g frantax=fedbonusdep + ss_FranchiseTax
g incrma=ss_incr_ma + frantax
g incrfixed=incrma + ss_incr_fixed

assert incrfixed>.99
replace incrfixed = 1 

*Labels
label var fedincbase "Federal Inc as State Base"
label var fedincded "Federal Inc Deductible"
label var throwback "Throwback Rules"
label var saleswgt "Sales Apportionment Wgt"
label var losscarryforward "Loss Carryforward"
label var losscarryback "Loss Carryback"
label var combined "Combined Reporting"

label var investmentcredit "Investment Tax Credit"
label var recval "R&D Credit"
label var acrsdep "ACRS Depreciation"
label var allowfedaccdep "Federal Accelerated Dep"
label var fedbonusdep "Federal Bonus Dep"
label var frantax "Franchise Tax"
label var incrma "Incr R&D, Moving Avg Base"
label var incrfixed "Incr R&D, Fixed Base"
	

*Figure (with all categories)

twoway (area incrfixed id, color(emerald)) ///
	(area incrma id, color(gs11)) ///
	(area frantax id, color(navy)) ///
	(area fedbonusdep id, color(maroon)) ///
	(area allowfedaccdep id, color(forest_green)) ///
	(area acrsdep id, color(dkorange)) /// 
	(area recval id, color(teal)) ///
	(area investmentcredit id, color(red)) ///
	(area combined id, color(lavender)) ///
	(area losscarryback id, color(stone)) ///
	(area losscarryforward id, color(dknavy*.8)) ///
	(area saleswgt id, color(maroon*.7)) ///
	(area throwback id, color(erose*1.5)) ///
	(area fedincded id, color(red*1.65)) ///
	(area fedincbase id, color(dknavy)), ///
		ylabel(0 (.25) 1, notick) ///
		xlabel(0 1 2 3 4 5 6, valuelabel notick) ///
		plotregion(fcolor(white) lcolor(white)) ///
		graphregion(fcolor(white) lcolor(white)) ///
		legend(order(15 14 13 12 11 10 9 8 7 6 5 4 3 2 1)) ///
		yti("% Explained", height(5)) ///
		xti("")
	
graph display, ysize(4)	
graph export "$figdir/figure`fignum'b.pdf", replace
