* This model is the same as that in Appendix E except for:
* 1. Option of selecting infinite horizon balancing of government budget.
* 2. Option of including Lump Sum Redistribution Authority.
* 3. MPSGE representation of the transition model.

* Set options (0 = No, 1 = Yes):

SCALAR	GBINF	Flag for infinite horizon balancing of the government budget	/0/,
	LSRA	Flag lump-sum redistribution authority				/0/;

$ONTEXT

The benchmark social accounting matrix: 

      | Output| Income categories    |  Consumption categories  
      | OUT   | CAP     LAB     TAX  |  CON     INV     GOV     ROW
---------------------------------------------------------------------
OUT   |                                 5,397   1,786   1,474     802
CAP   | 3,521
LAB   | 5,041           
TAX   |           779   1,491
CON   |         2,742   3,550                             995
INV   |                                 1,890            -199      95
GOV   |                         2,270
ROW   |   897
---------------------------------------------------------------------
Note: Based on 1996 IO tables for USA. Numbers in 1996 USD billion.

$OFFTEXT

*=====================================================================
* Introduce intertemporal sets
*=====================================================================


* The model captures all generations alive in the first model period
* (year 0) and all those born in the span of the subsequent 150
* years, where generations are labeled according to the year in which
* they are born. The model is solved in 5-year intervals with each
* new generation being born at the start of a period and living to
* the age of 55.

SCALAR
        TIMINT  Single period time interval                     /5/,
        INIYEAR Year in with oldest generation was born         /-50/;
SETS
        G Generations in the model /
        "-50","-45","-40","-35","-30","-25","-20","-15","-10","-5",
        0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,
        100,105,110,115,120,125,130,135,140,145,150/,
        T(G) Time periods in the model / 
        0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,
        100,105,110,115,120,125,130,135,140,145,150/,
        A(T)   Typical life-cycle / 0,5,10,15,20,25,30,35,40,45,50/;
SETS	ALABELS(T)	Labels for plots /0,10,20,30,40,50/,
	GLABELS(G)	Labels for plots /"-40","-20",0,20,40,60,80,100,120,140/,
	TLABELS(G)	Labels for plots /0,20,40,60,80,100,120,140/;

* We need some special sets to identify key time periods and
* generations.

SETS
        TFIRST(T)       First period in the model,
        TLAST(T)        Last period in the model,
        ATGEN(G)        Generations with terminal assets;

* These special sets are identified by their order in the declaration.

TFIRST(A)       = YES$(ORD(A) EQ 1);
TLAST(T)        = YES$(ORD(T) EQ CARD(T));
ATGEN(G)        = YES$((CARD(G)-CARD(A)+1) LT ORD(G));

* Aliases used to manipulate sets.

ALIAS (G,GG,YR), (T,TT), (A,AA);

*=====================================================================
* Introduce fundamental parameters
*=====================================================================

SCALARS
        RBAR_A          Annual interest rate                    /0.05/,
        GAMMA_A         Annual population growth rate           /0.01/,
        DELTA_A         Annual depreciation rate                /0.07/,
        THETA           Inverse intertemporal elasticity        /4.00/,
        SIGMA_CL        Elasticity of substitution (C vs L)     /0.8/
        PHI             Consumption share parameter             /0.4/
        ETADX           Elasticity of transformation D vs. X    /4/
        SIGMA           Armington elasticity on imports         /4/;

* Modify annual rates of change to 5-year interval between solution
* periods

SCALAR          RBAR            Periodic interest rate,
                GAMMA           Periodic population growth rate
                DELTA           Periodic depreciation rate
                RHO_CL          Exponent in intratemporal utility;

RBAR            = (1+RBAR_A)**TIMINT  - 1;
GAMMA           = (1+GAMMA_A)**TIMINT - 1;
DELTA           = 1 - (1-DELTA_A)**TIMINT;
RHO_CL          = 1 - 1/SIGMA_CL;

*=====================================================================
* Time profiles
*=====================================================================

* Declare variables relating values to intertemporal sets and use
* annual growth and interest rates to create time profiles consistent
* with the 5-year interval between solution periods.

PARAMETERS
        YEAR(G)         Point in time,
        AGE(A)          Age at a given point in the life cycle,
        PREF(G)         Reference price path (present value index),
        QREF(G)         Reference quantity path (index),
        PSHR(A)         Population share for agents of age A,
        PI(A)           Productivity index;


* Time periods and ages can be identified by the order of the
* relevant set using the fact that each period has a length of 5
* years, and that generations are labeled according to the year they
* are born and live for 55 years.

YEAR(G)         = INIYEAR + TIMINT * (ORD(G)-1);
AGE(A)          = TIMINT * (ORD(A)-1);

* Declare indices for population size and present value prices.

QREF(G)         = (1+GAMMA_A)**YEAR(G);
PREF(G)         = 1 /(1+RBAR_A)**YEAR(G);

* Age group A share in total polutation

PSHR(A) = (1/QREF(A)) / SUM(AA, (1/QREF(AA)));

* Productivity index as in Auerbach and Kotlikoff (1987)

PI(A) = EXP(4.47 + 0.033*AGE(A) - 0.00067*(AGE(A))**2) / EXP(4.47);

* Use ages and years to set up correspondence between generations,
* age, and year.

SET MAPG(G,A,YR)    Assignment from generation and age to time period;
 
MAPG(G,A,YR)    = YES$(YEAR(G)+AGE(A) EQ YEAR(YR));

*=====================================================================
* Read benchmark data
*=====================================================================

SCALARS
        C0      Benchmark private consumption           /5.397/,
        I0      Benchmark investment                    /1.786/,
        G0      Benchmark government consumption        /1.474/,
        X0      Benchmark exports                       /0.802/,
        M0      Benchmark imports                       /0.897/,
        R0      Benchmark capital earnings (net of tax) /2.742/,
        L0      Benchmark labor earnings (net of tax)   /3.550/,
        S0      Benchmark savings                       /1.890/,
        T0      Benchmark transfers  to households      /0.995/,
        D0      Benchmark government budget deficit     /0.199/,
        B0      Benchmark trade deficit                 /0.095/,
        Y0      Benchmark output                        /8.562/,
        TR0     Benchmark tax rate on capital income
        TL0     Benchmark tax rate on labor income; 

TR0             = 779  / 2742;
TL0             = 1491 / 3550;

* Infer capital stock from earnings and the steady-state return:

SCALARS         K0      Initial capital stock;

K0              = R0 / (RBAR+DELTA);

*=====================================================================
* Modify benchmark data to represent a consistent steady-state
*=====================================================================

* Modify investment level and revise consumption accordingly to keep
* total demand constant:
                
C0      = C0 + I0 - (GAMMA+DELTA)*K0;
I0      = (GAMMA+DELTA)*K0;
S0      = R0 + L0 + T0 - C0;

*=====================================================================
* Calibration model: Solve for benchmark steady state of reference
* generation
*=====================================================================


* Find utility discount rate, RHO, and time endowment, OMEGA, to set
* implied aggregate values at the benchmark level. Government
* transfers to households, T0, are modeled as exogenous lump-sum
* payments and are added to household incomes according to each
* generation's share in the total population. We use the equations
* arising from the household utility maximization problem to set up
* an mixed complementarity problem (MCP) and use the solver to find
* the value of RHO that satisfies all the equations in the system. 

VARIABLES
        CA(A)           Present value of assets over the life cycle,
        CMA(A)          Value of assets held by age,
        CCMA            Aggregate value of assets held by age,
        RHO             Period utility discount rate,
        OMEGA           Scaling factor on time endowment;

POSITIVE VARIABLES
        CZ(A)           Full consumption,
        CC(A)           Consumption,
        CCC             Aggregate consumption,
        CELL(A)         Leisure time,
        CL(A)           Labor time,
        CPZ(A)          Price of full consumption (present value),
        ETA(A)          Price of time (present value utils),
        LAMDA           Price of income (present value utils);

EQUATIONS
        EQZ(A)          Definition of consumption,
        EQPZ(A)         Definition of price of full consumption,
        EQC(A)          FOC for consumption,
        EQS(A)          FOC for leisure time,
        EQL(A)          FOC for labor time,
        EQETA(A)        FOC for price of time, 
        EQLAMDA         FOC for price of income,
        EQCA(A)         Present value assets over the life cycle,
        EQCMA(A)        Value of assets held by age,
        EQCCC           Aggregate consumption,
        EQCCMA          Aggregate value of assets,
        EQCCCLEV        Fix level of aggregate consumption,
        EQCCMALEV       Fix level of aggregate assets;

* Equation definitions:

EQZ(A)..        CZ(A) =E= ( PHI*CC(A)**RHO_CL + 
                                (1-PHI)*CELL(A)**RHO_CL )**(1/RHO_CL);

* First order conditions:

EQC(A).. 
        LAMDA*PREF(A) =E= (1+RHO)**(1-ORD(A)) 
                * CZ(A)**(1-RHO_CL-THETA) 
                * PHI*CC(A)**(RHO_CL-1);
EQS(A)..        
        ETA(A) =E= (1+RHO)**(1-ORD(A))
                * CZ(A)**(1-RHO_CL-THETA)
                * (1-PHI)*CELL(A)**(RHO_CL-1);

EQL(A)..        ETA(A)=G=LAMDA*PREF(A)*PI(A);

EQLAMDA..
        SUM(A,PREF(A)*CC(A)) =E= 
                SUM(A,PREF(A)*(PI(A)*CL(A)+PSHR(A)*QREF(A)*T0));
EQETA(A)..      OMEGA =E= CELL(A)+CL(A);

* Price indices:

EQPZ(A)..       
        CPZ(A)=E=(     PHI**SIGMA_CL*       PREF(A)**(1-SIGMA_CL)
                +(1-PHI)**SIGMA_CL 
                * (ETA(A)/LAMDA)**(1-SIGMA_CL))**(1/(1-SIGMA_CL));

* Asset positions:

EQCA(A)..
        CA(A)   =E=     SUM(AA$(ORD(AA) LT ORD(A)), 
                          PREF(AA)*(PI(AA)*CL(AA)
                        + PSHR(AA)*QREF(AA)*T0-CC(AA)));

EQCMA(A)..      CMA(A)  =E=     CA(A)/(QREF(A)*PREF(A));

* Aggregate values:

EQCCC..         CCC     =E=     SUM(A,CC(A)/QREF(A));
EQCCMA..        CCMA    =E=     SUM(A,CMA(A));

* Fix aggregate level of consumption and assets at benchmark level:

EQCCCLEV..      CCC =E=     C0;
EQCCMALEV..     CCMA =E= (1+RBAR)*K0 + (B0-D0)*(1+RBAR)/(RBAR-GAMMA);

* Associate variables with equations:

*=====================================================================

MODEL BENCH     
        /EQZ.CZ, EQPZ.CPZ, EQCA.CA, EQCMA.CMA, EQC.CC, EQS.CELL, EQL.CL, 
        EQETA.ETA, EQLAMDA.LAMDA, EQCCC.CCC, EQCCMA.CCMA, EQCCCLEV.RHO, 
        EQCCMALEV.OMEGA/;

* Set bounds to prevent operation errors:

RHO.LO          = -0.99;
CZ.LO(A)        = 1E-5;
CC.LO(A)        = 1E-5;
CELL.LO(A)      = 1E-5;
LAMDA.LO        = 1E-5;

* Initialize variables:

RHO.L           = 0.01;
CZ.L(A)         = 0.5;
CC.L(A)         = 0.5;
CELL.L(A)       = 0.5;
CL.L(A)         = 0.5;
CPZ.L(A)        = 0.5;
ETA.L(A)        = 0.5;
LAMDA.L         = 0.5;
CCC.L           = 0.5;

* Solve calibration model:

BENCH.ITERLIM=50000;
SOLVE BENCH USING MCP;

* Calibration results

PARAMETERS      RHO_A           Annual utility discount rate,
                PELLRATIO(A)    Ratio of reservation to market wage;

RHO_A           = (1+RHO.L)**(1/TIMINT) - 1;
PELLRATIO(A)    = 100 * ETA.L(A)/(PREF(A)*PI(A)*LAMDA.L);

*=====================================================================
* Use endowments and the calibrated consumption and leisure time
* profiles for generation 0 to install baseline values for all
* generations
*=====================================================================

PARAMETERS
	PIREF(G,T)      Baseline productivity profile,
	EREF(G,T)       Baseline endowment profile,
	CREF(G,T)       Baseline consumption profile,
	ELLREF(G,T)     Baseline leisure time profile,
	LREF(G,T)       Baseline labor time profile,
	ZREF(G,T)       Baseline full consumption profile,
	TREF(G,T)       Baseline transfers to households,
	PELLREF(G,T)    Baseline reservation wage,
	PZREF(G,T)      Baseline price of full consumption,
	ZREF_T(G,A)     Baseline post-terminal consumption profile,
	PREF_T(A)       Baseline post-terminal price path,
	PZREF_T(G,A)    Baseline post-terminal full consumption,
	MREF(G)         Baseline present value of consumption;

* We assign demand and income profiles for generation G at time T
* based on endowments and the calibrated consumption profile for
* generation 0. The trick here is to use a GAMS loop over the mapping
* which relates generations (G), ages (A) and time periods (T):

LOOP(MAPG(G,A,T),
        PIREF(G,T)      = PI(A);
        EREF(G,T)       = QREF(G) * OMEGA.L;
        CREF(G,T)       = QREF(G) * CC.L(A); 
        ELLREF(G,T)     = QREF(G) * CELL.L(A);
        LREF(G,T)       = QREF(G) * CL.L(A);
        ZREF(G,T)       = QREF(G) * CZ.L(A);
        PELLREF(G,T)    = PREF(G) * ETA.L(A)/LAMDA.L; 
        TREF(G,T)       = QREF(G) * PSHR(A)*T0*QREF(A);
        PZREF(G,T)      = PREF(G) * CPZ.L(A);   );

* The last model generation is born in year 150 which means that in
* order to capture the full life cycle of all model generations we
* need to cover a 50-year "post-terminal" period. We index these
* post-terminal periods by the same index (A) that we use to index
* ages in a life cycle.

* Consumption profiles in post-terminal periods for generation G at
* age A are inferred from the consumption levels in the initial
* period of generations that have the same age.

LOOP((G,A,TLAST)$(YEAR(G)+AGE(A) GT YEAR(TLAST)),
        ZREF_T(G,AA)$(AGE(AA)+YEAR(TLAST) EQ AGE(A)+YEAR(G)) 
        = QREF(G) * CZ.L(A); );

* Present value prices in post-terminal periods are extrapolated from
* the value of the reference price index in the terminal period.

LOOP((A,TLAST)$AGE(A), PREF_T(A) = PREF(TLAST) / (1 + RBAR_A)**AGE(A); );

LOOP((G,A,TLAST)$(YEAR(G)+AGE(A) GT YEAR(TLAST)),
        PZREF_T(G,AA)$(AGE(AA)+YEAR(TLAST) EQ AGE(A)+YEAR(G))  
        = CPZ.L(A)*PREF(G); );

* Present value of consumption by generation, including post-terminal
* consumption by generations who live beyond the model horizon.

MREF(G) = SUM(T,  ZREF(G,T)*PZREF(G,T)) 
        + SUM(A, PZREF_T(G,A)*ZREF_T(G,A));

*=====================================================================
* Distribute assets holdings by type
*=====================================================================

SCALARS         THETAC          Ratio of capital stock to assets,
                THETAD          Ratio of government deficit to assets,
                THETAB          Ratio of trade deficit to assets;

PARAMETERS      A0REF(G)        Baseline initial asset holdings,
                ATREF(G)        Baseline terminal asset holdings;

* Value shares of the different asset types as implied by benchmark
* value flows. 

THETAC          = (1+RBAR)*K0 / CCMA.L;
THETAB          = (B0*(1+RBAR)/(RBAR-GAMMA)) / CCMA.L;
THETAD          = (-D0*(1+RBAR)/(RBAR-GAMMA)) / CCMA.L;

* Distribute asset types by assuming that all age groups hold the
* different types in same proportion. Use mapping to identify
* generation at time zero from age of reference generation.

A0REF(G)        = SUM(MAPG(G,A,"0"), CMA.L(A));

* Assets left at end of terminal period for generation G are inferred
* from inital assets.

LOOP((G,GG),    ATREF(G)$(ORD(G) EQ (ORD(GG) + (CARD(G) + 1 - CARD(A))))
                = A0REF(GG) * (1+GAMMA)**CARD(T) / (1+RBAR); );

*=====================================================================
* Parameters for counterfactual experiments
*=====================================================================

PARAMETER       
        TAXR    Model tax rate on capital earnings,
        TAXL    Model tax rate on labor earnings;
                
* Initialize model tax rates at benchmark values:

TAXR            = TR0;
TAXL            = TL0;

*=====================================================================
* Model in MPSGE. This model solves for the equilibrium transition path 
* subject to terminal conditions that assume the presence of a steady 
* state. If there are no exogenous changes the model replicates the 
* calibrated consumption profiles. We use this feature to check the 
* calibrations and then solve for the results of fundamental tax reform
*=====================================================================

$LABEL MPSGE

* Shift compiler from GAMS to MPSGE and set model name:

$ONTEXT
$MODEL:OLG

* Declare production activities. These determine how inputs are converted 
* into outputs according to the technology implied by the benchmark data. 
* The variables here are activity levels and an equilibrium requires that 
* each active sector earns zero profit. 

$SECTORS:
	 QY(T)			! Domestic production
	 QA(T)			! Supply of Armington composite
	 QX(T)			! Export and domestic supply
	 QK(T)			! Capital stock
	 QI(T)			! Investment
	 QC(T)			! Private consumption
	 QL(G,T)$CREF(G,T)	! Labor supply
	 QZ(G,T)$CREF(G,T)	! Full consumption
	 QU(G)			! Utility
 
* Declare commodities. The variables here are the prices that are 
* associated with each commodity. An equilibrium requires that prices 
* are such that supply equals demand.

$COMMODITIES:
	PY(T)		! Price of output					
	PH(T)		! Price of output for domestic use				
	PFX		! Price of foreign exchange
	PA(T)		! Price of Armington composite
	PTAX(T)		! Tax revenue market
	PL(T)		! Wage rate (price of labor in efficiency units)
	PR(T)		! Rental rate
	PK(T)		! Price of capital
	PU(G)		! Price of intertemporal utility
	PKT		! Price of post-terminal capital
	PC(T)		! Price of private consumption
	PELL(G,T)$CREF(G,T)	! Reservation wage
	PZ(G,T)$CREF(G,T)	! Price of full consumption (current value)
	PZT(G,A)$ZREF_T(G,A)	! Price of full consumption (current value)

* Declare consumers. These are agents that receive income from endowments 
* or taxes and spend it to maximize utility. The variables here are income
* levels and an equilibrium requires that total income equals total 
* expenditure. The formulation of government demand depends on how the 
* government budget is balanced as determined by the flag GBINF. 

$CONSUMERS:
	RA(G)			! Representative agents by generation
	IRS(T)			! Tax collector
	GOVY(T)$(NOT GBINF)	! Government with period-by-period budget
	GOVI$GBINF		! Government with infinite horizon budget

* Declare auxiliary variables. These are endogenous variables associated
* with model constraints that relate the transition to the steady state. 
* The replacement tax is either varying period by period or constant as 
* implied by the flag GBINF. If the "Lump Sum Redistribution Authority" 
* option is selected, as determined by the flag LSRA, there is an 
* endogenous LSRA payment or receipt and a common equivalent variation.

$AUXILIARY:
	KT			! Terminal capital
	ZT(G,A)$ZREF_T(G,A)	! Post-terminal consumption of goods
	AT(G)$ATGEN(G)		! Terminal bonds 
	TAU_TAXY(T)$(NOT GBINF)	! Replacement tax (period-by-period balancing)
	TAU_TAXI$GBINF		! Replacement tax (infinite horizon balancing)
	GT$GBINF		! Terminal government assets
	TAU_LSRA(G)$LSRA	! Lump sum transfer in counterfactual with LSRA
	NKTLSRA(G)$(LSRA AND (NOT ATGEN(G)))	! LSRA payment to pre-terminal g
	KTLSRA(G)$(LSRA AND ATGEN(G))		! LSRA payment to terminal g
	EV$LSRA					! Common welfare index with LSRA

*=====================================================================
* $PROD blocks describe the production activities using the benchmark data 
* and exogenous elasticities. I: fields denote inputs, O: fields denote outputs, 
* P: fields denote the reference price level, and the s: fields denotes the 
* elasticity of substitution
*=====================================================================

* This block constructs a Cobb-Douglas function (s:1 indicates that the 
* elasticity of substitution between inputs is unity) where output is produced 
* using labor and capital services. Each input is associated with an exogenous 
* tax rate.

$PROD:QY(T)  s:1
	O:PY(T)		Q:Y0
	I:PR(T)		Q:R0	P:(PREF(T)*(1+TR0))	A:IRS(T)	T:TAXR
	I:PL(T)		Q:L0	P:(PREF(T)*(1+TL0))	A:IRS(T)	T:TAXL

* This block constructs a constant elasticity of transformation function that 
* distinguishes exports from output used domestically. (t:4 indicates that the 
* elasticity of transformation is equal to 4). Because of the assumption of 
* perfect international capital markets the current value price of exports 
* is constant and we therefore only opperate with
* a single price for foreign exchange determining the level.

$PROD:QX(T)  t:4
	O:PH(T)		Q:(Y0-X0)		P:PREF(T) 
	O:PFX		Q:(PREF(T)*X0)	
	I:PY(T)		Q:Y0

* This block constructs a constant elasticity of substitution function that 
* produces a "Armington" composite of domestic goods and imports.
 
$PROD:QA(T)  s:4
	O:PA(T)		Q:(Y0-X0+M0)
	I:PFX		Q:(PREF(T)*M0)		
	I:PH(T)		Q:(Y0-X0)		P:PREF(T)

* This block accounts for the evolution of the capital stock. In each period
* an unit of capital produces rental services and what is left after depreciation 
* enters as next period's capital stock. To elasticities for capital left 
* after the terminal period this commodity is accounted for separately. 
* Without s: or t: fields elasticities take the default value of zero.

$PROD:QK(T)
	O:PKT$TLAST(T)	Q:(K0*(1-DELTA))
	O:PK(T+1)	Q:(K0*(1-DELTA))
	O:PR(T)		Q:R0
	I:PK(T)		Q:K0

* This block accounts for investments. In each period investments are produced 
* from the Armington composite and add to next period's capital stock.

$PROD:QI(T)
	O:PKT$TLAST(T)	Q:I0
	O:PK(T+1)	Q:I0
	I:PA(T)		Q:I0

* This block accounts for the conversion of labor time to efficiency units.

$PROD:QL(G,T)$CREF(G,T)
	O:PL(T)		Q:PIREF(G,T)
	I:PELL(G,T)	Q:1

* This block accounts private consumption. Consumption goods are Armington
* goods where an endogenous consumption tax since this is the replacement 
* tax. Which type of replacement tax that enters depends on how the 
* government budget is balanced as implied by the flag GBINF.

$PROD:QC(T)
	O:PC(T)	Q:C0
	I:PA(T)	Q:C0	A:IRS(T)  N:TAU_TAXY(T)$(NOT GBINF)  N:TAU_TAXI$GBINF

* This block constructs full consumption as a composite of material 
* consumption and leisure.
 
$PROD:QZ(G,T)$CREF(G,T)  s:SIGMA_CL
	O:PZ(G,T)	Q:ZREF(G,T)
	I:PC(T)		Q:CREF(G,T)		P:PREF(T) 
	I:PELL(G,T)	Q:ELLREF(G,T)		P:PELLREF(G,T)

* This block constructs the intertemporal composites of full consumption 
* that determine the utility level for each generation. Utility is treated
* as a commodity demanded by the different generations which implies that 
* the utility function is modeled as any other production activity. Note 
* that by representing utility in a standard linearly homogenous CES
* function the equivalent variation is simply the change in the quantity index. 
* The activity level here is initialized at unity implying an overall output
* level equal to the present value of consumption, MREF(G).

$PROD:QU(G)  s:(1/THETA)
	O:PU(G)		Q:MREF(G)
	I:PZ(G,T)	Q:ZREF(G,T)		P:PZREF(G,T)
	I:PZT(G,A)	Q:ZREF_T(G,A)		P:PZREF_T(G,A)

*=====================================================================
* Use a REPORT block to recover the level of inputs in CES production 
* activities.
*=====================================================================

$REPORT:
	V:RK(T)		I:PR(T)		PROD:QY(T)
	V:LS(T)		I:PL(T)		PROD:QY(T)
	V:X(T)		O:PFX		PROD:QX(T)
	V:M(T)		I:PFX		PROD:QA(T)

*=====================================================================
* The following blocks describe top-level demands and endowment incomes 
* of each consumer.
*=====================================================================

* Each generation h as an endowment of labor time and exogenous transfers
*  and consumes the "utility" composite. Generations living at time 0 are 
* endowed with a initial assets which comprise capital and bonds (government 
* and foreign bonds are both denominated in the price of foreign exchange 
* with perfect international capital markets implying that they earn a constant 
* level of interest equal to RBAR. Post-terminal consumption and leisure enter as
* endogenous endowments to satisfy demands of generations lining into the 
* post-terminal periods. Generations living into the post-terminal periods 
* leave behind an amount of assets in the terminal period. The LSRA flag 
* determines if the endogenous LSRA payment applies.

$DEMAND:RA(G)
	D:PU(G)		Q:MREF(G)
	E:PELL(G,T)	Q:EREF(G,T)	
	E:PFX		Q:(SUM(T,PREF(T)*TREF(G,T)))
	E:PK(TFIRST)	Q:(THETAC*A0REF(G)/(1+RBAR))
	E:PFX		Q:((1-THETAC)*A0REF(G))
	E:PZT(G,A)	Q:ZREF_T(G,A)		R:ZT(G,A)
	E:PFX$ATGEN(G)	Q:(-SUM(TLAST, PREF(TLAST)*(1-THETAC)*ATREF(G))) R:AT(G) 
	E:PKT$ATGEN(G)	Q:(-THETAC*ATREF(G))				R:KT
	E:PFX$LSRA	Q:(-1)						R:TAU_LSRA(G)

* A seprate agents receives all the tax revenue. By normalizing the quantity 
* index to unity the price level is equal to total revenue.

$DEMAND:IRS(T)
	D:PTAX(T) 	Q:1
 
* To balance the government budget in each period, the government is 
* constructed by assuming a separate agent in each period. The government 
* consumes the Armington composite, and receives tax revenue. The budget 
* deficit and transfers to households are treated as endogenous endowments 
* of foreign exchange.

$DEMAND:GOVY(T)$(NOT GBINF)
	D:PA(T) 	Q:(QREF(T)*G0)
	E:PFX		Q:(PREF(T)*QREF(T)*(D0-T0))
	E:PTAX(T)	Q:1

* When the government budget is balanced over the infinite horizon 
* there is just a single government agent. In this case it is necessary 
* to know the terminal value of government assets to balance the budget.

$DEMAND:GOVI$GBINF
  	D:PA(T) 	Q:(QREF(T)*G0)
  	E:PFX		Q:(-SUM(T,PREF(T)*QREF(T)*T0))
  	E:PFX		Q:(D0*(1+RBAR)/(RBAR-GAMMA))
  	E:PTAX(T) 	Q:1
  	E:PFX		Q:(-D0*SUM(TLAST,PREF(TLAST)*QREF(TLAST))*(1+GAMMA)/(RBAR-GAMMA))

*=====================================================================
* The following equations describe additional constraints used to close 
* the model and select the level of endogenous taxes.
*=====================================================================

* Set the endogenous tax to balance the government budget either period 
* by period or over the infinite horizon.

$CONSTRAINT:TAU_TAXY(T)$(NOT GBINF)
	PA(T) * QREF(T) * G0 =E= GOVY(T);

$CONSTRAINT:TAU_TAXI$GBINF
	PFX*D0*( (1+RBAR)/(RBAR-GAMMA)
		- GT*SUM(T$TLAST(T),PREF(T)*QREF(T)*(1+GAMMA)/(RBAR-GAMMA)))
	=E= SUM(T, QREF(T)*(PA(T)*G0 + PFX*PREF(T)*T0) - IRS(T));

* With the government budget balanced over the infinite horizon, the terminal
* level of government assets is endogenous.

$CONSTRAINT:GT$GBINF
	PFX*D0*GT*SUM(T$TLAST(T),PREF(T)*QREF(T))
	=E= SUM(T$TLAST(T), QREF(T)*(PA(T)*G0 + PFX*PREF(T)*T0) - IRS(T));

* Select terminal capital stocks so that all generations living past the 
* terminal period achieve the same equivalent variation.

$CONSTRAINT:AT(G)$ATGEN(G)
	QU(G) - QU(G-1) =E= 0;

* Select the levels of post-terminal consumption of goods and leisure so 
* that the present value price declines with the steady-state interest rate.

$CONSTRAINT:ZT(G,A)$ZREF_T(G,A)
	SUM(TLAST, PZ(G-(ORD(A)-1),TLAST)) =E= PZT(G,A) * (1+RBAR)**(ORD(A)-1);

* Scale the level of the terminal capital stock to achieve steady-state growth
* in last period investment.

$CONSTRAINT:KT
	SUM(TLAST(T), QI(T)/QI(T-1)) =E= 1 + GAMMA;

* In the situation with the lump-sum redistribution authority, select the
* level of inter-generational transfers to achieve a common equivalent 
* variation and ensure that the present value of transfers sum to zero. 
* The lump sum payment for generations living into the terminal periods
* is selected by a steady-state projection.

$CONSTRAINT:NKTLSRA(G)$(LSRA AND (NOT ATGEN(G)))
  EV =E= QU(G) - 1;

$CONSTRAINT:TAU_LSRA(G)$LSRA
  TAU_LSRA(G) =E= NKTLSRA(G)$(NOT ATGEN(G)) + KTLSRA(G)$ATGEN(G);

$CONSTRAINT:KTLSRA(G)$(LSRA AND ATGEN(G))
  KTLSRA(G) =E= SUM(GG$(ORD(GG) EQ (CARD(G)-CARD(A)+1)),
  TAU_LSRA(GG))*((1+GAMMA)/(1+RBAR))**(ORD(G)-(CARD(G)-CARD(A)+1));

$CONSTRAINT:EV$LSRA
  SUM(G, PFX*TAU_LSRA(G)
  *(1 + ((1+GAMMA)/(RBAR-GAMMA))$(ORD(G) EQ CARD(G)))) =E= 0;

*=====================================================================
* End model declaration and shift compiler back to GAMS:
*=====================================================================

$OFFTEXT
$SYSINCLUDE MPSGESET OLG

*=====================================================================
* Assign initial values and bounds for activity levels, prices, and 
* auxiliary variables:
*=====================================================================

QY.L(T)		= QREF(T);
QA.L(T)		= QREF(T);
QX.L(T)		= QREF(T);
QK.L(T)		= QREF(T);
QI.L(T)		= QREF(T);
QC.L(T)		= QREF(T);
QL.L(G,T)	= LREF(G,T);
PY.L(T)		= PREF(T);
PH.L(T)		= PREF(T);
PFX.L		= 1;
PTAX.L(T)	= PREF(T)*QREF(T)*(TR0*R0+TL0*L0);
PA.L(T)		= PREF(T);
PL.L(T)		= PREF(T);
PC.L(T)		= PREF(T);
PZ.L(G,T)	= PZREF(G,T);
PZT.L(G,A)	= PZREF_T(G,A);
PR.L(T)		= PREF(T);
PK.L(T)		= PREF(T)*(1+RBAR);
PELL.L(G,T)	= PELLREF(G,T);
PZT.L(G,A)	= PZREF_T(G,A);
LOOP(TLAST,PKT.L= PK.L(TLAST) / (1+RBAR));
KT.L		= 1;
KT.LO		= -INF;
GT.L		= 1;
GT.LO		= -INF;
AT.L(G)		= 1;
AT.LO(G)	= -INF;
ZT.L(G,A)	= 1$ZREF_T(G,A);
TAU_TAXY.LO(T)	= -INF;
TAU_TAXY.L(T)	= 0;
TAU_TAXI.LO	= -INF;
TAU_TAXI.L	= 0;
EV.LO		= -INF;
EV.L		= 0;
TAU_LSRA.LO(G)	= -INF;
TAU_LSRA.L(G)	= 0;
NKTLSRA.LO(G)	= -INF;
NKTLSRA.L(G)	= 0;
KTLSRA.LO(G)	= -INF;
KTLSRA.L(G)	= 0;

* Numeraire:

PA.FX(TFIRST)	= 1;

TAU_TAXI.FX$(NOT GBINF) = 0;
TAU_TAXY.FX(T)$GBINF = 0;
GT.FX$(NOT GBINF) = 0;
EV.FX$(NOT LSRA) = 0;

*=====================================================================
* Replicate the benchmark equilibrium:
*=====================================================================


OLG.ITERLIM=0;
$INCLUDE OLG.GEN
SOLVE OLG USING MCP;

*=====================================================================
* Run counterfactual: reduce taxes on capital and labor income:
*=====================================================================

* Parameters for reporting results from counterfactual experiment:

PARAMETERS	
	WCHANGE	Welfare change (% equivalent variation by year of birth),
	WGAIN	Benchmark equiv of long-term welfare gain (1996 USD b.),
	TDEF	Trade deficit (% of baseline level),
	GBDEF	Government budget deficit (% of baseline level),
	KSTOCK	Capital stock (% change from baseline level),
	LSUPPLY	Aggregate labor supply (% change from baseline level),
	CONSTAX	Consumption tax rate (%),
	LSRALEV	LSRA transfer paid (% of baseline full consumption);

* Reduce tax on capital income or tax on labor income by $100 billion:

SETS	SCENARIO		/CAPITAL,LABOR/,
	CAPTAX(SCENARIO)	/CAPITAL/
	LABTAX(SCENARIO)	/LABOR/;

LOOP(SCENARIO,	

	TAU_TAXY.L(T)	= 0; 
	TAU_TAXI.L	= 0; 
	TAXR		= TR0;
	TAXL		= TL0;

	IF (CAPTAX(SCENARIO), TAXR = TR0 - 100*1E-3/R0; ); 
	IF (LABTAX(SCENARIO), TAXL = TL0 - 100*1E-3/L0; ); 

* Solve model

OLG.ITERLIM=10000;
$INCLUDE OLG.GEN
SOLVE OLG USING MCP;

*=====================================================================
* Report results from tax reform
*=====================================================================

	WCHANGE(G,SCENARIO)	= 100 * (QU.L(G) - 1);
	WGAIN(SCENARIO)		= SUM(G$(ORD(G) EQ CARD(G)),(QU.L(G)-1)) 
	*SUM(A, (CC.L(A)+(ETA.L(A)/LAMDA.L)*CELL.L(A)/PREF(A))/QREF(A))/1E-3;

	TDEF(T,SCENARIO)	= 100 * ((M.L(T) - X.L(T))/(PREF(T)*QREF(T)*B0) -1);
	GBDEF(T,SCENARIO)	= 100 * ((QREF(T)*(PA.L(T)*G0+PFX.L*PREF(T)*T0)-IRS.L(T))
	/(PFX.L*PREF(T)*QREF(T)*D0) -1); 
	KSTOCK(T,SCENARIO)	= 100 * (QK.L(T) / QREF(T) - 1);
	LSUPPLY(T,SCENARIO)	= 100 * (LS.L(T) / (L0*QREF(T)) - 1);
	CONSTAX(T,SCENARIO)	= 100 * (TAU_TAXY.L(T)$(NOT GBINF)+TAU_TAXI.L$GBINF);
	LSRALEV(G,SCENARIO)$LSRA= 100 * (TAU_LSRA.L(G) / MREF(G));

* End scenario loop
);

DISPLAY PSHR,QREF,PREF,TR0,TL0,K0,PIREF,EREF,CREF,ELLREF,LREF,ZREF,
	TREF,PELLREF,PZREF,ZREF_T,PREF_T,PZREF_T,MREF,RHO.L,RHO_A,
	OMEGA.L,PELLRATIO,THETAC,THETAD,THETAB,WCHANGE,WGAIN,TDEF,
	GBDEF,KSTOCK,LSUPPLY,CONSTAX,LSRALEV;

*=====================================================================
* Graphics:
*=====================================================================

* Exit if GNUPLOT is not installed

$IF NOT EXIST '%gams.sysdir%\wgnupl32.exe' $EXIT

PARAMETERS
	FIG1	Productivity index (first period = 100) and allocation of time (%),
	FIG2	Income and consumption indices,
	FIG3 	Welfare change by year of birth,
	FIG4	Capital stock and labor supply (% change from baseline);

FIG1(A,"Prod. indx")	= 100 * PI(A);
FIG1(A,"Work time")	= 100 * CL.L(A)/OMEGA.L + 1E-6;
FIG1(A,"Leis. time")	= 100 * CELL.L(A)/OMEGA.L + 1E-6;

FIG2(A,"Consum.")	= 100 * CC.L(A) / SUM(AA$TFIRST(AA),CC.L(AA));
FIG2(A,"L-income")	= 100 * PI(A)*CL.L(A) / SUM(AA$TFIRST(AA),CC.L(AA)) + 1E-6;
FIG2(A,"R-income")	= 100 * (RBAR+DELTA)*THETAC*(CA.L(A)/((1+RBAR)*PREF(A))) 
				/ SUM(AA$TFIRST(AA),CC.L(AA)) + 1E-6;
FIG2(A,"T-income")	= 100 * PSHR(A)*QREF(A)*T0 / SUM(AA$TFIRST(AA),CC.L(AA));

FIG3(G,"Capital")	= WCHANGE(G,"CAPITAL");
FIG3(G,"Labor")		= WCHANGE(G,"LABOR");

FIG4(T,"StockC")	= KSTOCK(T,"CAPITAL");
FIG4(T,"LaborC")	= LSUPPLY(T,"CAPITAL");
FIG4(T,"StockL")	= KSTOCK(T,"LABOR");
FIG4(T,"LaborL")	= LSUPPLY(T,"LABOR");

$SETGLOBAL labels ALABELS
$SETGLOBAL domain A
$SETGLOBAL gp_opt1 "set xlabel 'Age in life-cycle (beginning of period)'"
$LIBINCLUDE PLOT FIG1

$SETGLOBAL gp_opt2 "set ylabel 'index (first year consumption =100)'"
$LIBINCLUDE PLOT FIG2

$SETGLOBAL labels glabels
$SETGLOBAL domain G
$SETGLOBAL gp_opt1 "set xlabel 'Generation'"
$SETGLOBAL gp_opt2 "set yrange [-0.5:0.5]"
$SETGLOBAL gp_opt3 "set ytics 0.1"
$SETGLOBAL gp_opt4 "set ylabel 'Hicksian equivalent variation (%)'"
$LIBINCLUDE PLOT FIG3
$SETGLOBAL gp_opt2
$SETGLOBAL gp_opt3
$SETGLOBAL gp_opt4
$LIBINCLUDE PLOT LSRALEV


$SETGLOBAL labels tlabels
$SETGLOBAL domain t
$SETGLOBAL gp_opt1 "set xlabel 'Year'"
$LIBINCLUDE PLOT FIG4
$LIBINCLUDE PLOT CONSTAX

$SETGLOBAL labels tlabels
$SETGLOBAL domain t
$SETGLOBAL gp_opt1 "set xlabel 'Year'"
$LIBINCLUDE PLOT TDEF

IF (GBINF,
$LIBINCLUDE PLOT GBDEF
);