$TITLE Appendix F: OLG exchange model in MPSGE format

* This model is the same as that in Appendix C except for:
* 1. Option of calibrating to an exogenous baseline consumption profile.
* 2. Option of alternative time intervals between solution periods.
* 3. MPSGE representation of the transition model.

* Select option for derived (XC=0) or exogenous (XC=1) consumption profile.

$SETGLOBAL	XC 0
SCALAR	XC	Flag for exogenous consumption profile	/%XC%/;

* Jump to the desired time structure (1, 2, 3, 4, 5 or 10 year intervals)

$GOTO 1

*=====================================================================
* 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  intervals with each new generation
* being born at the start of a period and living to the age of roughly 55.

*	Annual time intervals:

$LABEL 1
SCALAR	TIMINT		Single period time interval	/1/,
	INIYEAR		Year in with oldest generation was born	/-54/;
SETS	G		Generations in the model	/
	"-54","-53","-52","-51",
	"-50","-49","-48","-47","-46","-45","-44","-43","-42","-41",
	"-40","-39","-38","-37","-36","-35","-34","-33","-32","-31",
	"-30","-29","-28","-27","-26","-25","-24","-23","-22","-21",
	"-20","-19","-18","-17","-16","-15","-14","-13","-12","-11",
	"-10","-9","-8","-7","-6","-5","-4","-3","-2","-1", 0*150/,
	T(G)		Time periods in the model	/ 0*150/,
	A(T)		Typical life-cycle		/0*54/,
	GLABELS(G)	Labels for plots 
	/"-40","-20",0,20,40,60,80,100,120,140/,
	ALABELS(T)	Labels for plots /0,10,20,30,40,50/,
	TLABELS(G)	Labels for plots /0,20,40,60,80,100,120,140/;


$GOTO START

*	2-year time intervals:

$LABEL 2
SCALAR	TIMINT		Single period time interval	/2/,
	INIYEAR		Year in with oldest generation was born /-54/;
SETS	G		Generations in the model	/
	"-54","-52","-50","-48","-46","-44","-42","-40","-38","-36",
	"-34","-32","-30","-28","-26","-24","-22","-20",
	"-18","-16","-14","-12","-10","-8","-6","-4","-2",
	0,  2, 4, 6, 8,10,12,14,16,18,20,22,24,26,28,30,
	32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,
	64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,
	96,98,100,102,104,106,108,110,112,114,116,118,120,122,
	124,126,128,130,132,134,136,138,140,142,144,146,148,150/,
	T(G)		Time periods in the model	/ 
	0,  2, 4, 6, 8,10,12,14,16,18,20,22,24,26,28,30,
	32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,
	64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,
	96,98,100,102,104,106,108,110,112,114,116,118,120,122,
	124,126,128,130,132,134,136,138,140,142,144,146,148,150/,
	A(T)		Typical life-cycle	/
	0,  2, 4, 6, 8,10,12,14,16,18,20,22,24,26,28,30,
	32,34,36,38,40,42,44,46,48,50,52,54 /,
	GLABELS(G)	Labels for plots /"-30",0,30,60,90,120,150/,
	ALABELS(T)	Labels for plots /0,12,24,36,48/,
	TLABELS(G)	Labels for plots /0,30,60,90,120,150/;
$GOTO START

*	3 year time intervals:

$LABEL 3
SCALAR	TIMINT		Single period time interval		/3/,
	INIYEAR		Year in with oldest generation was born /-54/;
SETS	G		Generations in the model		/
	"-54","-51","-48","-45","-42","-39","-36","-33","-30",
	"-27","-24","-21","-18","-15","-12","-9","-6","-3",
	0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,
	60,63,66,69,72,75,78,81,84,87,90,93,96,99,102,105,108,111,
	114,117,120,123,126,129,132,135,138,141,144,147,150/,
	T(G)		Time periods in the model / 
	0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,
	60,63,66,69,72,75,78,81,84,87,90,93,96,99,102,105,108,111,
	114,117,120,123,126,129,132,135,138,141,144,147,150/,
	A(T)		Life-cycle 
	/0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54/,
	ALABELS(T)	Labels for plots /0,12,24,36,48,51,54/,
	GLABELS(G)	Labels for plots /"-30",0,30,60,90,120,150/,
	TLABELS(G)	Labels for plots /0,30,60,90,120,150/;
$GOTO START

*	4 year time intervals:

$LABEL 4
SCALAR	TIMINT		Single period time interval		/4/,
	INIYEAR		Year in with oldest generation was born /-52/;
SETS	G		Generations in the model		/
	"-52","-48","-44","-40","-36","-32","-28","-24","-20","-16",
	"-12","-8","-4",0,4,8,12,16,20,24,28,32,36,40,44,48,52,56,60,
	64,68,72,76,80,84,88,92,96,100,104,108,112,116,120,124,128,
	132,136,140,144,148/,
	T(G)		Time periods in the model		/ 
	0,4,8,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68,72,76,80,
	84,88,92,96,	100,104,108,112,116,120,124,128,132,136,140,
	144,148/,
	A(T)		Life-cycle 
	/0,4,8,12,16,20,24,28,32,36,40,44,48,52/,
	ALABELS(T)	Labels for plots /0,12,24,36,48/,
	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/;
$GOTO START

*	5 year time intervals:

$LABEL 5
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/,
	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/;
$GOTO START

*	10 year time intervals

$LABEL 10
SCALAR	TIMINT		Single period time interval		/10/,
	INIYEAR		Year in with oldest generation was born	/-50/;
SETS	G		Generations in the model 
	/"-50","-40","-30","-20","-10",0,10,20,30,40,50,60,70,80,90,
	100,110,120,130,140,150/,
	T(G)		Time periods in the model		/
	0,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150/,
	A(T)		Life-cycle /0,10,20,30,40,50/,
	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/;

$LABEL START

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

SETS	TFIRST(T)	First period in the model,
	AFIRST(A)	First period in lifecycle,
	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(T)	= YES$(ORD(T) EQ 1);
AFIRST(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/,
	THETA		Exponent in intertemporal utility	/4.00/,
	TDEF0		Base year trade deficit			/0.01/;

* Modify annual rates of change  according to time intervals

SCALAR	RBAR		Periodic interest rate,
	GAMMA		Periodic population growth rate;

RBAR	= (1+RBAR_A)**TIMINT  - 1;
GAMMA	= (1+GAMMA_A)**TIMINT - 1;

*=====================================================================
* 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 price index),
	QREF(G)		Reference quantity path (index of population size),
	OMEGA0(A)	Initial endowment profile;

* 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);

* 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));

* Endowment profile as in Auerbach and Kotlikoff (1987):

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

* Endowment profiles are scaled to an economy-wide level of unity in 
* the base year

OMEGA0(A)	= OMEGA0(A) / SUM(AA, (1+GAMMA)**(1-ORD(AA))*OMEGA0(AA));

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

$IF "%XC%"=="1" $GOTO XCLABEL

*=====================================================================
* Declare calibration model for endogenous consumption profile
*=====================================================================

* Find utility discount rate, RHO, to set implied aggregate consumption
* equal to aggregate endowments plus the trade deficit. 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. 
* Alternatively, since the first-order conditions in this simple setting 
* dictate that consumption is growing over the life cycle at the constant
* rate ((1+RBAR)/(1+RHO))*(1/THETA), we could derive RHO analytically.

VARIABLES	
	RHO	! Period utility discount rate;

POSITIVE VARIABLES
	CC(A)	! Consumption profile of reference generation,
	LAMDA	! Shadow price of income (present value utils);

EQUATIONS
	EQC(A)	! First order condition for consumption,
	EQCCC	! Base year aggregate consumption,
	EQLAMDA	! First order condition for price of income;

* First order conditions.

EQC(A)..	LAMDA*PREF(A) =E= (1+RHO)**(1-ORD(A))*CC(A)**(-THETA);
EQLAMDA..	SUM(A,PREF(A)*CC(A)) =E= SUM(A,PREF(A)*OMEGA0(A));

* Aggregate consumption in the base year is implied by the consumption
* profile of the generation born in year 0 since the steady state 
* assumption determines the relative sizes of each generation. We 
* require that aggregate consumption equals the quantity of aggregate 
* endowments (unity) plus the trade deficit.

EQCCC..		 SUM(A,CC(A)/QREF(A)) =E= 1 + TDEF0;

* Associate variables with equations.

MODEL BENCH	/EQC.CC, EQLAMDA.LAMDA, EQCCC.RHO/;

* Initialize variables and set bounds to prevent operation errors.
* Note that because changing the time interval changes the implies
* value of RHO it may be necessary to adjust the initialization
* of this variable.

RHO.L		= 0.01;
RHO.LO		= -0.99;
CC.L(A)		= 1/CARD(A);
CC.LO(A)	= 1E-9;
LAMDA.L		= 1;
LAMDA.LO	= 1E-9;

* Solve calibration model.

BENCH.ITERLIM=50000;
SOLVE BENCH USING MCP;

* Derived utility discount rate on an annual basis.

PARAMETER RHO_A	Annual utility discount rate w exog cons profile (%);

RHO_A		= 100 * ((1+RHO.L)**(1/TIMINT) - 1); DISPLAY RHO_A;

$IF NOT "%XC%"=="1" $GOTO SKIPXC

*=====================================================================
* Declare calibration model for exogenous consumption profile
*=====================================================================

$LABEL XCLABEL

* Impose a consumption profile with linear growth.

PARAMETER  CINDEX(A)	Benchmark consumption profile index;

CINDEX(A) =  1 + 0.01*AGE(A);

* Find utility discount rates, RHOXC, to fix consumption growth rates 
* over the life cycle at the level implied by the exogenous consumption 
* profile. In this case we calibrate the benchmark trade deficit to 
* ensure consistency between aggregate consumption and aggregate 
* supply.

VARIABLES	
	RHOXC(A)	! Period utility discount rate,
	CTDEF		! Base year trade deficit;

POSITIVE VARIABLES
	CC(A)		! Consumption profile of reference generation,
	LAMDA		! Shadow price of income (present value utils);

EQUATIONS
	EQC(A)		! First order condition for consumption,
	EQLAMDA		! First order condition for price of income,
	EQCG		! Fix consumption profile,
	EQCCC		! Fix base year aggregate consumption;

* First order conditions.

EQC(A)..	LAMDA*PREF(A) =E= (1+RHOXC(A))**(1-ORD(A))*CC(A)**(-THETA);
EQLAMDA..	SUM(A,PREF(A)*CC(A)) =E= SUM(A,PREF(A)*OMEGA0(A));

* Aggregate consumption in the base year is implied by the consumption
* profile of the generation born in year 0 since the steady state 
* assumption determines the relative sizes of each generation. We 
* require that aggregate consumption equals the quantity of aggregate 
* endowments (unity) plus the trade deficit.

EQCCC..		 SUM(A,CC(A)/QREF(A)) =E= 1 + CTDEF;

* The growth rate of consumption over the life cycle is given by 
* the exogenous consumption profile.

EQCG(A)..	CC(A)=E=CINDEX(A)*CC("0");

* Associate variables with equations.

MODEL BENCH	/EQC.CC, EQLAMDA.LAMDA, EQCCC.CTDEF, EQCG.RHOXC/;

* No discounting of period zero:

RHOXC.FX("0")   = 1;

* Initialize variables and set bounds to prevent operation errors.
* Note that because changing the time interval changes the implies
* value of RHO it may be necessary to adjust the initialization
* of this variable.

RHOXC.L(A)	= 0.01;
RHOXC.LO(A)	= -0.99;
CC.L(A)		= 1/CARD(A);
CC.LO(A)	= 1E-9;
LAMDA.L		= 1;
LAMDA.LO	= 1E-9;

* Solve calibration model.

BENCH.ITERLIM=50000;
SOLVE BENCH USING MCP;

* Derived  trade deficit and utility discount rates on an annual basis.

PARAMETER RHOXC_A(A) Annual utility discount rate w endog cons profile (%);

RHOXC_A(A)	= 100 * ((1+RHOXC.L(A))**(1/TIMINT) - 1)$(ORD(A) GT 1); 
TDEF0		= CTDEF.L;

DISPLAY RHOXC_A, TDEF0;

$LABEL SKIPXC
*=====================================================================
* Use endowments and the calibrated consumption profile for generation 
* 0 to install baseline values for all generations
*=====================================================================

PARAMETERS	
	EREF(G,T)	Baseline endowment profile,
	CREF(G,T)	Baseline consumption profile,
	PREF_T(A)	Baseline post-terminal price path,
	CREF_T(G,A)	Baseline post-terminal consumption profile,
	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),
	EREF(G,T) = QREF(G) * OMEGA0(A);
	CREF(G,T) = QREF(G) * CC.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.

* 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); );

* Consumption profiles in post-terminal periods for generation G at age 
* AA 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)),
	CREF_T(G,AA)$(AGE(AA)+YEAR(TLAST) EQ AGE(A)+YEAR(G))  
	= CC.L(A) * QREF(G); );

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

MREF(G)	= SUM(T, PREF(T)*CREF(G,T)) + SUM(A,  PREF_T(A)*CREF_T(G,A)); 

*=====================================================================
* Use endowments and the calibrated consumption profiles for generation 
* 0 to back out the evolution of asset holdings and distinguish between
* domestic and foreign debt
*=====================================================================

PARAMETERS
	ASSETS(A)	Present value of generation 0 assets over life cycle,
	MA(A)		Assets held in year 0 by age of generation,
	ASSETH		Positive asset holdings by age in year 0,
	DEBT		Net debt by age in year 0;

SCALAR	THETAD		Ratio of total assets to total debt;

* The present value of assets equals the sum of the value of endowments 
* less consumption in all previous periods of the life cycle. The asset 
* profile of the representative generation can then be used to find 
* the distribution of asset holdings across generations alive in the 
* base year.

ASSETS(A) = SUM(AA$(ORD(AA) LT ORD(A)), PREF(AA)*(OMEGA0(AA) - CC.L(AA)));
MA(A) = ASSETS(A)/(QREF(A)*PREF(A));

* We assume that negative asset positions reflect holdings of both 
* domestic and foreign debt, while positive asset positions reflect 
* holdings of domestic assets. We assume that all age groups with 
* negative assets hold foreign and domestic debt in the same proportion 
* which means that we can use the ratio of total assets to total debt 
* to decompose the asset 
* holdings by type.

THETAD	= -SUM(A$(MA(A) GT 0), MA(A))/ SUM(A$(MA(A) LT 0), MA(A));

ASSETH(A,"DOMESTIC")$(MA(A) GT 0)	= MA(A);
DEBT(A,"DOMESTIC")$(MA(A) LT 0)		= -MA(A)*THETAD;
DEBT(A,"FOREIGN")$(MA(A) LT 0)		= -MA(A)*(1-THETAD);

* We model baseline assets and debt positions as inital endowments for 
* generations alive in year 0.

PARAMETERS
	DASSET(G)	Initial endowment of domestic assets,
	FASSET(G)	Initial endowment of foreign assets;

DASSET(G) = SUM(MAPG(G,A,"0"), ASSETH(A,"DOMESTIC") - DEBT(A,"DOMESTIC"));
FASSET(G) = SUM(MAPG(G,A,"0"), - DEBT(A,"FOREIGN"));


*=====================================================================
*  Model in GAMS/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 en
*  exogenous change in the endowment profile
*=====================================================================

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

$ONTEXT
$MODEL:EXCHANGE

* 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:
	U(G)			! Utility
	X(T)			! Export
	M(T)			! Import

* 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:
	PC(T)			! Price of private consumption
	PCT(G,A)$CREF_T(G,A)	! Price of post-terminal consumption of goods
	PU(G)			! Price of intertemporal utility
	PFX			! Price of foreign exchange

* 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.

$CONSUMERS:
	RA(G)			! Representative agents by generation

* Declare auxiliary variables. These are endogenous variables associated 
* with model constraints that relate the transition to the steady state.

$AUXILIARY:
	CT(G,A)$CREF_T(G,A)	! Post-terminal consumption of goods
	AT(G)$ATGEN(G)		! Terminal assets 

*=====================================================================
* $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
*=====================================================================

* Utility is treated of as a commodity demanded by the different 
* generations which implies that the utility function is modeled as any 
* other production activity. The activity level here is initialized at 
* unity implying an overall output level equal to the present value of
* consumption, MREF(G).

$PROD:U(G) s:(1/THETA)
	O:PU(G)		Q:MREF(G)
	I:PC(T)		Q:CREF(G,T)		P:PREF(T)
	I:PCT(G,A)	Q:CREF_T(G,A)		P:PREF_T(A)

* This block models the level of imports in each year. The assumption 
* of a small open economy and perfect capital mobility implies that the 
* price of imports is constant in current value terms. We therefore do 
* not need to distinguish between years, but only operate with a single 
* present value price for foreign exchange. This activity is initialized
* at the reference quantity path implying an overall output level equal 
* to the baseline trade deficit.

$PROD:M(T)
	O:PC(T)		Q:TDEF0
	I:PFX		Q:(TDEF0*PREF(T))
 
* There are no exports in the baseline so this activity is initialized at
* zero and the input assignments ensure that it is marginally unprofitable.

$PROD:X(T)
	O:PFX		Q:(TDEF0*PREF(T))		
	I:PC(T)		Q:TDEF0

*=====================================================================
* $REPORT blocks recover the level of inputs (I: fields) in production 
* activities (PROD: fields). V: fields declare the variables
*=====================================================================

* Store consumption in year T by generation G.

$REPORT:
	V:C(G,T)$CREF(G,T)	 I:PC(T)	PROD:U(G)

*=====================================================================
* $DEMAND blocks represent demands (D: fields) and endowments (E: fields) 
* of the consumers in the model. Endowments may be associated with 
* endogenous auxiliary variables (R: fields)
*=====================================================================

* Each generation demands "utility" and is endowed with an amount of the 
* consumption good in each period. In addition, generations alive in the
* initial period are endowed with domestic and foreign assets. To 
* terminate the model generations alive in the terminal period are required 
* to leave an amount of assets and are also endowed with goods for consumption 
* in the post-terminal periods.

$DEMAND:RA(G)
	D:PU(G)		Q:MREF(G)
	E:PC(T)		Q:EREF(G,T)
	E:PC(TFIRST)	Q:DASSET(G)
	E:PFX		Q:FASSET(G)
	E:PFX$ATGEN(G)	Q:1		R:AT(G)	
	E:PCT(G,A)	Q:CREF_T(G,A)	R:CT(G,A)
 
* Select terminal asset position so that all generations living past 
* the terminal period achieve the same equivalent variation.

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

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

$CONSTRAINT:CT(G,A)$CREF_T(G,A)
	SUM(TLAST, PC(TLAST)) =E= PCT(G,A)*(1+RBAR)**(ORD(A)-1);

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

$OFFTEXT
$SYSINCLUDE MPSGESET EXCHANGE

$LABEL SOLVE

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

X.L(T)		= 0;
M.L(T)		= QREF(T);
PC.L(T)		= PREF(T);
PCT.L(G,A)	= PREF_T(A);
CT.L(G,A)	= 1$CREF_T(G,A);
AT.L(G)		= SUM(T,CREF(G,T)*PREF(T))-SUM(T,EREF(G,T)*PREF(T))$ATGEN(G);
AT.LO(G)	= -INF;

* Numeraire:

PC.FX(TFIRST)	= 1;

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

EXCHANGE.ITERLIM=0;
$INCLUDE EXCHANGE.GEN
SOLVE EXCHANGE USING MCP;
DISPLAY "Benchmark tolerance CHK:",EXCHANGE.OBJVAL;

*=====================================================================
* Run counterfactual
*=====================================================================

* Modify the endowment profile, and scale it to maintain an economy-wide
* level of unity in the base year.

PARAMETER	OMEGA(A)	Counterfactual endowment profile;

OMEGA(A)	= EXP(4.47 + 0.02*AGE(A) - 0.0007*(AGE(A))**2);
OMEGA(A)	= OMEGA(A) / SUM(AA, (1+GAMMA)**(1-ORD(AA)) * OMEGA(AA));

LOOP(A,EREF(G,T)$MAPG(G,A,T) = QREF(G) * OMEGA(A); );

* Solve the model.

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

* Parameters for reporting results from the counterfactual experiment.

PARAMETERS	
	WCHANGE	Welfare change (% equivalent variation by year of birth),
	TDEF	Trade deficit (change from baseline level);

* Due to production activities being homogenous of degree 1, the 
* equivalent variation is the percentage change in output from sector U. 
* The trade deficit in year T is the difference between aggregate 
* consumption and aggregate endowment.

WCHANGE(G)	= 100 * (U.L(G) - 1);
TDEF(T)		= TDEF0*(M.L(T)-X.L(T)) - QREF(T)*TDEF0;

*=====================================================================
* Display statements
*=====================================================================

DISPLAY YEAR, AGE, PREF, PREF_T, QREF, OMEGA0, OMEGA, EREF, CREF, CREF_T, 
	MREF, ASSETS, MA, ASSETH, DEBT, DASSET, FASSET, WCHANGE, TDEF;

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

* Exit if GNUPLOT is not installed

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

SCALAR	ZERO	Small number to avoid zeros in plots	/1E-6/;

PARAMETERS
	FIG1	Endowments and calibrated consumption,
	FIG2	Endowment profiles;

FIG1(A,"Endowment")	= ZERO + 100*OMEGA0(A) / SUM(AFIRST,CC.L(AFIRST));
FIG1(A,"Consum.")	= ZERO + 100*CC.L(A)   / SUM(AFIRST,CC.L(AFIRST));
FIG2(A,"Old")		= ZERO + 100*OMEGA0(A) / SUM(AFIRST(AA),CC.L(AFIRST));
FIG2(A,"New")		= ZERO + 100*OMEGA(A)  / SUM(AFIRST(AA),CC.L(AFIRST));

$SETGLOBAL labels ALABELS
$SETGLOBAL gp_opt1 "set xlabel 'Age in life cycle (beginning of period)'"
$IF "%XC%"=="1" $GOTO SKIPRANGE
$SETGLOBAL gp_opt2 "set ylabel 'first period consumption = 100'"
$SETGLOBAL gp_opt3 "set yrange [60:130]"
$LABEL SKIPRANGE
$LIBINCLUDE PLOT FIG1

$SETGLOBAL gp_opt3
$LIBINCLUDE PLOT FIG2

$SETGLOBAL labels GLABELS
$SETGLOBAL gp_opt1 "set xlabel 'Generation'"
$LIBINCLUDE PLOT WCHANGE

$SETGLOBAL labels TLABELS
$SETGLOBAL gp_opt1 "set xlabel 'Year'"
$LIBINCLUDE PLOT TDEF