거래 로봇을 무료로 다운로드 하는 법을 시청해보세요
당사를 Telegram에서 찾아주십시오!
당사 팬 페이지에 가입하십시오
스크립트가 흥미로우신가요?
그렇다면 링크 to it -
하셔서 다른 이들이 평가할 수 있도록 해보세요
스크립트가 마음에 드시나요? MetaTrader 5 터미널에서 시도해보십시오
라이브러리

Kalman: exact diffuse Kalman filter, local level and time-varying hedge ratio - MetaTrader 5용 라이브러리

Mohamed-amine Baddir
Mohamed-amine Baddir
MetaTrader 5용 Expert Advisor(EA)를 개발하고, 실제 거래에 사용하기 전에 충분히 테스트합니다.
제가 제공하는 작업:
고객의 전략, TradingView 스크립트 또는 문서화된 규칙을 깔끔한 MT5 Expert Advisor로 구현
기존 EA 수정 및 문제 해결: % 기준 리스크 포지션 사이징, 트레일링 스톱, 세션 및 시간 필터, 스프레드 필터, 멀티 심볼 포트폴리오, 드로다운 보호 기능
조회수:
78
게시됨:
업데이트됨:
\MQL5\Include\Kalman\
Kalman.mqh (33.88 KB) 조회
\MQL5\Scripts\Kalman\
MQL5 프리랜스 이 코드를 기반으로 한 로봇이나 지표가 필요하신가요? 프리랜스로 주문하세요 프리랜스로 이동

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.