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

Garch: GARCH, GJR-GARCH and EGARCH volatility models with forecasts - MetaTrader 5용 라이브러리

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

Garch.mqh fits GARCH volatility models to a series of returns by maximum likelihood and forecasts the variance of the next periods. It gives the parameters with classic and robust standard errors, the log-likelihood with AIC and BIC, the conditional variance of every period, the persistence and the half-life of a shock. No DLL; the matrix type of MQL5 is used for the covariances.

Usage

#include <Garch\Garch.mqh>

double y[];                           // returns, for example 100 * log(close[i] / close[i-1])
// ... fill y ...
CGarch g;
g.Model(GARCH_MEAN_CONSTANT, GARCH_VOL_GJR, GARCH_DIST_T);
if(g.Fit(y))
  {
   for(int i = 0; i < g.Parameters(); i++)
      PrintFormat("%s %.5f (%.5f)", g.Name(i), g.Parameter(i), g.StdError(i));   // robust standard error
   double variance[];
   g.Forecast(20, variance);          // variance of each of the next 20 periods
   double half = g.HalfLife();        // periods for a shock to lose half its effect
  }

Models

  • Mean: zero or constant.
  • Variance: GARCH(1,1); GJR-GARCH(1,1,1), where a fall adds gamma times the squared return to the next variance; EGARCH(1,1,1), a model of the log variance with a sign term.
  • Shocks: normal, Student t (standardized) or generalized error distribution (GED), with the shape estimated.

How it works

  • The recursion starts from an exponentially weighted variance of the first 75 residuals, and the variance is kept within bounds taken from an EWMA variance, as in the Python package arch, so the likelihoods of the two are the same for the same parameters.
  • The optimum is found in three steps: quasi-Newton (BFGS) on free parameters for which every point is a valid model, a Nelder-Mead search with the bounds of the parameters, then BFGS again with the bounds that are reached held fixed. The last two steps matter when an optimum sits on a bound (a persistence of 1, a shape at its limit), or when the GED shape is near 1 and the likelihood has kinks.
  • Standard errors come from numerical derivatives with the steps of statsmodels: classic from the inverse Hessian, robust (Bollerslev-Wooldridge) from the sandwich with the scores of each period.
  • Forecasts are exact for GARCH and GJR (a fall has a probability of one half). For EGARCH the first period is exact and the next ones come from a simulation with a seed (ForecastSimulated is also available for every model).

Two things to know

  • EGARCH with Student t shocks has no finite mean variance beyond one period: the exponential of a t variable has no expectation, so simulated forecasts do not settle. Use the normal or GED shocks with EGARCH for forecasts.
  • When the GED shape is close to 1 the fitted mean sits on a kink of the likelihood, and its numerical standard error comes out far too small. arch gives the same figure.

Example

The script GarchExample.mq5 takes the returns of a symbol, fits the nine models with a constant mean, keeps the best by BIC and prints its parameters, the volatility now, the long-run volatility and the volatility expected over the next 1 to 60 periods, all in percent a year (picture 1). It can write the returns and the fitted volatility to a CSV file (picture 2).

Output of GarchExample.mq5

Fitted and forecast volatility

Picture 3: every daily return of XAUUSDm with the band of two conditional standard deviations that the model gave for that day. The band widens after large moves and narrows again in calm months, which a constant volatility cannot do. 5.1% of the days fall outside it; the fitted GED expects 5.9%, a normal distribution 4.6%.

Returns of XAUUSDm and the band of the model

Picture 4: the returns minus their mean, divided by the volatility of the model for that day. With normal shocks they would follow the dashed curve. They do not: 49.7% of the days are within half a standard deviation (38.3% for a normal) and 1.45% beyond three (0.27% for a normal). The GED with shape 1.04 follows both the peak and the tails, which is why the GED models have the lowest BIC in picture 1.

Standardised returns against the normal and the GED

Checked

108 fits (every mean, variance and distribution) on six series: three simulated, daily BTCUSDT, hourly XAUUSD and the daily results of a trading portfolio, compared with arch 8.0:

  • for the same parameters, the log-likelihood, the conditional variances and the forecasts were equal within 1e-12, and the standard errors within 3e-4 (the precision of numerical second derivatives);
  • the likelihood found was never lower than arch's. In 6 fits arch stopped early and Garch.mqh found up to 0.21 more; in 4 fits with a persistence of 1, arch ended slightly past its own constraint.

A fit of 2 000 returns takes 10 to 100 ms; the slowest, with a shape that goes to its bound, about 1.5 s.

Files

Garch.mqh goes to MQL5\Include\Garch, GarchExample.mq5 to MQL5\Scripts\Garch.

Session Time Highlighter Session Time Highlighter

Highlights the Asia, London and New York sessions and the London/New York overlap using real local time and daylight saving rules, so the session boxes are correct on any broker.

Order Watchdog - alerts on unknown magic, duplicates, no SL, stop outs (read-only) Order Watchdog - alerts on unknown magic, duplicates, no SL, stop outs (read-only)

Read-only watchdog for MT5: alerts on unknown magic numbers, duplicate positions after reconnects, missing SL, stop outs and what happened while it was off. Never trades.

VpsToolkit - safe order send and restart-safe state for VPS EAs VpsToolkit - safe order send and restart-safe state for VPS EAs

Include for EAs running 24/7 on an MQL5 VPS or PC: run-where switch, order send with OK/FAIL/UNKNOWN result (no duplicate orders after a timeout), restart-safe counters, positions closed while the EA was off, append-only log and optional Telegram. No trading logic inside.

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.