'31/01/2024
'Nwabisa
'PhD thesis: Chapter 4

'VAR
'This code is generating random positive definite covariance matrices (rnd_pos_def_mat) and then generating random multivariate normal samples (rnd_multivariate_normal) based on these covariance matrices.
' I am employing  the same code, but with covariance matrices from the VAR ,model , instead of randomly generated matrix.

'open VAR_ca_forecast.wf1

!read = 0 ' =1 if create a workfile, read data, create pages
'!Nwabisa =1
'!Zsolt = 0

'!stop_after_read = 0

if !read = 1 then
'--------------------------------------------------------------
 'close CA_forecast.wf1
  'wfcreate(wf=CA_forecast, 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

'Pagecreate(page=distribution) U 1000

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*

Pagecreate(page=distributionVAR) U 1000

Pageselect Annual
table table_countries


'smpl 1971 2027

  !i=0
   For %c BRA MEX  ZAF 'USA 'DEU 'IND IDN MEX HUN RUS ZAF AUS GBR FRA DEU USA 'CHN	'Prelimenary sample
	 !i=!i+1
	 table_countries(!i,1) = %c
   Next '%c!

%start_est_date = "1980"  ' the first date for the estimation of models
%start_forecast_date =  "2005" '2000  the first date for which a forecast will be made (from the preceding quarter, i.e. if %start_forecast_date =  "2000", then we use actual data up to 1999 and caclulate forecasts for 2000, 2001, 2002,....
%last_Y_obs = "2022"  ' 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

For !c = 1 to 3 '5   'total number of selected countries
	  %c = table_countries(!c,1)  'table with 4 rows and 1 column

      For !smpl = 0 to !num_forecasts

         ' 1st you estimate the model
          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}_var02.ls 1 2 CA_{%c} GDP_GROWTH_{%c} REER_ZD_{%c} TRADE_OPENNESS_{%c} ' 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

         ' 2nd you calculate out of sample forecasts and forecasts errors (for all 4 variables in the model)
         smpl %start_forecast_date+!smpl %start_forecast_date+!smpl+!forc_period_ahead 'oos 'out-of-sample
         ca_{%c}_var02.forecast(f=na) NNF    ' forecasts for all 4 variables

         ' 1-year ahead forecast errors
          smpl %start_forecast_date+!smpl %start_forecast_date+!smpl
         genr errorf_1y_gdp_growth_{%c}_var02 = gdp_growth_{%c} - gdp_growth_{%c}_NNF ' gdp_growth forecasts error
         genr errorf_1y_ca_{%c}_var02 = CA_{%c} - CA_{%c}_NNF ' CA forecasts error
         genr errorf_1y_reer_zd_{%c}_var02 = reer_zd_{%c} - reer_zd_{%c}_NNF ' reer_zd forecasts error
         genr errorf_1y_trade_openness_{%c}_var02 = trade_openness_{%c} - trade_openness_{%c}_NNF ' trade_openness forecasts error

         ' 2-year ahead forecast errors
          smpl %start_forecast_date+!smpl+1 %start_forecast_date+!smpl+1
         genr errorf_2y_gdp_growth_{%c}_var02 = gdp_growth_{%c} - gdp_growth_{%c}_NNF ' gdp_growth forecasts error
         genr errorf_2y_ca_{%c}_var02 = CA_{%c} - CA_{%c}_NNF ' CA forecasts error
         genr errorf_2y_reer_zd_{%c}_var02 = reer_zd_{%c} - reer_zd_{%c}_NNF ' reer_zd forecasts error
         genr errorf_2y_trade_openness_{%c}_var02 = trade_openness_{%c} - trade_openness_{%c}_NNF ' trade_openness forecasts error

         ' 3-year ahead forecast errors
          smpl %start_forecast_date+!smpl+2 %start_forecast_date+!smpl+2
         genr errorf_3y_gdp_growth_{%c}_var02 = gdp_growth_{%c} - gdp_growth_{%c}_NNF ' gdp_growth forecasts error
         genr errorf_3y_ca_{%c}_var02 = CA_{%c} - CA_{%c}_NNF ' CA forecasts error
         genr errorf_3y_reer_zd_{%c}_var02 = reer_zd_{%c} - reer_zd_{%c}_NNF ' reer_zd forecasts error
         genr errorf_3y_trade_openness_{%c}_var02 = trade_openness_{%c} - trade_openness_{%c}_NNF ' trade_openness forecasts error

         ' 4-year ahead forecast errors
          smpl %start_forecast_date+!smpl+3 %start_forecast_date+!smpl+3
         genr errorf_4y_gdp_growth_{%c}_var02 = gdp_growth_{%c} - gdp_growth_{%c}_NNF ' gdp_growth forecasts error
         genr errorf_4y_ca_{%c}_var02 = CA_{%c} - CA_{%c}_NNF ' CA forecasts error
         genr errorf_4y_reer_zd_{%c}_var02 = reer_zd_{%c} - reer_zd_{%c}_NNF ' reer_zd forecasts error
         genr errorf_4y_trade_openness_{%c}_var02 = trade_openness_{%c} - trade_openness_{%c}_NNF ' trade_openness forecasts error

         ' 5-year ahead forecast errors
          smpl %start_forecast_date+!smpl+4 %start_forecast_date+!smpl+4
         genr errorf_5y_gdp_growth_{%c}_var02 = gdp_growth_{%c} - gdp_growth_{%c}_NNF ' gdp_growth forecasts error
         genr errorf_5y_ca_{%c}_var02 = CA_{%c} - CA_{%c}_NNF ' CA forecasts error
         genr errorf_5y_reer_zd_{%c}_var02 = reer_zd_{%c} - reer_zd_{%c}_NNF ' reer_zd forecasts error
         genr errorf_5y_trade_openness_{%c}_var02 = trade_openness_{%c} - trade_openness_{%c}_NNF ' trade_openness forecasts error

    Next ' !smpl

      ' 3rd: after you calculated forecasts for all periods, you create a group of forecast errors:
     group group_forecast_errors_1y_{%c} errorf_1y_ca_{%c}_var02 errorf_1y_gdp_growth_{%c}_var02 errorf_1y_reer_zd_{%c}_var02  errorf_1y_trade_openness_{%c}_var02
     show group_forecast_errors_1y_{%c}

     group group_forecast_errors_2y_{%c} errorf_2y_ca_{%c}_var02 errorf_2y_gdp_growth_{%c}_var02 errorf_2y_reer_zd_{%c}_var02  errorf_2y_trade_openness_{%c}_var02
     show group_forecast_errors_2y_{%c}

     group group_forecast_errors_3y_{%c} errorf_3y_ca_{%c}_var02 errorf_3y_gdp_growth_{%c}_var02 errorf_3y_reer_zd_{%c}_var02  errorf_3y_trade_openness_{%c}_var02
     show group_forecast_errors_3y_{%c}

     group group_forecast_errors_4y_{%c} errorf_4y_ca_{%c}_var02 errorf_4y_gdp_growth_{%c}_var02 errorf_4y_reer_zd_{%c}_var02  errorf_4y_trade_openness_{%c}_var02
     show group_forecast_errors_4y_{%c}

     group group_forecast_errors_5y_{%c} errorf_5y_ca_{%c}_var02 errorf_5y_gdp_growth_{%c}_var02 errorf_5y_reer_zd_{%c}_var02  errorf_5y_trade_openness_{%c}_var02
     show group_forecast_errors_5y_{%c}

     ' 4th: then calculate the covariance matrix over the forecast sample period
     smpl %start_forecast_date %last_Y_obs
     d covs*_{%c}
'     sym covs = @var(ca_zaf_var02_f)
     sym covs_1y_{%c} = @cov(group_forecast_errors_1y_{%c}) ' note: @cov and not @var calculates the covariance matrix
     show covs_1y_{%c}

     sym covs_2y_{%c} = @cov(group_forecast_errors_2y_{%c}) ' note: @cov and not @var calculates the covariance matrix
     show covs_2y_{%c}

     sym covs_3y_{%c} = @cov(group_forecast_errors_3y_{%c}) ' note: @cov and not @var calculates the covariance matrix
     show covs_3y_{%c}

     sym covs_4y_{%c} = @cov(group_forecast_errors_4y_{%c}) ' note: @cov and not @var calculates the covariance matrix
     show covs_4y_{%c}

     sym covs_5y_{%c} = @cov(group_forecast_errors_5y_{%c}) ' note: @cov and not @var calculates the covariance matrix
     show covs_5y_{%c}

    ' 5th: you draw random numbers
     matrix draw_var_1y_{%c}=@rmvnorm(covs_1y_{%c}, 1000) 'random draws from the normal distribution
     show  draw_var_1y_{%c}

     matrix draw_var_2y_{%c}=@rmvnorm(covs_2y_{%c}, 1000) 'random draws from the normal distribution
     show  draw_var_2y_{%c}

     matrix draw_var_3y_{%c}=@rmvnorm(covs_3y_{%c}, 1000) 'random draws from the normal distribution
     show  draw_var_3y_{%c}

     matrix draw_var_4y_{%c}=@rmvnorm(covs_4y_{%c}, 1000) 'random draws from the normal distribution
     show  draw_var_4y_{%c}

     matrix draw_var_5y_{%c}=@rmvnorm(covs_5y_{%c}, 1000) 'random draws from the normal distribution
     show  draw_var_5y_{%c}

 Next '!c
'stop

'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
'New Page: Distribution. Process: 1. Copy the random draws matrix from 'Annual' to 'distribution'; 2. Convert the marix to a series
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
For !c = 1 to 3 '5   'total number of selected countries
	  %c = table_countries(!c,1)  'table with 4 rows and 1 column      
        
         'delete distribution*    ' Delete existing objects with names starting with "distribution"

         Pageselect Annual
         copy Annual\draw_var_1y_{%c} distributionVAR\*
         copy Annual\draw_var_2y_{%c} distributionVAR\*
         copy Annual\draw_var_3y_{%c} distributionVAR\*
         copy Annual\draw_var_4y_{%c} distributionVAR\*
         copy Annual\draw_var_5y_{%c} distributionVAR\*

         'mtos(draw_var_{%c}, series_var_{%c})  'covert the matrix to series       
 Next '!c

Pageselect distributionVAR

' NO NEED TO CREATE THIS TABLE AGAIN, WHICH HAS ALREADY BEEN CREATED IN THE ANNUAL PAGE. PLUS IF YOU CREATE IT AGAIN HERE, AND CHANGE THE COUNTRIES FOR THE ANNUAL PAGE BUT FORGET TO CHANGE THE COUNTRIES HERE, YOU'LL GET AN ERROR MESSAGE. BETTER TO COPY THE TABLE FROM THE ANNUAL SHEET TO THE DISTRBUTION SHEET.

'table table_countries
'!i=0
'For %c BRA HUN ZAF USA 'DEU 'IND IDN MEX HUN RUS ZAF AUS GBR FRA DEU USA 'CHN	'Prelimenary sample
'	 !i=!i+1
'	 table_countries(!i,1) = %c
'Next '%c!

copy Annual\table_countries distributionVAR\*


For !c = 1 to 3 '5   'total number of selected countries
	     %c = table_countries(!c,1)    

' READ EVIEWS HELP: "If the target group object does not exist, the group is created and populated with series named <prefix>1, <prefix>2, etc. If the prefix is omitted, the default prefix is “SER”." THUS, IN YOUR VERSION, ca_1fperiod_draw_var_{%c} BECAME A GROUP AND ITS SINGLE TIME SERIES WAS NAMED SER1. WHEN YOU CREATE MANY SERIES NAMED SER1, SER2, ETC, IT WILL BE DIFFICULT TO KNOW WHAT IS INCLUDED IN. BETTER TO TREAT ca_1fperiod_draw_var_{%c} AS A SERIES (NOT A GROUP).

         series ca_1fperiod_draw_var_{%c}
         matrix ca_1fperiod_matrix_{%c}= @columnextract(draw_var_1y_{%c},1)  ' extracts the first column (C1) of the matrix , C1= CURRENT ACCCOUNT Variable
         mtos(ca_1fperiod_matrix_{%c}, ca_1fperiod_draw_var_{%c})  'converts the matrix to series   "1fperiod = 1 forecast period ahead

         series ca_2fperiod_draw_var_{%c}
         matrix ca_2fperiod_matrix_{%c}= @columnextract(draw_var_2y_{%c},1)  ' extracts the first column (C1) of the matrix , C1= CURRENT ACCCOUNT Variable
         mtos(ca_2fperiod_matrix_{%c}, ca_2fperiod_draw_var_{%c})  'converts the matrix to series   "2fperiod = 2 forecast periods ahead

         series ca_3fperiod_draw_var_{%c}
         matrix ca_3fperiod_matrix_{%c}= @columnextract(draw_var_3y_{%c},1)  ' extracts the first column (C1) of the matrix , C1= CURRENT ACCCOUNT Variable
         mtos(ca_3fperiod_matrix_{%c}, ca_3fperiod_draw_var_{%c})  'converts the matrix to series   "3fperiod = 3 forecast periods ahead

         series ca_4fperiod_draw_var_{%c}
         matrix ca_4fperiod_matrix_{%c}= @columnextract(draw_var_4y_{%c},1)  ' extracts the first column (C1) of the matrix , C1= CURRENT ACCCOUNT Variable
         mtos(ca_4fperiod_matrix_{%c}, ca_4fperiod_draw_var_{%c})  'converts the matrix to series   "4fperiod = 4 forecast periods ahead

         series ca_5fperiod_draw_var_{%c}
         matrix ca_5fperiod_matrix_{%c}= @columnextract(draw_var_5y_{%c},1)  ' extracts the first column (C1) of the matrix , C1= CURRENT ACCCOUNT Variable
         mtos(ca_5fperiod_matrix_{%c}, ca_5fperiod_draw_var_{%c})  'converts the matrix to series   "5fperiod = 5 forecast periods ahead


         Pageselect Annual
' THIS WAS CORRECT, BUT IT IS BETTER TO CONVERT THE FORECAST TO SCALAR ON THE ANNUAL SHEET, BECAUSE THEN YOU CAN REFER TO YEAR 2023 WHEN YOU WISH TO USE THE FORECAST FOR 2023, INSTEAD OF REFERRING TO A NUMBER IN THE DISTRBUTION SHEET. THEREBY, SURELY, YOU WILL NOT USE ANOTHER DATE ACCIDENTIELLY

'         copy Annual\ca_{%c}_nnf distribution\*    'copy current account point forecast from "annual page" to "distribution" page
'         ' scalar  ca_bra_point_forecast = @elem(ca_bra_nnf,"2023")
'         Pageselect distribution
'         scalar  ca_{%c}_point_forecast = @elem(ca_{%c}_nnf,"48")  '  "44" is draw no.44 corresponding with = 2023 forecast , 45= 2024; 46=2025; 47=2026; 48=2027; converts the points forecasts to a scalar
'       

        scalar  ca_{%c}_point_forecast_2023 = @elem(ca_{%c}_nnf,"2023")
        scalar  ca_{%c}_point_forecast_2024 = @elem(ca_{%c}_nnf,"2024")
        scalar  ca_{%c}_point_forecast_2025 = @elem(ca_{%c}_nnf,"2025")
        scalar  ca_{%c}_point_forecast_2026 = @elem(ca_{%c}_nnf,"2026")
        scalar  ca_{%c}_point_forecast_2027 = @elem(ca_{%c}_nnf,"2027")
 
         copy Annual\ca_{%c}_point_forecast_2023 distributionVAR\*    'copy current account point forecast from "annual page" to "distribution" page
         copy Annual\ca_{%c}_point_forecast_2024 distributionVAR\*    'copy current account point forecast from "annual page" to "distribution" page
         copy Annual\ca_{%c}_point_forecast_2025 distributionVAR\*    'copy current account point forecast from "annual page" to "distribution" page
         copy Annual\ca_{%c}_point_forecast_2026 distributionVAR\*    'copy current account point forecast from "annual page" to "distribution" page
         copy Annual\ca_{%c}_point_forecast_2027 distributionVAR\*    'copy current account point forecast from "annual page" to "distribution" page

         Pageselect distributionVAR

         genr ca_1_forecast_draws_{%c} = ca_1fperiod_draw_var_{%c}+ca_{%c}_point_forecast_2023   'generating 1 forecast period ahead; combining point forcasts and the random draws which we generated , with zero mean
         genr ca_2_forecast_draws_{%c} = ca_2fperiod_draw_var_{%c}+ca_{%c}_point_forecast_2024   'generating 2 forecast periods ahead; combining point forcasts and the random draws which we generated , with zero mean
         genr ca_3_forecast_draws_{%c} = ca_3fperiod_draw_var_{%c}+ca_{%c}_point_forecast_2025   'generating 3 forecast periods ahead; combining point forcasts and the random draws which we generated , with zero mean
         genr ca_4_forecast_draws_{%c} = ca_4fperiod_draw_var_{%c}+ca_{%c}_point_forecast_2026   'generating 4 forecast periods ahead; combining point forcasts and the random draws which we generated , with zero mean
         genr ca_5_forecast_draws_{%c} = ca_5fperiod_draw_var_{%c}+ca_{%c}_point_forecast_2027   'generating 5 forecast periods ahead; combining point forcasts and the random draws which we generated , with zero mean


          '--------------DISTRIBUTION: KERNEL DENSITY , assmuing Normal (Gaussian)---------------'  
          'Here we study the distribution of 1, 2, 3, 4, and 5 period ahead forecast for CA balance. Annual data. 
          '-------------------------------------------------------------------------------------------------------------------------
           'ca_1_forecast_draws_bra.distdata(dtype=kernel, k=n) ca_pdf_bra  
           'show ca_pdf_bra.xyline
            ca_1_forecast_draws_{%c}.distdata(dtype=kernel, k=n) ca_pdf_{%c}_2023 
            show ca_pdf_{%c}_2023.xyline
            'freeze ca_pdf_{%c}.xyline         
            ca_2_forecast_draws_{%c}.distdata(dtype=kernel, k=n) ca_pdf_{%c}_2024 
            show ca_pdf_{%c}_2024.xyline
            ca_3_forecast_draws_{%c}.distdata(dtype=kernel, k=n) ca_pdf_{%c}_2025 
            show ca_pdf_{%c}_2025.xyline
            ca_4_forecast_draws_{%c}.distdata(dtype=kernel, k=n) ca_pdf_{%c}_2026 
            show ca_pdf_{%c}_2026.xyline
            ca_5_forecast_draws_{%c}.distdata(dtype=kernel, k=n) ca_pdf_{%c}_2027 
            show ca_pdf_{%c}_2027.xyline



           '-------------------------------------------------------------------------------------------------------------------------
            'CALCULATE THE PROBABILITY OF CA (UN)SUSTAINABILITY 
                  'Elements:
                  '1. Threshold  = 5, 8,
                  '2. Mean 
                  '3. Standard Deviation
             'country sample? = Episodes in which persistent current account imbalances have been followed by an external crisis, resulting in debt rescheduling, renegotiations, or a massive bailout. 
                                                'This includes countries such as Chile (1977–1982), Mexico (1991-1994), Hungary and Latvia (2008-2010), and Greece (2010-2018).
           '-------------------------------------------------------------------------------------------------------------------------


Next '!c



'---------------------------------------------------------------------------------
'VECM Model  (populary refered to as restricted VAR model)
'---------------------------------------------------------------------------------
Pageselect Annual

For !c = 1 to 3 '4 '5   'total number of selected countries
	  %c = table_countries(!c,1)  'table with 4 rows and 1 column

        For !smpl = 0 to !num_forecasts

         ' 1st you conduct the johansen test and estimate the VECM model
          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}_var02.coint(determ=cbtl) 1 3 @CA_{%c} GDP_GROWTH_{%c} TRADE_OPENNESS_{%c} REER_ZD_{%c}  'save(john_test_results_{%c})            'Johansen cointegration test
          'show john_test_results_{%c}
           var ca_{%c}_var03.ec 1 2 CA_{%c} GDP_GROWTH_{%c} TRADE_OPENNESS_{%c} REER_ZD_{%c}      'Estimate VECM
           


         ' 2nd you calculate out of sample forecasts and forecasts errors (for all 4 variables in the model)
           smpl %start_forecast_date+!smpl %start_forecast_date+!smpl+!forc_period_ahead 'oos 'out-of-sample
           d CA_{%c}_NNE*
           ca_{%c}_var03.forecast(f=na) NNE    ' forecasts for all 4 variables using VECM
           genr errorf_gdp_growth_{%c}_var03 = gdp_growth_{%c} - gdp_growth_{%c}_NNE 'gdp_growth forecasts error
           genr errorf_ca_{%c}_var03 = CA_{%c} - CA_{%c}_NNE ' CA forecasts error
           genr errorf_reer_zd_{%c}_var03 = reer_zd_{%c} - reer_zd_{%c}_NNE ' reer_zd forecasts error
           genr errorf_trade_openness_{%c}_var03 = trade_openness_{%c} - trade_openness_{%c}_NNE ' trade_openness forecasts error

 
         ' 1-year ahead forecast errors
          smpl %start_forecast_date+!smpl %start_forecast_date+!smpl
         genr errorf_1y_gdp_growth_{%c}_var03 = gdp_growth_{%c} - gdp_growth_{%c}_NNE 'gdp_growth forecasts error
         genr errorf_1y_ca_{%c}_var03 = CA_{%c} - CA_{%c}_NNE ' CA forecasts error
         genr errorf_1y_reer_zd_{%c}_var03 = reer_zd_{%c} - reer_zd_{%c}_NNE ' reer_zd forecasts error
         genr errorf_1y_trade_openness_{%c}_var03 = trade_openness_{%c} - trade_openness_{%c}_NNE ' trade_openness forecasts error

         ' 2-year ahead forecast errors
          smpl %start_forecast_date+!smpl+1 %start_forecast_date+!smpl+1
         genr errorf_2y_gdp_growth_{%c}_var03 = gdp_growth_{%c} - gdp_growth_{%c}_NNE 'gdp_growth forecasts error
         genr errorf_2y_ca_{%c}_var03 = CA_{%c} - CA_{%c}_NNE ' CA forecasts error
         genr errorf_2y_reer_zd_{%c}_var03 = reer_zd_{%c} - reer_zd_{%c}_NNE ' reer_zd forecasts error
         genr errorf_2y_trade_openness_{%c}_var03 = trade_openness_{%c} - trade_openness_{%c}_NNE ' trade_openness forecasts error

         ' 3-year ahead forecast errors
          smpl %start_forecast_date+!smpl+2 %start_forecast_date+!smpl+2
         genr errorf_3y_gdp_growth_{%c}_var03 = gdp_growth_{%c} - gdp_growth_{%c}_NNE 'gdp_growth forecasts error
         genr errorf_3y_ca_{%c}_var03 = CA_{%c} - CA_{%c}_NNE ' CA forecasts error
         genr errorf_3y_reer_zd_{%c}_var03 = reer_zd_{%c} - reer_zd_{%c}_NNE ' reer_zd forecasts error
         genr errorf_3y_trade_openness_{%c}_var03 = trade_openness_{%c} - trade_openness_{%c}_NNE ' trade_openness forecasts error

         ' 4-year ahead forecast errors
          smpl %start_forecast_date+!smpl+3 %start_forecast_date+!smpl+3
         genr errorf_4y_gdp_growth_{%c}_var03 = gdp_growth_{%c} - gdp_growth_{%c}_NNE 'gdp_growth forecasts error
         genr errorf_4y_ca_{%c}_var03 = CA_{%c} - CA_{%c}_NNE ' CA forecasts error
         genr errorf_4y_reer_zd_{%c}_var03 = reer_zd_{%c} - reer_zd_{%c}_NNE ' reer_zd forecasts error
         genr errorf_4y_trade_openness_{%c}_var03 = trade_openness_{%c} - trade_openness_{%c}_NNE ' trade_openness forecasts error

         ' 5-year ahead forecast errors
          smpl %start_forecast_date+!smpl+4 %start_forecast_date+!smpl+4
         genr errorf_5y_gdp_growth_{%c}_var03 = gdp_growth_{%c} - gdp_growth_{%c}_NNE 'gdp_growth forecasts error
         genr errorf_5y_ca_{%c}_var03 = CA_{%c} - CA_{%c}_NNE ' CA forecasts error
         genr errorf_5y_reer_zd_{%c}_var03 = reer_zd_{%c} - reer_zd_{%c}_NNE ' reer_zd forecasts error
         genr errorf_5y_trade_openness_{%c}_var03 = trade_openness_{%c} - trade_openness_{%c}_NNE ' trade_openness forecasts error


   Next ' !smpl

         ' 3rd: after you calculated forecasts for all periods, you create a group of forecast errors:
           group groupvecm_1y_forecast_errors_{%c}  errorf_1y_gdp_growth_{%c}_var03 errorf_1y_ca_{%c}_var03 errorf_1y_reer_zd_{%c}_var03  errorf_1y_trade_openness_{%c}_var03
           show groupvecm_1y_forecast_errors_{%c}

           group groupvecm_2y_forecast_errors_{%c}  errorf_2y_gdp_growth_{%c}_var03 errorf_2y_ca_{%c}_var03 errorf_2y_reer_zd_{%c}_var03  errorf_2y_trade_openness_{%c}_var03
           show groupvecm_2y_forecast_errors_{%c}

           group groupvecm_3y_forecast_errors_{%c}  errorf_3y_gdp_growth_{%c}_var03 errorf_3y_ca_{%c}_var03 errorf_3y_reer_zd_{%c}_var03  errorf_3y_trade_openness_{%c}_var03
           show groupvecm_3y_forecast_errors_{%c}

           group groupvecm_4y_forecast_errors_{%c}  errorf_4y_gdp_growth_{%c}_var03 errorf_4y_ca_{%c}_var03 errorf_4y_reer_zd_{%c}_var03  errorf_4y_trade_openness_{%c}_var03
           show groupvecm_4y_forecast_errors_{%c}

           group groupvecm_5y_forecast_errors_{%c}  errorf_5y_gdp_growth_{%c}_var03 errorf_5y_ca_{%c}_var03 errorf_5y_reer_zd_{%c}_var03  errorf_5y_trade_openness_{%c}_var03
           show groupvecm_5y_forecast_errors_{%c}



          ' 4th: then calculate the covariance matrix over the forecast sample period
           smpl %start_forecast_date %last_Y_obs
           d covsvecm*
      '     sym covs = @var(ca_zaf_var02_f)
            sym covsvecm_1y_{%c} = @cov(groupvecm_1y_forecast_errors_{%c}) ' note: @cov and not @var calculates the covariance matrix
            show covsvecm_1y_{%c}

            sym covsvecm_2y_{%c} = @cov(groupvecm_2y_forecast_errors_{%c}) ' note: @cov and not @var calculates the covariance matrix
            show covsvecm_2y_{%c}

            sym covsvecm_3y_{%c} = @cov(groupvecm_3y_forecast_errors_{%c}) ' note: @cov and not @var calculates the covariance matrix
            show covsvecm_3y_{%c}

            sym covsvecm_4y_{%c} = @cov(groupvecm_4y_forecast_errors_{%c}) ' note: @cov and not @var calculates the covariance matrix
            show covsvecm_4y_{%c}

            sym covsvecm_5y_{%c} = @cov(groupvecm_5y_forecast_errors_{%c}) ' note: @cov and not @var calculates the covariance matrix
            show covsvecm_5y_{%c}


          ' 5th: you draw random numbers
            matrix draw_1y_vecm_{%c}=@rmvnorm(covsvecm_1y_{%c}, 1000) 'random draws from the normal distribution
            show  draw_1y_vecm_{%c}

            matrix draw_2y_vecm_{%c}=@rmvnorm(covsvecm_2y_{%c}, 1000) 'random draws from the normal distribution
            show  draw_2y_vecm_{%c}

            matrix draw_3y_vecm_{%c}=@rmvnorm(covsvecm_3y_{%c}, 1000) 'random draws from the normal distribution
            show  draw_3y_vecm_{%c}

            matrix draw_4y_vecm_{%c}=@rmvnorm(covsvecm_4y_{%c}, 1000) 'random draws from the normal distribution
            show  draw_4y_vecm_{%c}

            matrix draw_5y_vecm_{%c}=@rmvnorm(covsvecm_5y_{%c}, 1000) 'random draws from the normal distribution
            show  draw_5y_vecm_{%c}

 Next '!c


'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
'VECM MODEL=======New Page: Distribution. Process: 1. Copy the random draws matrix from 'Annual' to 'distribution'; 2. Convert the marix to a series
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
For !c = 1 to 3 '4 '5   'total number of selected countries
	  %c = table_countries(!c,1)  'table with 4 rows and 1 column      
        
         delete distributionvecm*    ' Delete existing objects with names starting with "distribution"
         Pagecreate(page=distributionvecm) U 1000

         Pageselect Annual
         copy Annual\draw_1y_vecm_{%c} distributionvecm\*
         copy Annual\draw_2y_vecm_{%c} distributionvecm\*
         copy Annual\draw_3y_vecm_{%c} distributionvecm\*
         copy Annual\draw_4y_vecm_{%c} distributionvecm\*
         copy Annual\draw_5y_vecm_{%c} distributionvecm\*

         'mtos(draw_var_{%c}, series_var_{%c})  'covert the matrix to series       
 Next '!c

copy Annual\table_countries distributionvecm\*

Pageselect distributionvecm

For !c = 1 to 3 '5   'total number of selected countries
	     %c = table_countries(!c,1)    

' READ EVIEWS HELP: "If the target group object does not exist, the group is created and populated with series named <prefix>1, <prefix>2, etc. If the prefix is omitted, the default prefix is “SER”." THUS, IN YOUR VERSION, ca_1fperiod_draw_var_{%c} BECAME A GROUP AND ITS SINGLE TIME SERIES WAS NAMED SER1. WHEN YOU CREATE MANY SERIES NAMED SER1, SER2, ETC, IT WILL BE DIFFICULT TO KNOW WHAT IS INCLUDED IN. BETTER TO TREAT ca_1fperiod_draw_var_{%c} AS A SERIES (NOT A GROUP).

         series ca_1fperiod_draw_vecm_{%c}
         matrix ca_1fperiod_matrix_vecm_{%c}= @columnextract(draw_1y_vecm_{%c},1)  ' extracts the first column (C1) of the matrix , C1= CURRENT ACCCOUNT Variable
         mtos(ca_1fperiod_matrix_vecm_{%c}, ca_1fperiod_draw_vecm_{%c})  'converts the matrix to series   "1fperiod = 1 forecast period ahead


        series ca_2fperiod_draw_vecm_{%c}
        matrix ca_2fperiod_matrix_vecm_{%c}= @columnextract(draw_2y_vecm_{%c},1)  ' extracts the first column (C1) of the matrix , C1= CURRENT ACCCOUNT Variable
        mtos(ca_2fperiod_matrix_vecm_{%c}, ca_2fperiod_draw_vecm_{%c})  'converts the matrix to series   "2fperiod = 2 forecast periods ahead
        
        series ca_3fperiod_draw_vecm_{%c}
        matrix ca_3fperiod_matrix_vecm_{%c}= @columnextract(draw_3y_vecm_{%c},1)  ' extracts the first column (C1) of the matrix , C1= CURRENT ACCCOUNT Variable
        mtos(ca_3fperiod_matrix_vecm_{%c}, ca_3fperiod_draw_vecm_{%c})  'converts the matrix to series   "3fperiod = 3 forecast periods ahead

        series ca_4fperiod_draw_vecm_{%c}
        matrix ca_4fperiod_matrix_vecm_{%c}= @columnextract(draw_4y_vecm_{%c},1)  ' extracts the first column (C1) of the matrix , C1= CURRENT ACCCOUNT Variable
        mtos(ca_4fperiod_matrix_vecm_{%c}, ca_4fperiod_draw_vecm_{%c})  'converts the matrix to series   "4fperiod = 4 forecast periods ahead

        series ca_5fperiod_draw_vecm_{%c}
        matrix ca_5fperiod_matrix_vecm_{%c}= @columnextract(draw_5y_vecm_{%c},1)  ' extracts the first column (C1) of the matrix , C1= CURRENT ACCCOUNT Variable
        mtos(ca_5fperiod_matrix_vecm_{%c}, ca_5fperiod_draw_vecm_{%c})  'converts the matrix to series   "4fperiod = 4 forecast periods ahead


         Pageselect Annual
         'copy Annual\ca_{%c}_nne distributionvecm\*    'copy current account point forecast from "annual page" to "distribution" page
         ' scalar  ca_bra_point_forecast = @elem(ca_bra_nnf,"2023")
         'Pageselect distributionvecm
         'scalar  ca_{%c}_point_forecastvecm = @elem(ca_{%c}_nne,"44")  '  "44" is draw no.44 corresponding with = 2023 forecast , 45= 2024; 46=2025; 47=2026; 48=2027; converts the points forecasts to a scalar
        
        ' genr ca_1_forecast_draws_bra = ser01+ca_bra_point_forecast  'generating 1 forecast period ahead; combining point forcasts and the random draws which we generated , with zero mean
         'genr ca_1_forecast_drawsvecm_{%c} = ser01+ca_{%c}_point_forecastvecm   'SIUMULATED SERIES: generating 1 forecast period ahead; combining point forcasts and the random draws which we generated , with zero mean
         

        scalar  ca_{%c}_point_forecast_vecm_2023 = @elem(ca_{%c}_nne,"2023")
        scalar  ca_{%c}_point_forecast_vecm_2024 = @elem(ca_{%c}_nne,"2024")
        scalar  ca_{%c}_point_forecast_vecm_2025 = @elem(ca_{%c}_nne,"2025")
        scalar  ca_{%c}_point_forecast_vecm_2026 = @elem(ca_{%c}_nne,"2026")
        scalar  ca_{%c}_point_forecast_vecm_2027 = @elem(ca_{%c}_nne,"2027")
 
         copy Annual\ca_{%c}_point_forecast_vecm_2023 distributionvecm\*   'copy current account point forecast from "annual page" to "distribution" page
         copy Annual\ca_{%c}_point_forecast_vecm_2024 distributionvecm\*    'copy current account point forecast from "annual page" to "distribution" page
         copy Annual\ca_{%c}_point_forecast_vecm_2025 distributionvecm\*   'copy current account point forecast from "annual page" to "distribution" page
         copy Annual\ca_{%c}_point_forecast_vecm_2026 distributionvecm\*    'copy current account point forecast from "annual page" to "distribution" page
         copy Annual\ca_{%c}_point_forecast_vecm_2027 distributionvecm\*    'copy current account point forecast from "annual page" to "distribution" page

         Pageselect distributionvecm
          'SIMULATED SERIES'
           '-----------------------------
         genr ca_1_forecast_draws_vecm_{%c} = ca_1fperiod_draw_vecm_{%c}+ca_{%c}_point_forecast_vecm_2023   'generating 1 forecast period ahead; combining point forcasts and the random draws which we generated , with zero mean
         genr ca_2_forecast_draws_vecm_{%c} = ca_2fperiod_draw_vecm_{%c}+ca_{%c}_point_forecast_vecm_2024   'generating 2 forecast periods ahead; combining point forcasts and the random draws which we generated , with zero mean
         genr ca_3_forecast_draws_vecm_{%c} = ca_3fperiod_draw_vecm_{%c}+ca_{%c}_point_forecast_vecm_2025   'generating 3 forecast periods ahead; combining point forcasts and the random draws which we generated , with zero mean
         genr ca_4_forecast_draws_vecm_{%c} = ca_4fperiod_draw_vecm_{%c}+ca_{%c}_point_forecast_vecm_2026   'generating 4 forecast periods ahead; combining point forcasts and the random draws which we generated , with zero mean
         genr ca_5_forecast_draws_vecm_{%c} = ca_5fperiod_draw_vecm_{%c}+ca_{%c}_point_forecast_vecm_2027   'generating 5 forecast periods ahead; combining point forcasts and the random draws whi



          '--------------DISTRIBUTION: KERNEL DENSITY , assmuing Normal (Gaussian)---------------'  
          'Here we study the distribution of 1, 2, 3, 4, and 5 period ahead forecast for CA balance. Annual data. 
          '-------------------------------------------------------------------------------------------------------------------------
          ca_1_forecast_draws_vecm_{%c}.distdata(dtype=kernel, k=n) ca_pdf_vecm_{%c}_2023 
           show ca_pdf_vecm_{%c}_2023.xyline

           ca_2_forecast_draws_vecm_{%c}.distdata(dtype=kernel, k=n) ca_pdf_vecm_{%c}_2024 
           show ca_pdf_vecm_{%c}_2024.xyline

           ca_3_forecast_draws_vecm_{%c}.distdata(dtype=kernel, k=n) ca_pdf_vecm_{%c}_2025 
           show ca_pdf_vecm_{%c}_2025.xyline

           ca_4_forecast_draws_vecm_{%c}.distdata(dtype=kernel, k=n) ca_pdf_vecm_{%c}_2026 
           show ca_pdf_vecm_{%c}_2026.xyline

           ca_5_forecast_draws_vecm_{%c}.distdata(dtype=kernel, k=n) ca_pdf_vecm_{%c}_2027 
           show ca_pdf_vecm_{%c}_2027.xyline



           '-------------------------------------------------------------------------------------------------------------------------
            'CALCULATE THE PROBABILITY OF CA (UN)SUSTAINABILITY 
                  'Elements:
                  '1. Threshold  = 5, 8,
                  '2. Mean 
                  '3. Standard Deviation
             'country sample? = Episodes in which persistent current account imbalances have been followed by an external crisis, resulting in debt rescheduling, renegotiations, or a massive bailout. 
                                                'This includes countries such as Chile (1977–1982), Mexico (1991-1994), Hungary and Latvia (2008-2010), and Greece (2010-2018).
           '-------------------------------------------------------------------------------------------------------------------------





Next '!c
'STOP




'---------------------------------------------------------------------------------
'Bayesian VAR Model  (BVAR)
'---------------------------------------------------------------------------------
Pageselect Annual

For !c = 1 to 3 '4 '5   'total number of selected countries
	  %c = table_countries(!c,1)  'table with 4 rows and 1 column

        For !smpl = 0 to !num_forecasts

         ' 1st you estimate the BVAR model
          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}_var04.bvar(initcov=diag) 1 3 CA_{%c} GDP_GROWTH_{%c} TRADE_OPENNESS_{%c} REER_ZD_{%c}      'Estimate BVAR
         
         ' 2nd you calculate out of sample forecasts and forecasts errors (for all 4 variables in the model)
           smpl %start_forecast_date+!smpl %start_forecast_date+!smpl+!forc_period_ahead 'oos 'out-of-sample
           ca_{%c}_var04.forecast(f=na) NNB    ' forecasts for all 4 variables using BVAR
           genr errorf_gdp_growth_{%c}_var04 = gdp_growth_{%c} - gdp_growth_{%c}_NNB 'gdp_growth forecasts error
           genr errorf_ca_{%c}_var04 = CA_{%c} - CA_{%c}_NNB ' CA forecasts error
           genr errorf_reer_zd_{%c}_var04 = reer_zd_{%c} - reer_zd_{%c}_NNB ' reer_zd forecasts error
           genr errorf_trade_openness_{%c}_var04 = trade_openness_{%c} - trade_openness_{%c}_NNB ' trade_openness forecasts error


         ' 1-year ahead forecast errors
           smpl %start_forecast_date+!smpl %start_forecast_date+!smpl
           genr errorf_1y_gdp_growth_{%c}_var04 = gdp_growth_{%c} - gdp_growth_{%c}_NNB 'gdp_growth forecasts error
           genr errorf_1y_ca_{%c}_var04 = CA_{%c} - CA_{%c}_NNB ' CA forecasts error
           genr errorf_1y_reer_zd_{%c}_var04 = reer_zd_{%c} - reer_zd_{%c}_NNB ' reer_zd forecasts error
           genr errorf_1y_trade_openness_{%c}_var04 = trade_openness_{%c} - trade_openness_{%c}_NNB ' trade_openness forecasts error

         ' 2-year ahead forecast errors
          smpl %start_forecast_date+!smpl+1 %start_forecast_date+!smpl+1
          genr errorf_2y_gdp_growth_{%c}_var04 = gdp_growth_{%c} - gdp_growth_{%c}_NNB 'gdp_growth forecasts error
          genr errorf_2y_ca_{%c}_var04 = CA_{%c} - CA_{%c}_NNB ' CA forecasts error
          genr errorf_2y_reer_zd_{%c}_var04 = reer_zd_{%c} - reer_zd_{%c}_NNB ' reer_zd forecasts error
          genr errorf_2y_trade_openness_{%c}_var04 = trade_openness_{%c} - trade_openness_{%c}_NNB ' trade_openness forecasts error

         ' 3-year ahead forecast errors
          smpl %start_forecast_date+!smpl+2 %start_forecast_date+!smpl+2
           genr errorf_3y_gdp_growth_{%c}_var04 = gdp_growth_{%c} - gdp_growth_{%c}_NNB 'gdp_growth forecasts error
           genr errorf_3y_ca_{%c}_var04 = CA_{%c} - CA_{%c}_NNB ' CA forecasts error
           genr errorf_3y_reer_zd_{%c}_var04 = reer_zd_{%c} - reer_zd_{%c}_NNB ' reer_zd forecasts error
           genr errorf_3y_trade_openness_{%c}_var04 = trade_openness_{%c} - trade_openness_{%c}_NNB ' trade_openness forecasts error

         ' 4-year ahead forecast errors
          smpl %start_forecast_date+!smpl+3 %start_forecast_date+!smpl+3
           genr errorf_4y_gdp_growth_{%c}_var04 = gdp_growth_{%c} - gdp_growth_{%c}_NNB 'gdp_growth forecasts error
           genr errorf_4y_ca_{%c}_var04 = CA_{%c} - CA_{%c}_NNB ' CA forecasts error
           genr errorf_4y_reer_zd_{%c}_var04 = reer_zd_{%c} - reer_zd_{%c}_NNB ' reer_zd forecasts error
           genr errorf_4y_trade_openness_{%c}_var04 = trade_openness_{%c} - trade_openness_{%c}_NNB ' trade_openness forecasts error

         ' 5-year ahead forecast errors
          smpl %start_forecast_date+!smpl+4 %start_forecast_date+!smpl+4
          genr errorf_5y_gdp_growth_{%c}_var04 = gdp_growth_{%c} - gdp_growth_{%c}_NNB 'gdp_growth forecasts error
           genr errorf_5y_ca_{%c}_var04 = CA_{%c} - CA_{%c}_NNB ' CA forecasts error
           genr errorf_5y_reer_zd_{%c}_var04 = reer_zd_{%c} - reer_zd_{%c}_NNB ' reer_zd forecasts error
           genr errorf_5y_trade_openness_{%c}_var04 = trade_openness_{%c} - trade_openness_{%c}_NNB ' trade_openness forecasts error



           Next ' !smpl

         ' 3rd: after you calculated forecasts for all periods, you create a group of forecast errors:
           group groupBVAR_1y_forecast_errors_{%c} errorf_1y_gdp_growth_{%c}_var04 errorf_1y_ca_{%c}_var04  errorf_1y_reer_zd_{%c}_var04  errorf_1y_trade_openness_{%c}_var04
           show groupBVAR_1y_forecast_errors_{%c}

          group groupBVAR_2y_forecast_errors_{%c} errorf_2y_gdp_growth_{%c}_var04 errorf_2y_ca_{%c}_var04  errorf_2y_reer_zd_{%c}_var04  errorf_2y_trade_openness_{%c}_var04
          show groupBVAR_2y_forecast_errors_{%c}

          group groupBVAR_3y_forecast_errors_{%c} errorf_3y_gdp_growth_{%c}_var04 errorf_3y_ca_{%c}_var04  errorf_3y_reer_zd_{%c}_var04  errorf_3y_trade_openness_{%c}_var04
          show groupBVAR_3y_forecast_errors_{%c}
          
          group groupBVAR_4y_forecast_errors_{%c} errorf_4y_gdp_growth_{%c}_var04 errorf_4y_ca_{%c}_var04  errorf_4y_reer_zd_{%c}_var04  errorf_4y_trade_openness_{%c}_var04
          show groupBVAR_4y_forecast_errors_{%c}
          
          group groupBVAR_5y_forecast_errors_{%c} errorf_5y_gdp_growth_{%c}_var04 errorf_5y_ca_{%c}_var04  errorf_5y_reer_zd_{%c}_var04  errorf_5y_trade_openness_{%c}_var04
          show groupBVAR_5y_forecast_errors_{%c}

        

          ' 4th: then calculate the covariance matrix over the forecast sample period
           smpl %start_forecast_date %last_Y_obs
           d covsbvar*
      '     sym covs = @var(ca_zaf_var02_f)
            sym covsbvar_1y_{%c} = @cov(groupBVAR_1y_forecast_errors_{%c}) ' note: @cov and not @var calculates the covariance matrix
            show covsbvar_1y_{%c} 

            sym covsbvar_2y_{%c} = @cov(groupBVAR_2y_forecast_errors_{%c}) ' note: @cov and not @var calculates the covariance matrix
            show covsbvar_2y_{%c} 

            sym covsbvar_3y_{%c} = @cov(groupBVAR_3y_forecast_errors_{%c}) ' note: @cov and not @var calculates the covariance matrix
            show covsbvar_3y_{%c} 
            
            sym covsbvar_4y_{%c} = @cov(groupBVAR_4y_forecast_errors_{%c}) ' note: @cov and not @var calculates the covariance matrix
            show covsbvar_4y_{%c} 

            sym covsbvar_5y_{%c} = @cov(groupBVAR_5y_forecast_errors_{%c}) ' note: @cov and not @var calculates the covariance matrix
            show covsbvar_5y_{%c} 


          ' 5th: you draw random numbers
            matrix draw_1y_bvar_{%c}=@rmvnorm(covsbvar_1y_{%c}, 1000) 'random draws from the normal distribution
            show  draw_1y_bvar_{%c}

            matrix draw_2y_bvar_{%c}=@rmvnorm(covsbvar_2y_{%c}, 1000) 'random draws from the normal distribution
            show  draw_2y_bvar_{%c}

            matrix draw_3y_bvar_{%c}=@rmvnorm(covsbvar_3y_{%c}, 1000) 'random draws from the normal distribution
            show  draw_3y_bvar_{%c}

            matrix draw_4y_bvar_{%c}=@rmvnorm(covsbvar_4y_{%c}, 1000) 'random draws from the normal distribution
            show  draw_4y_bvar_{%c}

            matrix draw_5y_bvar_{%c}=@rmvnorm(covsbvar_5y_{%c}, 1000) 'random draws from the normal distribution
            show  draw_5y_bvar_{%c}



 Next '!c



'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
'BVAR MODEL=======New Page: Distribution. Process: 1. Copy the random draws matrix from 'Annual' to 'distribution'; 2. Convert the marix to a series
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
For !c = 1 to 3 '4 '5   'total number of selected countries
	  %c = table_countries(!c,1)  'table with 4 rows and 1 column      
        
         delete distributionBVAR*    ' Delete existing objects with names starting with "distribution"
         Pagecreate(page=distributionBVAR) U 1000
        
         Pageselect Annual
         copy Annual\draw_1y_bvar_{%c} distributionBVAR\*
         copy Annual\draw_2y_bvar_{%c} distributionBVAR\*
         copy Annual\draw_3y_bvar_{%c} distributionBVAR\*
         copy Annual\draw_4y_bvar_{%c} distributionBVAR\*
         copy Annual\draw_5y_bvar_{%c} distributionBVAR\*
Next '!c

copy Annual\table_countries distributionBVAR\*

Pageselect distributionBVAR

For !c = 1 to 3 '4 '5   'total number of selected countries
	     %c = table_countries(!c,1)    

         series ca_1fperiod_draw_BVAR_{%c}
         matrix ca_1fperiod_matrix_BVAR_{%c}= @columnextract(draw_1y_bvar_{%c},1)  ' extracts the first column (C1) of the matrix , C1= CURRENT ACCCOUNT Variable
         mtos(ca_1fperiod_matrix_BVAR_{%c}, ca_1fperiod_draw_BVAR_{%c})  'converts the matrix to series   "1fperiod = 1 forecast period ahead
        
         series ca_2fperiod_draw_BVAR_{%c}
         matrix ca_2fperiod_matrix_BVAR_{%c}= @columnextract(draw_2y_bvar_{%c},1)  ' extracts the first column (C1) of the matrix , C1= CURRENT ACCCOUNT Variable
         mtos(ca_2fperiod_matrix_BVAR_{%c}, ca_2fperiod_draw_BVAR_{%c})  'converts the matrix to series   "1fperiod = 1 forecast period ahead
        
         series ca_3fperiod_draw_BVAR_{%c}
         matrix ca_3fperiod_matrix_BVAR_{%c}= @columnextract(draw_3y_bvar_{%c},1)  ' extracts the first column (C1) of the matrix , C1= CURRENT ACCCOUNT Variable
         mtos(ca_3fperiod_matrix_BVAR_{%c}, ca_3fperiod_draw_BVAR_{%c})  'converts the matrix to series   "1fperiod = 1 forecast period ahead

         series ca_4fperiod_draw_BVAR_{%c}
         matrix ca_4fperiod_matrix_BVAR_{%c}= @columnextract(draw_4y_bvar_{%c},1)  ' extracts the first column (C1) of the matrix , C1= CURRENT ACCCOUNT Variable
         mtos(ca_4fperiod_matrix_BVAR_{%c}, ca_4fperiod_draw_BVAR_{%c})  'converts the matrix to series   "1fperiod = 1 forecast period ahead

         series ca_5fperiod_draw_BVAR_{%c}
         matrix ca_5fperiod_matrix_BVAR_{%c}= @columnextract(draw_5y_bvar_{%c},1)  ' extracts the first column (C1) of the matrix , C1= CURRENT ACCCOUNT Variable
         mtos(ca_5fperiod_matrix_BVAR_{%c}, ca_5fperiod_draw_BVAR_{%c})  'converts the matrix to series   "1fperiod = 1 forecast period ahead


         Pageselect Annual
    
        scalar  ca_{%c}_point_forecast_BVAR_2023 = @elem(ca_{%c}_nnb,"2023")
        scalar  ca_{%c}_point_forecast_BVAR_2024 = @elem(ca_{%c}_nnb,"2024")
        scalar  ca_{%c}_point_forecast_BVAR_2025 = @elem(ca_{%c}_nnb,"2025")
        scalar  ca_{%c}_point_forecast_BVAR_2026 = @elem(ca_{%c}_nnb,"2026")
        scalar  ca_{%c}_point_forecast_BVAR_2027 = @elem(ca_{%c}_nnb,"2027")
 
         copy Annual\ca_{%c}_point_forecast_BVAR_2023 distributionBVAR\*   'copy current account point forecast from "annual page" to "distribution" page
         copy Annual\ca_{%c}_point_forecast_BVAR_2024 distributionBVAR\*     'copy current account point forecast from "annual page" to "distribution" page
         copy Annual\ca_{%c}_point_forecast_BVAR_2025 distributionBVAR\*  'copy current account point forecast from "annual page" to "distribution" page
         copy Annual\ca_{%c}_point_forecast_BVAR_2026 distributionBVAR\*   'copy current account point forecast from "annual page" to "distribution" page
         copy Annual\ca_{%c}_point_forecast_BVAR_2027 distributionBVAR\*   'copy current account point forecast from "annual page" to "distribution" page

         Pageselect distributionBVAR 
          'SIMULATED SERIES'
           '-----------------------------
         genr ca_1_forecast_draws_BVAR_{%c} = ca_1fperiod_draw_BVAR_{%c}+ca_{%c}_point_forecast_BVAR_2023   'generating 1 forecast period ahead; combining point forcasts and the random draws which we generated , with zero mean
         genr ca_2_forecast_draws_BVAR_{%c} = ca_2fperiod_draw_BVAR_{%c}+ca_{%c}_point_forecast_BVAR_2024   'generating 2 forecast periods ahead; combining point forcasts and the random draws which we generated , with zero mean
         genr ca_3_forecast_draws_BVAR_{%c} = ca_3fperiod_draw_BVAR_{%c}+ca_{%c}_point_forecast_BVAR_2025   'generating 3 forecast periods ahead; combining point forcasts and the random draws which we generated , with zero mean
         genr ca_4_forecast_draws_BVAR_{%c} = ca_4fperiod_draw_BVAR_{%c}+ca_{%c}_point_forecast_BVAR_2026   'generating 4 forecast periods ahead; combining point forcasts and the random draws which we generated , with zero mean
         genr ca_5_forecast_draws_BVAR_{%c} = ca_5fperiod_draw_BVAR_{%c}+ca_{%c}_point_forecast_BVAR_2027   'generating 5 forecast periods ahead; combining point forcasts and the random draws whi


         '--------------DISTRIBUTION: KERNEL DENSITY , assmuing Normal (Gaussian)---------------'  
          'Here we study the distribution of 1, 2, 3, 4, and 5 period ahead forecast for CA balance. Annual data. 
          '-------------------------------------------------------------------------------------------------------------------------
           ca_1_forecast_draws_BVAR_{%c}.distdata(dtype=kernel, k=n) ca_pdf_BVAR_{%c}_2023
           show ca_pdf_BVAR_{%c}_2023.xyline
          
           ca_2_forecast_draws_BVAR_{%c}.distdata(dtype=kernel, k=n) ca_pdf_BVAR_{%c}_2024
           show ca_pdf_BVAR_{%c}_2024.xyline

           ca_3_forecast_draws_BVAR_{%c}.distdata(dtype=kernel, k=n) ca_pdf_BVAR_{%c}_2025
           show ca_pdf_BVAR_{%c}_2025.xyline

           ca_4_forecast_draws_BVAR_{%c}.distdata(dtype=kernel, k=n) ca_pdf_BVAR_{%c}_2026
           show ca_pdf_BVAR_{%c}_2026.xyline

           ca_5_forecast_draws_BVAR_{%c}.distdata(dtype=kernel, k=n) ca_pdf_BVAR_{%c}_2027
           show ca_pdf_BVAR_{%c}_2027.xyline




           '-------------------------------------------------------------------------------------------------------------------------
            'CALCULATE THE PROBABILITY OF CA (UN)SUSTAINABILITY 
                  'Elements:
                  '1. Threshold  = 5, 8,
                  '2. Mean 
                  '3. Standard Deviation
           '-------------------------------------------------------------------------------------------------------------------------






Next '!c
'STOP

'-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
'Bayesian Time-Varying Coefficient VAR Model  (BTVC-VAR)
'-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

'It is often difficult to justify the VAR assumption that model parameters are constant over time. For example, a basic VAR fitted to post-war macroeconomic data assumes that economic relationships have not changed since the mid-1940s.
 'Two popular modeling approaches that do away with this assumption are the switching VAR and the time-varying coefficients VAR (TVCVAR). 
T'he switching VAR deals with occasional discrete changes (e.g., structural breaks), whereas the TVCVAR handles constant, smooth changes. The discussion here pertains to the latter.
'--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Pageselect Annual

For !c = 1 to 3 '4 '5   'total number of selected countries
	  %c = table_countries(!c,1)  'table with 4 rows and 1 column

        For !smpl = 0 to !num_forecasts

         ' 1st you estimate the BTVC-VAR model
          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}_var05.btvcvar (t0=50) 1 2 CA_{%c} GDP_GROWTH_{%c} TRADE_OPENNESS_{%c} REER_ZD_{%c}      'Estimate BTVC-VAR  : The model contains errors and could not be compiled in "CA_{%C}_VAR05.FORECAST(F=NA) NNT" on line 789.
          'var myvar.btvcvar(t0=40, nsub=12, seed=342458900, rng=kn, showci, cilevels="0.3 0.5") 1 3 CA_{%c} GDP_GROWTH_{%c} TRADE_OPENNESS_{%c} REER_ZD_{%c}  
          
         ' 2nd you calculate out of sample forecasts and forecasts errors (for all 4 variables in the model)
           smpl %start_forecast_date+!smpl %start_forecast_date+!smpl+!forc_period_ahead 'oos 'out-of-sample
           ca_{%c}_var05.forecast(f=na) NNT    ' forecasts for all 4 variables using BTVC-VAR
           genr errorf_gdp_growth_{%c}_var05 = gdp_growth_{%c} - gdp_growth_{%c}_NNT 'gdp_growth forecasts error
           genr errorf_ca_{%c}_var05 = CA_{%c} - CA_{%c}_NNT ' CA forecasts error
           genr errorf_reer_zd_{%c}_var05 = reer_zd_{%c} - reer_zd_{%c}_NNT ' reer_zd forecasts error
           genr errorf_trade_openness_{%c}_var05 = trade_openness_{%c} - trade_openness_{%c}_NNT ' trade_openness forecasts error

         Next ' !smpl

         ' 3rd: after you calculated forecasts for all periods, you create a group of forecast errors:
           group groupBTVC_forecast_errors_{%c} errorf_gdp_growth_{%c}_var05 errorf_ca_{%c}_var05 errorf_reer_zd_{%c}_var05  errorf_trade_openness_{%c}_var05
           show groupBTVC_forecast_errors_{%c}
          ' 4th: then calculate the covariance matrix over the forecast sample period
           smpl %start_forecast_date %last_Y_obs
           d covsbtvc*
      '     sym covs = @var(ca_zaf_var02_f)
            sym covsbtvc_{%c} = @cov(groupbtvc_forecast_errors_{%c}) ' note: @cov and not @var calculates the covariance matrix
            show covsbtvc_{%c}

          ' 5th: you draw random numbers
            matrix draw_btvc_{%c}=@rmvnorm(covsbtvc_{%c}, 1000) 'random draws from the normal distribution
            show  draw_btvc_{%c}




           '-------------------------------------------------------------------------------------------------------------------------
            'CALCULATE THE PROBABILITY OF CA (UN)SUSTAINABILITY 
                  'Elements:
                  '1. Threshold  = 5, 8,
                  '2. Mean 
                  '3. Standard Deviation
           '-------------------------------------------------------------------------------------------------------------------------


Next '!c

STOP


'
' this is my covariance matrix of the residuals from a var I estimatedm
'matrix covs = cazaf_var.@residcov
'd covs*
'sym covs = ca_zaf_var02.@residcov
'matrix draw_zaf=@rmvnorm(covs, 1000) 'normal
'show  draw_zaf



'pageselect\untiltled


' this is the subroutine taken from the posted code in Eviews forum

'!size=4
'matrix(!size,!size) rnd_covs
'call rnd_pos_def_mat(rnd_covs)
'' I was having some trouble with the near singular matrix problem. This while was my best solution for now...
'while @issingular(@implode(rnd_covs))=1 ''
 ' call rnd_pos_def_mat(rnd_covs)
'wend
'call rnd_multivariate_normal(rnd_covs)

'subroutine local rnd_pos_def_mat(matrix mat_res)
'!size=@columns(mat_res)
'matrix(!size,!size) tmp=0
'for !i=1 to !size
' tmp(!i,!i)=@sqrt(@rfdist(100,100))
   'for !j=!i+1 to !size
    ' tmp(!i,!j)=@nrnd
   'next
'next
'matrix mat_res=@transpose(tmp)*tmp
'endsub


subroutine rnd_multivariate_normal(covs)
'sym covs_sym=@implode(covs)   'converting the input covariance matrix covs into a symmetric matrix covs_sym.
matrix cholesky=@cholesky(covs)   'It performs a Cholesky decomposition on covs_sym to obtain the lower triangular matrix cholesky.Performing the Cholesky decomposition on a symmetric positive definite matrix (covs_sym) and storing the result in a matrix variable (cholesky). The resulting cholesky matrix will be a lower triangular matrix, and its conjugate transpose will be the upper triangular matrix needed for the original matrix reconstruction. 
matrix(@columns(covs),@obssmpl) vz_mat  'It then generates a matrix vz_mat of random normal deviates.
for !i=1 to @columns(covs) 
   series z_norm=nrnd
   stom(z_norm,vz_norm)
   rowplace(vz_mat,@transpose(vz_norm),!i)
   delete z_norm vz_norm
next
matrix mat_xs=cholesky*vz_mat   'It multiplies cholesky with vz_mat to obtain a matrix mat_xs representing multivariate normal samples.
matrix mat_xs=@transpose(mat_xs)  ' 
'mtos(mat_xs, ca_zaf_xs)
mtos(mat_xs, xs)
'if @isseries(ca_zaf_xs) then
  '  freeze(ca_zaf_xs) ' This freezes the existing series for inspection
'endif
' Output information about the generated series
'show "Number of rows in ca_zaf_xs: ", @obs(ca_zaf_xs)
'show ca_zaf_xs
'mtos(mat_xs,ca_zaf_xs)  'converts the marix to a series. Each series corresponds to a column of the original matrix.
delete covs_sym cholesky vz_mat mat_xs
endsub





'--------------------
'Bootstrapping
'---------------------

'!num_bootstrapping=1000

'Loop for bootstrap samples
'for !i = 1 to !num_bootstrapping
      ' vector@resample(ca_zaf)
'Next


