Article-23677-EGARCH-MQL5-V.../EGARCH_InnovationZscore.mq5

228 lines
9.7 KiB
MQL5
Raw Permalink Normal View History

2026-07-24 23:03:06 +02:00
//+------------------------------------------------------------------+
//| EGARCH_InnovationZscore.mq5 |
//| Copyright 2025, MetaQuotes Ltd. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.00"
// Preprocessor directives and indicator properties
#define __SLSQP__ // Enable Sequential Least Squares Programming optimization algorithm
#property indicator_separate_window // Render indicator in an independent subwindow
#include "Arch\Univariate\mean.mqh" // Include statistical mean model header dependencies
// Define fixed indicator visual threshold levels
#property indicator_level1 2.0 // Upper extreme threshold line
#property indicator_level2 0.0 // Zero baseline
#property indicator_level3 -2.0 // Lower extreme threshold line
// Define buffer and plotting counts
#property indicator_buffers 1
#property indicator_plots 1
// --- Plot 1: Standardized Innovation Z-Score
#property indicator_label1 "Eiz"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrRed
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//+------------------------------------------------------------------+
//| INPUT PARAMETERS |
//+------------------------------------------------------------------+
input int BarsToDraw = 500; // Number of historical bars to calculate and render
input ulong HistoryLen = 200; // Rolling sample size (lookback period) for EGARCH fitting
input ulong WindowLen = 20; // Rolling window length for Z-score standardizing residuals
input double ScaleFactor = 100.; // Multiplier applied to log returns (improves numerical optimizer stability)
input ENUM_MEAN_MODEL MeanModel = MEAN_CONSTANT; // Model type for time-series conditional mean
input bool MeanConstant = true; // Include intercept constant in mean specification
input string MeanLags = ""; // Comma-separated list of AR lag terms (e.g. "1,2")
ENUM_VOLATILITY_MODEL VolatilityModel = VOL_EGARCH; // Volatility process specified as Exponential GARCH
input ulong _P_ = 1; // GARCH order (lagged conditional log-variances)
input ulong _O_ = 1; // Asymmetry order (leverage/asymmetric magnitude terms)
input ulong _Q_ = 1; // ARCH order (lagged innovations)
input int Volatility_Seed = 0; // Seed for volatility model random generator initialization
input ENUM_DISTRIBUTION_MODEL ErrorDistribution = DIST_NORMAL; // Innovation error distribution assumption
input int Distribution_Seed = 0; // Seed for distribution model random generator initialization
//+------------------------------------------------------------------+
//| GLOBAL INDICATOR BUFFERS AND STATE VARIABLES |
//+------------------------------------------------------------------+
// Dynamic array mapped to indicator plot buffer
double EizBuffer[];
// Computational vectors and model pointers
vector returns = vector::Zeros(HistoryLen); // Rolling logarithmic returns vector
vector stdresid = returns; // Model-standardized residuals vector
vector window; // Sliced sub-vector of standardized residuals for local normalization
ArchParameters model_spec; // Struct holding model specifications and hyperparameters
HARX* full_model; // Polymorphic pointer to mean model instance
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Validate lookback window length
if(HistoryLen < 30)
{
Print("Invalid input value for HistoryLen");
return INIT_FAILED;
}
// --- Map dynamic array to primary indicator buffer
SetIndexBuffer(0, EizBuffer, INDICATOR_DATA);
// --- Set plot properties and drawing offset
PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, BarsToDraw);
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
// --- Configure model specifications
model_spec.mean_model_type = MeanModel;
// Parse comma-separated mean lag configuration string if provided
if(StringLen(MeanLags))
{
string lag_info[];
int nlags = StringSplit(MeanLags, StringGetCharacter(",", 0), lag_info);
if(nlags > 0)
{
for(uint i = 0; i < uint(nlags); ++i)
{
if(StringLen(lag_info[i]) > 0)
{
if(model_spec.mean_lags.Resize(model_spec.mean_lags.Size() + 1, 3))
model_spec.mean_lags[model_spec.mean_lags.Size() - 1] = StringToDouble(lag_info[i]);
else
{
Print(" error ", GetLastError());
return INIT_FAILED;
}
}
}
}
}
// Set EGARCH structural dynamics and seeds
model_spec.vol_rng_seed = Volatility_Seed;
model_spec.garch_o = _O_;
model_spec.garch_p = _P_;
model_spec.garch_q = _Q_;
model_spec.dist_type = ErrorDistribution;
model_spec.dist_rng_seed = Distribution_Seed;
// Factory instantiation of the requested mean model class
switch(MeanModel)
{
case MEAN_CONSTANT:
full_model = new ConstantMean();
break;
case MEAN_ZERO:
full_model = new ZeroMean();
break;
case MEAN_AR:
full_model = new AR();
break;
default:
full_model = new ConstantMean();
break;
}
// Ensure memory allocation for mean model succeeded
if(CheckPointer(full_model) == POINTER_INVALID)
return INIT_FAILED;
model_spec.vol_model_type = VolatilityModel;
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Free dynamic memory allocated for the mean model instance
if(CheckPointer(full_model) == POINTER_DYNAMIC)
delete full_model;
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int32_t rates_total,
const int32_t prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int32_t &spread[])
{
int32_t limit = 0;
// Verify total bars available meet the required lookback + rendering window
if(rates_total < int32_t(HistoryLen + BarsToDraw))
{
Print("Not enough bars for indicator calculation");
return -1;
}
// Determine starting index for incremental bar calculation
if(prev_calculated <= 0)
{
limit = rates_total - int32_t(fabs(BarsToDraw)); // First run: calculate specified historical depth
ArrayInitialize(EizBuffer, EMPTY_VALUE);
}
else
limit = prev_calculated - 1; // Subsequent runs: update only latest bar(s)
// Main calculation loop iterating through historical price bars
for(int32_t shift = limit; shift < rates_total; ++shift)
{
int32_t from = (shift - int32_t(HistoryLen)) + 1;
// Calculate logarithmic returns over the rolling lookback window
for(int32_t i = from, k = 0; k < int32_t(HistoryLen); ++i, ++k)
returns[k] = log(close[i] / close[i - 1]);
// Scale returns to assist optimizer convergence
returns *= fabs(ScaleFactor);
// Load current sample window into specification structure
model_spec.observations = returns;
// Re-initialize model state with new sample window
if(!full_model.initialize(model_spec))
{
Print(" initialization error ");
return 0;
}
// Fit EGARCH model via maximum likelihood optimization
ArchModelResult result = full_model.fit();
if(!result.conditional_volatility.Size())
{
Print(" model fit error ");
return 0;
}
// Extract full vector of standardized residuals (innovations divided by fitted volatility)
stdresid = result.std_resid();
// Slice out the dynamic evaluation window (last WindowLen entries) from standardized residuals
window = np::sliceVector(stdresid, long(stdresid.Size() - WindowLen));
// Calculate local Z-score of the most recent innovation over the sliced window (with epsilon to prevent division by zero)
EizBuffer[shift] = (window[window.Size() - 1] - window.Mean()) / (window.Std() + 1.e-8);
}
// Return calculated count to optimize subsequent iteration calls
return(rates_total);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+