program GWA_EJ

*** Program to calculate Generational Wealth Accounts
*** David G McCarthy 2015
*** Takes in the following arguments:
***  ///assumptions
***     (1)  current year
***     (2)  discount rate
***     (3)  growth rate
***  ///input files containing data
***     (4)  input filename for source NTA profiles (with full path) e.g. "C:\Profiles-2007.csv"
***     (5)  input filename for population projections (with full path) e.g. "C:\PopulationProjection-2007.csv"
***     (6)  input filename with OBR-projected percentages of GDP for cg (govt consumption) tgi (cash transfers received) and tgo (cash transfers paid)
***  ///other data
***     (7)  GDP in current year (in GBP)
***     (8)  total private sector net worth (in billions of GBP)
***  ///output parameters and files
***     (9)  distance between age categories for aggregating results e.g. 1, 5, 10
***     (10)  output filename for saved GWA data (with full path) "C:\GWA-2007.dta"
***     (11) output filename containing projections of annual flows for robustness checking
***     (12) name for these runs


clear
set more off

* Define local variables (update these for your project, for now only constant)
local current_year= `1'
local disc_rate = `2'
local gr_rate = `3'
local data_storage_file = "`10'"
local run_name = "`12'"
local age_delta = `9'
local nnw = `8'

* Import age profiles and save as .dta file for use as merge
quietly import delimited "`4'"
quietly save "profiles-interim.dta", replace
clear

* Import population projection files
quietly import delimited "`5'"

* Merge with NTA profiles
quietly merge 1:1 age using "profiles-interim.dta"
quietly drop _merge

* Perform data checks

* Check life cycle deficit (check1 should be zero)
quietly gen lcd2 = cg+cf-yl
quietly gen check1 = lcd-lcd2
sum check1

* Check Asset-Based Reallocations (check2 should be zero)
quietly gen abr2 = yl+cg+tgi+tfi-cg-cf-tfo-tgo
quietly gen check2 = abr+abr2
sum check2

* Calculate discounted grown aggregate profiles for each future population for each year
local iter=`current_year'
local ann = 0

quietly gen pv_pop=0

while `iter'<=4000     {
   quietly gen yl_a`iter' =p`iter'*yl *((1+`gr_rate')^(`iter'-`current_year'))/((1+`disc_rate')^(`iter'-`current_year'))
   quietly gen cg_a`iter' =p`iter'*cg *((1+`gr_rate')^(`iter'-`current_year'))/((1+`disc_rate')^(`iter'-`current_year'))
   quietly gen cf_a`iter' =p`iter'*cf *((1+`gr_rate')^(`iter'-`current_year'))/((1+`disc_rate')^(`iter'-`current_year'))
   quietly gen tgi_a`iter'=p`iter'*tgi*((1+`gr_rate')^(`iter'-`current_year'))/((1+`disc_rate')^(`iter'-`current_year'))
   quietly gen tgo_a`iter'=p`iter'*tgo*((1+`gr_rate')^(`iter'-`current_year'))/((1+`disc_rate')^(`iter'-`current_year'))
   quietly gen tfi_a`iter'=p`iter'*tfi*((1+`gr_rate')^(`iter'-`current_year'))/((1+`disc_rate')^(`iter'-`current_year'))
   quietly gen tfo_a`iter'=p`iter'*tfo*((1+`gr_rate')^(`iter'-`current_year'))/((1+`disc_rate')^(`iter'-`current_year'))
   quietly replace pv_pop= pv_pop + p`iter'[1]*((1+`gr_rate')^(`iter'-`current_year'))/((1+`disc_rate')^(`iter'-`current_year'))
local iter=`iter'+1
}

* Balance transfers in (tfi) and out (tfo) to ensure that aggregate transfers in each year are 0
* Go up to the year 4000 to ensure that all transfers to and within the unborn are covered in PV terms
local iter=`current_year'
while `iter'<=4000   {
   quietly egen total_tfi = total(tfi_a`iter')
   quietly egen total_tfo = total(tfo_a`iter')
   quietly replace tfi_a`iter'=tfi_a`iter'*0.5*(total_tfi+total_tfo)/total_tfi
   quietly replace tfo_a`iter'=tfo_a`iter'*0.5*(total_tfi+total_tfo)/total_tfo
   quietly drop total_tfi
   quietly drop total_tfo
local iter=`iter'+1
}

* save interim results
gen dumb_key = 0
sort dumb_key
quietly save "profiles-interim.dta", replace
clear
set maxvar 30000
use "profiles-interim.dta"

* get rid of duplicated data
local iter=`current_year'
while `iter'<=4000   {
   quietly egen total_yl`iter' = total(yl_a`iter')
   quietly egen total_cg`iter' = total(cg_a`iter')
   quietly egen total_cf`iter' = total(cf_a`iter')
   quietly egen total_tgi`iter' = total(tgi_a`iter')
   quietly egen total_tgo`iter' = total(tgo_a`iter')
   quietly egen total_tfi`iter' = total(tfi_a`iter')
   quietly egen total_tfo`iter' = total(tfo_a`iter')
   quietly egen total_pop`iter' = total(p`iter')
   quietly drop yl_a`iter'
   quietly drop cg_a`iter'
   quietly drop cf_a`iter'
   quietly drop tgi_a`iter'
   quietly drop tgo_a`iter'
   quietly drop tfi_a`iter'
   quietly drop tfo_a`iter'
   quietly drop p`iter'
local iter=`iter'+1
}
keep if age==0
* perform obr adjustments if needed
* assume gdp per capita grows at rate `gr_rate' and calculate updated projected aggregates for yl, cg, tgi and tgo
reshape long total_yl total_cg total_cf total_tgi total_tgo total_tfi total_tfo total_pop, i(age) j(year)
keep total_yl total_cg total_cf total_tgi total_tgo total_tfi total_tfo total_pop year
gen total_gdp = `7'
gen total_gdp2 = ln(total_pop[_n]/total_pop[_n-1]) // one missing value
recode total_gdp2 .=0 in 1                         // fill the missing with zero
gen total_gdp3 = sum(total_gdp2)
gen total_gdp4 = exp(total_gdp3)
gen total_gdp5 = total_gdp*total_gdp4*((1+`gr_rate')^(year-`current_year'))*((1+`disc_rate')^(-(year-`current_year')))
replace total_gdp = total_gdp5
drop total_gdp2 total_gdp3 total_gdp4 total_gdp5
sort year
merge year using "`6'"

gen yl_adj = yl_obr/(total_yl/total_gdp)
gen cg_adj = cg_obr/(total_cg/total_gdp)
gen tgi_adj = tgi_obr/(total_tgi/total_gdp)
gen tgo_adj = tgo_obr/(total_tgo/total_gdp)

gen yl_adj = 1
gen cg_adj = 1
gen tgi_adj = 1
gen tgo_adj = 1
quietly replace total_yl=total_yl*yl_adj
quietly replace total_cg=total_cg*cg_adj
quietly replace total_tgi=total_tgi*tgi_adj
quietly replace total_tgo=total_tgo*tgo_adj
quietly save "`11'", replace

keep year *_adj
gen dumb_key=0
reshape wide *_adj, i(dumb_key) j(year)
sort dumb_key

merge dumb_key using "profiles-interim.dta"

* Count up each profile by year of birth for the currently living
quietly gen pv_yl=0
quietly gen pv_cg=0
quietly gen pv_cf=0
quietly gen pv_tgi=0
quietly gen pv_tgo=0
quietly gen pv_tfi=0
quietly gen pv_tfo=0

local current_age=1
while `current_age' <= 111    {
   local max_year = `current_year'+111-`current_age'
   forvalues iter=`current_year'(1)`max_year'    {
      quietly replace pv_yl =pv_yl +   yl_adj`iter'*yl_a`iter'[`iter'-`current_year'+`current_age']/1000000 in `current_age'
	  quietly replace pv_cg =pv_cg +   cg_adj`iter'*cg_a`iter'[`iter'-`current_year'+`current_age']/1000000 in `current_age'
	  quietly replace pv_cf =pv_cf +                cf_a`iter'[`iter'-`current_year'+`current_age']/1000000 in `current_age'
	  quietly replace pv_tgi=pv_tgi+ tgi_adj`iter'*tgi_a`iter'[`iter'-`current_year'+`current_age']/1000000 in `current_age'
	  quietly replace pv_tgo=pv_tgo+ tgo_adj`iter'*tgo_a`iter'[`iter'-`current_year'+`current_age']/1000000 in `current_age'
	  quietly replace pv_tfi=pv_tfi+               tfi_a`iter'[`iter'-`current_year'+`current_age']/1000000 in `current_age'
	  quietly replace pv_tfo=pv_tfo+               tfo_a`iter'[`iter'-`current_year'+`current_age']/1000000 in `current_age'
	  local `iter'=`iter'+1
   }
local current_age=`current_age'+1
}

gen pv_yl_u=0
gen pv_cg_u=0
gen pv_cf_u=0
gen pv_tgi_u=0
gen pv_tgo_u=0
gen pv_tfi_u=0
gen pv_tfo_u=0

* count up each profile for the currently unborn
local this_year=`current_year'+1
*local current_year=2013
while `this_year' <= 4000    {
   local max_row = min(`this_year'-`current_year',111)
*   local max_age = min(`current_year'-2012,110)
   forvalues iter=1(1)`max_row'    {
      quietly replace pv_yl_u =pv_yl_u   +yl_adj`this_year'*yl_a`this_year'[`iter']/1000000 in `iter'
	  quietly replace pv_cg_u =pv_cg_u   +cg_adj`this_year'*cg_a`this_year'[`iter']/1000000 in `iter'
	  quietly replace pv_cf_u =pv_cf_u                     +cf_a`this_year'[`iter']/1000000 in `iter'
	  quietly replace pv_tgi_u=pv_tgi_u+tgi_adj`this_year'*tgi_a`this_year'[`iter']/1000000 in `iter'
	  quietly replace pv_tgo_u=pv_tgo_u+tgo_adj`this_year'*tgo_a`this_year'[`iter']/1000000 in `iter'
	  quietly replace pv_tfi_u=pv_tfi_u                   +tfi_a`this_year'[`iter']/1000000 in `iter'
	  quietly replace pv_tfo_u=pv_tfo_u                   +tfo_a`this_year'[`iter']/1000000 in `iter'
	  local `iter'=`iter'+1
   }
local this_year=`this_year'+1
}

* Keep variables of interest, current population and current per-capita wealth
quietly keep age w pv_yl pv_cg pv_cf pv_tgi pv_tgo pv_tfi pv_tfo p`current_year' pv_yl_u pv_cg_u pv_cf_u pv_tgi_u pv_tgo_u pv_tfi_u pv_tfo_u pv_pop

quietly gen pv_w = w/1000000*p`current_year'

egen total_wealth = total(pv_w)

* do a macroadjustment here - ensure total wealth balances to correct figure including NI
replace pv_w = 1000*pv_w*`nnw'/total_wealth

sort age
quietly save "profiles-interim.dta", replace

quietly gen r_yl=pv_yl
quietly gen r_w=pv_w
quietly gen r_gag = pv_cg+pv_tgi
quietly gen r_gaf = pv_tfi
quietly gen r_tot = r_yl+r_w+r_gag+r_gaf
quietly gen u_cg = pv_cg
quietly gen u_cf = pv_cf
quietly gen u_gag = pv_tgo
quietly gen u_gaf = pv_tfo
quietly gen u_tot = u_cg+u_cf+u_gag+u_gaf
quietly gen u_bal = r_tot-u_tot

sort age

quietly gen agecat = round((age+`age_delta'/2)/`age_delta')

* generate waterfall
local new = _N+1
quietly set obs `new'
quietly recode agecat .=0

quietly gen agecat2 = -agecat

quietly gen age2 = -age
quietly sort agecat2 age2

quietly gen cum_beq = sum(u_bal)

quietly gen check_cum_beq = 1 if cum_beq>=0 & u_bal>=0
quietly recode check_cum_beq .=2 if cum_beq>=0 & u_bal<0
quietly recode check_cum_beq .=3 if cum_beq<0 & u_bal>=0
quietly recode check_cum_beq .=4 if cum_beq<0 & u_bal<0

quietly gen u_beq = u_bal if check_cum_beq == 1
quietly gen r_beq =-u_bal if check_cum_beq == 2
quietly replace r_beq=max(cum_beq-u_bal,0) if check_cum_beq==4

quietly egen u_beq_total = total(u_beq)
quietly egen r_beq_total = total(r_beq)
quietly gen test_r = max(r_beq_total-u_beq_total,0)
quietly gen test_u = max(u_beq_total-r_beq_total,0)
quietly replace u_beq =test_r  if agecat==0
quietly replace r_beq =test_u  if agecat==0

quietly recode u_beq .=0
quietly recode r_beq .=0

quietly replace u_tot = u_tot+u_beq
quietly replace r_tot = r_tot+r_beq


* generate public sector transfers with the unborn
quietly egen u_gag_total = total(u_gag)
quietly egen r_gag_total = total(r_gag)
quietly gen test_rgag = max(r_gag_total-u_gag_total,0)
quietly gen test_ugag = max(u_gag_total-r_gag_total,0)
quietly replace u_gag =test_rgag  if agecat==0
quietly replace r_gag =test_ugag  if agecat==0

* generate private sector transfers with the unborn
quietly egen u_gaf_total = total(u_gaf)
quietly egen r_gaf_total = total(r_gaf)
quietly gen test_rgaf = max(r_gaf_total-u_gaf_total,0)
quietly gen test_ugaf = max(u_gaf_total-r_gaf_total,0)
quietly replace u_gaf =test_rgaf  if agecat==0
quietly replace r_gaf =test_ugaf  if agecat==0

* generate any funding gap
quietly gen r_gap = u_tot-r_tot
quietly replace r_tot = r_tot+r_gap
quietly replace r_gap = u_gag - r_beq - r_gaf if agecat==0

local new = _N+1
quietly set obs `new'
quietly recode agecat .=-1

* fill in missing variables for unborn
quietly egen pv_yl_u_tot = total(pv_yl_u)
quietly egen pv_cg_u_tot = total(pv_cg_u)
quietly egen pv_cf_u_tot = total(pv_cf_u)
quietly egen pv_tgi_u_tot = total(pv_tgi_u)
quietly egen pv_tgo_u_tot = total(pv_tgo_u)
quietly egen pv_tfi_u_tot = total(pv_tfi_u)
quietly egen pv_tfo_u_tot = total(pv_tfo_u)

quietly replace r_yl=pv_yl_u_tot if agecat==-1
quietly replace r_w= 0 if agecat==-1
quietly replace r_gag = pv_cg_u_tot+pv_tgi_u_tot if agecat==-1
quietly replace r_gaf = pv_tfi_u_tot if agecat==-1
quietly replace r_tot = r_yl+r_w+r_gag+r_gaf if agecat==-1
quietly replace u_cg = pv_cg_u_tot if agecat==-1
quietly replace u_cf = pv_cf_u_tot if agecat==-1
quietly replace u_gag = pv_tgo_u_tot if agecat==-1
quietly replace u_gaf = pv_tfo_u_tot if agecat==-1
quietly replace u_tot = u_cg+u_cf+u_gag+u_gaf if agecat==-1
quietly replace u_bal = r_tot-u_tot if agecat==-1
quietly replace p`current_year' = pv_pop[1] if agecat==-1

* drop interim variables
quietly drop agecat2 age2 cum_beq check_cum_beq u_beq_total r_beq_total test_r test_u r_gaf_total u_gaf_total test_rgaf test_ugaf r_gag_total u_gag_total test_rgag test_ugag u_bal pv_yl_u_tot pv_yl_u pv_cg_u_tot pv_cg_u pv_cf_u_tot pv_cf_u pv_tgi_u_tot pv_tgi_u pv_tgo_u_tot pv_tgi_u_tot pv_tfi_u_tot pv_tfi_u pv_tfo_u_tot pv_tfo_u

* collapse by agecate
quietly collapse (sum) r_yl r_w r_gag r_gaf r_beq r_gap r_tot u_cg u_cf u_gag u_gaf u_beq u_tot p`current_year', by(agecat)

* order variables
order age p`current_year' r_yl r_w r_gag r_gaf r_beq r_gap r_tot u_cg u_cf u_gag u_gaf u_beq u_tot

quietly replace r_yl = r_yl/1000
quietly replace r_w = r_w/1000
quietly replace r_gag = r_gag/1000
quietly replace r_gaf = r_gaf/1000
quietly replace r_beq = r_beq/1000
quietly replace r_gap = r_gap/1000
quietly replace r_tot = r_tot/1000
quietly replace u_cg = u_cg/1000
quietly replace u_cf = u_cf/1000
quietly replace u_gag = u_gag/1000
quietly replace u_gaf = u_gaf/1000
quietly replace u_beq = u_beq/1000
quietly replace u_tot = u_tot/1000
quietly replace p`current_year' = p`current_year'/1000000

quietly gen pc_r_yl = r_yl/p`current_year'
quietly gen pc_r_w = r_w/p`current_year'
quietly gen pc_r_gag = r_gag/p`current_year'
quietly gen pc_r_gaf = r_gaf/p`current_year'
quietly gen pc_r_beq = r_beq/p`current_year'
quietly gen pc_r_gap = r_gap/p`current_year'
quietly gen pc_r_tot = r_tot/p`current_year'
quietly gen pc_u_cg = u_cg/p`current_year'
quietly gen pc_u_cf = u_cf/p`current_year'
quietly gen pc_u_gag = u_gag/p`current_year'
quietly gen pc_u_gaf = u_gaf/p`current_year'
quietly gen pc_u_beq = u_beq/p`current_year'
quietly gen pc_u_tot = u_tot/p`current_year'

quietly gen year = `current_year'
quietly rename p`current_year' pop

* sort in reverse agecat order
gen reversekey = -agecat
sort reversekey
drop reversekey
quietly gen run_type="`run_name'"
quietly append using "`data_storage_file'"
quietly save "`data_storage_file'", replace

end