'Author: Nwabisa Florence Ndzama
'Corvinus Univeristy of Budapest




!read = 1 
!Nwabisa =1'0
!Zsolt = 0 '1
!stop_after_read = 0

if !read = 1 then
'----------------------------------------------------------------------------------
 close CA_forecast_sustainability_probabilities.wf1
  wfcreate(wf=CA_forecast_sustainability_probabilities, page = Read) a 1948 2030

  smpl 1948 2029   'Actual data starts from 1960. The "period" 1948 -1959 are data decsription colums from the Excel spreadsheet. 1955=0, its the scale (one of descriptive items.)
  For %sheet CA GDP_growth Trade_Openness REER_ZD Budget_balance  OAD 
       if !Nwabisa = 1 then
           read(c3,s={%sheet},t)"File Path" 204   ' 204 is the number of observations (countries + regions in the sample) from excel file
         endif
 
        if !Zsolt = 1 then
    '      read(c3,s={%sheet},t) "C:\Users\Zsolt\Dropbox\2023-04 CA reversals\Data\WEO_data_for_probit.xls" 204
           read(c3,s={%sheet},t)"File Path" 204   ' 204 is the number of observations (countries + regions in the sample) from excel file

          endif   
  Next ' %sheet
'stop
  ' these series are not included in the dataset; we create them (with NA values) to eliminate some error messages when this code is running
  series REER_ZD_SOM 
  series REER_ZD_TLS
  series REER_ZD_PRI 

'1948 value in the excel file is the numerical code of the country. To avoid confusion of these numerical codes with actual data, we create a new sheet for the sample 1980-2027 and copy all data there:
Pagecreate(page=Annual) a 1960 2029   '1977- 2028  , Starting few years before our year (1983) of interest (due to data for all other variables in the analysis)
copy Read\* Annual\*

if !stop_after_read = 1 then
     Statusline Stopped after reading the data
      STOP 
endif

endif !read=1

'STOP
group a_group_BUDGET_BALANCE BUDGET_BALANCE*
'show a_group_BUDGET_BALANCE
group a_group_ca  ca*
'show a_group_ca
group a_group_GDP_growth GDP_growth*
'show a_group_GDP_growth
group a_group_Trade_Openness Trade_Openness*
'show a_group_Trade_Openness
group a_group_OAD OAD*
'show a_group_OAD
group a_group_REER_ZD REER_ZD*
'show a_group_REER_ZD


'stop

'Pagecreate(page=distributionVAR)  1000000
!forc_period_ahead =5'  1 2 3 4 5   number of periods ahead for which out-of-sample forecasts will be made from each date. For Annual DATA, 5 means 5 years.
!n = 1000000 '1000 ' The number of observations (e.g. the number of forecasts made)
!threshold = -8 '-8   '-5 '-4 '-2   ' The threshold value: this code calculates the probability that an observation is BELOW this value. 

'=================================================================================================
'Nwabisa 22/06/2024 MODEL TYPE
%forecast_model = "STVAR"  ' AR, VAR, BVAR,vecm, BTVC, STVAR, SWTVAR
'====================================================================================================

'Pageselect Annual
table table_countries

   '!i=0
    !c=0
For %c AUS 'FRA GRC IRL ESP 'BGR CYP HUN ITA PRT ROU 'FRA GRC IRL PRT ROU ESP 'AUS 'CHL KOR MEX USA 'ZAF 'HUN MYS' GRC  'LVA ISR HUN   USA 'DEU 'IND IDN MEX HUN RUS ZAF AUS GBR FRA DEU USA 'CHN	'Prelimenary sample, Chapter 5
'For %c GRC 'HUN GRC 'IRL MYS ZAF 'HUN 'MYS 'HUN	' for this sample the model excludes the budget balance variable due to data unavailability , vcem model : we exclude TO and BB for Hungary due to Data limitations (error message: insufficient parameters)
  
  'For %c 	 ALB  ARG	ARM	AUS	AUT	AZE	BGD	BLR	BEL	BGR BOL	BRA	BRN	BDI	CPV	KHM	CMR	CAN	CAF	TCD	CHL	COL	CRI	CIV	CYP	DNK	DOM DZA ECU	EGY	SLV	FJI	FIN	FRA	GAB	DEU	GHA	GRC	GTM	GIN	HTI	HND	HKG	HUN	ISL	IND	IDN	IRL	ITA    KEN	KOR MDG	MYS	MLI	MUS	MEX	MNG	MAR	NAM	NPL	NLD	NIC	NER	MKD	NOR	PAK	PRY	PER	PHL	PRT	ROU	RUS	RWA	SAU	SEN	SYC	SGP	ZAF	ESP SDN	SWE	CHE	TZA	THA	BHS	GMB	TGO	TUN	TUR	UGA	UKR	GBR	USA  'Extended SAMPLE, CHAPTER 5
     'BGR JAM JOR KGZ LKA

'UPDATED FULL/EXTENDED SAMPLE - 8/10/2024
  
  ' For %c  ALB DZA	ARG	ARM	AUS	AUT	AZE	BGD	BLR	BEL	BLZ	BOL	BRA	BRN	BGR	BDI	CPV	KHM	CMR	CAN	CAF	TCD	CHL	COL	CRI	CIV	CYP	DNK	DOM	ECU	EGY	SLV	FJI	FIN	FRA GAB DEU	GHA	GRC	GTM	GIN	HTI	HND	HKG	HUN	ISL	IND	IDN	IRL	ITA	JAM	JOR	KEN	KOR	KGZ	MDG	MYS	MLI	MUS	MEX	MNG	MAR	NAM	NPL	NLD	NIC	NER	MKD	NOR	PAK	PRY	PER	PHL	PRT	ROU	RUS	RWA	SAU	SEN	SYC	SGP	ZAF	ESP	LKA	SDN	SWE	CHE	TZA	THA	BHS	GMB	TGO	TUN	TUR	UGA	UKR	GBR	USA

'For %c BWA  'NAM SWZ ZAF 'BWA LSO BGR USA 'CYP FRA GRC HUN IRL ITA PRT ROU ESP 'BGR 
    ' !i=!i+1
      !c=!c+1
      Pageselect Annual
	 table_countries(!c,1) = %c
  'Next '%c!

%start_est_date = "1980"  ' the first date for the estimation of models
%start_forecast_date =  "2005" '2005 is  the first date for which a forecast will be made, therefore the recursive estimation goes upto 2004, that is 1980-2004
%last_Y_obs = "2023"  ' the last observation of the sample period
!forc_period_ahead = 5' 1 2 3 4 5   number of periods for which out-of-sample forecasts will be made. if its Annual DATA, 5 means 5 years. 

!start_forecast_date = @val(%start_forecast_date)
!last_Y_obs = @val(%last_Y_obs)
!num_forecasts = !last_Y_obs - !start_forecast_date  ' e.g. if the %start_forecast_date =  "2017" and %last_Y_obs = "2018" , then !num_forecasts=1
' !num_forecasts = !last_Y_obs - !start_forecast_date +1




'------------------------------------------------------------------------------------------------------------------------------------------------------------
'SMOOTH TRANSITION VAR MODEL (ST-VAR)

       ' Step 1: Estimate the Model   'ADDED ON 09/10/2024
'Strength: Unlike traditional linear VAR models, ST-VAR allows for nonlinear dynamics and captures abprut changes in a times series.
'------------------------------------------------------------------------------------------------------------------------------------------------------------
 if %forecast_model = "STVAR" then




   Pageselect Annual
table table_probabilitiesSTVAR 'Create a table that collects the probability results
table_probabilitiesSTVAR(1,1) = "This table shows the probability that the CA balance will be lower than a threshold value"
table_probabilitiesSTVAR(2,1) = "model: "
table_probabilitiesSTVAR(2,2) = "STVAR"
table_probabilitiesSTVAR(3,1) = "number of forecasts (!n): "
table_probabilitiesSTVAR(3,2) = !n
table_probabilitiesSTVAR(4,1) = "threshold: "
table_probabilitiesSTVAR(4,2) = !threshold

table_probabilitiesSTVAR(5,1) = "Forecast Period: "
table_probabilitiesSTVAR(5,2) = "1 year ahead"
table_probabilitiesSTVAR(5,3) = "2 year ahead"
table_probabilitiesSTVAR(5,4) = "3 year ahead"
table_probabilitiesSTVAR(5,5) = "4 year ahead"
table_probabilitiesSTVAR(5,6) = "5 year ahead"


table_probabilitiesSTVAR(6,1) = "country"
table_probabilitiesSTVAR(6,2) = "probability"
table_probabilitiesSTVAR(6,3) = "probability"
table_probabilitiesSTVAR(6,4) = "probability"
table_probabilitiesSTVAR(6,5) = "probability"
table_probabilitiesSTVAR(6,6) = "probability"

' Zsolt 01/06/2024: important to add this info to the table, so you'll surely know for which period the analysis is made
table_probabilitiesSTVAR(5,8) = "%start_est_date"
table_probabilitiesSTVAR(5,9) = "%start_forecast_date"
table_probabilitiesSTVAR(5,10) = "%last_Y_obs"
       

' 24 Aug 2024: I added the CA balance value at %last_Y_obs, and the forecasts for the next 5 years, which help to the check visually if estimated probabilities look correct or not

table_probabilitiesSTVAR(4,12) = "Actual CA balance"
table_probabilitiesSTVAR(5,12) = "%last_Y_obs"
table_probabilitiesSTVAR(4,13) = "Forecast CA balance"
table_probabilitiesSTVAR(5,13) = "%last_Y_obs+1"
table_probabilitiesSTVAR(4,14) = "Forecast CA balance"
table_probabilitiesSTVAR(5,14) = "%last_Y_obs+2"
table_probabilitiesSTVAR(4,15) = "Forecast CA balance"
table_probabilitiesSTVAR(5,15) = "%last_Y_obs+3"
table_probabilitiesSTVAR(4,16) = "Forecast CA balance"
table_probabilitiesSTVAR(5,16) = "%last_Y_obs+4"
table_probabilitiesSTVAR(4,17) = "Forecast CA balance"
table_probabilitiesSTVAR(5,17) = "%last_Y_obs+5"

' Zsolt 01/06/2024: for each country, we create a separate page, e.g. for South Africa the name of the page will be:  distributionVAR_ZAF
%pagename = "distributionSTVAR" + "_" + %c

' Zsolt 01/06/2024: we add this info to the table, so you'll surely know for which period the analysis is made 
table_probabilitiesSTVAR(6+!c,1) = %c
table_probabilitiesSTVAR(6+!c,8) = %start_est_date
table_probabilitiesSTVAR(6+!c,9) = %start_forecast_date
table_probabilitiesSTVAR(6+!c,10) = %last_Y_obs



Pagecreate(page={%pagename}) U !n

 Pageselect Annual

'var estimates
        For !smpl = 0 to !num_forecasts 


          smpl %start_est_date %start_forecast_date-1+!smpl ' so when %start_forecast_date =  "2017" and !smpl = 0, you estimate the model till 2016 and make a forecast for 2017
        'var ca_{%c}_var06.threhold(method=fixedseq, type=smooth)  1 1 CA_{%c} GDP_GROWTH_{%c} REER_ZD_{%c} OAD_{%c} TRADE_OPENNESS_{%c} BUDGET_BALANCE_{%c} @thresh 6 
         'equation ca_{%c}_var06.threhold(method=fixedseq, type=smooth) CA_{%c} GDP_GROWTH_{%c} REER_ZD_{%c} OAD_{%c} TRADE_OPENNESS_{%c} BUDGET_BALANCE_{%c} @thresh 6 '' NOTE: I changed the lag lenght to 2 so that fewer parameters have to be estimated, which allows a longer out-of-sample forecast period
'equation eq1.threshold(method=fixedseq, type=discrete) ss_transf c ss_transf(-1 to -11) @thresh 2
'show ca_{%c}_var06


          '================CREATING A SYSTEM OF EQUATIONS TO STVAR===========================================
        system STVAR

       STVAR.append CA_{%c} = c(1)+c(2)*CA_{%c}(-1)+c(3)*GDP_GROWTH_{%c}(-1)+(1-EXP( -c(4)*(CA_{%c}(-1)-c(5))^2 )  )*(c(6)+c(7)*CA_{%c}(-1)+c(8)*GDP_GROWTH_{%c}(-1))
       STVAR.append GDP_GROWTH_{%c} = C(9)+C(10)*GDP_GROWTH_{%c}(-1)+c(11)*CA_{%c}(-1)+(1-EXP( -c(4)*(GDP_GROWTH_{%c}(-1)-c(5))^2 ))*(c(12)+c(13)*GDP_GROWTH_{%c}(-1)+c(14)*CA_{%c}(-1))
       STVAR.append CA_{%c}(-1) GDP_GROWTH_{%c}(-1)
       STVAR.nls ' estimate the parameters of a model using nonlinear least squares.
       show STVAR.results

        Next !smpl
   endif     '%forecast_model = "STVAR" then
Next '!c
Stop      




