Saturday, 18 March 2017

Online Zeit Serie Glättung Algorithmus Forex

MetaTrader 5 - Indikatoren Zeitreihenvorhersage mit exponentieller Glättung (Fortsetzung) Einführung Der Artikel Zeitreihenvorhersage mit Exponentialglättung 1 gab eine kurze Zusammenfassung der exponentiellen Glättungsmodelle, illustrierte einen der möglichen Ansätze zur Optimierung der Modellparameter und schlug schließlich den entwickelten Prognoseindikator vor Auf der Basis des linearen Wachstumsmodells mit Dämpfung. Dieser Artikel stellt einen Versuch dar, die Genauigkeit dieses Prognoseindikators etwas zu erhöhen. Es ist kompliziert, Währungszitate vorherzusagen oder eine relativ zuverlässige Prognose sogar für drei oder vier Schritte vor sich zu erhalten. Dennoch, wie im vorigen Artikel dieser Serie, werden wir 12-Schritt-Voraus-Prognosen produzieren, die klar erkennen, dass es unmöglich sein wird, befriedigende Ergebnisse über solch einen langen Horizont zu erhalten. Die ersten Schritte der Prognose mit den engsten Konfidenzintervallen sollten daher vorrangig beachtet werden. Eine 10- bis 12-stufige Prognose ist vor allem für die Darstellung von Verhaltensmerkmalen verschiedener Modelle und Prognosemethoden gedacht. In jedem Fall kann die Genauigkeit der erhaltenen Prognose für jeden Horizont anhand der Konfidenzintervallgrenzen bewertet werden. Dieser Artikel ist im Wesentlichen auf Demonstration von einigen Methoden, die helfen können, um den Indikator, wie in dem Artikel 1 dargelegt. Der Algorithmus für die Suche nach dem Minimum einer Funktion von mehreren Variablen, die bei der Entwicklung der Indikatoren angewendet wurde, wurde in der Vergangenheit behandelt Und wird daher hier nicht wiederholt beschrieben. Um den Artikel nicht zu überladen, werden die theoretischen Eingaben auf ein Minimum reduziert. 1. Initial Indicator Die IndicatorES. mq5-Anzeige (siehe Artikel 1) wird als Ausgangspunkt verwendet. Für die Zusammenstellung des Indikators benötigen wir IndicatorES. mq5, CIndicatorES. mqh und PowellsMethod. mqh, die alle im selben Verzeichnis liegen. Die Dateien befinden sich im Archiv files2.zip am Ende des Artikels. Lassen Sie uns die Gleichungen auffrischen, die das exponentielle Glättungsmodell, das bei der Entwicklung dieses Indikators verwendet wird, definieren - das lineare Wachstumsmodell mit Dämpfung. Der einzige Eingangsparameter des Indikators ist der Wert, der die Länge des Intervalls bestimmt, nach dem die Modellparameter optimiert und die Anfangswerte (Studienintervall) ausgewählt werden. Nach der Ermittlung der optimalen Werte der Modellparameter in einem gegebenen Intervall und den erforderlichen Berechnungen werden die Prognose, das Konfidenzintervall und die Zeile, die der einstufigen Prognose entsprechen, erzeugt. Bei jedem neuen Balken werden die Parameter optimiert und die Prognose erstellt. Da der betreffende Indikator aktualisiert wird, wird die Auswirkung der Änderungen, die wir machen werden, mit den Testsequenzen aus dem Files2.zip Archiv am Ende des Artikels beurteilt. Das Archivverzeichnis Dataset2 enthält Dateien mit den gespeicherten EURUSD-, USDCHF-, USDJPY-Zitaten und US-Dollar-Index DXY. Jeder von diesen ist für drei Zeitrahmen vorgesehen, wobei M1, H1 und D1 sind. Die in den Dateien gespeicherten offenen Werte befinden sich so, dass sich der letzte Wert am Ende der Datei befindet. Jede Datei enthält 1200 Elemente. Prognosefehler werden durch die Berechnung des MAPE-Koeffizienten (Mean Absolute Percentage Error) abgeschätzt. Wir teilen jede der zwölf Testsequenzen in 50 überlappende Abschnitte mit jeweils 80 Elementen auf und berechnen den MAPE-Wert für jede einzelne davon. Der Mittelwert der so erhaltenen Schätzungen wird als Prognosefehlerindex in Bezug auf die Vergleichsindikatoren verwendet. MAPE-Werte für zwei - und dreistufige Prognosefehler werden auf die gleiche Weise berechnet. Solche gemittelten Schätzungen werden weiterhin wie folgt bezeichnet: MAPE1 gemittelte Schätzung des einstufigen Vorhersagefehlers MAPE2 gemittelter Schätzwert des zweistufigen Vorhersagefehlers MAPE3 gemittelte Schätzung des dreistufigen Vorhersagefehlers MAPE1-3 bedeutet (MAPE1MAPE2MAPE3) 3. Bei der Berechnung des MAPE-Werts wird der absolute Prognosefehlerwert bei jedem Schritt durch den aktuellen Wert der Sequenz dividiert. Um eine Division durch Null zu vermeiden oder negative Werte zu erhalten, müssen die Eingabesequenzen, wie in unserem Fall, nur ungleich positive Werte annehmen. Die Schätzwerte für unseren Anfangsindikator sind in Tabelle 1 dargestellt. Tabelle 1: Schätzungen der anfänglichen Indikatorprognosefehler Die in Tabelle 1 dargestellten Daten werden mit dem Skript ErrorsIndicatorES. mq5 (aus dem Archiv files2.zip am Ende des Artikels) . Zum Kompilieren und Ausführen des Skripts ist es erforderlich, dass CIndicatorES. mqh und PowellsMethod. mqh im selben Verzeichnis wie ErrorsIndicatorES. mq5 befinden und die Eingabesequenzen im Verzeichnis FilesDataset2 sind. Nach dem Ermitteln der anfänglichen Schätzungen der Prognosefehler können wir nun mit dem Upgrade des betrachteten Indikators fortfahren. 2. Optimierungskriterium Die Modellparameter im Anfangsindikator, wie in dem Artikel Zeitreihenvorhersage mit Exponentialglättung angegeben, wurden durch Minimierung der Quadratsumme des einstufigen Prognosefehlers bestimmt. Es erscheint logisch, dass die Modellparameter, die für eine Ein-Schritt-Voraus-Prognose optimal sind, nicht zu minimalen Fehlern für eine Prognose mit mehr Stufen führen können. Es wäre natürlich wünschenswert, Prognosefehler von 10- bis 12-Schritt-Vorhersage zu minimieren, aber ein zufriedenstellendes Prognoseergebnis über den gegebenen Bereich für die betrachteten Sequenzen wäre eine Mission unmöglich. Realistisch werden bei der Optimierung der Modellparameter die Summe der Quadrate der ein-, zwei - und dreistufigen Prognosefehler als erstes Upgrade unseres Indikators verwendet. Es ist zu erwarten, dass die durchschnittliche Anzahl von Fehlern über dem Bereich der ersten drei Schritte der Prognose etwas abnimmt. Es ist klar, dass eine solche Aufrüstung des Anfangsindikators nicht seine Hauptstrukturprinzipien betrifft, sondern nur das Parameteroptimierungskriterium ändert. Daher können wir nicht erwarten, dass sich die Prognosegenauigkeit um ein Vielfaches erhöht, obwohl die Anzahl der Zwei - und Drei-Schritt-Vorhersagefehler etwas zurückgehen sollte. Um die Prognoseergebnisse zu vergleichen, haben wir die CMod1-Klasse ähnlich der CIndicatorES-Klasse eingeführt, die im vorherigen Artikel mit der modifizierten Zielfunktion func eingeführt wurde. Die func-Funktion der initialen CIndicatorES-Klasse: Nach einigen Modifikationen erscheint nun die func-Funktion wie folgt Nun wird bei der Berechnung der Zielfunktion die Summe der Quadrate der Ein-Zwei - und Drei-Schritt-Vorhersagefehler verwendet. Des Weiteren wurde basierend auf dieser Klasse das Skript ErrorsMod1.mq5 entwickelt, das es ermöglicht, die Prognosefehler zu schätzen, wie das bereits erwähnte Skript ErrorsIndicatorES. mq5. CMod1.mqh und ErrorsMod1.mq5 befinden sich im Archiv files2.zip am Ende des Artikels. Tabelle 2 zeigt die Prognosefehlerschätzungen für die ersten und die aktualisierten Versionen. Tabelle 2. Vergleich der Prognosefehlerschätzungen Die Fehlerkoeffizienten MAPE2 und MAPE3 und der Mittelwert MAPE1-3 haben sich für die betrachteten Sequenzen tatsächlich etwas geringer gezeigt. Lassen Sie uns also diese Version speichern und zur weiteren Modifizierung unseres Indikators übergehen. 3. Einstellung der Parameter im Glättungsvorgang Die Idee, die Glättungsparameter abhängig von den aktuellen Werten der Eingangsfolge zu verändern, ist nicht neu oder originell und stammt aus dem Wunsch, die Glättungskoeffizienten so einzustellen, dass sie bei jeder Änderung des Optimums optimal bleiben Art der Eingangsfolge. Einige Möglichkeiten, die Glättungskoeffizienten einzustellen, werden in der Literatur 2, 3 beschrieben. Um das Indikator weiter zu verbessern, verwenden wir das Modell mit dynamisch änderndem Glättungskoeffizienten, der erwartet, daß die Verwendung des adaptiven exponentiellen Glättungsmodells es uns ermöglicht, die Prognosegenauigkeit zu erhöhen Unseres Indikators. Unglücklicherweise liefern die meisten adaptiven Verfahren, wenn sie in Prognosealgorithmen verwendet werden, nicht immer die gewünschten Ergebnisse. Die Auswahl der adäquaten adaptiven Methode mag zu schwerfällig und zeitintensiv sein, daher werden wir in unserem Fall die in der Literatur 4 enthaltenen Erkenntnisse nutzen und versuchen, den in dem Artikel 5 dargelegten "Smooth Transition Exponential Smoothing" (STES) zu verwenden , Wobei der Kern des Ansatzes in dem angegebenen Artikel klar umrissen ist, so dass wir ihn hier auslassen werden und unter Berücksichtigung der Verwendung des adaptiven Glättungskoeffizienten direkt zu den Gleichungen für unser Modell (siehe Anfang des angegebenen Artikels) gehen. Wie wir nun sehen können, wird der Wert des Glättungskoeffizienten alpha bei jedem Schritt des Algorithmus berechnet und hängt vom quadratischen Prognosefehler ab. Die Werte der b - und g-Koeffizienten bestimmen die Auswirkung des Prognosefehlers auf den Alphawert. Im Übrigen blieben die Gleichungen für das eingesetzte Modell unverändert. Zusätzliche Informationen zur Verwendung des STES-Ansatzes finden Sie im Artikel 6. Während in den früheren Versionen der optimale Wert des Alphakoeffizienten über die gegebene Eingabesequenz ermittelt werden musste, gibt es nun zwei adaptive Koeffizienten b und g, die sind Unterliegt der Optimierung und der Alpha-Wert wird dynamisch in dem Prozess des Glättens der Eingangsfolge bestimmt. Dieses Upgrade wird in Form der CMod2-Klasse implementiert. Die Hauptänderungen (wie die vorherige Zeit) betrafen vor allem die func-Funktion, die nun wie folgt erscheint. Bei der Entwicklung dieser Funktion wurde die Gleichung, die den Alphakoeffizientenwert definiert, leicht modifiziert. Dies wurde durchgeführt, um die Grenze des maximalen und des minimal zulässigen Wertes dieses Koeffizienten bei 0,05 bzw. 0,95 einzustellen. Um die Prognosefehler zu schätzen, wurde das Skript ErrorsMod2.mq5 auf der Grundlage der CMod2-Klasse geschrieben. CMod2.mqh und ErrorsMod2.mq5 befinden sich im Archiv files2.zip am Ende des Artikels. Die Ergebnisse des Skripts sind in Tabelle 3 dargestellt. Tabelle 3. Vergleich der Prognosefehlerschätzungen Wie aus Tabelle 3 hervorgeht, hat die Verwendung des adaptiven Glättungskoeffizienten im Durchschnitt eine weitere Verringerung der Prognosefehler für unsere Testsequenzen ermöglicht. So konnten wir nach zwei Upgrades den Fehlerkoeffizienten MAPE1-3 um etwa zwei Prozent senken. Trotz eines eher bescheidenen Upgrade-Ergebnisses, werden wir mit der resultierenden Version bleiben und lassen Sie weitere Upgrades aus dem Geltungsbereich des Artikels. Als nächsten Schritt wäre es interessant, die Box-Cox-Transformation zu versuchen. Diese Transformation wird hauptsächlich verwendet, um die anfängliche Sequenzverteilung an die Normalverteilung anzunähern. In unserem Fall könnte es verwendet werden, um die anfängliche Sequenz zu transformieren, die Prognose zu berechnen und die Prognose umgekehrt zu transformieren. Der so angewandte Transformationskoeffizient sollte so gewählt werden, dass der resultierende Prognosefehler minimiert wird. Ein Beispiel für die Verwendung der Box-Cox-Transformation in Prognose-Sequenzen finden Sie im Artikel 7. 4. Prognose-Konfidenzintervall Das prognostizierte Konfidenzintervall im IndicatorES. mq5-Indikator (wie im vorherigen Artikel dargelegt) wurde nach analytischer Methode berechnet Ausdrücke, die für das ausgewählte exponentielle Glättungsmodell 8 abgeleitet wurden. Die in unserem Fall vorgenommenen Änderungen haben zu Änderungen des betrachteten Modells geführt. Der variable Glättungskoeffizient macht es unangemessen, die oben erwähnten analytischen Ausdrücke zur Abschätzung des Konfidenzintervalls zu verwenden. Die Tatsache, dass die zuvor verwendeten analytischen Ausdrücke auf der Grundlage der Annahme, dass die Prognosefehlerverteilung symmetrisch und normal ist, abgeleitet wurden, können einen zusätzlichen Grund für die Änderung des Konfidenzintervallschätzungsverfahrens darstellen. Diese Anforderungen sind für unsere Sequenzreihe nicht erfüllt und die Prognosefehlerverteilung kann nicht normal oder symmetrisch sein. Bei der Schätzung des Konfidenzintervalls im Anfangsindikator wurde die einstufige Vorhersagefehlervarianz an erster Stelle aus der Eingabesequenz berechnet, gefolgt von der Berechnung der Varianz für eine Zwei-, Drei - und Mehrschrittvoraussetzung Prognose auf der Basis des erhaltenen einstufigen Vorhersagefehlerabweichungswertes unter Verwendung der analytischen Ausdrücke. Um die Verwendung von analytischen Ausdrücken zu vermeiden, gibt es einen einfachen Ausweg, bei dem die Varianz für eine Zwei-, Drei - und Mehrschrittvorhersage direkt aus der Eingangsfolge sowie aus der Varianz für einen Schritt berechnet wird - Ahead-Prognose. Allerdings hat dieser Ansatz einen erheblichen Nachteil: In kurzen Eingabefolgen werden die Vertrauensintervallschätzungen weit gestreut, und die Berechnung der Varianz und des mittleren quadratischen Fehlers wird es nicht erlauben, Beschränkungen hinsichtlich der erwarteten Normalität von Fehlern zu entlasten. Eine Lösung in diesem Fall kann in der Verwendung von nichtparametrischen Bootstrap (Resampling) gefunden werden 9. Das Rückgrat der Idee, die einfach ausgedrückt: bei der Stichprobe in einer zufälligen Weise (einheitliche Verteilung) mit Ersatz aus der ursprünglichen Sequenz, die Verteilung der so erzeugten Künstliche Sequenz ist die gleiche wie die des ersten. Nehmen wir an, wir haben eine Eingangssequenz von N Elementen, indem wir eine gleichmäßig verteilte pseudo-zufällige Sequenz über den Bereich von 0, N-1 erzeugen und diese Werte als Indizes verwenden, wenn wir von der anfänglichen Matrix abtasten, können wir eine künstliche Sequenz von im wesentlichen erzeugen Größer als die erste. Das heißt, die Verteilung der erzeugten Sequenz ist die gleiche (fast die gleiche) wie die des ersten. Das Bootstrap-Verfahren zur Schätzung der Konfidenzintervalle kann folgendermaßen sein: Bestimmen Sie die optimalen Anfangswerte der Modellparameter, ihrer Koeffizienten und adaptiven Koeffizienten aus der Eingangsfolge für das exponentielle Glättungsmodell, das als Ergebnis der Modifikation erhalten wird. Die optimalen Parameter werden, wie zuvor, anhand des Algorithmus bestimmt, der das Powells-Suchverfahren verwendet. Verwenden Sie die ermittelten optimalen Modellparameter, gehen Sie durch die anfängliche Sequenz und bilden Sie ein Array von Prognosefehlern in einem Schritt. Die Anzahl der Array-Elemente ist gleich der Eingangs-Sequenzlänge N Ausrichten der Fehler durch Subtrahieren der Mittelwerte aus jedem Element des Fehler-Arrays mit dem Pseudo-Zufalls-Sequenz-Generator Indizes im Bereich von 0, N-1 Und verwenden Sie sie, um eine künstliche Sequenz von 9999 Elementen zu bilden, die lang sind (Resampling) Form eines Arrays, das 9999 Werte der Pseudoeingabesequenz enthält, indem die Werte aus dem künstlich erzeugten Fehlerfeld in die Gleichungen eingefügt werden, die das gegenwärtig verwendete Modell definieren. Mit anderen Worten, während wir zuvor die Eingabesequenzwerte in die Modellgleichungen einfügen mussten, um so den Prognosefehler zu berechnen, werden nun die inversen Berechnungen durchgeführt. Für jedes Element des Arrays wird der Fehlerwert eingefügt, um den Eingabewert zu berechnen. Als Ergebnis erhalten wir das Array von 9999 Elementen, die die Sequenz mit der gleichen Verteilung wie die Eingangssequenz enthalten, während sie ausreichend lang sind, um die voraussichtlichen Konfidenzintervalle direkt abzuschätzen. Dann schätzen Sie die Konfidenzintervalle unter Verwendung der erzeugten Sequenz von adäquater Länge ab. Zu diesem Zweck werden wir die Tatsache ausnutzen, dass, wenn das erzeugte Prognosefehler-Array in aufsteigender Reihenfolge sortiert wird, die Array-Zellen mit den Indizes 249 und 9749 für das Array mit 9999 Werten die Werte aufweisen, die den Grenzen des 95-Konfidenzintervalls 10 entsprechen Um eine genauere Schätzung der Vorhersageintervalle zu erhalten, muss die Array-Länge ungerade sein. In unserem Fall werden die Grenzen der prognostizierten Konfidenzintervalle wie folgt geschätzt: Unter Verwendung der optimalen Modellparameter, wie sie vorher bestimmt wurden, gehen Sie durch die erzeugte Sequenz und bilden ein Array von 9999 Prognosefehlern mit einem Schritt Vor dem sortierten sortieren Fehler-Array, wählen Sie Werte mit Indizes 249 und 9749, die die Grenzen des 95 Konfidenzintervalls darstellen. Wiederholen Sie die Schritte 1, 2 und 3 für zwei-, drei - und mehrschrittige Prognosefehler. Dieser Ansatz zur Schätzung der Konfidenzintervalle hat seine Vor - und Nachteile. Zu seinen Vorteilen zählt das Fehlen von Annahmen hinsichtlich der Art der Verteilung der Prognosefehler. Sie müssen nicht normal oder symmetrisch verteilt sein. Außerdem kann dieser Ansatz nützlich sein, wo es unmöglich ist, analytische Ausdrücke für das verwendete Modell abzuleiten. Eine dramatische Erhöhung des erforderlichen Berechnungsumfangs und die Abhängigkeit der Schätzungen von der Qualität des verwendeten pseudozufälligen Sequenzgenerators können als seine Nachteile betrachtet werden. Der vorgeschlagene Ansatz zur Schätzung der Konfidenzintervalle unter Verwendung von Resampling und Quantilen ist eher primitiv und es muss Möglichkeiten zur Verbesserung bestehen. Da aber die Konfidenzintervalle in unserem Fall nur für die visuelle Beurteilung bestimmt sind, kann die Genauigkeit, die durch die obige Vorgehensweise bereitgestellt wird, als ausreichend erscheinen. 5. Modifizierte Version des Indikators Unter Berücksichtigung der im Artikel eingeführten Upgrades wurde der Indikator ForecastES. mq5 entwickelt. Für die Neuabtastung wurde der zuvor in dem Artikel 11 vorgeschlagene Pseudozufallsgenerator verwendet. Der Standard-MathRand () - Generator lieferte etwas schlechtere Ergebnisse, wahrscheinlich aufgrund der Tatsache, daß der Wertebereich, der 0,32767 erzeugt wurde, nicht breit genug war. Bei der Erstellung des Signals ForecastES. mq5 müssen sich PowellsMethod. mqh, CForeES. mqh und RNDXor128.mqh im selben Verzeichnis befinden. Alle diese Dateien finden Sie im fore. zip Archiv. Unten ist der Quellcode des Signals ForecastES. mq5. Für bessere Demonstrationszwecke wurde der Indikator so weit wie möglich als Geradencode ausgeführt. Keine Optimierung war beabsichtigt, während es codiert. Die Fig. 1 und 2 zeigen die Betriebsergebnisse des Indikators für zwei verschiedene Fälle. Abbildung 1: Erstes Beispiel für die Prognose des Prognoses. mq5-Indikators Abbildung 2: Zweites Operationsbeispiel für den Prognosebericht. Abbildung 2 zeigt deutlich, dass das Prognose-Konfidenzintervall 95 asymmetrisch ist. Dies liegt daran, dass die Eingabesequenz beträchtliche Ausreißer enthält, die zu einer asymmetrischen Verteilung der Prognosefehler geführt haben. Webseiten mql4 und mql5 früher bereitgestellt Extrapolator Indikatoren. Nehmen wir einen solchen - arextrapolatorofprice. mq5 und setzen Sie seine Parameterwerte wie in Abbildung 3 gezeigt, um seine Ergebnisse mit den Ergebnissen zu vergleichen, die mit dem von uns entwickelten Indikator erhalten wurden. Abbildung 3. Einstellungen der Anzeige "arextrapolatorofprice. mq5" Der Betrieb dieser beiden Indikatoren wurde visuell auf unterschiedlichen Zeitrahmen für EURUSD und USDCHF verglichen. Auf der Oberfläche scheint es, dass die Richtung der Prognose beider Indikatoren in der Mehrzahl der Fälle zusammenfällt. Bei längeren Beobachtungen kann es jedoch zu ernsthaften Divergenzen kommen. Davon abgesehen, produziert wird, werden Sie, wenn Sie wollen. Ein Beispiel für den gleichzeitigen Betrieb von ForecastES. mq5 und arextrapolatorofprice. mq5-Indikatoren ist in Abbildung 4 dargestellt. Abbildung 4. Vergleich der Prognoseergebnisse Die Prognose, die durch die Anzeige von arextrapolatorofprice. mq5 erzeugt wird, wird in Abbildung 4 als eine orange-rote Linie dargestellt. Schlussfolgerung Zusammenfassung der Ergebnisse zu diesem und dem vorherigen Artikel: Exponentielle Glättungsmodelle für die Zeitreihenvorhersage wurden eingeführt Programmierlösungen für die Implementierung der Modelle wurden vorgeschlagen Ein kurzer Einblick in die Fragen der Auswahl der optimalen Anfangswerte und Modellparameter erfolgte Es wurde eine Programmimplementierung des Algorithmus zur Ermittlung des Minimums einer Funktion mehrerer Variablen unter Verwendung der Powells - Methode bereitgestellt. Es wurden Programmierlösungen zur Parameteroptimierung des Prognosemodells unter Verwendung der Eingangssequenz vorgeschlagen. Einige einfache Beispiele für die Aktualisierung des Prognosealgorithmus wurden gezeigt Schätzung der Prognose-Konfidenzintervalle mittels Bootstrapping und Quantilen wurde kurz skizziert Der Prognoseindikator ForecastES. mq5 wurde mit allen in den Artikeln beschriebenen Methoden und Algorithmen entwickelt. Es wurden einige Links zu den Artikeln, Zeitschriften und Büchern zu diesem Thema gegeben. Hinsichtlich des resultierenden Indikators ForecastES. mq5 ist anzumerken, dass der Optimierungsalgorithmus, der das Powells-Verfahren anwendet, in bestimmten Fällen das Minimum der Zielfunktion nicht mit einer gegebenen Genauigkeit bestimmen kann. In diesem Fall wird die maximal zulässige Anzahl von Iterationen erreicht und eine entsprechende Meldung im Protokoll angezeigt. Diese Situation wird jedoch nicht in irgendeiner Weise in dem Code des Indikators verarbeitet, der für die Demonstration der Algorithmen, die in dem Artikel dargelegt werden, durchaus akzeptabel ist. Wenn es jedoch um ernsthafte Anwendungen geht, werden solche Fälle auf eine oder andere Weise überwacht und verarbeitet. Um den Prognoseindikator weiter zu entwickeln und zu verbessern, könnten wir vorschlagen, bei jedem Schritt mehrere verschiedene Prognosemodelle gleichzeitig zu verwenden, um eine weitere Auswahl unter Verwendung von z. B. Das Akaikes Informationskriterium. Oder im Falle der Verwendung mehrerer ähnlicher Modelle, um den gewichteten Durchschnittswert ihrer Prognoseergebnisse zu berechnen. Die Gewichtungskoeffizienten können in diesem Fall abhängig vom prognostizierten Fehlerkoeffizienten jedes Modells ausgewählt werden. Das Thema der Prognose Zeitreihen ist so breit, dass leider diese Artikel haben kaum an der Oberfläche von einigen der betreffenden Themen zerkratzt. Es ist zu hoffen, dass diese Publikationen dazu beitragen, die Leser auf die Fragen der Prognose und zukünftiger Arbeiten in diesem Bereich aufmerksam zu machen. ReferenzenMetaTrader 5 - Statistik und Analyse Zeitreihenvorhersage mit exponentieller Glättung Einleitung Zurzeit gibt es eine Vielzahl von bekannten Prognosemethoden, die nur auf der Analyse vergangener Werte einer Zeitfolge basieren, dh Methoden, die in der Technik übliche Prinzipien verwenden Analyse. Das Hauptinstrument dieser Verfahren ist das Extrapolationsschema, bei dem die bei einer bestimmten Zeitverzögerung identifizierten Sequenzeigenschaften ihre Grenzen überschreiten. Gleichzeitig wird davon ausgegangen, dass die Sequenz-Eigenschaften in der Zukunft die gleichen sein werden wie in der Vergangenheit und Gegenwart. Ein komplexeres Extrapolationsschema, das eine Untersuchung der Dynamik von Änderungen der Charakteristiken der Sequenz unter gebührender Berücksichtigung einer solchen Dynamik innerhalb des Prognoseintervalls beinhaltet, wird weniger häufig in der Prognose verwendet. Die bekanntesten Prognosemethoden, die auf einer Extrapolation basieren, sind unter anderem die autoregressiven integrierten Moving Average Modells (ARIMA). Die Beliebtheit dieser Methoden ist vor allem auf die Arbeiten von Box und Jenkins zurückzuführen, die ein integriertes ARIMA-Modell vorgeschlagen und entwickelt haben. Es gibt natürlich andere Modelle und Prognosemethoden außer den Modellen von Box und Jenkins eingeführt. Dieser Artikel wird kurz auf einfachere Modelle - exponentielle Glättung Modelle von Holt und Brown vor dem Erscheinen der Arbeiten von Box und Jenkins vorgeschlagen. Trotz der einfacheren und klareren mathematischen Werkzeuge führt die Prognose unter Verwendung exponentieller Glättungsmodelle oft zu Ergebnissen, die mit den Ergebnissen des ARIMA-Modells vergleichbar sind. Das ist kaum verwunderlich, da exponentielle Glättungsmodelle ein Spezialfall des ARIMA-Modells sind. Mit anderen Worten, jedes exponentielle Glättungsmodell, das in diesem Artikel untersucht wird, hat ein entsprechendes äquivalentes ARIMA-Modell. Diese äquivalenten Modelle werden in dem Artikel nicht berücksichtigt und nur zur Information erwähnt. Es ist bekannt, dass die Prognose in jedem Einzelfall einen individuellen Ansatz erfordert und normalerweise eine Reihe von Prozeduren beinhaltet. Analyse der Zeitfolge für fehlende Werte und Ausreißer. Einstellung dieser Werte. Identifizierung des Trends und seiner Art. Bestimmung der Sequenzperiodizität. Prüfen Sie auf die Stationarität der Sequenz. Sequenzvorverarbeitung (Logarithmen, Differenzierung usw.). Modellauswahl. Modellparameterbestimmung. Prognose basierend auf dem ausgewählten Modell. Modellvorhersagegenauigkeitsbewertung. Analyse der Fehler des ausgewählten Modells. Bestimmung der Angemessenheit des gewählten Modells und ggf. Ersetzen des Modells und Rückkehr zu den vorstehenden Punkten. Dies ist bei weitem nicht die vollständige Liste der Maßnahmen für eine effektive Prognose erforderlich. Es sollte betont werden, dass die Modellparameterbestimmung und der Erhalt der Prognoseergebnisse nur ein kleiner Teil des allgemeinen Prognoseprozesses sind. Aber es scheint unmöglich, die ganze Bandbreite von Problemen in der einen oder anderen Weise mit der Prognose in einem Artikel zu decken. Dieser Artikel behandelt daher nur exponentielle Glättungsmodelle und verwendet nicht-vorverarbeitete Währungszitate als Testsequenzen. Begleitende Fragen können in dem Artikel zwar nicht vermieden werden, doch werden sie nur insofern berührt, als sie für die Überprüfung der Modelle erforderlich sind. 1. Stationarität Der Begriff der Extrapolation impliziert, dass die zukünftige Entwicklung des untersuchten Prozesses die gleiche sein wird wie in der Vergangenheit und Gegenwart. Mit anderen Worten, es geht um die Stationarität des Prozesses. Stationäre Prozesse sind aus Sicht der Prognose sehr attraktiv, aber sie existieren leider nicht in der Natur, da jeder reale Prozeß sich im Laufe seiner Entwicklung ändern kann. Reale Prozesse können im Laufe der Zeit deutlich unterschiedliche Erwartungen, Varianzen und Verteilungen aufweisen, aber die Prozesse, deren Eigenschaften sich sehr langsam verändern, können wahrscheinlich auf stationäre Prozesse zurückgeführt werden. Sehr langsam bedeutet in diesem Fall, daß Änderungen der Prozeßcharakteristiken innerhalb des endlichen Beobachtungsintervalls so unbedeutend erscheinen, daß solche Veränderungen vernachlässigt werden können. Es ist klar, dass je kürzer das verfügbare Beobachtungsintervall (kurze Probe) ist, desto höher die Wahrscheinlichkeit, die falsche Entscheidung hinsichtlich der Stationarität des gesamten Prozesses zu treffen. Wenn wir andererseits mehr an dem Zustand des Prozesses interessiert sind, zu einem späteren Zeitpunkt, der plant, eine kurzfristige Prognose durchzuführen, kann die Verringerung der Stichprobengröße in einigen Fällen zu einer Erhöhung der Genauigkeit dieser Prognose führen. Wenn das Verfahren Änderungen unterliegt, werden die Sequenzparameter, die innerhalb des Beobachtungsintervalls bestimmt werden, außerhalb seiner Grenzen verschieden sein. Je länger das Prognoseintervall ist, desto stärker ist die Auswirkung der Variabilität der Sequenzmerkmale auf den Prognosefehler. Aufgrund dieser Tatsache müssen wir uns auf eine kurzfristige Prognose beschränken und nur eine signifikante Reduktion des Prognoseintervalls erlaubt, dass die sich langsam verändernden Sequenzmerkmale nicht zu erheblichen Prognosefehlern führen werden. Außerdem führt die Variabilität der Sequenzparameter dazu, dass der Wert, der bei der Schätzung durch das Beobachtungsintervall erhalten wird, gemittelt wird, da die Parameter nicht innerhalb des Intervalls konstant bleiben. Die erhaltenen Parameterwerte beziehen sich daher nicht auf den letzten Zeitpunkt dieses Intervalls, sondern spiegeln einen bestimmten Mittelwert davon wieder. Leider ist es unmöglich, dieses unangenehme Phänomen vollständig zu eliminieren, aber es kann verringert werden, wenn die Länge des Beobachtungsintervalls, das in der Modellparameterschätzung (Untersuchungsintervall) involviert ist, soweit wie möglich verringert wird. Gleichzeitig kann das Untersuchungsintervall nicht auf unbestimmte Zeit verkürzt werden, da es, wenn es extrem reduziert wird, sicherlich die Genauigkeit der Sequenzparameter-Schätzung verringern wird. Man sollte einen Kompromiss zwischen der Wirkung von Fehlern, die mit der Variabilität der Sequenzcharakteristiken verbunden sind, und einer Erhöhung der Fehler aufgrund der extremen Verringerung des Untersuchungsintervalls suchen. Alle oben genannten Bedingungen gelten für die Prognose mit exponentiellen Glättungsmodellen, da sie auf der Annahme der Stationarität von Prozessen beruhen, wie zB ARIMA-Modelle. Dennoch werden wir der Einfachheit halber nachfolgend konventionell davon ausgehen, daß die Parameter aller betrachteten Sequenzen innerhalb des Beobachtungsintervalls aber in einer so langsamen Weise variieren, daß diese Änderungen vernachlässigt werden können. Der Artikel befasst sich daher mit Fragen der kurzfristigen Prognose von Sequenzen mit sich langsam verändernden Charakteristika auf der Basis exponentieller Glättungsmodelle. Die kurzfristige Prognose sollte in diesem Fall eine Prognose für ein, zwei oder mehr Zeitintervalle vorhersehen, anstatt für einen Zeitraum von weniger als einem Jahr zu prognostizieren, wie es in der Regel in der Volkswirtschaft verstanden wird. 2. Testsequenzen Beim Schreiben dieses Artikels wurden zuvor die EURRUR-, EURUSD-, USDJPY - und XAUUSD-Zitate für M1, M5, M30 und H1 verwendet. Jede der gespeicherten Dateien enthält 1100 offene Werte. Der älteste Wert befindet sich am Anfang der Datei und der letzte am Ende. Der letzte in der Datei gespeicherte Wert entspricht dem Zeitpunkt der Erstellung der Datei. Dateien, die Testsequenzen enthalten, wurden mit dem HistoryToCSV. mq5-Skript erstellt. Die Dateien und das Skript, mit denen sie erstellt wurden, befinden sich am Ende des Artikels im Files. zip Archiv. Wie bereits erwähnt, werden die gespeicherten Anführungszeichen in diesem Artikel ohne Vorverarbeitung verwendet, trotz der offensichtlichen Probleme, auf die ich Sie aufmerksam machen möchte. Zum Beispiel enthalten EURRURH1-Kurse während des Tages von 12 bis 13 Bar, XAUUSD-Quotes am Freitag enthalten eine Bar weniger als an anderen Tagen. Diese Beispiele zeigen, dass die Anführungszeichen mit unregelmßigem Abtastintervall erzeugt werden, was für Algorithmen, die für die Arbeit mit korrekten Zeitabschnitten, die ein einheitliches Quantisierungsintervall vorschlagen, völlig unakzeptabel sind. Auch wenn die fehlenden Anführungswerte mittels Extrapolation wiedergegeben werden, bleibt die Frage nach dem fehlenden Angebot an Wochenenden offen. Wir können annehmen, dass die Ereignisse, die am Wochenende in der Welt auftreten, die gleichen Auswirkungen auf die Weltwirtschaft haben wie die Wochentagsveranstaltungen. Revolutionen, Naturereignisse, hochkarätige Skandale, Regierungswechsel und andere mehr oder weniger große Ereignisse dieser Art können jederzeit auftreten. Wenn ein solches Ereignis am Samstag stattfände, würde es kaum einen geringeren Einfluss auf die Weltmärkte haben als an einem Wochentag. Es sind vielleicht diese Ereignisse, die zu Lücken in Zitate führen, die so häufig am Ende der Arbeitswoche beobachtet werden. Anscheinend geht die Welt nach eigenen Regeln weiter, auch wenn FOREX nicht funktioniert. Es ist noch unklar, ob die Werte in den Anführungszeichen, die den Wochenenden entsprechen, die für eine technische Analyse bestimmt sind, reproduziert werden sollten und welchen Nutzen es geben könnte. Offensichtlich sind diese Fragen über den Rahmen dieses Artikels hinaus, aber auf den ersten Blick scheint eine Sequenz ohne Lücken für die Analyse geeigneter zu sein, zumindest hinsichtlich der Erfassung zyklischer (saisonaler) Komponenten. Die Wichtigkeit der Vorbereitung der Daten für die weitere Analyse ist in unserem Fall kaum zu überschätzen, da es sich um ein weitgehend unabhängiges Problem handelt, da Zitate, wie sie im Terminal erscheinen, für eine technische Analyse im Allgemeinen nicht wirklich geeignet sind. Abgesehen von den oben genannten Lücke-Probleme, gibt es eine ganze Reihe von anderen Problemen. Bei der Bildung der Anführungszeichen wird beispielsweise ein fester Zeitpunkt mit Öffnungs - und Schließwerten verknüpft, die nicht zu ihm gehören, diese Werte entsprechen der Tickbildungszeit anstelle eines festen Moments eines ausgewählten Zeitrahmendiagramms, wohingegen es allgemein bekannt ist, dass Ticks Sind manchmal sehr selten. Another example can be seen in complete disregard of the sampling theorem, as nobody can guarantee that the sampling rate even within a minute interval satisfies the above theorem (not to mention other, bigger intervals). Furthermore, one should bear in mind the presence of a variable spread which in some cases may be superimposed on quote values. Let us however leave these issues out of the scope of this article and get back to the primary subject. 3. Exponential Smoothing Let us first have a look at the simplest model , X(t) (simulated) process under study, L(t) variable process level, r(t) zero mean random variable. As can be seen, this model comprises the sum of two components we are particularly interested in the process level L(t) and will try to single it out. It is well-known that the averaging of a random sequence may result in decreased variance, i. e. reduced range of its deviation from the mean. We can therefore assume that if the process described by our simple model is exposed to averaging (smoothing), we may not be able to get rid of a random component r(t) completely but we can at least considerably weaken it thus singling out the target level L(t) . For this purpose, we will use a simple exponential smoothing (SES). In this well known formula, the degree of smoothing is defined by alpha coefficient which can be set from 0 to 1. If alpha is set to zero, new incoming values of the input sequence X will have no effect whatsoever on the smoothing result. Smoothing result for any time point will be a constant value. Consequently, in extreme cases like this, the nuisance random component will be fully suppressed yet the process level under consideration will be smoothed out to a straight horizontal line. If the alpha coefficient is set to one, the input sequence will not be affected by smoothing at all. The level under consideration L(t) will not be distorted in this case and the random component will not be suppressed either. It is intuitively clear that when selecting the alpha value, one has to simultaneously satisfy the conflicting requirements. On the one hand, the alpha value shall be near zero in order to effectively suppress the random component r(t) . On the other, it is advisable to set the alpha value close to unity not to distort the L(t) component we are so interested in. In order to obtain the optimal alpha value, we need to identify a criterion according to which such value can be optimized. Upon determining such criterion, remember that this article deals with forecasting and not just smoothing of sequences. In this case regarding the simple exponential smoothing model, it is customary to consider value obtained at a given time as a forecast for any number of steps ahead. Hence, the forecast of the sequence value at the time t will be a one-step-ahead forecast made at the previous step In this case, one can use a one-step-ahead forecast error as a criterion for optimization of the alpha coefficient value Thus, by minimizing the sum of squares of these errors over the entire sample, we can determine the optimal value of the alpha coefficient for a given sequence. The best alpha value will of course be the one at which the sum of squares of the errors would be minimal. Figure 1 shows a plot of the sum of squares of one-step-ahead forecast errors versus alpha coefficient value for a fragment of test sequence USDJPY M1. Figure 1. Simple exponential smoothing The minimum on the resulting plot is barely discernible and is located close to the alpha value of approximately 0.8. But such picture is not always the case with regard to the simple exponential smoothing. When trying to obtain the optimal alpha value for test sequence fragments used in the article, we will more often than not get a plot continuously falling to unity. Such high values of the smoothing coefficient suggest that this simple model is not quite adequate for the description of our test sequences (quotes). It is either that the process level L(t) changes too fast or there is a trend present in the process. Let us complicate our model a little by adding another component , It is known that linear regression coefficients can be determined by double smoothening of a sequence: For coefficients a1 and a2 obtained in this manner, the m-step-ahead forecast at the time t will be equal to It should be noted that the same alpha coefficient is used in the above formulas for the first and repeated smoothing. This model is called the additive one-parameter model of linear growth. Let us demonstrate the difference between the simple model and the model of linear growth. Suppose that for a long time the process under study represented a constant component, i. e. it appeared on the chart as a straight horizontal line but at some point a linear trend started to emerge. A forecast for this process made using the above mentioned models is shown in Figure 2. Figure 2. Model comparison As can be seen, the simple exponential smoothing model is appreciably behind the linearly varying input sequence and the forecast made using this model is moving yet further away. We can see a very a different pattern when the linear growth model is used. When the trend emerges, this model is as if trying to come up with the linearly varying sequence and its forecast is closer to the direction of varying input values. If the smoothing coefficient in the given example was higher, the linear growth model would be able to reach the input signal over the given time and its forecast would nearly coincide with the input sequence. Despite the fact that the linear growth model in the steady state gives good results in the presence of a linear trend, it is easy to see that it takes a certain time for it to catch up with the trend. Therefore there will always be a gap between the model and input sequence if the direction of a trend frequently changes. Besides, if the trend grows nonlinearly but instead follows the square law, the linear growth model will not be able to reach it. But despite these drawbacks, this model is more beneficial than the simple exponential smoothing model in the presence of a linear trend. As already mentioned, we used a one-parameter model of linear growth. In order to find the optimal value of the alpha parameter for a fragment of test sequence USDJPY M1, let us build a plot of the sum of squares of one-step-ahead forecast errors versus alpha coefficient value. This plot built on the basis of the same sequence fragment as the one in Figure 1, is displayed in Figure 3. Figure 3. Linear growth model As compared with the result in Figure 1, the optimal value of the alpha coefficient has in this case decreased to approximately 0.4. The first and second smoothing have the same coefficients in this model, although theoretically their values can be different. The linear growth model with two different smoothing coefficients will be reviewed further. Both exponential smoothing models we considered have their analogs in MetaTrader 5 where they exist in the form of indicators. These are well-known EMA and DEMA which are not designed for forecasting but for smoothing of sequence values. It should be noted that when using DEMA indicator, a value corresponding to the a1 coefficient is displayed instead of the one-step forecast value. The a2 coefficient (see the above formulas for the linear growth model) is in this case not calculated nor used. In addition, the smoothing coefficient is calculated in terms of the equivalent period n For example, alpha equal to 0.8 will correspond to n being approximately equal to 2 and if alpha is 0.4, n is equal to 4. 4. Initial Values As already mentioned, a smoothing coefficient value shall in one way or another be obtained upon application of exponential smoothing. But this appears to be insufficient. Since in exponential smoothing the current value is calculated on the basis of the previous one, there is a situation where such value does not yet exist at the time zero. In other words, initial value of S or S1 and S2 in the linear growth model shall in some way be calculated at the time zero. The problem of obtaining initial values is not always easy to solve. If (as in the case of using quotes in MetaTrader 5) we have a very long history available, the exponential smoothing curve will, had the initial values been inaccurately determined, have time to stabilize by a current point, having corrected our initial error. This will require about 10 to 200 (and sometimes even more) periods depending on the smoothing coefficient value. In this case it would be enough to roughly estimate the initial values and start the exponential smoothing process 200-300 periods before the target time period. It gets more difficult, though, when the available sample only contains e. g. 100 values. There are various recommendations in literature regarding the choice of initial values. For example, the initial value in the simple exponential smoothing can be equated to the first element in a sequence or calculated as the mean of three to four initial elements in a sequence with a view to smoothing random outliers. The initial values S1 and S2 in the linear growth model can be determined based on the assumption that the initial level of the forecasting curve shall be equal to the first element in a sequence and the slope of the linear trend shall be zero. One can find yet more recommendations in different sources regarding the choice of initial values but none of them can ensure the absence of noticeable errors at early stages of the smoothing algorithm. It is particularly noticeable with the use of low value smoothing coefficients when a great number of periods is required in order to attain a steady state. Therefore in order to minimize the impact of problems associated with the choice of initial values (especially for short sequences), we sometimes use a method which involves a search for such values that will result in the minimum forecast error. It is a matter of calculating a forecast error for the initial values varying at small increments over the entire sequence. The most appropriate variant can be selected after calculating the error within the range of all possible combinations of initial values. This method is however very laborious requiring a lot of calculations and is almost never used in its direct form. The problem described has to do with optimization or search for a minimum multi-variable function value. Such problems can be solved using various algorithms developed to considerably reduce the scope of calculations required. We will get back to the issues of optimization of smoothing parameters and initial values in forecasting a bit later. 5. Forecast Accuracy Assessment Forecasting procedure and selection of the model initial values or parameters give rise to the problem of estimating the forecast accuracy. Assessment of accuracy is also important when comparing two different models or determining the consistency of the obtained forecast. There is a great number of well-known estimates for the forecast accuracy assessment but the calculation of any of them requires the knowledge of the forecast error at every step. As already mentioned, a one-step-ahead forecast error at the time t is equal to Probably the most common forecast accuracy estimate is the mean squared error (MSE): where n is the number of elements in a sequence. Extreme sensitivity to occasional single errors of large value is sometimes pointed out as a disadvantage of MSE. It derives from the fact that the error value when calculating MSE is squared. As an alternative, it is advisable to use in this case the mean absolute error (MAE). The squared error here is replaced by the absolute value of the error. It is assumed that the estimates obtained using MAE are more stable. Both estimates are quite appropriate for e. g. assessment of forecast accuracy of the same sequence using different model parameters or different models but they appear to be of little use for comparison of the forecast results received in different sequences. Besides, the values of these estimates do not expressly suggest the quality of the forecast result. For example, we cannot say whether the obtained MAE of 0,03 or any other value is good or bad. To be able to compare the forecast accuracy of different sequences, we can use relative estimates RelMSE and RelMAE: The obtained estimates of forecast accuracy are here divided by the respective estimates obtained using the test method of forecasting. As a test method, it is suitable to use the so-called naive method suggesting that the future value of the process will be equal to the current value. If the mean of forecast errors equals the value of errors obtained using the naive method, the relative estimate value will be equal to one. If the relative estimate value is less than one, it means that, on the average, the forecast error value is less than in the naive method. In other words, the accuracy of forecast results ranks over the accuracy of the naive method. And vice versa, if the relative estimate value is more than one, the accuracy of the forecast results is, on the average, poorer than in the naive method of forecasting. These estimates are also suitable for assessment of the forecast accuracy for two or more steps ahead. A one-step forecast error in calculations just needs to be replaced with the value of forecast errors for the appropriate number of steps ahead. As an example, the below table contains one-step ahead forecast errors estimated using RelMAE in one-parameter model of linear growth. The errors were calculated using the last 200 values of each test sequence. Table 1. One-step-ahead forecast errors estimated using RelMAE RelMAE estimate allows to compare the effectiveness of a selected method when forecasting different sequences. As the results in Table 1 suggest, our forecast was never more accurate than the naive method - all RelMAE values are more than one. 6. Additive Models There was a model earlier in the article that comprised the sum of the process level, linear trend and a random variable. We will expand the list of the models reviewed in this article by adding another model which in addition to the above components includes a cyclic, seasonal component. Exponential smoothing models comprising all components as a sum are called the additive models. Apart from these models there are multiplicative models where one, more or all components are comprised as a product. Let us proceed to reviewing the group of additive models. The one-step-ahead forecast error has repeatedly been mentioned earlier in the article. This error has to be calculated in nearly any application related to forecasting based on exponential smoothing. Knowing the value of the forecast error, the formulas for the exponential smoothing models introduced above can be presented in a somewhat different form (error-correcting form). The form of the model representation we are going to use in our case contains an error in its expressions that is partially or fully added to the previously obtained values. Such representation is called the additive error model. Exponential smoothing models can also be expressed in a multiplicative error form which will however not be used in this article. Let us have a look at additive exponential smoothing models. Simple exponential smoothing: Additive linear growth model: In contrast to the earlier introduced one-parameter linear growth model, two different smoothing parameters are used here. Linear growth model with damping: The meaning of such damping is that the trend slope will recede at every subsequent forecasting step depending on the value of the damping coefficient. This effect is demonstrated in Figure 4. Figure 4. Damping coefficient effect As can be seen in the figure, when making a forecast, a decreasing value of the damping coefficient will cause the trend to be losing its strength faster, thus the linear growth will get more and more damped. By adding a seasonal component as a sum to each of these three models we will get three more models. Simple model with additive seasonality: Linear growth model with additive seasonality: Linear growth model with damping and additive seasonality: There are also ARIMA models equivalent to the models with seasonality but they will be left out here as they will hardly have any practical importance whatsoever. Notations used in the formulas provided are as follows: It is easy to see that the formulas for the last model provided include all six variants under consideration. If in the formulas for the linear growth model with damping and additive seasonality we take , the seasonality will be disregarded in forecasting. Further, where , a linear growth model will be produced and where , we will get a linear growth model with damping. The simple exponential smoothing model will correspond to . When employing the models that involve seasonality, the presence of cyclicity and period of the cycle should first be determined using any available method in order to further use this data for initialization of values of seasonal indices. We didnt manage to detect a considerable stable cyclicity in the fragments of test sequences used in our case where the forecast is made over short time intervals. Therefore in this article we will not give relevant examples and expand on the characteristics associated with seasonality. In order to determine the probability prediction intervals with regard to the models under consideration, we will use analytical derivations found in the literature 3. The mean of the sum of squares of one-step-ahead forecast errors calculated over the entire sample of size n will be used as the estimated variance of such errors. Then the following expression will be true for determination of the estimated variance in a forecast for 2 and more steps ahead for the models under consideration: Having calculated the estimated variance of the forecast for every step m, we can find the limits of the 95 prediction interval: We will agree to name such prediction interval the forecast confidence interval. Let us implement the expressions provided for the exponential smoothing models in a class written in MQL5. 7. Implementation of the AdditiveES Class The implementation of the class involved the use of the expressions for the linear growth model with damping and additive seasonality. As mentioned earlier, other models can be derived from it by an appropriate selection of parameters. Let us briefly review methods of AdditiveES class. double s - sets the initial value of the smoothed level double t - sets the initial value of the smoothed trend double alpha1 - sets the smoothing parameter for the level of the sequence double gamma0 - sets the smoothing parameter for the trend double phi1 - sets the damping parameter double delta0 - sets the smoothing parameter for seasonal indices int nses1 - sets the number of periods in the seasonal cycle. It returns a one-step-ahead forecast calculated on the basis of the initial values set. The Init method shall be called in the first place. This is required for setting the smoothing parameters and initial values. It should be noted that the Init method does not provide for initialization of seasonal indices at arbitrary values when calling this method, seasonal indices will always be set to zero. Int m - seasonal index number double is - sets the value of the seasonal index number m. The IniIs(. ) method is called when the initial values of seasonal indices need to be other than zero. Seasonal indices should be initialized right after calling the Init(. ) method. double y new value of the input sequence It returns a one-step-ahead forecast calculated on the basis of the new value of the sequence This method is designed for calculating a one-step-ahead forecast every time a new value of the input sequence is entered. It should only be called after the class initialization by the Init and, where necessary, IniIs methods. int m forecasting horizon of 1,2,3, period It returns the m-step-ahead forecast value. This method calculates only the forecast value without affecting the state of the smoothing process. It is usually called after calling the NewY method. int m forecasting horizon of 1,2,3, period It returns the coefficient value for calculating the forecast variance. This coefficient value shows the increase in the variance of a m-step-ahead forecast compared to the variance of the one-step-ahead forecast. GetS, GetT, GetF, GetIs methods These methods provide access to the protected variables of the class. GetS, GetT and GetF return values of the smoothed level, smoothed trend and a one-step-ahead forecast, respectively. GetIs method provides access to seasonal indices and requires the indication of the index number m as an input argument. The most complex model out of all we have reviewed is the linear growth model with damping and additive seasonality based on which the AdditiveES class is created. This brings up a very reasonable question - what would the remaining, simpler models be needed. Despite the fact, that more complex models should seemingly have a clear advantage over simpler ones, it is actually not always the case. Simpler models that have less parameters will in the vast majority of cases result in lesser variance of forecast errors, i. e. their operation will be more steady. This fact is employed in creating forecasting algorithms based on simultaneous parallel operation of all available models, from the simplest to the most complex ones. Once the sequence have been fully processed, a forecasting model that demonstrated the lowest error, given the number of its parameters (i. e. its complexity), is selected. There is a number of criteria developed for this purpose, e. g. Akaikes Information Criterion (AIC). It will result in selection of a model which is expected to produce the most stable forecast. To demonstrate the use of the AdditiveES class, a simple indicator was created all smoothing parameters of which are set manually. The source code of the indicator AdditiveESTest. mq5 is set forth below. A call or a repeated initialization of the indicator sets the exponential smoothing initial values There are no initial settings for seasonal indices in this indicator, their initial values are therefore always equal to zero. Upon such initialization, the influence of seasonality on the forecast result will gradually increase from zero to a certain steady value, with the introduction of new incoming values. The number of cycles required to reach a steady-state operating condition depends on the value of the smoothing coefficient for seasonal indices: the smaller the smoothing coefficient value, the more time it will require. The operation result of the AdditiveESTest. mq5 indicator with default settings is shown in Figure 5. Figure 5. The AdditiveESTest. mq5 indicator Apart from the forecast, the indicator displays an additional line corresponding to the one-step forecast for the past values of the sequence and limits of the 95 forecast confidence interval. The confidence interval is based on the estimated variance of the one-step-ahead error. To reduce the effect of inaccuracy of the selected initial values, the estimated variance is not calculated over the entire length nHist but only with regard to the last bars the number of which is specified in the input parameter nTest. Files. zip archive at the end of the article includes AdditiveES. mqh and AdditiveESTest. mq5 files. When compiling the indicator, it is necessary that the include AdditiveES. mqh file is located in the same directory as AdditiveESTest. mq5. While the problem of selecting the initial values was to some extent solved when creating the AdditiveESTest. mq5 indicator, the problem of selecting the optimal values of smoothing parameters has remained open. 8. Selection of the Optimal Parameter Values The simple exponential smoothing model has a single smoothing parameter and its optimal value can be found using the simple enumeration method. After calculating the forecast error values over the entire sequence, the parameter value is changed at a small increment and a full calculation is made again. This procedure is repeated until all possible parameter values have been enumerated. Now we only need to select the parameter value which resulted in the smallest error value. In order to find an optimal value of the smoothing coefficient in the range of 0.1 to 0.9 at 0.05 increments, the full calculation of the forecast error value will need to be made seventeen times. As can be seen, the number of calculations required is not so big. But the linear growth model with damping involves the optimization of three smoothing parameters and in this case it will take 4913 calculation runs in order to enumerate all their combinations in the same range at the same 0.05 increments. The number of full runs required for enumeration of all possible parameter values rapidly increases with the increase in the number of parameters, decrease in the increment and expansion of the enumeration range. Should it further be necessary to optimize the initial values of the models in addition to the smoothing parameters, it will be quite difficult to do using the simple enumeration method. Problems associated with finding the minimum of a function of several variables are well studied and there is quite a lot of algorithms of this kind. Description and comparison of various methods for finding the minimum of a function can be found in the literature 7. All these methods are primarily aimed at reducing the number of calls of the objective function, i. e. reducing the computational efforts in the process of finding the minimum. Different sources often contain a reference to the so-called quasi-Newton methods of optimization. Most likely this has to do with their high efficiency but the implementation of a simpler method should also be sufficient to demonstrate an approach to the optimization of forecasting. Let us opt for Powells method. Powells method does not require calculation of derivatives of the objective function and belongs to search methods. This method, like any other method, may be programmatically implemented in various ways. The search should be completed when a certain accuracy of the objective function value or the argument value is attained. Besides, a certain implementation may include the possibility of using limitations on the permissible range of function parameter changes. In our case, the algorithm for finding an unconstrained minimum using Powells method is implemented in PowellsMethod. class. The algorithm stops searching once a given accuracy of the objective function value is attained. In the implementation of this method, an algorithm found in the literature 8 was used as a prototype. Below is the source code of the PowellsMethod class. The Optimize method is the main method of the class. double ampp - array that at the input contains the initial values of parameters the optimal values of which shall be found the obtained optimal values of these parameters are at the output of the array. int n0 - number of arguments in array p. Where n0, the number of parameters is considered to be equal to the size of array p. It returns the number of iterations required for operation of the algorithm, or -1 if the maximum permissible number thereof has been reached . When searching for optimal parameter values, an iterative approximation to the minimum of the objective function occurs. The Optimize method returns the number of iterations required to reach the function minimum with a given accuracy. The objective function is called several times at every iteration, i. e. the number of calls of the objective function may be significantly (ten and even hundred times) bigger than the number of iterations returned by the Optimize method. Other methods of the class. Int n - maximum permissible number of iterations in Powells method. The default value is 200. It sets the maximum permissible number of iterations once this number is reached, the search will be over regardless of whether the minimum of the objective function with a given accuracy was found. And a relevant message will be added to the log. double er - accuracy. Should this value of deviation from the minimum value of the objective function be reached, Powells method stops searching. The default value is 1e-6. Int n - maximum permissible number of iterations for an auxiliary Brents method. The default value is 200. It sets the maximum permissible number of iterations. Once it is reached, the auxiliary Brents method will stop searching and a relevant message will be added to the log. double er accuracy. This value defines accuracy in the search of the minimum for the auxiliary Brents method. The default value is 1e-4. It returns the minimum value of the objective function obtained. It returns the number of iterations required for operation of the algorithm. Virtual function func(const double ampp) const double ampp address of the array containing the optimized parameters. The size of the array corresponds to the number of function parameters. It returns the function value corresponding to the parameters passed to it. The virtual function func() shall in every particular case be redefined in a class derived from the PowellsMethod class. The func() function is the objective function the arguments of which corresponding to the minimum value returned by the function will be found when applying the search algorithm. This implementation of Powells method employs Brents univariate parabolic interpolation method for determining the direction of search with regard to each parameter. The accuracy and maximum permissible number of iterations for these methods can be set separately by calling SetItMaxPowell, SetFtolPowell, SetItMaxBrent and SetFtolBrent. So the default characteristics of the algorithm can be changed in this manner. This may appear useful when the default accuracy set to a certain objective function turns out to be too high and the algorithm requires too many iterations in the search process. The change in the value of the required accuracy can optimize the search with regard to different categories of objective functions. Despite the seeming complexity of the algorithm that employs Powells method, it is quite simple in use. Let us review an example. Assume, we have a function and we need to find the values of parameters and at which the function will have the smallest value. Let us write a script demonstrating a solution to this problem. When writing this script, we first create the func() function as a member of the PMTest class which calculates the value of the given test function using the passed values of parameters p0 and p1. Then in the body of the OnStart() function, the initial values are assigned to the required parameters. The search will start from these values. Further, a copy of the PMTest class is created and the search for the required values of p0 and p1 starts by calling the Optimize method the methods of the parent PowellsMethod class will call the redefined func() function. Upon completion of the search, the number of iterations, function value at the minimum point and the obtained parameter values p00.5 and p16 will be added to the log. PowellsMethod. mqh and a test case PMTest. mq5 are located at the end of the article in Files. zip archive. In order to compile PMTest. mq5, it should be located in the same directory as PowellsMethod. mqh. 9. Optimization of the Model Parameter Values The previous section of the article dealt with implementation of the method for finding the function minimum and gave a simple example of its use. We will now proceed to the issues related to optimization of the exponential smoothing model parameters. For a start, let us simplify the earlier introduced AdditiveES class to the maximum by excluding from it all elements associated with the seasonal component, as the models that take into consideration seasonality are not going to be further considered in this article anyway. This will allow to make the source code of the class much easier to comprehend and reduce the number of calculations. In addition, we will also exclude all calculations related to forecasting and computations of the forecast confidence intervals for an easy demonstration of an approach to the optimization of parameters of the linear growth model with damping under consideration. The OptimizeES class derives from the PowellsMethod class and includes redefining of the virtual function func(). As mentioned earlier, the parameters whose calculated value will be minimized in the course of optimization shall be passed at the input of this function. In accordance with the maximum likelihood method, the func() function calculates the logarithm of the sum of squares of one-step-ahead forecast errors. The errors are calculated in a loop with regard to NCalc recent values of the sequence. To preserve the stability of the model, we should impose limitations on the range of changes in its parameters. This range for Alpha and Gamma parameters will be from 0.05 to 0.95, and for Phi parameter - from 0.05 to 1.0. But for optimization in our case, we use a method for finding an unconstrained minimum which does not imply the use of limitations on the arguments of the objective function. We will try to turn the problem of finding the minimum of the multi-variable function with limitations into a problem of finding an unconstrained minimum, to be able to take into consideration all limitations imposed on the parameters without changing the search algorithm. For this purpose, the so-called penalty function method will be used. This method can easily be demonstrated for a one-dimensional case. Suppose that we have a function of a single argument (whose domain is from 2.0 to 3.0) and an algorithm which in the search process can assign any values to this function parameter. In this case, we can do as follows: if the search algorithm has passed an argument which exceeds the maximum permissible value, e. g. 3.5, the function can be calculated for the argument equal to 3.0 and the obtained result is further multiplied by a coefficient proportional to the excess of the maximum value, for example k1(3.5-3)200. If similar operations are performed with regard to argument values that turned out to be below the minimum permissible value, the resulting objective function is guaranteed to increase outside the permissible range of changes in its argument. Such artificial increase in the resulting value of the objective function allows to keep the search algorithm unaware of the fact that the argument passed to the function was in any way limited and guarantee that the minimum of the resulting function will be within the set limits of the argument. Such approach is easily applied to a function of several variables. The main method of the OptimizeES class is the Calc method. A call of this method is responsible for reading data from a file, search for optimal parameter values of a model and estimation of the forecast accuracy using RelMAE for the obtained parameter values. The number of processed values of the sequence read from a file is in this case set in the variable NCalc. Below is the example of the OptimizationTest. mq5 script that uses the OptimizeES class. Following the execution of this script, the obtained result will be as shown below. Figure 6. OptimizationTest. mq5 script result Although we can now find optimal parameter values and initial values of the model, there is yet one parameter which cannot be optimized using simple tools - the number of sequence values used in optimization. In optimization with regard to a sequence of great length, we will obtain the optimal parameter values that, on the average, ensure a minimum error over the entire length of the sequence. However if the nature of the sequence varied within this interval, the obtained values for some of its fragments will no longer be optimal. On the other hand, if the sequence length is dramatically decreased, there is no guarantee that the optimal parameters obtained for such a short interval will be optimal over a longer time lag. OptimizeES. mqh and OptimizationTest. mq5 are located at the end of the article in Files. zip archive. When compiling, it is necessary that OptimizeES. mqh and PowellsMethod. mqh are located in the same directory as the compiled OptimizationTest. mq5. In the given example, USDJPYM11100.TXT file is used that contains the test sequence and that should be located in the directory MQL5FilesDataset. Table 2 shows the estimates of the forecast accuracy obtained using RelMAE by means of this script. Forecasting was done with regard to eight test sequences mentioned earlier in the article using the last 100, 200 and 400 values of each of these sequences. Table 2. Forecast errors estimated using RelMAE As can be seen, the forecast error estimates are close to unity but in the majority of cases the forecast for the given sequences in this model is more accurate than in the naive method. 10. The IndicatorES. mq5 Indicator The AdditiveESTest. mq5 indicator based on the AdditiveES. mqh class was mentioned earlier upon review of the class. All smoothing parameters in this indicator were set manually. Now after considering the method allowing to optimize the model parameters, we can create a similar indicator where the optimal parameter values and initial values will be determined automatically and only the processed sample length will need to be set manually. That said, we will exclude all calculations related to seasonality. The source code of the CIndiatorES class used in creating the indicator is set forth below. This class contains CalcPar and GetPar methods the first one is designed for calculation of the optimal parameter values of the model, the second one is intended for accessing those values. Besides, the CIndicatorES class comprises the redefining of the virtual function func(). The source code of the IndicatorES. mq5 indicator: With every new bar, the indicator finds the optimal values of the model parameters, makes calculations in the model for a given number of bars NHist, builds a forecast and defines the forecast confidence limits. The only parameter of the indicator is the length of the processed sequence the minimum value of which is limited to 24 bars. All calculations in the indicator are made on the basis of the open values. The forecasting horizon is 12 bars. The code of the IndicatorES. mq5 indicator and CIndicatorES. mqh file are located at the end of the article in Files. zip archive. Figure 7. Operation result of the IndicatorES. mq5 indicator An example of the operation result of the IndicatorES. mq5 indicator is shown in Figure 7. In the course of operation of the indicator, the 95 forecast confidence interval will take values corresponding to the obtained optimal parameter values of the model. The bigger the smoothing parameter values, the faster the increase in the confidence interval upon the increasing forecasting horizon. With a simple improvement, the IndicatorES. mq5 indicator can be used not only for forecasting currency quotes but also for forecasting values of various indicators or preprocessed data. Conclusion The main objective of the article was to familiarize the reader with additive exponential smoothing models used in forecasting. While demonstrating their practical use, some accompanying issues were also dealt with. However the materials provided in the article can be considered merely an introduction to the large range of problems and solutions associated with forecasting. I would like to draw your attention to the fact that the classes, functions, scripts and indicators provided were created in the process of writing the article and are primarily designed to serve as examples to the materials of the article. Therefore no serious testing for stability and errors was performed. Besides, the indicators set forth in the article should be considered to be only a demonstration of the implementation of the methods involved. The forecast accuracy of the IndicatorES. mq5 indicator introduced in the article can most likely be somewhat improved by using the modifications of the applied model which would be more adequate in terms of peculiarities of the quotes under consideration. The indicator can also be amplified by other models. But these issues fall beyond the scope of this article. In conclusion, it should be noted that exponential smoothing models can in certain cases produce forecasts of the same accuracy as the forecasts obtained by applying more complex models thus proving once again that even the most complex model is not always the best. Referenzen


No comments:

Post a Comment