//+------------------------------------------------------------------+ //| ADF.mqh | //| Copyright 2000-2026, MetaQuotes Ltd. | //| www.mql5.com | //+------------------------------------------------------------------+ #property copyright "Copyright 2026" #property link "" #property version "1.00" //+------------------------------------------------------------------+ #include //+------------------------------------------------------------------+ //--- Lag selection modes enum ENUM_LAG_MODE { LAG_FIXED, // Fixed lag (user-defined) LAG_MIN_AIC, // Minimization from 0 to max lag using AIC LAG_MIN_BIC // Minimization from 0 to max lag using BIC }; //+------------------------------------------------------------------+ //--- Significance levels enum ENUM_SIGNIFICANCE_LEVEL { SIGNIFICANCE_LEVEL_1PC, // 1% significance level SIGNIFICANCE_LEVEL_5PC, // 5% significance level SIGNIFICANCE_LEVEL_10PC // 10% significance level }; //+------------------------------------------------------------------+ //--- Test specification enum ENUM_ADF_TYPE { ADF_TYPE_NONE, // No trend and no constant ADF_TYPE_DRIFT, // With constant, no trend ADF_TYPE_TREND // With trend and constant }; //+------------------------------------------------------------------+ //--- Series analysis verdict in the Dolado procedure enum ENUM_ADF_VERDICT { ADF_STATIONARY_TREND, // Stationary around a deterministic trend ADF_STATIONARY_DRIFT, // Stationary around a non-zero mean ADF_STATIONARY_ZERO, // Stationary around zero ADF_NONSTATIONARY_TREND, // Non-stationary with a deterministic trend ADF_NONSTATIONARY_DRIFT, // Random walk with drift ADF_NONSTATIONARY_RANDOM_WALK, // Pure random walk ADF_ERROR // Calculation error }; //+------------------------------------------------------------------+ //| Linear regression estimation via Ordinary Least Squares (OLS) | //| Model: y = X * beta + e, beta = (X^T * X)^(-1) * X^T * y | //| | //| Input parameters: | //| y - dependent variable vector (size n) | //| X - regressor matrix (size n x k; for k = 0, a model without | //| regressors is estimated, where rss = y^T * y) | //| | //| Output parameters: | //| rss - residual sum of squares (RSS) | //| tau - t-statistic for the last column of matrix X (index k-1) | //| | //| Return value: | //| true on success, false on dimension mismatch, insufficient | //| degrees of freedom (n <= k), or singular (X^T * X) matrix | //+------------------------------------------------------------------+ bool ADF_OLS(const vector& y, const matrix& X, double& rss, double &tau) { ulong n=y.Size(); rss=tau=0.0; if(n < 2) return false; ulong k=X.Cols(); if(k==0) { rss=y.Dot(y); return true; } if(X.Rows()!=n || n<=k) return false; matrix Xt = X.Transpose(); matrix XtX = Xt.MatMul(X); // Check full rank before matrix inversion if(XtX.Rank() < XtX.Rows()) return false; matrix invXtX = XtX.Inv(); vector beta = invXtX.MatMul(Xt.MatMul(y)); // Residuals and residual sum of squares (RSS) vector resid = y - X.MatMul(beta); rss = resid.Dot(resid); //--- Calculate tau double var_beta = rss * invXtX[k-1][k-1] / double(n - k); if(var_beta > DBL_MIN) tau = beta[k-1] / MathSqrt(var_beta); return true; } //+------------------------------------------------------------------+ //| Augmented Dickey-Fuller (ADF) test with constant and trend | //| Model: d_y[t] = a + b*t + g*y[t-1] + sum(d_i * d_y[t-i]) + e[t] | //| | //| Input parameters: | //| y - time series to test (forward indexing) | //| p_max - fixed lag (for LAG_FIXED) or maximum lag for | //| selection from 0 to p_max | //| lag_method - lag selection method (ENUM_LAG_MODE) | //| | //| Output parameters: | //| p - selected optimal number of difference lags | //| tau3 - t-statistic for hypothesis H0: g = 0 | //| phi3 - F-statistic for joint hypothesis H0: b = g = 0 | //| phi2 - F-statistic for joint hypothesis H0: a = b = g = 0| //| | //| Return value: | //| true on success, false if sample size is insufficient, | //| regressor matrix is singular, or residual variance is zero | //+------------------------------------------------------------------+ bool ADF_trend(const vector& y, ulong p_max, ENUM_LAG_MODE lag_method, ulong& p, double& tau3, double& phi3, double& phi2) { //--- Check sample size sufficiency ulong T = y.Size(), k_max = p_max + 3; if(T <= p_max + 1 + k_max) return false; //--- Determine number of difference lags p if(lag_method==LAG_FIXED || p_max==0) p=p_max; else { //--- Prepare data for p optimization ulong T_eff=T-p_max-1; vector d(T_eff); matrix X(T_eff,k_max); for(ulong i=0; ip_max) return false; } //--- Prepare data for calculating tau3, phi3, phi2 statistics ulong T_eff=T-p-1, k=p+3; vector d(T_eff); matrix X(T_eff,k); for(ulong i=0; ip_max) return false; } //--- Prepare data for calculating tau2, phi1 statistics ulong T_eff=T-p-1, k=p+2; vector d(T_eff); matrix X(T_eff,k); for(ulong i=0; ip_max) return false; } //--- Prepare data for calculating tau1 statistic ulong T_eff=T-p-1, k=p+1; vector d(T_eff); matrix X(T_eff,k); double rss; for(ulong i=0; i 1%, 1 -> 5%, 2 -> 10% double inv_T = 1.0 / double(T_eff); double inv_T2 = inv_T * inv_T; double inv_T3 = inv_T2 * inv_T; //--- 1. MacKinnon (2010) coefficients for tau1, tau2, tau3: [model][level][b_inf, b1, b2, b3] static const double mk[3][3][4] = { { // tau1 (nc: no constant and no trend) {-2.56574, -2.2358, -3.627, 0.000}, {-1.94100, -0.2686, -3.365, 31.223}, {-1.61682, 0.2656, -2.714, 25.364} }, { // tau2 (c: with constant) {-3.43035, -6.5393, -16.786, -79.433}, {-2.86154, -2.8903, -4.234, -40.040}, {-2.56677, -1.5384, -2.809, 0.000} }, { // tau3 (ct: with constant and trend) {-3.95877, -9.0531, -28.428, -134.155}, {-3.41049, -4.3904, -9.036, -45.374}, {-3.12705, -2.5856, -3.925, -22.380} } }; for(int m = 0; m < 3; ++m) crit6[m] = mk[m][s][0] + mk[m][s][1] * inv_T + mk[m][s][2] * inv_T2 + mk[m][s][3] * inv_T3; //--- 2. Dickey-Fuller (1981) tables for phi1, phi2, phi3: [statistic][level][T node] static const double inv_nodes[6] = {1.0/25.0, 1.0/50.0, 1.0/100.0, 1.0/250.0, 1.0/500.0, 0.0}; static const double df_phi[3][3][6] = { { // phi1 (with constant: H0: a = g = 0) {7.88, 7.06, 6.70, 6.52, 6.47, 6.43}, // 1% {5.18, 4.86, 4.71, 4.63, 4.61, 4.59}, // 5% {4.12, 3.94, 3.86, 3.81, 3.79, 3.78} // 10% }, { // phi2 (with trend: H0: a = b = g = 0) {8.21, 7.02, 6.50, 6.22, 6.15, 6.09}, // 1% {5.68, 5.13, 4.88, 4.75, 4.71, 4.68}, // 5% {4.67, 4.31, 4.16, 4.07, 4.05, 4.03} // 10% }, { // phi3 (with trend: H0: b = g = 0) {10.61, 9.31, 8.73, 8.43, 8.34, 8.27}, // 1% { 7.24, 6.73, 6.49, 6.34, 6.30, 6.25}, // 5% { 5.91, 5.61, 5.47, 5.39, 5.36, 5.34} // 10% } }; //--- Clamp critical values to the boundary table node (T = 25) when T_eff <= 25 if(T_eff <= 25) { for(int f = 0; f < 3; ++f) crit6[3 + f] = df_phi[f][s][0]; return true; } //--- Piecewise linear interpolation over 1 / T_eff for T_eff > 25 int idx = 4; for(int k = 0; k < 5; ++k) { if(inv_T >= inv_nodes[k + 1]) { idx = k; break; } } double w = (inv_T - inv_nodes[idx + 1]) / (inv_nodes[idx] - inv_nodes[idx + 1]); for(int f = 0; f < 3; ++f) crit6[3 + f] = df_phi[f][s][idx + 1] + w * (df_phi[f][s][idx] - df_phi[f][s][idx + 1]); return true; } //+------------------------------------------------------------------+ //| Augmented Dickey-Fuller (ADF) test with full report output | //| | //| Input parameters: | //| y - time series to test (forward indexing) | //| model_type - model specification (ENUM_ADF_TYPE: no constant, | //| with constant, or with constant and trend) | //| lag_method - lag selection method (defaults to BIC) | //| p_max - fixed lag (for LAG_FIXED) or upper bound for lag | //| search (for LAG_MIN_AIC / BIC). | //| Defaults to ULONG_MAX — auto-calculated via | //| Schwert's rule floor(12 * (T / 100)^(1/4)) both | //| as the search upper bound and as a fixed lag | //| slvl - significance level for critical values | //| (defaults to 5%) | //| | //| Return value: | //| None (void) — prints a formatted report with estimated | //| statistics, critical values, and H0 hypothesis verdict to the | //| terminal Experts log | //+------------------------------------------------------------------+ void ADF_Test(const vector& y, ENUM_ADF_TYPE model_type, ENUM_LAG_MODE lag_method=LAG_MIN_BIC, ulong p_max=ULONG_MAX, ENUM_SIGNIFICANCE_LEVEL slvl=SIGNIFICANCE_LEVEL_5PC) { Print("##########################################"); Print("# Augmented Dickey-Fuller Unit Root Test #"); Print("##########################################"); ulong T=y.Size(); if(T<20) { Print("Sample too short"); return; } //--- Schwert's rule if(p_max==ULONG_MAX) p_max = (ulong)MathFloor(12.0 * MathPow(double(T) / 100.0, 0.25)); int n_stat=0; string stat_names[3]; double stat[3],stat_crits[3], slvl_percent; ulong p=0; vector crits(6); switch(slvl) { case SIGNIFICANCE_LEVEL_1PC: slvl_percent=1.0; break; case SIGNIFICANCE_LEVEL_5PC: slvl_percent=5.0; break; case SIGNIFICANCE_LEVEL_10PC: slvl_percent=10.0; break; } switch(model_type) { case ADF_TYPE_TREND: if(!ADF_trend(y,p_max,lag_method,p,stat[0],stat[1],stat[2])) { Print("ADF_trend() error"); return; } if(!ADF_CriticalValues(T-p-1,slvl,crits)) { Print("ADF_CriticalValues() error"); return; } stat_names[0]="tau3"; stat_names[1]="phi3"; stat_names[2]="phi2"; stat_crits[0]=crits[2]; stat_crits[1]=crits[5]; stat_crits[2]=crits[4]; n_stat=3; break; case ADF_TYPE_DRIFT: if(!ADF_drift(y,p_max,lag_method,p,stat[0],stat[1])) { Print("ADF_drift() error"); return; } if(!ADF_CriticalValues(T-p-1,slvl,crits)) { Print("ADF_CriticalValues() error"); return; } stat_names[0]="tau2"; stat_names[1]="phi1"; stat_crits[0]=crits[1]; stat_crits[1]=crits[3]; n_stat=2; break; case ADF_TYPE_NONE: if(!ADF_none(y,p_max,lag_method,p,stat[0])) { Print("ADF_none() error"); return; } if(!ADF_CriticalValues(T-p-1,slvl,crits)) { Print("ADF_CriticalValues() error"); return; } stat_names[0]="tau1"; stat_crits[0]=crits[0]; n_stat=1; break; } //--- Formatted printout in R::urca style string model_str = (model_type == ADF_TYPE_TREND) ? "trend (const + trend)" : (model_type == ADF_TYPE_DRIFT) ? "drift (const)" : "none"; string lag_str = (lag_method == LAG_FIXED) ? "fixed" : (lag_method == LAG_MIN_AIC) ? "AIC" : "BIC"; PrintFormat("Model: %s | Sample size T: %llu (T_eff: %llu)", model_str, T, T - p - 1); PrintFormat("Lags p: %llu (selection: %s, p_max: %llu) | Significance: %.0f%%", p, lag_str, p_max, slvl_percent); Print("---------------------------------------------------------------"); Print("Statistic | Value | Critical Val | H0 Decision"); Print("---------------------------------------------------------------"); for(int i = 0; i < n_stat; ++i) { // i == 0 is always tau (left-tailed test), i > 0 is always phi (right-tailed test) bool reject_h0 = (i == 0) ? (stat[i] < stat_crits[i]) : (stat[i] > stat_crits[i]); string verdict = reject_h0 ? "REJECT H0" : "Fail to reject H0"; PrintFormat("%-9s | %9.4f | %12.4f | %s", stat_names[i], stat[i], stat_crits[i], verdict); } Print("---------------------------------------------------------------"); } //+------------------------------------------------------------------+ //| Sequential unit root testing procedure following | //| Dolado-Jenkinson-Sosvilla-Rivero (Dolado et al., 1990) | //| Automatically determines the deterministic specification | //| (trend -> constant -> no constant) and tests for stationarity | //| | //| Input parameters: | //| y - time series to test (forward indexing) | //| lag_method - lag selection method (defaults to BIC) | //| p_max - fixed lag (for LAG_FIXED) or upper bound for lag | //| search (for LAG_MIN_AIC / BIC). | //| Defaults to ULONG_MAX — auto-calculated via | //| Schwert's rule floor(12 * (T / 100)^(1/4)) | //| slvl - significance level for hypothesis testing | //| (defaults to 5%) | //| | //| Return value: | //| Final verdict on series behavior (ENUM_ADF_VERDICT): | //| stationary (around trend, constant, or zero), | //| non-stationary (with trend, drift, or random walk), | //| or ADF_ERROR on invalid input data or calculation failure | //+------------------------------------------------------------------+ ENUM_ADF_VERDICT ADF_Dolado(const vector& y, ENUM_LAG_MODE lag_method=LAG_MIN_BIC, ulong p_max=ULONG_MAX, ENUM_SIGNIFICANCE_LEVEL slvl=SIGNIFICANCE_LEVEL_5PC) { ulong T=y.Size(); if(T<20) return ADF_ERROR; if(p_max==ULONG_MAX) p_max = (ulong)MathFloor(12.0 * MathPow(double(T) / 100.0, 0.25)); ulong p; vector crits(6); double plvl = (slvl == SIGNIFICANCE_LEVEL_1PC) ? 0.01 : (slvl == SIGNIFICANCE_LEVEL_5PC) ? 0.05 : 0.1; int err=0; double crit_norm = MathQuantileNormal(plvl,0.0,1.0,err); if(err!=0) return ADF_ERROR; //--- Step 1: Model with constant and trend double tau3,phi3,phi2; if(!ADF_trend(y,p_max,lag_method,p,tau3,phi3,phi2)) return ADF_ERROR; if(!ADF_CriticalValues(T-p-1,slvl,crits)) return ADF_ERROR; if(tau3 < crits[2]) return ADF_STATIONARY_TREND; if(phi3 > crits[5]) { if(tau3 < crit_norm) return ADF_STATIONARY_TREND; return ADF_NONSTATIONARY_TREND; } //--- Step 2: Model with constant, no trend double tau2,phi1; if(!ADF_drift(y,p_max,lag_method,p,tau2,phi1)) return ADF_ERROR; if(!ADF_CriticalValues(T-p-1,slvl,crits)) return ADF_ERROR; if(tau2 < crits[1]) return ADF_STATIONARY_DRIFT; if(phi1 > crits[3]) { if(tau2 < crit_norm) return ADF_STATIONARY_DRIFT; return ADF_NONSTATIONARY_DRIFT; } //--- Step 3: Model without constant and trend double tau1; if(!ADF_none(y, p_max, lag_method, p, tau1)) return ADF_ERROR; if(!ADF_CriticalValues(T - p - 1, slvl, crits)) return ADF_ERROR; if(tau1 < crits[0]) return ADF_STATIONARY_ZERO; return ADF_NONSTATIONARY_RANDOM_WALK; } //+------------------------------------------------------------------+