* ANOVA TS DECOMP USING LOG R AS THE DEPENDENT OUTCOME
* Local assignment
local fignum = "A3"

set more off
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)

g period=0
replace period = 1 if year >= 1980 & year <= 1985
replace period = 2 if year >= 1986 & year <= 1990
replace period = 3 if year >= 1991 & year <= 1995
replace period = 4 if year >= 1996 & year <= 2000
replace period = 5 if year >= 2001 & year <= 2005
replace period = 6 if year >= 2006 & year <= 2010

gen corprev_share_gdp = (rev_corptax)/GDP

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

rename corprev_share_gdp r_g
g l_r_g=log(r_g)
g l_r  =log(rev_corptax)
g r    =rev_corptax
	
/*			
** Keep final regression sample first 
reg r_g corporate_rate  ///
	`base'  i.fips i.year [aw=mean_GDP]
*keep if e(sample) 	
*/

*Assign variables
g x0= corporate_rate
g x1= FederalIncomeasStateTaxBase
g x2= FedIncomeTaxDeductible 
g x3= throwback 
g x4= sales_wgt 
g x5= Losscarryforward 
g x6= Losscarryback 
g x7= combined 
g x8= investment_credit 
g x9= rec_val
g x10= ACRSDepreciation 
g x11= AllowFedAccDep 
g x12= FederalBonusDepreciation 
g x13= FranchiseTax
g x14= incr_ma //includes rec val as moving avg
g x15= incr_fixed //includes rec val fixed

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

/********************************/
/*** Explained vs Unexplained ***/
/********************************/

use `data', clear

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

use `data', clear

keep l_r_g x0-x15 mean_GDP  year

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
}
/*anova l_r_g c.corporate_rate FederalIncomeasStateTaxBase FedIncomeTaxDeductible ///
	throwback c.payroll_wgt c.Losscarryforward c.Losscarryback combined ///
	c.investment_credit c.rec_val ACRSDepreciation ///
	AllowFedAccDep FederalBonusDepreciation  FranchiseTax ///
	[aw = mean_GDP]
*/
reg l_r_g x0-x15 [aw=mean_GDP]

local tss = e(mss) + e(rss) /* Total ss */
gen res = e(rss)/`tss' /* Residual */
gen model = e(mss)/`tss'

keep res model
keep if _n == 1

qui replace model = model/(model+res)
qui replace res = 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
}

*Labels
label var model "Explained Variance"
label var res "Unexplained Variance"

*Finish prep for figure
ds id, 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


*Figure
twoway (area res id, color(maroon)) ///
(area model id, color(dknavy)), ////
	ylabel(0 (25) 100, notick) ///
	xlabel(0 1 2 3 4 5 6, valuelabel notick) ///
	plotregion(fcolor(white) lcolor(white)) ///
	graphregion(fcolor(white) lcolor(white)) ///
	legend(order(2 1)) ///
	yti("Percent", height(5)) ///
	xti("")
graph export "$figdir/figure`fignum'a.pdf", replace



/*********************/
/*** Rates vs Base ***/
/*********************/

use `data', clear

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

use `data', clear

keep l_r_g x0-x15 mean_GDP year

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
}

reg l_r_g x0-x15 [aw=mean_GDP]

local tss = e(mss) + e(rss) /* Total ss */
gen res = e(rss)/`tss' /* Residual share of total ss*/
gen model = e(mss)/`tss' /* Model share of total ss*/

* corp_sh_gdp = b0 + x1b1 + ...  x13b13 + e
* --> var(corp_sh_gdp). = var(x1)b1^2 + ... + var(x13)b14 + var(e), assuming covs = 0
	forv j =0/15{
	local beta=_b[x`j']
	summ x`j'
	local var=(r(sd))^2

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

gen ss_corprate = bsqXx0/`tss'
gen ss_fedincbase = bsqXx1/`tss'
gen ss_fedincded = bsqXx2/`tss'
gen ss_throwback = bsqXx3/`tss'
gen ss_saleswgt = bsqXx4/`tss'
gen ss_losscarryforward = bsqXx5/`tss'
gen ss_losscarryback = bsqXx6/`tss'
gen ss_combined = bsqXx7/`tss'
gen ss_investment_credit = bsqXx8/`tss'
*gen ss_rec_val = (bsqXx9+bsqXx14+bsqXx15)/`tss'
gen ss_rec_val = bsqXx9/`tss'
gen ss_acrsdep = bsqXx10/`tss'
gen ss_allowfedaccdep = bsqXx11/`tss'
gen ss_fedbonusdep = bsqXx12/`tss'
gen ss_frantax = bsqXx13/`tss'
gen ss_incr_ma = bsqXx14/`tss'
gen ss_incr_fixed = bsqXx15/`tss'

keep bsqXx* res model ss_*
keep if _n == 1

drop bsqXx0-bsqXx15

egen sum_ss = rowtotal(ss_*)

drop res model
ds sum_ss, not
foreach var in `r(varlist)' {
	qui replace `var' = `var'/sum_ss
}
drop sum_ss

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
}

*Generate new %s for stacked graph
gen corp = ss_corprate
gen base = 1

*Labels
drop ss*
label var corp "Corporate Tax Rate"
label var base "Corporate Tax Base Rules"

*Finish prep for figure
ds id, 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


*Figure
twoway (area base id, color(dknavy*.8)) ///
(area corp id, color(dknavy)), ////
	ylabel(0 (25) 100, notick) ///
	xlabel(0 1 2 3 4 5 6, valuelabel notick) ///
	plotregion(fcolor(white) lcolor(white)) ///
	graphregion(fcolor(white) lcolor(white)) ///
	legend(order(2 1)) ///
	yti("% Explained Variance", height(5)) ///
	xti("")
graph export "$figdir/figure`fignum'b.pdf", replace


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

use `data', clear

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

use `data', clear

keep l_r_g x0-x15 mean_GDP year

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
}

reg l_r_g x0-x15 [aw=mean_GDP] 

local tss = e(mss) + e(rss) /* Total ss */
gen res = e(rss)/`tss' /* Residual share of total ss*/
gen model = e(mss)/`tss' /* Model share of total ss*/

* corp_sh_gdp = b0 + x1b1 + ...  x13b13 + e
* --> var(corp_sh_gdp). = var(x1)b1^2 + ... + var(x13)b14 + var(e), assuming covs = 0
	forv j =0/15{
	local beta=_b[x`j']
	summ x`j'
	local var=(r(sd))^2

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

gen ss_corprate = bsqXx0/`tss'
gen ss_fedincbase = bsqXx1/`tss'
gen ss_fedincded = bsqXx2/`tss'
gen ss_throwback = bsqXx3/`tss'
gen ss_saleswgt = bsqXx4/`tss'
gen ss_losscarryforward = bsqXx5/`tss'
gen ss_losscarryback = bsqXx6/`tss'
gen ss_combined = bsqXx7/`tss'
gen ss_investment_credit = bsqXx8/`tss'
*gen ss_rec_val = (bsqXx9+bsqXx14+bsqXx15)/`tss'
gen ss_rec_val = bsqXx9/`tss'
gen ss_acrsdep = bsqXx10/`tss'
gen ss_allowfedaccdep = bsqXx11/`tss'
gen ss_fedbonusdep = bsqXx12/`tss'
gen ss_frantax = bsqXx13/`tss'
gen ss_incr_ma = bsqXx14/`tss'
gen ss_incr_fixed = bsqXx15/`tss'

keep bsqXx* res model ss_*
keep if _n == 1

drop bsqXx0-bsqXx15

egen sum_ss = rowtotal(ss_*)

egen sum_base = rowtotal(ss_*)
qui replace sum_base = sum_base - ss_corprate /* re-adjust */

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

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
}


*Generate new %s for stacked graph
gen fedincbase = ss_fedincbase
gen fedincded = fedincbase + ss_fedincded
gen throwback = fedincded + ss_throwback
gen saleswgt = throwback + ss_saleswgt
gen losscarryforward = saleswgt + ss_losscarryforward
gen losscarryback = losscarryforward + ss_losscarryback
gen combined = losscarryback + ss_combined
gen other = 1


*Other categories (for "large" figure)
gen investmentcredit = combined + ss_investment_credit
gen recval = investmentcredit + ss_rec_val
gen acrsdep = recval + ss_acrsdep
gen allowfedaccdep = acrsdep + ss_allowfedaccdep
gen fedbonusdep = allowfedaccdep + ss_fedbonusdep
gen frantax = fedbonusdep + ss_frantax
gen incrma = frantax + ss_incr_ma
gen 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 other "Other Tax Base Rules"

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"

*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

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) 100, 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 Var Among Base Rules", height(5)) ///
	xti("")

graph display, ysize(4) scale(.9)

graph export "$figdir/figure`fignum'c.pdf", replace
