Voir comment télécharger gratuitement des robots de trading
Retrouvez-nous sur Facebook !
Rejoignez notre page de fans
Un script intéressant ?
Poster un lien vers celui-ci -
laisser les autres l'évaluer
Vous avez aimé le script ? Essayez-le dans le terminal MetaTrader 5
Bibliothèque

Kalman: exact diffuse Kalman filter, local level and time-varying hedge ratio - bibliothèque pour MetaTrader 5

Mohamed-amine Baddir
Mohamed-amine Baddir
Je développe des Expert Advisors pour MetaTrader 5 et je les teste correctement avant que vous ne les utilisiez pour trader.
Ce que je fais :
- Je transforme votre stratégie, votre script TradingView ou vos règles écrites en un Expert Advisor MT5 propre et professionnel
Vues:
101
Publié:
Mise à jour:
\MQL5\Include\Kalman\
Kalman.mqh (33.88 KB) afficher
\MQL5\Scripts\Kalman\
MQL5 Freelance Besoin d'un robot ou d'un indicateur basé sur ce code ? Commandez-le sur Freelance Aller sur Freelance

Kalman.mqh is a Kalman filter and smoother for linear Gaussian state space models with one observation per bar. It starts with the exact diffuse initialization of Durbin and Koopman, so no first state and no large "starting variance" has to be guessed, it accepts missing values, and it estimates the variances by maximum likelihood for three ready models: a local level (a level that drifts, seen with noise), a local linear trend, and a regression whose coefficients drift, for example the hedge ratio of a pair. No DLL.

Usage

#include <Kalman\Kalman.mqh>

vector y, x;                               // for example log prices of two symbols on the same bars
// ... fill y and x ...
matrix X(x.Size(), 1);
X.Col(x, 0);
CKalman k;
if(k.FitDynamicRegression(y, X, true))     // intercept and hedge ratio follow random walks
  {
   const int last = k.Observations() - 1;
   double beta = k.Filtered(last, 1);       // hedge ratio now, from the data up to now
   double sd = k.FilteredStd(last, 1);      // its standard deviation
   double z = k.Innovation(last) / MathSqrt(k.InnovationVariance(last));   // last forecast error in sd
  }

CKalman ll;
if(ll.FitLocalLevel(y))                    // y = level + noise
  {
   double now = ll.Filtered(ll.Observations() - 1, 0);
   vector mean, var;
   ll.Forecast(10, mean, var);
  }

Any other model y(t) = Z(t) a(t) + e(t), a(t+1) = T a(t) + w(t) can be set with SetModel(Z, T, Q, H), then Filter(y) and Smooth(). SetDynamicRegression() runs the regression with variances you choose instead of fitting them.

What it gives

  • Filtered states (from the data up to each bar: what was known then, the one to use in a test) and smoothed states (from all the data), each with its standard deviation; one step forecast errors and their variances; forecasts of y with their variances.
  • The log-likelihood (exact diffuse, as defined by Durbin and Koopman), AIC and BIC, the number of diffuse bars.
  • Variances by maximum likelihood on their logarithms: a grid of 20 starts, BFGS from the 3 best, a Nelder-Mead polish. The likelihood of the regression can have two maxima, one of them with no observation noise; the grid finds the higher one.

Numerical care

  • The diffuse period is ended by counting: each bar that removes a diffuse direction lowers its rank by one. A test on the size of the diffuse variance fails when two prices are almost equal.
  • In the regression the regressors are centered inside, an exact change of coordinates of the state that the results are converted back from. With a raw log price of gold (always between 7.5 and 8.4) next to the intercept, the covariances of the state are badly conditioned: the standard deviations of the smoothed hedge ratio were 7% wrong without it, they are within 6e-6 of a 40-digit computation with it.
  • The optimizer uses a separate likelihood routine on plain arrays: a fit of 2 000 bars takes 10 to 400 ms.

Example

The script KalmanHedge.mq5 fits the regression of one symbol on another (log prices by default), prints the fitted variances, the hedge ratio now and 20, 60, 250 and 500 bars ago as it was known then, with its standard deviation and its smoothed value, the z-scores of the last forecast errors (the signal of a Kalman pair trade) and the share of errors beyond 2 standard deviations (picture 1). It can write the hedge ratio of every bar to a CSV file (picture 2).

Output of KalmanHedge.mq5

Hedge ratio of silver on gold

Picture 3: the hedge ratio of the Kalman filter, known each day from the past only, against an ordinary regression on the last 60 days. The rolling regression jumps from below 0 to above 4, and its day-to-day changes have a standard deviation of 0.060, against 0.009 for the filter. The filter does not need a window length: it estimates from the data how fast the ratio really drifts.

Kalman filter against a 60-day rolling regression

Picture 4: log silver against log gold, one shade per year. A single regression line over the six years (slope 1.14) misses whole years, above it in 2021 and 2026, below it in 2025. This is why the hedge ratio is modelled as a value that moves slowly instead of a constant.

Log silver against log gold by year

Checked

On six series (simulated local level, the same with 10% missing values, simulated local linear trend, the log price of gold, a simulated regression and silver on gold, H4), against the state space models of statsmodels 0.15 with exact diffuse initialization and against a 40-digit computation of the same recursions:

  • the same number of diffuse bars; log-likelihoods and smoothed states within 2e-11 of the 40-digit values, smoothed standard deviations within 2e-9 (6e-6 on silver on gold). statsmodels differs from the 40-digit values by up to 7e-9 in the log-likelihood and 2e-2 in the standard deviations on the same data;
  • maximum likelihood: the same variances and likelihood as statsmodels (within 3e-7) on every series.

Files

Kalman.mqh goes to MQL5\Include\Kalman, KalmanHedge.mq5 to MQL5\Scripts\Kalman.

RegimeHMM: market regimes with a hidden Markov model RegimeHMM: market regimes with a hidden Markov model

Gaussian hidden Markov model fitted by Baum-Welch: regime probabilities without look-ahead, most likely path, expected durations and regime forecasts.

CME equity index futures holiday calendar CME equity index futures holiday calendar

Holidays and early halts of the CME equity index futures (S&P 500, Nasdaq-100, Dow, Russell 2000, E-mini and Micro), computed from the US holiday rules for any year, with a script that checks the calendar against your broker's own M1 history.

Cointegration: ADF, Engle-Granger and Johansen tests with a pair scanner Cointegration: ADF, Engle-Granger and Johansen tests with a pair scanner

Unit root and cointegration tests (ADF, Engle-Granger, Johansen) with MacKinnon p-values, hedge ratio, half-life and z-score of the spread, and a pair scanner.

Basket Pair Closer Basket Pair Closer

Position manager for MT5 that closes the best winner together with the worst loser when their combined result reaches your minimum. Basket take profit and stop loss in money, magic filter, simple panel. Works with grid, martingale and manual trades. Open source code.