'Chapter 4 Current Account balance
'09/05/2023

' This code estimates, forecasts of the Current Account Balance, and calculates forecast errors for several countries.
' This code can be used to check the forecasting performance of alternative methods and for alternative forecasting horizons.


' Structure of the code:
'   1. fetches data from database and reads data from excel
'   2. Estimates and calculates out-of-sample forecasts for the Current Account Bakance (using the selected method)
'   3. calculates out-of-sample forecast errors and the following statistics (Ross, 2014):
'    -A probability integral transform (PIT): is the cumulative probability evaluated at the actual, realized value of the target variable. It measures the likelihood of observing a value less than the actual realized value, where the probability is measured by the density forecast.
'    -Uniformity: The uniformity property means that the probability that the realized value is higher (lower) than the forecasted value is the same (on average over time) no matter whether we consider high realizations or low realizations of the variable we are forecasting. The test for uniformity may involve plotting the empirical distribution of the PIT (or histogram).
'    - Independence   
'    -Identical distribution
'    -Evaluating the “relative” performance of density forecast
'4. tests whether forecasts are unbiased?
'   5. creates a table with the forecast statistics?

%CA_forecast_model1 = "AR" 'AR" ,stochatsic models TO BE ADDED later
 
%AR_type = "AR1" ' if AR model, its order

!forc_period_ahead =  20 '  number of periods for which out-of-sample forecasts will be made. QUARTERELY DATA

%start_est_date = "1980"  ' the first date for the estimation of models
%start_forecast_date =  "2000" ' the first date for which a forecast will be made (from the preceding quarter, i.e. if %start_forecast_date =  "2015Q1", then we use actual data up to 2014Q4 and caclulate forecasts for 2015Q1, 2015Q2, ...
%last_Y_obs = "2022"  ' the last observation of the sample period

!est_recursive = 1  ' =1 if recursice estimation
!est_rolling = 0        ' =1 if rolling estimation
!estimation_obs = 60  ' the number of observations for rolling estimation 

!read = 1 ' Create a workfile and read data
!Nwabisa =1
!Zsolt = 0

!stop_after_read = 0

if !read = 1 then
'--------------------------------------------------------------
 close CA_reversals.wf1
  wfcreate(wf=CA_reversals, page = Read) a 1971 2030

  smpl 1971 2027

  For %sheet CA Population GDP_cap_PPP GNI_pc Inflation GDP_growth Budget_balance Public_debt Savings Investments REER_ZD Reserves_M_Cover Reserves_to_ExDebt Trade_Openness  Interest_payment FDI_net_inflows Consumption_growth Terms_of_Trade External_Debt Short_term_debt  Debt_Service OECD_growth Real_interest_rate_USA RIR_BL_INFL_USA 'REER
       if !Nwabisa = 1 then
          read(c3,s={%sheet},t)"C:\Users\P519987\Desktop\CORVINUS\CORVINUS\PhD\DATA\Thesis Data\Eviews\WEO_data_for_probit.xls" 204
         endif

        if !Zsolt = 1 then
          read(c3,s={%sheet},t) "C:\Users\Zsolt\Documents\Data\OKONOMET\Temavezetes\2020 Nwabisa Florence Ndzama\WEO_data_for_probit.xls" 204
         endif   
  Next ' %sheet

  ' 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


endif !read=1
'STOP
'1971 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 1980 2027
copy Read\* Annual\*

group a_group_ca ca*
'STOP
'-------------------------------------------------------------------------------

Pageselect Annual
table table_countries

  !i=0
   For %c BRA CHN	IND RUS ZAF	
	 !i=!i+1
	 table_countries(!i,1) = %c
   Next '%c!

!start_forecast_date = @dtoo(%start_forecast_date)


smpl %start_forecast_date %last_Y_obs
d temp*         
genr temp = 1 
!forecast_length = @obs(temp) ' WE HAVE SET THE SAMPLE BETWEEN %start_forecast_date AND %last_Q_obs AND HERE WE GET THE NUMBER OF OBSERVATIONS IN THIS SAMPLE
smpl @all

if !est_recursive = 1 then
     %est_method = "Recursive estimation"
endif
if !est_rolling =1 then
     %est_method = "Rolling estimation " + @str(!estimation_obs)
endif
'STOP
' --------------------------------------------------------------------
' ---------------- MAIN SMPL LOOP --------------------------
' --------------------------------------------------------------------
For !smpl = 0 to !forecast_length-1
' --------------------------------------------------------------------
' --------------------------------------------------------------------
!current_forecast_date = !start_forecast_date + !smpl  ' The first quarter for which we make a forecast
%current_forecast_date = @otod(!current_forecast_date) 'THIS IS A STRING WHICH INCLUDES THE CURRENT FORECAST DATE
!current_forecast_date_m1 = !current_forecast_date - 1 ' The year before forecast start date; "m1"= minus 1, i.e. the last date for which actual data is used. In this case "1989" I SUGGEST TO USE "M" FOR MINUS
%current_forecast_date_m1 = @otod(!current_forecast_date_m1)


Statusline {%fx}    Start forecast date {%start_forecast_date}   Smpl = !smpl   {%current_forecast_date}

' ----------------------------------------------------------------------------------------------------
' --------- This is the estimation sample; note: !smpl starts from zero  (WHY) --------- IN THIS CASE, THE FIRST FORECAST DATE %start_forecast_date+!smpl = %start_forecast_date
' ----------------------------------------------------------------------------------------------------
if !est_recursive = 1 then
   smpl %start_est_date %start_forecast_date+!smpl-1
endif

if !est_rolling = 1 then
   smpl %start_forecast_date+!smpl-1-!estimation_obs %start_forecast_date+!smpl-1
endif


'************************************************************************************************************************************
' Setting up the models and estimating equations when needed, for all countries, for a particular %current_forecast_date

For !c = 1 to 5   'total number of rows for selected countries
	  %c = table_countries(!c,1)  'table with 196 rows and 1 column

      if %CA_forecast_model1 = "AR" then
     ' Model assuming an AR(p) model for CAB(% of GDP)
        if %AR_type = "AR1" then   'USED AS AR BENCHMARK
           equation eq_CA_{%c}.ls CA_{%c} c CA_{%c}(-1)
           eq_CA_{%c}.makemodel(model_CA_AR_{%c})
        endif
	   if %AR_type = "AR2" then
           equation eq_CA_{%c}.ls CA_{%c} c CA_{%c}(-1)  CA_{%c}(-2)
           eq_CA_{%c}.makemodel(model_CA_AR_{%c})
        endif
        if %AR_type = "AR3" then
           equation eq_CAB_{%c}.ls CA_{%c} c CA_{%c}(-1)  CA_{%c}(-2) CA_{%c}(-3)
           eq_CA_{%c}.makemodel(model_CA_AR_{%c})
        endif
        if %AR_type = "AR4" then   
           equation eq_CA_{%c}.ls CA_{%c} c CA_{%c}(-1)  CA_{%c}(-2) CA_{%c}(-3) CA_{%c}(-4)
           eq_CA_{%c}.makemodel(model_CA_AR_{%c})
        endif
	  if %AR_type = "AR5" then
           equation eq_CA_{%c}.ls CA_{%c} c CA_{%c}(-1)  CA_{%c}(-2) CA_{%c}(-3) CA_{%c}(-4) CA_{%c}(-5)
           eq_CA_{%c}.makemodel(model_CA_AR_{%c})
        endif
        if %AR_type = "AR6" then
           equation eq_CA_{%c}.ls CA_{%c} c CA_{%c}(-1)  CA_{%c}(-2) CA_{%c}(-3) CA_{%c}(-4) CA_{%c}(-5) CA_{%c}(-6)
           eq_CA_{%c}.makemodel(model_CA_AR_{%c})
        endif
      endif ' %CA_forecast_model1 = "AR"
Next '!c
'STOP
' -------------------------------------------------------------------------------------------------------
' --- We calculate CA forecasts for !forc_period_ahead---- using probability density forecast
' -------------------------------------------------------------------------------------------------------
smpl %start_forecast_date+!smpl %start_forecast_date+!smpl+!forc_period_ahead


For !c = 1 to 5
      %c = table_countries(!c,1)  

	 d CA_{%c}_0*  ' Note: when you solve a model, the new series resultig from the solution will have a "_0" at the end of its name. Just in case, before solving a model, it's better to delete the previous solution. Otherwise, if for any reason the model cannot be solved, but a cpi_{%c}_0 exists in the workfile, you might erroneously think that this is the solution for the current model.

     if %CA_forecast_model1 = "AR" then
           solve model_CA_AR_{%c}    'All the preceding AR_types? NO, THERE WERE 6 IFs SUCH AS  if %AR_type = "AR1" then, SO THE AR TYPE SET FOR THE STRING %AR_type WAS ADDED TO THE MODEL model_cpi_AR_{%c}, SEE ABOVE
           genr CA_{%c}_0_AR1 = CA_{%c}_0   
           'scalar caf = @dnorm(CA_{%c}_0)  'or use this one "model_ca_ar_bra.eqs"

      endif
Next '!c 
'STOP

