Quantitative Trading Strategien Excel


Ein Leser kommentiert den Handel mit Excel VBA und Factor Model Nachdenkliche Kommentare von einem Leser John S. aus Großbritannien auf seine Erfahrung mit Handelstechnologie und Modelle: Ich habe meine eigenen persönlichen automatischen Handelssysteme mit Excel VBA entwickelt und basiert auf Regeln, die ich habe Entwickelte sich im Laufe der Jahre als aktiver privater Händlerinvestor mit technischer und fundamentaler Datenanalyse. Eines der wichtigsten Vorzüge bei der Annahme eines automatischen Handelssystemansatzes, der mir geholfen hat, ist, die Versuchung für manuelle Interferenzen zu vermeiden und dadurch die Rentabilität zu verbessern, indem sie Konsistenz bewahrt. Ich habe die Herausforderung gefunden, ein erfolgreiches System zu entwickeln, das aus einer persönlichen Perspektive sehr belohnt, da ich erkenne, dass es viele gibt, die versucht haben und gescheitert sind. Aber ein Problem, das ich begegnet habe, ist mein anhaltender Wunsch, das System regelmäßig zu modifizieren und zu verbessern, das ich gefunden habe, kann kontraproduktiv werden, da es eine echte Gefahr gibt, dass die Systementwicklung ein Selbstzweck wird. Ich kann einfach nicht aufhören zu basteln, sobald ich Kommen mit einer neuen Idee oder Eigenschaft Ein Vorteil der Verwendung von Excel VBA, die ich gefunden habe, ist, dass es inhärent flexibel ist, da es die Verarbeitung von Daten erleichtert, die vor allem bei der Verwendung von Fundamentaldaten als Teil des Systems wichtig sein können. In dieser Hinsicht erkenne ich, dass jeder Händler versucht, in einer Kante zu bauen, die das System rentabler macht. Ich habe bemerkt, dass viele Händler scheinen sich nur auf den Preis zu konzentrieren, indem sie versuchen, eine Kante zu suchen, indem sie spezielle Indikatoren oder Kombination von Indikatoren etc. anschließen. Die Kombination von Preisdatenanalyse mit einem Faktor-Modell-Ansatz ist eine Herausforderung, die ideal für Excel VBA geeignet ist Können leicht genutzt werden, um sowohl fundamentale als auch makroökonomische Daten in eine Form zu verarbeiten, die mit der Preisdatenanalyse integriert werden kann. Ich erkenne aus deinem Buch, dass Matlab stärker ist als Excel VBA und kann genauso flexibel sein, um fundamentale und makroökonomische Daten zu integrieren, aber ich wollte nur deine Aufmerksamkeit auf Vorteile lenken, die ich mit Excel VBA gefunden habe, die denen entsprechen kann, die mich selbst mögen Bequem in der Verwendung von Excel VBA und sind nur ungern zu ändern. Andere Features, die ausgenutzt werden können, die ich bei der Rückprobe hilfreich gefunden habe, produzieren automatisch Preis-Charts, die Einstiegs - und Ausstiegspunkte enthalten, die eine visuelle Beruhigung bieten, die das System wie beabsichtigt bearbeitet, sowie die Erstellung von automatischen Word-Berichten zur Aufzeichnung der Schlüsselausgabe für zukünftige Referenz. Es tut mir leid, wenn ich zu viel wie eine Anzeige für Microsoft 7 kommentiere: Ich rechne die wichtigsten Gründe für eine Popularität von ExcelVBA in einer Quant - und Quant-Trading-Welt: 1. Eine Menge Leute, die es bereits benutzen - also jeder denkt das Weg zu gehen. 2. Einfachheit von VBA (nicht sicher, ob es mit seiner Flexibilität korreliert) - das macht es möglich, effektiv von jedermann zu benutzen - ob es sich um einen Händler, einen Quant oder einen Schreibtischentwickler handelt. 3. VBA und Excel konnten problemlos erweitert werden (um eine Performance zu verbessern, eine Software von Drittanbietern zu integrieren oder nur modularisierbare Zwecke zu nutzen), indem sie die tatsächliche Modelllogik in C, COM oder As für die spätere (einfache Möglichkeit zur Integration von quant analytics) Geschrieben mit Excel und VBA) - man kann mir einen Blick auf meine Lösung werfen: excel4net Ich denke definitiv den Bandwagon Faktor ist im Spiel, wir sind oft wie Schafe, und ich sehe keinen Grund, warum Anlagestrategie oder Systeme anders wäre. Ein bisschen Glück wird sich nicht in den Forex einmischen. Aber ein Problem, das ich begegnet habe, ist mein anhaltender Wunsch, das System, das ich gefunden habe, regelmäßig zu modifizieren und zu verbessern, da es eine wirkliche Gefahr dafür gibt, dass die Systementwicklung ein Selbstzweck wird Interessanter Punkt. Ich glaube, dass der beste Weg, um damit umzugehen ist zu akzeptieren (oder ablehnen) die Art von WinLoss-Verhältnis Ihre Trading-Methode produziert. Was ich meine, ist, dass, wenn Sie gegen Zähler Trend handeln, und psychologisch fühlen Sie sich nur mit einem hohen Niveau von Gewinnen Trades, youll haben eine harte Zeit Bewältigung eines Systems, das so viele Gewinne oder Verluste erzeugt. Unter diesen Umständen werden Sie vielleicht (und das System) besser dran sein, indem Sie strengere Kriterien aufstellen und einige Setups - aber nicht zu viele - opfern, um ein höheres Niveau an Gewinnen zu erzielen (auch wenn Sie dabei auch Könnte Ihre Avg Win Avg Loss Ratio reduzieren). Aber ich bin einverstanden: seine heikle Frage, die die meisten erfahrenen Händler verbrennen. Aber ein Problem, das ich begegnet habe, ist mein anhaltender Wunsch, das System regelmäßig zu modifizieren und zu verbessern, das ich gefunden habe, kann kontraproduktiv werden, da es eine echte Gefahr gibt, dass die Systementwicklung ein Selbstzweck wird. Ich war von deinem Post sehr überrascht. In der Welt der quantitativen Analysten (Derivatmodelle Design und Umsetzung etc. für Top-Tier-Investment-Banken habe ich 6 Jahre damit verbracht) Excel VBA ist vermutlich die am wenigsten flexible und nachhaltige Programmiersprache, die wir mit Systemen beschäftigen müssen, die mit diesen geschrieben wurden Sprachen sind im Ruhestand. Ich verstehe, dass du jetzt noch glücklich bist, aber du denkst vielleicht, dass du die Alternativen studieren möchtest. Bei einem relativ bescheidenen Einstiegspreis können Sie Leistung und Nachhaltigkeit bekommen, die Sie überraschen würde. VBA-Probleme, die in den Sinn kommen, sind: schlechte Leistung, schlechtes Speicher-Management (dies kann die Leistung noch schlimmer machen), können Sie nicht verwenden Versionskontrollsystem, das Ihnen erlauben würde, Änderungen zu verfolgen (wer-was-warum-wann) und würde die Zusammenarbeit erleichtern (Siehe z. B. svnbook. red-beannightlyensvn. intro. whatis. htmlsvn. intro. righttool und tortoisesvn. tigris. org gibt es einige Microsoft Versionskontroll-Tools). Basierend auf meiner Erfahrung, beginnend von einigen Volumen VBA-Code wird unüberschaubar, einer der Gründe dafür, dass Sie nicht verwenden können, um die Kontrolle zu kontrollieren. Schlechte Flexibilität (im Vergleich zu den Alternativen werde ich Abwesenheit von Klassen sein (Klassenstrukturmethoden, die auf den Inhalt der Struktur zugreifen und diese ändern können) Virtuelle Abwesenheit von Abstraktionsmechanismen (Variante ist sehr fehleranfällig) Sie könnten sie brauchen, wenn Sie wollen Verwenden Sie den gleichen Algorithmus für eine Aktie und für eine Zinskurve (gleiche Aktion, verschiedene Objekte). Alternative, einfach zu bedienende Programmiersprachen wäre Matlab und Python. Beide Sprachen sind SVN-freundlich (siehe die dritte Aufzählung), Excel-freundlich, aber (1K - 10K, je nachdem, welche Pakete du brauchst und an deinem Standort), viel schöner und benutzerfreundlicher, Support-Team ist fertig. Matlab Performance Tipp: vektorisieren Sie Ihren Code (mit Vektoren arbeiten) Und Matrizen statt auf Element-für-Element-Basis, zB Vektor, wo Element wäre ein Preis von Lager X auf Datum Beobachtung Datum i Tage oder Matrix, wo Element ij wäre eine Rendite der Währung Y am Datum i für die Fälligkeit j). Ein weiterer Weg, um Matlab zu beschleunigen ist ein Paket zu kaufen, das Matlab Code Code in C-Code konvertieren kann, die in einer DLL kompiliert werden können, die Sie in Excel verwenden können. Solche DLL würde viel schneller arbeiten (kann hundertmal schneller sein, hängt von deiner Aufgabe ab). Python ist eine Freeware, ganz streng, es dauert ein bisschen Zeit, um hineinzukommen, aber es würde sich lohnen. Es ist flexibler, mehr eine richtige Programmiersprache. Andere Sprachen, die Sie vielleicht betrachten möchten, sind C, VB und Stand-alone VB (alle von Microsoft, alle preiswert). Ich würde sie zwischen C stellen (siehe unten) und Excel VBA C wäre die mächtigste, VB wäre die einfachste für Sie zu verwenden - es ist fast identisch mit VBA. Auch hier gibt es einen Kompromiss zwischen Performanceflexibilität und Gleichzeitigkeit gegenüber Excel VBA. Handschriftlicher C-Code ist das beste aus der Leistungsperspektive, das ist eine ziemlich vielseitige Sprache, aber es braucht viel mehr Zeit, um es zu lernen. Hoffe, du würdest es interessant finden. Hallo Dr. Ernie Chan Ich habe dein Buch über den quantitativen Handel gelesen. Es wird gesagt, dass MATLAB ein gutes Werkzeug ist, um komplexe Strategien zu entwickeln. Aber dafür gibt es keine gut genehmigte API. Es gibt eine vor kurzem gefundene MATLAB2IB. Aber ist es gut genug und gut getestet Es ist in Ihrem Buch gesagt, dass ExcelVBA ist langsam im Vergleich zu C. Ich interessiere mich für die Entwicklung eines automatisierten Handelssystems. Soll ich diese neue MATLAB2IB verwenden und weiterhin Strategien in Matlab entwickeln, bin ich in Matlab gut und ich habe es bei meinem Ph. D und anderen Arbeiten ausführlich genutzt. Ich habe nicht viel benutzt und ich fand es schwieriger im Vergleich zu MATLAB. Angesichts einer Wahl, werde ich immer Codierung in MATLAB. Aber ist es notwendig, Strategien in C zu entwickeln, wenn ich ein automatisches Handelssystem Hi Vinay entwickeln möchte, habe ich matlab2ibapi seit mehreren Monaten benutzt und habe es für nützlich gehalten, meine Strategien zu automatisieren. In der Tat, ich werde einen Artikel veröffentlichen, wie man es benutzt. ErnieMany populäre quantitative Handelsstrategien sind für eine ganze Weile öffentlich. Nun, wenn Sie eine solche Strategie mit echtem Geld nutzen möchten, müssen Sie sicherstellen, dass Ihre Strategie gut funktioniert. Für einfache Strategien ist MS Excel perfekt für diese Aufgabe. Aber da wir eine Optimierung und eine spezifische Visualisierung später nutzen möchten, verwenden wir Theta Suite und Matlab. Dies ermöglicht auch die Analyse von komplexeren Strategien, wenn Sie möchten. Einrichten einer quantitativen Handelsstrategie: MACD 8211 Signal Einer der beliebtesten technischen Indikatoren ist die Moving Average ConvergenceDivergence (MACD), die im Wesentlichen die Differenz zwischen zwei gleitenden Durchschnitten. Die Literatur sagt, der Nulldurchgang einer MACD-Linie würde einen guten Hinweis für den Kauf von Verkaufsbeständen geben. Irgendwann fügen sie ein Trigger-Signal hinzu und behaupten, das wäre noch besser. Let8217s sehen, ob das wahr ist. Genauer handelnder MACD ist in der Regel als resp. In einer Schleife über die Zeit sieht das aus, wo EMA12 und EMA26 zwei verschiedene exponentielle gleitende Mittelwerte mit den Konstanten 8220constl128221 und 82208221constl268221 sind. Die EMA ist definiert als: Das entsprechende Handelssystem mit einer Signalperiode von 8220constl 98221 sieht aus wie Testen der Strategie mit echten historischen Daten Dieser Teil ist sehr wichtig. Ich kann diese Tatsache nicht zu stark betonen: In einem späteren Beitrag werden wir noch mehr über das Back-Testen sprechen. Die Zuordnung dieser Daten zu einem ThetaML-Prozess ermöglicht die Einschätzung der Performance der MACD-basierten Handelsstrategie. Hier ist ein Diagramm der IBM Aktienkurse von 2000-01-01 bis 2011-12-31: Matlab Plot von IBM Aktienkurs Backtesting der MACD Trading Strategie Wir können die oben genannten ThetaML Modelle mit dem Theta Suite Orchestrator und verbinden Sie es mit dem historischen IBM Daten in Matlab im Konfigurator. Dann, im Ergebnis-Explorer, erhalten wir die Leistung der entsprechenden MACD-Signal Trading-Strategie ohne Leerverkäufe Plot der Performance der MACD Trading-Strategie und mit Leerverkäufen, sieht es wie Performance der MACD Trading-Strategie mit Leerverkäufe Beachten Sie, dass in den meisten Jahren , Die MACD-Signal-Strategie nicht besser als die zugrunde liegenden selbst. Unter Berücksichtigung der Transaktionskosten sieht das noch schlimmer aus. Interessanterweise lieferte das Jahr 2000 eine große Leistung der MACD-Strategie, aber alle späteren Jahre haben das nicht gut gemacht. Schlussfolgerung Es ist leicht zu überprüfen, ob eine Strategie gut mit historischen Daten durchgeführt hätte. ThetaML und Matlab sind hervorragende Werkzeuge für diese Aufgabe. Die von uns analysierte MACD-basierte Handelsstrategie ist nicht wesentlich besser als das zugrunde liegende Unternehmen zu halten. Andere Parameter der Handelsstrategie könnten zu besseren Ergebnissen führen, so dass wir eine Optimierung durchführen können. Wir werden sehen, dass nächste Woche. November 30, 2016, 12:34 pm Vor ein paar Monaten ein Leser zeigt mir diese neue Art der Verbindung von R und Excel. Ich weiß nicht, wie lange das schon gewesen ist, aber ich habe nie darauf gekommen und ich habe nie einen Blog-Post oder Artikel darüber gesehen. Also habe ich beschlossen, einen Beitrag zu schreiben, da das Tool es wirklich wert ist und bevor jemand fragt, I8217m nicht mit dem Unternehmen in irgendeiner Weise verwandt. BERT steht für Basic Excel R Toolkit. It8217s kostenlos (lizenziert unter der GPL v2) und wurde von Structured Data LLC entwickelt. Zum Zeitpunkt des Schreibens der aktuellen Version von BERT ist 1.07. Weitere Informationen finden Sie hier. Aus technischer Sicht ist BERT entworfen, um laufende R-Funktionen aus Excel-Tabellenkalkulationen zu unterstützen. In Excel-Begriffen, it8217s für das Schreiben von benutzerdefinierten Funktionen (UDFs) in R. In diesem Beitrag I8217m nicht zeigen, wie R und Excel über BERT interagieren. Es gibt hier sehr gute Tutorials. Hier und hier Stattdessen möchte ich dir zeigen, wie ich BERT benutzt habe, um einen 8220control tower8221 für meinen Handel zu bauen. Meine Trading-Signale werden mit einer langen Liste von R-Dateien generiert, aber ich brauche die Flexibilität von Excel, um Ergebnisse schnell und effizient anzuzeigen. Wie oben gezeigt, kann BERT dies für mich tun, aber ich möchte auch die Anwendung auf meine Bedürfnisse anpassen. Durch die Kombination der Power von XML, VBA, R und BERT kann ich eine gut aussehende und dennoch leistungsstarke Anwendung in Form einer Excel-Datei mit minimalem VBA-Code erstellen. Letztlich habe ich eine einzige Excel-Datei, die alle notwendigen Aufgaben sammelt, um mein Portfolio zu verwalten: Datenbank-Update, Signalerzeugung, Auftragsvorlage etc8230 Mein Ansatz könnte in den folgenden 3 Schritten abgebaut werden: Verwenden Sie XML, um benutzerdefinierte Menüs und Schaltflächen in einem Excel zu erstellen Datei. Die oben genannten Menüs und Tasten sind im Wesentlichen Anrufe an VBA-Funktionen. Diese VBA-Funktionen werden um R-Funktionen, die mit BERT definiert sind, umbrochen. Mit diesem Ansatz kann ich eine klare Unterscheidung zwischen dem Kern meines Codes, der in R, SQL und Python gehalten wird, und alles, was verwendet wird, um Ergebnisse anzuzeigen und zu formatieren, die in Excel, VBA amp XML gespeichert sind. In den folgenden Abschnitten stelle ich die Voraussetzung für die Entwicklung eines solchen Ansatzes und eine Schritt für Schritt Anleitung, die erklärt, wie BERT verwendet werden könnte, um einfach Daten von R nach Excel mit minimalem VBA-Code zu übergeben. 1 8211 BERT von diesem Link herunterladen und installieren. Sobald die Installation abgeschlossen ist, sollten Sie ein neues Add-Ins-Menü in Excel mit den Schaltflächen wie unten gezeigt haben. Dies ist, wie BERT in Excel materialisiert. 2 8211 Herunterladen und Installieren des benutzerdefinierten UI-Editors. Der benutzerdefinierte UI-Editor ermöglicht das Erstellen von benutzerdefinierten Menüs und Schaltflächen im Excel-Band. Hier finden Sie eine Schritt-für-Schritt-Prozedur. Schritt für Schritt Anleitung 1 8211 R Code: Die untenstehende R-Funktion ist ein sehr einfaches Stück Code zur Veranschaulichung nur. Es berechnet und gibt die Residuen aus einer linearen Regression zurück. Das wollen wir in Excel abrufen. Speichern Sie diese in einer Datei namens myRCode. R (jeder andere Name ist in Ordnung) in einem Verzeichnis Ihrer Wahl. 2 8211 funktionen. R in BERT. Wählen Sie aus Excel das Add-Ins - gt Home Directory aus und öffnen Sie die Datei function. R. Fügen Sie in dieser Datei den folgenden Code ein. Stellen Sie sicher, dass Sie den richtigen Pfad einfügen. Dies ist nur Sourcing in BERT die R-Datei, die Sie oben erstellt. Dann speichern und schließen Sie die Datei functions. R. Sollten Sie die in Schritt 1 erstellte R-Datei ändern wollen, müssen Sie sie mit dem BERT-Button 8220Reload Startup File8221 aus dem Add-Ins-Menü in Excel 3 8211 in Excel neu laden: Eine Datei mit dem Namen myFile. xslm erstellen und speichern (Jeder andere name ist gut). Dies ist eine Makro-fähige Datei, die Sie im Verzeichnis Ihrer Wahl speichern. Sobald die Datei gespeichert ist, schließen Sie es. 4 8211 Öffnen Sie die oben erstellte Datei im Custom UI Editor: Sobald die Datei geöffnet ist, fügen Sie den folgenden Code ein. Sie sollten so etwas im XML-Editor haben: Im Wesentlichen erstellt dieses Stück XML-Code ein zusätzliches Menü (RTrader), eine neue Gruppe (Meine Gruppe) und eine benutzerdefinierte Schaltfläche (New Button) im Excel-Band. Sobald you8217re getan ist, öffnen Sie myFile. xslm in Excel und schließen Sie den benutzerdefinierten Benutzeroberteil-Editor. Du solltest so etwas sehen 5 8211 VBA-Editor öffnen In myFile. xlsm füge ein neues Modul ein. Fügen Sie den Code unten in das neu erstellte Modul ein. Dadurch werden die bisherigen Ergebnisse im Arbeitsblatt gelöscht. 6 8211 Klicken Sie auf Neue Schaltfläche. Gehen Sie nun wieder in die Kalkulationstabelle und klicken Sie im RTrader-Menü auf die Schaltfläche 8220New Button8221. Du solltest so etwas wie das unten erscheinen lassen. Der Leitfaden oben ist eine sehr grundlegende Version dessen, was mit BERT erreicht werden kann, aber es zeigt Ihnen, wie Sie die Kraft von mehreren spezifischen Werkzeugen kombinieren können, um Ihre eigene benutzerdefinierte Anwendung zu erstellen. Aus meiner Perspektive ist das Interesse eines solchen Ansatzes die Fähigkeit, zusammen R und Excel offensichtlich zusammenzukleben, aber auch über XML (und Batch) Stücke von Code von Python, SQL und mehr einzuschließen. Das ist genau das, was ich brauchte Schließlich wäre ich neugierig zu wissen, ob jemand irgendwelche Erfahrungen mit BERT hat. 19. August 2016, 9:26 Uhr Beim Testen von Handelsstrategien ist ein gemeinsamer Ansatz, den Anfangsdatensatz in die Beispieldaten aufzuteilen: den Teil der Daten, der entworfen ist, um zu kalibrieren Das Modell und aus den Beispieldaten: der Teil der Daten, die verwendet werden, um die Kalibrierung zu validieren und sicherzustellen, dass die Leistung, die in der Probe erstellt wird, in der realen Welt reflektiert wird. Als Faustregel können etwa 70 der Anfangsdaten für die Kalibrierung (d. h. in der Probe) und 30 für die Validierung (d. h. aus der Probe) verwendet werden. Dann hilft ein Vergleich der In und Out von Beispieldaten zu entscheiden, ob das Modell robust genug ist. Dieser Beitrag zielt darauf ab, einen Schritt weiter zu gehen und stellt eine statistische Methode zur Verfügung, um zu entscheiden, ob die aus den Beispieldaten im Einklang mit dem war, was in der Stichprobe erstellt wurde. In der Grafik unterhalb der blauen Bereich stellt die aus der Probe Leistung für eine meiner Strategien. Eine einfache visuelle Inspektion zeigt eine gute Passform zwischen der in und aus der Probe Leistung aber welchen Grad des Vertrauens habe ich in diesem In diesem Stadium nicht viel und das ist das Problem. Was wirklich benötigt wird, ist ein Maß für die Ähnlichkeit zwischen dem In und aus den Beispieldatensätzen. In statistischer Hinsicht könnte dies als die Wahrscheinlichkeit, dass die in und aus der Probe Leistung Zahlen aus der gleichen Verteilung übersetzt werden übersetzt werden. Es gibt einen nicht parametrischen statistischen Test, der genau das tut: der Kruskall-Wallis Test. Eine gute Definition dieses Tests konnte auf R-Tutor gefunden werden 8220A Sammlung von Datenproben sind unabhängig, wenn sie aus nicht verwandten Populationen kommen und die Proben sich nicht gegenseitig beeinflussen. Mit dem Kruskal-Wallis-Test. Können wir entscheiden, ob die Populationsverteilungen identisch sind, ohne davon auszugehen, dass sie der Normalverteilung folgen.8221 Der zusätzliche Vorteil dieses Tests nimmt keine normale Verteilung an. Es gibt andere Tests der gleichen Art, die in diesen Rahmen passen könnte. Der Mann-Whitney-Wilcoxon-Test oder die Kolmogorov-Smirnov-Tests passen perfekt zu dem Rahmen, der hier beschrieben wird, aber das geht über den Rahmen dieses Artikels hinaus, um die Vor - und Nachteile von jedem dieser Tests zu besprechen. Eine gute Beschreibung zusammen mit R-Beispielen finden Sie hier. Hier ist der Code, der verwendet wird, um das obige Diagramm und die Analyse zu erzeugen: Im obigen Beispiel ist die Abtastperiode länger als die aus der Stichprobenperiode, daher habe ich zufällig 1000 Teilmengen der in Beispieldaten erstellt, die jeweils dieselbe Länge haben wie die aus Der Beispieldaten. Dann habe ich jede in Probe Teilmenge gegen die aus der Probe Daten getestet und ich habe die p-Werte aufgezeichnet. Dieser Prozess schafft nicht einen einzigen p-Wert für den Kruskall-Wallis-Test, sondern eine Verteilung, die die Analyse robuster macht. In diesem Beispiel liegt der Mittelwert der p-Werte weit über null (0,478), was anzeigt, dass die Nullhypothese akzeptiert werden sollte: Es gibt starke Hinweise darauf, dass die Ein - und Ausstiegsproben aus derselben Verteilung stammen. Wie üblich, was in diesem Beitrag präsentiert wird, ist ein Spielzeugbeispiel, das nur die Oberfläche des Problems kratzt und auf individuelle Bedürfnisse zugeschnitten werden sollte. Allerdings denke ich, dass es einen interessanten und rationalen statistischen Rahmen vorschlägt, um die Ergebnisse der Ergebnisse zu bewerten. Dieser Beitrag wird von den folgenden zwei Beiträgen inspiriert: Vigier Alexandre, Chmil Swann (2007), Auswirkungen verschiedener Optimierungsfunktionen auf die Out-of-Sample-Performance von genetisch entwickelten Handelsstrategien, Prognose der Finanzmärkte Konferenz Vigier Alexandre, Chmil Swann (2010), An Optimierungsprozess zur Verbesserung der Stichprobenkonsistenz, ein Börsenkoffer, JP Morgan Cazenove Equity Quantitative Konferenz, London Oktober 2010 13. Dezember 2015, 14:03 Uhr Die quantitative Forschung impliziert viel Daten knirscht und man braucht saubere und zuverlässige Daten zu Dies erreichen. Was wirklich benötigt wird, ist saubere Daten, die leicht zugänglich sind (auch ohne Internetverbindung). Der effizienteste Weg, dies für mich zu tun, war, einen Satz von csv-Dateien zu pflegen. Offensichtlich kann dieser Prozess in vielerlei Hinsicht behandelt werden, aber ich fand sehr effiziente und einfache Überstunden, um ein Verzeichnis zu pflegen, in dem ich csv-Dateien speichere und aktualisiere. Ich habe eine csv datei pro instrument und jede datei benannt nach dem instrument es enthält. Der Grund, warum ich das tue, ist zweifach: Zuerst möchte ich keine Daten von Yahoo, Google etc8230 herunterladen, jedes Mal, wenn ich eine neue Idee testen möchte, aber noch wichtiger, sobald ich ein Problem erkannt und behoben habe, muss ich das auch nicht haben Mach das mal wieder das nächste Mal, wenn ich das gleiche Instrument brauche. Einfach und doch sehr effizient. Der Prozess ist in der folgenden Tabelle zusammengefasst. In allem, was folgt, nehme ich an, dass Daten von Yahoo kommen. Der Code muss für Daten von Google, Quandl etc8230 geändert werden. Darüber hinaus stelle ich den Prozess der Aktualisierung der täglichen Preisdaten vor. Das Setup wird für höhere Frequenzdaten und andere Arten von Datensätzen unterschiedlich sein (d. h. abweichend von den Preisen). 1 8211 Erstmaliges Herunterladen (listOfInstruments. R amp historicData. R) Die Datei listOfInstruments. R ist eine Datei, die nur die Liste aller Instrumente enthält. Wenn ein Instrument nicht Teil meiner Liste ist (d. h. keine csv-Datei in meinem Datenordner) oder wenn Sie es zum ersten Mal tun, müssen Sie den ursprünglichen historischen Datensatz herunterladen. Das Beispiel unten lädt eine Reihe von ETFs Tagespreise von Yahoo Finance zurück bis Januar 2000 und speichern Sie die Daten in einer CSV-Datei. 2 8211 Aktualisieren vorhandener Daten (updateData. R) Der untenstehende Code startet von vorhandenen Dateien im dedizierten Ordner und aktualisiert sie alle nacheinander. Ich laufe diesen Prozeß jeden Tag, außer wenn ich im Urlaub bin. Um ein neues Instrument hinzuzufügen, führen Sie einfach Schritt 1 oben für dieses Instrument allein. 3 8211 Erstellen einer Batch-Datei (updateDailyPrices. bat) Ein weiterer wichtiger Teil des Jobs ist die Erstellung einer Batch-Datei, die den Aktualisierungsprozess oben automatisiert (I8217m ein Windows-Benutzer). Dies vermeidet das Öffnen von RRStudio und führt den Code von dort aus. Der Code unten ist auf einer. bat-Datei platziert (der Pfad muss mit dem reader8217s Setup geändert werden). Beachten Sie, dass ich eine Ausgabedatei (updateLog. txt) hinzugefügt habe, um die Ausführung zu verfolgen. Der Prozess oben ist extrem einfach, weil er nur beschreibt, wie man tägliche Preisdaten aktualisiert. Ich habe das schon seit einiger Zeit benutzt und es hat mich schon sehr gut für mich gearbeitet. Für fortgeschrittenere Daten und höhere Frequenzen können die Dinge viel schwieriger werden. Wie üblich alle Kommentare begrüßen 23. März 2015, 20:55 Uhr Wenn es darum geht, ein Portfolio von Aktien zu versichern, ist ein Problem, dass es sich um eine absolute Rückkehrstrategie handelt. In der ehemaligen muss man mehr Aktien halten als in den späteren, wo überhaupt keine Aktien vorhanden sind, wenn es nicht gut genug gibt. Der Grund dafür ist der Tracking Error. Dies ist definiert als die Standardabweichung der Portfolio-Rendite abzüglich der Benchmark-Rendite. Je weniger Bestände gegenüber einem Benchmark gehalten werden, desto höher ist der Tracking-Error (z. B. höheres Risiko). Die nachfolgende Analyse ist weitgehend durch das Buch 8220Active Portfolio Management8221 von Grinold amp Kahn inspiriert. Dies ist die Bibel für alle, die daran interessiert sind, ein Portfolio gegen einen Benchmark zu führen. Ich ermutige jeden mit einem Interesse an dem Thema, das Buch von Anfang bis Ende zu lesen. It8217s sehr gut geschrieben und legt die Grundlagen des systematischen aktiven Portfoliomanagements (ich habe keine Zugehörigkeit zum Redakteur oder den Autoren). 1 8211 Faktoranalyse Hier versuchen wir, die Bestände im Anlageuniversum so genau wie möglich auf eine Forward-Return-Basis zu richten. Viele Menschen kamen mit vielen Werkzeugen und unzählige Varianten dieser Werkzeuge wurden entwickelt, um dies zu erreichen. In diesem Beitrag konzentriere ich mich auf zwei einfache und weit verbreitete Metriken: Information Coefficient (IC) und Quantiles Return (QR). 1.1 8211 Informationskoeffizient Der Horizont für die Forward Return muss vom Analytiker und it8217s eine Funktion der Strategie8217s Umsatz und der Alpha-Zerfall definiert werden (dies wurde Gegenstand umfangreicher Forschung). Offensichtlich müssen ICs in absoluten Zahlen so hoch wie möglich sein Für den scharfen Leser, im Buch von Grinold amp Kahn, wird eine Formel verknüpft Information Ratio (IR) und IC gegeben: mit der Breite ist die Anzahl der unabhängigen Wetten (Trades). Diese Formel ist als Grundgesetz des aktiven Managements bekannt. Das Problem ist, dass oft, definieren Breite genau ist nicht so einfach wie es klingt. 1.2 8211 Quantile Rückkehr Um eine genauere Schätzung der Faktor-Vorhersagekraft zu erhalten, ist es notwendig, einen Schritt weiter zu gehen und Gruppenbestände durch Quantil von Faktorwerten zu analysieren und dann die durchschnittliche Vorwärtsrendite (oder jede andere zentrale Tendenzmetrik) von jedem zu analysieren Quantile Die Nützlichkeit dieses Werkzeuges ist einfach. Ein Faktor kann einen guten IC haben, aber seine prädiktive Kraft könnte auf eine kleine Anzahl von Aktien begrenzt sein. Das ist nicht gut, da ein Portfoliomanager innerhalb des gesamten Universums Aktien auswählen muss, um seinen Tracking-Fehler-Constraint zu erfüllen. Gute Quantile Rückkehr sind durch eine monotone Beziehung zwischen den einzelnen Quantilen und Forward Returns gekennzeichnet. Alle Bestände im SampP500 Index (zum Zeitpunkt des Schreibens). Offensichtlich gibt es eine Überlebensschifffahrt: Die Liste der Bestände im Index hat sich zwischen dem Beginn und dem Ende der Stichprobenperiode deutlich verändert, aber es ist nur für die Veranschaulichung gut genug. Der Code unten lädt einzelne Aktienkurse im SampP500 zwischen Jan 2005 und heute (es dauert eine Weile) und verwandelt die Rohpreise in den letzten 12 Monaten und im letzten Monat. Der erstere ist unser Faktor, dieser wird als Vorwärtsrückmeldung verwendet. Unten ist der Code zur Berechnung von Information Coefficient und Quantiles Return. Beachten Sie, dass ich in diesem Beispiel Quintile verwendet habe, aber jede andere Gruppierungsmethode (Terciles, Deciles etc8230) verwendet werden kann. Es hängt wirklich von der Stichprobengröße ab, was Sie erfassen möchten und ob Sie einen breiten Überblick haben oder sich auf Vertriebsschwänze konzentrieren möchten. Für die Schätzung der Renditen innerhalb jedes Quintils wurde Median als zentraler Tendenzschätzer verwendet. Diese Maßnahme ist viel weniger empfindlich gegenüber Ausreißern als arithmetisches Mittel. Und schließlich der Code, um die Quantiles Return Chart zu produzieren. 3 8211 Wie man die oben genannten Informationen ausnutzt In der Grafik oben Q1 ist die letzte nach 12 Monaten Rückkehr und Q5 am höchsten. Es gibt eine fast monotone Zunahme der Quantile Rückkehr zwischen Q1 und Q5, die deutlich zeigt, dass Aktien, die in Q5 fallen, übertreffen diejenigen, die in Q1 um etwa 1 pro Monat fallen. Dies ist sehr wichtig und mächtig für solch einen einfachen Faktor (nicht wirklich eine Überraschung though8230). Daher gibt es größere Chancen, den Index zu übertreffen, indem sie die Bestände, die in Q5 fallen, überlagern und die im Vergleich zum Benchmark in Q1 fallenden Personen untergewichten. Ein IC von 0,0206 könnte nicht viel in sich selbst bedeuten, aber es8217s signifikant von 0 und zeigt eine gute prädiktive Macht der letzten 12 Monate Rückkehr insgesamt. Formale Signifikanztests können ausgewertet werden, aber das geht über den Rahmen dieses Artikels hinaus. 4 8211 Praktische Einschränkungen Das obige Rahmenwerk eignet sich hervorragend für die Bewertung von Investitionen Faktor8217s Qualität jedoch gibt es eine Reihe von praktischen Einschränkungen, die für die Umsetzung des realen Lebens angegangen werden müssen: Rebalancing. In der obigen Beschreibung hat it8217s davon ausgegangen, dass das Portfolio am Ende eines jeden Monats vollständig ausgeglichen wird. Dies bedeutet, dass alle Aktien, die in Q1 fallen, untergewichtet sind und alle Aktien, die in Q5 fallen, im Vergleich zur Benchmark übergewichtet sind. Dies ist aus praktischen Gründen nicht immer möglich: manche Bestände könnten aus dem Anlageuniversum ausgeschlossen werden, es bestehen Einschränkungen für die Industrie oder das Sektorgewicht, es bestehen Einschränkungen für den Umsatz usw8230 Transaktionskosten. Dies ist bei der obigen Analyse nicht berücksichtigt worden. Dies ist eine ernsthafte Bremse für die Umsetzung des realen Lebens. Umsatzüberlegungen werden in der Regel im realen Leben in Form einer Strafe auf Faktorqualität umgesetzt. Übertragungskoeffizient Dies ist eine Erweiterung des Grundgesetzes des aktiven Managements und es entspannt die Annahme von Grinold8217s Modell, dass Manager keine Einschränkungen, die sie von der Übersetzung ihrer Investitionen Einblicke direkt in Portfolio-Wetten auszuschließen. Und schließlich, ich bin begeistert von dem, was in weniger als 80 Zeilen Code mit R8230 erreicht werden kann. Wie üblich alle Kommentare willkommen 14. März 2014, 13:07 Die Frage sollte man sich immer fragen, wenn man technische Indikatoren verwendet, was wäre ein Ziel Kriterien, um Indikatorparameter auszuwählen (zB warum mit 14 Tagen RSI anstatt 15 oder 20 Tage). Genetische Algorithmen (GA) sind gut geeignet Werkzeuge, um diese Frage zu beantworten. In diesem Beitrag I8217ll zeigen Sie, wie Sie das Problem in R einrichten. Bevor ich die übliche Erinnerung vorangehe: Was ich in diesem Beitrag präsentiere, ist nur ein Spielzeugbeispiel und keine Einladung zu investieren. Es ist auch keine fertige Strategie, sondern eine Forschungsidee, die weiter erforscht, entwickelt und auf individuelle Bedürfnisse zugeschnitten werden muss. Was sind genetische Algorithmen Die beste Beschreibung von GA, auf die ich stieß, kommt von Cybernatic Trading ein Buch von Murray A. Ruggiero. 8220Genetische Algorithmen wurden von John Holland Mitte 1970 erfunden, um harte Optimierungsprobleme zu lösen. Diese Methode verwendet natürliche Auswahl, Überleben der fittest8221. Der allgemeine Prozess folgt den folgenden Schritten: Kodieren Sie das Problem in Chromosomen Verwenden Sie die Codierung, entwickeln Sie eine Fitness-Funktion für die Verwendung bei der Bewertung jedes Chromosomen8217s Wert bei der Lösung eines gegebenen Problems Initialisieren Sie eine Population von Chromosomen Auswerten jedes Chromosom in der Bevölkerung Erstellen Sie neue Chromosomen durch Paarung von zwei Chromosomen Dies geschieht durch Muting und Rekombination von zwei Eltern, um zwei Kinder zu bilden (Eltern werden zufällig ausgewählt, aber durch ihre Fitness vorgespannt) Bewerten Sie das neue Chromosom Löschen Sie ein Mitglied der Bevölkerung, das weniger fit ist als das neue Chromosom und legen Sie das neue Chromosom in die Bevölkerung ein . Wenn die Stop-Kriterien erreicht sind (maximale Anzahl von Generationen, Fitness-Kriterien ist gut genug8230) dann wieder das beste Chromosom alternativ gehen Sie zu Schritt 4 Aus einer Handelsperspektive GA sind sehr nützlich, weil sie gut im Umgang mit hoch nichtlinearen Problemen sind. Allerdings zeigen sie einige böse Features, die erwähnenswert sind: Über Montage: Dies ist das Hauptproblem und it8217s hinunter zum Analytiker, um das Problem in einer Weise einzurichten, die dieses Risiko minimiert. Rechenzeit. Wenn das Problem nicht richtig definiert ist, kann es extrem lang sein, eine anständige Lösung zu erreichen, und die Komplexität steigt exponentiell mit der Anzahl der Variablen an. Daher die Notwendigkeit, die Parameter sorgfältig auszuwählen. Es gibt mehrere R-Pakete, die sich mit GA beschäftigen, ich entschied mich für die häufigsten: rgenoud Tägliche Schlusskurse für die meisten flüssigen ETFs von Yahoo Finanzen gehen zurück bis Januar 2000. Die in der Probe Zeitraum geht von Januar 2000 bis Dezember 2010. Die Out of sample period starts on January 2011. The logic is as following: the fitness function is optimised over the in sample period to obtain a set of optimal parameters for the selected technical indicators. The performance of those indicators is then evaluated in the out of sample period. But before doing so the technical indicators have to be selected. The equity market exhibits two main characteristics that are familiar to anyone with some trading experience. Long term momentum and short term reversal. Those features can be translated in term of technical indicators by: moving averages cross over and RSI. This represents a set of 4 parameters: Look-back periods for long and short term moving averages, look-back period for RSI and RSI threshold. The sets of parameters are the chromosomes . The other key element is the fitness function . We might want to use something like: maximum return or Sharpe ratio or minimum average Drawdown. In what follows, I chose to maximise the Sharpe ratio. The R implementation is a set of 3 functions: fitnessFunction . defines the fitness function (e. g. maximum Sharpe ratio) to be used within the GA engine tradingStatistics . summary of trading statistics for the in and out of sample periods for comparison purposes genoud . the GA engine from the rgenoud package The genoud function is rather complex but I8217m not going to explain what each parameter means as I want to keep this post short (and the documentation is really good). In the table below I present for each instrument the optimal parameters (RSI look-back period, RSI threshold, Short Term Moving Average, and Long Term Moving Average) along with the in and out of sample trading statistics. Before commenting the above results, I want to explain a few important points. To match the logic defined above, I bounded the parameters to make sure the look-back period for the long term moving average is always longer that the shorter moving average. I also constrained the optimiser to choose only the solutions with more than 50 trades in the in sample period (e. g, statistical significance). Overall the out of sample results are far from impressive. The returns are low even if the number of trades is small to make the outcome really significant. However there8217s a significant loss of efficiency between in and out of sample period for Japan (EWJ) which very likely means over fitting. This post is intended to give the reader the tools to properly use GA in a quantitative trading framework. Once again, It8217s just an example that needs to be further refined. A few potential improvement to explore would be: fitness function . maximising the Sharpe ratio is very simplistic. A 8220smarter8221 function would certainly improve the out of sample trading statistics pattern . we try to capture a very straightforward pattern. A more in depth pattern research is definitely needed. optimisation . there are many ways to improve the way the optimisation is conducted. This would improve both the computation speed and the rationality of the results. The code used in this post is available on a Gist repository . As usual any comments welcome February 28, 2014, 3:52 pm There is an enormous body of literature both academic and empirical about market forecasting. Most of the time it mixes two market features: Magnitude and Direction. In this article I want to focus on identifying the market direction only. The goal I set myself, is to identify market conditions when the odds are significantly biased toward an up or a down market. This post gives an example of how CART (Classification And Regression Trees) can be used in this context. Before I proceed the usual reminder: What I present in this post is just a toy example and not an invitation to invest. Its not a finished strategy either but a research idea that needs to be further researched, developed and tailored to individual needs. 1 8211 What is CART and why using it From statistics, CART are a set of techniques for classification and prediction. The technique is aimed at producing rules that predict the value of an outcome (target) variable from known values of predictor (explanatory) variables. There are many different implementations but they are all sharing a general characteristic and thats what Im interested in. From Wikipedia, Algorithms for constructing decision trees usually work top-down, by choosing a variable at each step that best splits the set of items. Different algorithms use different metrics for measuring 8220best8221. These generally measure the homogeneity of the target variable within the subsets. These metrics are applied to each candidate subset, and the resulting values are combined (e. g. averaged) to provide a measure of the quality of the split. CART methodology exhibits some characteristics that are very well suited for market analysis: Non parametric . CART can handle any type of statistical distributions Non linear . CART can handle a large spectrum of dependency between variables (e. g. not limited to linear relationships) Robust to outliers There are various R packages dealing with Recursive Partitioning, I use here rpart for trees estimation and rpart. plot for trees drawing. 2 8211 Data amp Experiment Design Daily OHLC prices for most liquid ETFs from January 2000 to December 2013 extracted from Google finance. The in sample period goes from January 2000 to December 2010 the rest of the dataset is the out of sample period. Before running any type of analysis the dataset has to be prepared for the task. The target variable is the ETF weekly forward return defined as a two states of the world outcome (UP or DOWN). If weekly forward return gt 0 then the market in the UP state, DOWN state otherwise The explanatory variables are a set of technical indicators derived from the initial daily OHLC dataset. Each indicator represents a well-documented market behavior. In order to reduce the noise in the data and to try to identify robust relationships, each independent variable is considered to have a binary outcome. Volatility (VAR1) . High volatility is usually associated with a down market and low volatility with an up market. Volatility is defined as the 20 days raw ATR (Average True Range) spread to its moving average (MA). If raw ATR gt MA then VAR1 1, else VAR1 -1. Short term momentum (VAR2) . The equity market exhibits short term momentum behavior captured here by a 5 days simple moving averages (SMA). If Price gt SMA then VAR2 1 else VAR2 -1 Long term momentum (VAR3) . The equity market exhibits long term momentum behavior captured here by a 50 days simple moving averages (LMA). If Price gt LMA then VAR3 1 else VAR3 -1 Short term reversal (VAR4) . This is captured by the CRTDR which stands for Close Relative To Daily Range and calculated as following: . If CRTDR gt 0.5, then VAR4 1 else VAR4 -1 Autocorrelation regime (VAR5) . The equity market tends to go through periods of negative and positive autocorrelation regimes. If returns autocorrelation over the last 5 days gt 0 then VAR5 1 else VAR5 -1 I put below a tree example with some explanations In the tree above, the path to reach node 4 is: VAR3 gt0 (Long Term Momentum gt 0) and VAR4 gt 0 (CRTDR gt 0). The red rectangle indicates this is a DOWN leaf (e. g. terminal node) with a probability of 58 (1 8211 0.42). In market terms this means that if Long Term Momentum is Up and CRTDR is gt 0.5 then the probability of a positive return next week is 42 based on the in sample sample data. 18 indicates the proportion of the data set that falls into that terminal node (e. g. leaf). There are many ways to use the above approach, I chose to estimate and combine all possible trees. From the in sample data, I collect all leaves from all possible trees and I gather them into a matrix. This is the 8220rules matrix8221 giving the probability of next week beeing UP or DOWN. I apply the rules in the above matrix to the out of sample data (Jan 2011 8211 Dec 2013) and I compare the results to the real outcome. The problem with this approach is that a single point (week) can fall into several rules and even belong to UP and DOWN rules simultaneously. Therefore I apply a voting scheme . For a given week I sum up all the rules that apply to that week giving a 1 for an UP rule and -1 for a DOWN rule. If the sum is greater than 0 the week is classified as UP, if the sum is negative it8217s a DOWN week and if the sum is equal to 0 there will be no position taken that week (return 0) The above methodology is applied to a set of very liquid ETFs. I plot below the out of sample equity curves along with the buy and hold strategy over the same period. Initial results seem encouraging even if the quality of the outcome varies greatly by instrument. However there is a huge room for improvement. I put below some directions for further analysis Path optimality . The algorithm used here for defining the trees is optimal at each split but it doesn8217t guarantee the optimality of the path. Adding a metric to measure the optimality of the path would certainly improve the above results. Other variables . I chose the explanatory variables solely based on experience. It8217s very likely that this choice is neither good nor optimal. Backtest methodology . I used a simple In and Out of sample methodology. In a more formal backtest I would rather use a rolling or expanding window of in and out sample sub-periods (e. g. walk forward analysis) As usual, any comments welcomeCategory Archives: Trading Strategies Looks can be deceiving, a wise person once said. The phrase holds true for Algorithmic Trading Strategies. The term Algorithmic trading strategies might sound very fancy or too complicated. However, the concept is very simple to understand, once the basics are clear. In this article, I will be telling you about algorithmic trading strategies with some interesting examples. If you look at it from the outside, an algorithm is just a set of instructions or rules. These set of rules are then used on a stock exchange to automate the execution of orders without human intervention. This concept is called Algorithmic Trading. Let me start with a very simple trading strategy. Those who are already into trading would know about S. M.A and for those who dont S. M.A is Simple Moving Average. S. M.A can be calculated using any predefined and fixed number of days. An algorithmic trading strategy based on S. M.A can be simplified in these four simple steps: Calculate 5 day SMA Calculate 20 day SMA Take a long position when the 5 day SMA is larger than or equal to 20 day SMA Take a short position when the 5 day SMA is smaller than 20 day SMA We refer to this algorithmic trading strategy as Moving Average Crossover Strategy . This was just a simple example. Now don8217t get down to thinking that it is all going to be a bed of roses. Even if it were, then be prepared for the thorns. In everyday trading, far more complex trading algorithms are used to generate algorithmic trading strategies. Algorithmic Trading Strategies All the algorithmic trading strategies that are being used today can be classified broadly into the following categories: MomentumTrend Following Arbitrage Statistical Arbitrage Market Making Let me go into some detail. Momentum based Strategies Assuming that there is a particular trend in the market. As an algo trader, you are following that trend. Further to our assumption, the markets fall within the week. Now, you can use stats to determine if this trend is going to continue. Or if it will change in the coming weeks. Accordingly, you will make your next move. You have based your algorithmic trading strategy on the market trends which you determined by using statistics. This method of following trends is called Momentum Based Strategy. There are numerous ways to implement this algorithmic trading strategy and I have discussed this in detail in one of our previous articles called Methodology of Quantifying News for Automated Trading If we assume that a pharma-corp is to be bought by another company, then the stock price of our corp could go up. This is triggered by the acquisition which is a corporate event. If you are planning to invest based on the pricing inefficiencies that may happen during a corporate event (before or after), then you are using an event-driven strategy. Bankruptcy, acquisition, merger, spin-offs etc could be the event that drives such kind of an investment strategy. These strategies can be market neutral and used by hedge fund and proprietary traders widely. Statistical Arbitrage When an arbitrage opportunity arises because of misquoting in prices, it can be very advantageous to algo trading strategy. Although such opportunities exist for a very short duration as the prices in the market get adjusted quickly. And thats why this is the best use of algorithmic trading strategies, as an automated machine can track such changes instantly. For instance, if Apple8217s price falls under 1 then Microsoft will fall by 0.5 but Microsoft has not fallen, so you will go and sell Microsoft to make a profit. You can read about the common misconceptions people have about Statistical Arbitrage here . Market Making To understand Market making, let me first talk about Market Makers. According to Wikipedia: A market maker or liquidity provider is a company, or an individual, that quotes both a buy and a sell price in a financial instrument or commodity held in inventory, hoping to make a profit on the bid-offer spread, or turn. Market making provides liquidity to securities which are not frequently traded on the stock exchange. The market maker can enhance the demand-supply equation of securities. Let me give you an example: Lets assume you have Martin, a market maker, who buys for Rs. 500 from the market and sell it at 505. He will give you a bid-ask quote of Rs. 505-500. The profit of Rs. 5 cannot be sold or exchanged for cash without substantial loss in value. When Martin takes a higher risk then the profit is also higher. I found Michael Lewis book Flash Boys in Indian Bull Market pretty interesting and it talks about liquidity, market making and HFT in great detail. Check it out after you finish reading this article. Since you will need to be analytical amp quantitative while getting into or upgrading to algorithmic trading it is imperative to learn programming (some if not all) and build foolproof systems and execute right algorithmic trading strategy . Reading this article on Automated Trading with Interactive Brokers using Python will be very beneficial for you. You can read the article here . Paradigms amp Modeling Ideas Now that I have introduced you to algorithmic trading strategies, I will be throwing some light on the strategy paradigms and modeling ideas pertaining to each strategy. Market Making Statistical Arbitrage Momentum Machine Learning Based Market Making As I had mentioned earlier, the primary objective of Market making is to infuse liquidity in securities that are not traded on stock exchanges. In order to measure the liquidity, we take the bid-ask spread and trading volumes into consideration. The trading algorithms tend to profit from the bid-ask spread. I will be referring to our buddy, Martin, again in this section. Martin being a market maker is a liquidity provider who can quote on both buy and sell side in a financial instrument hoping to profit from the bid-offer spread. Martin will accept the risk of holding the securities for which he has quoted the price for and once the order is received, he will often immediately sell from his own inventory. He might seek an offsetting offer in seconds and vice versa. When it comes to illiquid securities, the spreads are usually higher and so are the profits. Martin will take a higher risk in this case. Several segments in the market lack investor interest due to lack of liquidity as they are unable to gain exit from several small - and mid-cap stocks at any given point in time. Market Makers like Martin are helpful as they are always ready to buy and sell at the price quoted by them. In fact, much of high frequency trading (HFT) is passive market making. The strategies are present on both sides of the market (often simultaneously) competing with each other to provide liquidity to those who need. So, when is this strategy most profitable This strategy is profitable as long as the model accurately predicts the future price variations. Modeling ideas based on this Paradigm The bid-ask spread and trade volume can be modeled together to get the liquidity cost curve which is the fee paid by the liquidity taker. If the liquidity taker only executes orders at the best bid and ask, the fee will be equal to the bid ask spread times the volume. When the traders go beyond best bid and ask taking more volume, the fee becomes a function of the volume as well. Trade volume is difficult to model as it depends on the liquidity takers execution strategy. The objective should be to find a model for trade volumes that is consistent with price dynamics. Market making models are usually based on one of the two: The first focuses on inventory risk. The model is based on preferred inventory position and prices based on the risk appetite. The second is based on adverse selection which distinguishes between informed and noise trades. Noise trades do not possess any view on the market whereas informed trades do. When the view of the liquidity taker is short term, its aim is to make short term profit utilizing the statistical edge. In the case of long term view, the objective is to minimize the transaction cost. The long-term strategies and liquidity constraints can be modeled as noise around the short-term execution strategies. To know more about Market Makers, you can check out this interesting article on QuantInstis blog. Statistical Arbitrage If Market making is the strategy that makes use of the bid-ask spread, Statistical Arbitrage seeks to profit from statistical mispricing of one or more assets based on the expected value of these assets. A more academic way to explain statistical arbitrage is to spread the risk among thousand to million trades in a very short holding time to, expecting to gain profit from the law of large numbers. Statistical Arbitrage Algorithms are based on mean reversion hypothesis, mostly as a pair. Pairs trading is one of the several strategies collectively referred to as Statistical Arbitrage Strategies. In pairs trade strategy, stocks that exhibit historical co-movement in prices are paired using fundamental or market-based similarities. The strategy builds upon the notion that the relative prices in a market are in equilibrium, and that deviations from this equilibrium eventually will be corrected. When one stock outperforms the other, the outperformer is sold short and the other stock is bought long with the expectation that the short term diversion will end in convergence. This often hedges market risk from adverse market movements i. e. makes the strategy beta neutral. However, the total market risk of a position depends on the amount of capital invested in each stock and the sensitivity of stocks to such risk. Momentum Strategies seek to profit from the continuance of existing trend by taking advantage of market swings. In simple words, buy high and sell higher and vice versa. And how do we achieve this In this particular algo-trading strategy we will take short-term positions in stocks that are going up or down until they show signs of reversal. It is counter-intuitive to almost all other well-known strategies. Value investing is generally based on long-term reversion to mean whereas momentum investing is based on the gap in time before mean reversion occurs. Momentum is chasing performance, but in a systematic way taking advantage of other performance chasers who are making emotional decisions. There are usually two explanations given for any strategy that has been proven to work historically, either the strategy is compensated for the extra risk that it takes or there are behavioral factors due to which premium exists. There is a long list of behavioral biases and emotional mistakes that investors exhibit due to which momentum works. However, this is easier said than done as trends dont last forever and can exhibit swift reversals when they peak and come to an end. Momentum trading carries a higher degree of volatility than most other strategies and tries to capitalize on the market volatility. It is important to time the buys and sells correctly to avoid losses by using proper risk management techniques and stop losses. Momentum investing requires proper monitoring and appropriate diversification to safeguard against such severe crashes. Firstly, you should know how to detect Price momentum or the trends. As you are already into trading, you know that trends can be detected by following stocks and ETFs that have been continuously going up for days, weeks or even several months in a row. For instance, identify the stocks trading within 10 of their 52 weeks high or look at the percentage price change over the last 12 or 24 weeks. Similarly to spot a shorter trend, include a shorter term price change. If you remember, back in 2008, the oil and energy sector was continuously ranked as one of the top sectors even while it was collapsing. We can also look at earnings to understand the movements in stock prices. Strategies based on either past returns (price momentum strategies) or on earnings surprise (known as earnings momentum strategies) exploit market under-reaction to different pieces of information. An earnings momentum strategy may profit from the under-reaction to information related to short-term earnings. Similarly, a price momentum strategy may profit from markets slow response to a broader set of information including longer-term profitability. Machine Learning based In Machine Learning based trading, algorithms are used to predict the range for very short term price movements at a certain confidence interval. The advantage of using Artificial Intelligence (AI) is that humans develop the initial software and the AI itself develops the model and improves it over time. A large number of funds rely on computer models built by data scientists and quants but theyre usually static, i. e. they dont change with the market. ML based models on the other hand can analyze large amounts of data at high speed and improve themselves through such analysis. A form of machine leaning called Bayesian networks can be used to predict market trends while utilizing a couple of machines. An AI which includes techniques such as evolutionary computation (which is inspired by genetics) and deep learning might run across hundreds or even thousands of machines. It can create a large and random collection of digital stock traders and test their performance on historical data. It then picks the best performers and uses their stylepatterns to create a new of evolved traders. This process repeats multiple times and a digital trader that can fully operate on its own is created. This process repeats multiple times and a digital trader that can fully operate on its own is created. This process repeats multiple times and a digital trader that can fully operate on its own is created. These were some important strategy paradigms and modelling ideas. Next, we will go through the step by step procedure to build a trading strategy. You can learn these Paradigms in great detail in QuantInstis Executive Programme in Algorithmic Trading (EPAT) . one of the most extensive algorithmic trading courses available online with lecture recordings and lifetime access and support. Building an algorithmic trading strategy From algo trading strategies to paradigms and modeling ideas, I come to that section of the article where I will tell you how to build a basic algorithmic trading strategy. How do you start with the implementation of algo trading strategies That is the first question that must have come to your mind, I presume. The point is that you have already started by knowing the basics and paradigms of algorithmic trading strategies while reading this article. Now, that our bandwagon has its engine turned on, it is time to press on the accelerator. And how exactly is this done I will explain how an algorithmic trading strategy is built, step by step. The concise description will give you an idea about the entire process. The first step is to decide the strategy paradigm. It can be Market Making, Arbitrage based, Alpha generating, Hedging or Execution based strategy. For this particular instance, I will choose pair trading which is a statistical arbitrage strategy that is market neutral (Beta neutral) and generates alpha, i. e.makes money irrespective of market movement. You can decide on the actual securities you want to trade based on market view or through visual correlation (in the case of pair trading strategy). Establish if the strategy is statistically significant for the selected securities. For instance, in the case of pair trading, check for co-integration of the selected pairs. Now, code the logic based on which you want to generate buysell signals in your strategy. For pair trading check for mean reversion calculate the z-score for the spread of the pair and generate buysell signals when you expect it to revert to mean. Decide on the Stop Loss and Profit Taking conditions. Stop Loss 8211 A stop-loss order limits an investors loss on a position in a security. It fires an order to square off the existing long or short position to avoid further losses and helps to take emotion out of trading decisions. Take Profit 8211 take-profit orders are used to automatically close out existing positions in order to lock in profits when there is a move in a favorable direction. Quoting or Hitting strategy It is very important to decide if the strategy will be quoting or hitting. Execution strategy to a great extent decides how aggressive or passive your strategy is going to be. Quoting 8211 In pair trading you quote for one security and depending on if that position gets filled or not you send out the order for the other. In this case, the probability of getting a fill is lesser but you save bid-ask on one side. Hitting - In this case, you send out simultaneous market orders for both securities. The probability of getting a fill is higher but at the same time slippage is more and you pay bid-ask on both sides. The choice between the probability of fill and Optimized execution in terms of slippage and timed executive is what this is if I have to put it that way. If you choose to quote, then you need to decide what are quoting for, this is how pair trading works. If you decide to quote for the less liquid security, slippage will be less but the trading volumes will come down liquid securities on the other hand increase the risk of slippage but trading volumes will be high. Using stats to check causality is another way of arriving at a decision, i. e. change in which security causes change in the other and which one leads. The causality test will determine the lead-lag pair quote for the leading and cover the lagging security. How do you decide if the strategy you chose was good or bad How do you judge your hypothesis This is where back-testing the strategy comes as an essential tool for estimation of the performance of the designed hypothesis based on historical data. A strategy can be considered to be good if the backtest results and performance statistics back the hypothesis. Hence, it is important to choose historical data with a sufficient number of data points. This is to create a sufficient number of sample trades (at least 100 trades) covering various market scenarios (bullish, bearish etc.). Ensure that you make provision for brokerage and slippage costs as well. This will get you more realistic results but you might still have to make some approximations while backtesting. For instance, while backtesting quoting strategies it is difficult to figure out when you get a fill. So, the common practice is to assume that the positions get filled with the last traded price. What kind of tools should you go for, while backtesting Since backtesting for algorithmic trading strategies involves a huge amount of data, especially if you are going to use tick by tick data. So, you should go for tools which can handle such mammoth load of data. R or MATLAB R is excellent for dealing with huge amounts of data and has a high computation power as well. Thus, making it one of the better tools for backtesting. Also, R is open source and free of cost. We can use MATLAB as well but it comes with a licensing cost. With great strategy, comes greater scrutiny, A Great Thinker once quoted. Fine, I just ripped off Ben Parkers famous quotation from the Spiderman movie (not the Amazing one). But trust me, it is 100 true. No matter how confident you seem with your strategy or how successful it might turn out previously, you must go down and evaluate each and everything in detail. There are several parameters that you would need to monitor when analyzing a strategys performance and risk. Some important metricsratios are mentioned below: Total Returns (CAGR)- Compound Annual Growth Rate (CAGR). It is the mean annual growth rate of an investment over a specified period of time longer than one year. Hit Ratio - Order to trade ratio. Average Profit per Trade - Total profit divided by the total number of trades Average Loss per trade - Total loss divided by the total number of trades Maximum Drawdown 8211 Maximum loss in any trade Volatility of Returns - Standard deviation of the returns Sharpe Ratio - Risk adjusted returns, i. e. excess returns (over risk free rate) per unit volatility or total risk. The entire process of Algorithmic trading strategies does not end here. What I have provided in this article is just the foot of an endless Everest. In order to conquer this, you must be equipped with the right knowledge and mentored by the right guide . Thats where QuantInsti comes in, to guide you through this journey. QuantInsti will help you conquer the Everest at the end. If you want to know more about algorithmic trading strategies then you can click here . This article is the final project submitted by the author as a part of his coursework in Executive Programme in Algorithmic Trading (EPAT) at QuantInsti. Do check our Projects page and have a look at what our students are building. Marco has spent his career as a trader and portfolio manager, with a particular focus in equity and derivatives markets. He specializes in quantitative finance and algorithmic trading and currently serves as head of the Quantitative Trading Desk and Vice-president of Argentina Valores S. A. Marco is also Co-Founder and CEO of Quanticko Trading SA, a firm devoted to the development of high frequency trading strategies and trading software. Marco holds a BS in Economics and an MSc in Finance from the University of San Andrs. Introduction One of my favorite classes during EPAT was the one on statistical arbitrage. so the pair trading strategy seemed a nice idea for me. My strategy triggers new orders when the pair ratio of the prices of the stocks diverge from the mean. But in order to work, we first have to test for the pair to be cointegrated. If the pair ratio is cointegrated, the ratio is mean-reverting and the greater the dispersion from its mean, the higher the probability of a reversal, which makes the trade more attractive. I chose the following pair of stocks: The idea is the following: If we find two stocks that are correlated (they correspond to the same sector), and the pair ratio diverges from a certain threshold, we short the stock that is expensive and buy the one that is cheap. Once they converge to the mean, we close the positions and profit from the reversal. In this post we see how to compute historical volatility in python, and the different measures of risk-adjusted return based on it. We have also provided the python codes for these measures which might be of help to the readers. Introduction Volatility measures the dispersion of returns for a given security. Volatility can be measured by the standard deviation of returns for a security over a chosen period of time. Historic volatility is derived from time series of past price data, whereas, an implied volatility is derived using the market price of a traded derivative instrument like an options contract. Sentiment Analysis. also known as opinion mining, is the process of computationally identifying and categorizing opinions expressed in a piece of text, especially in order to determine whether the writers attitude towards a particular topic, product, etc. is positive, negative, or neutral. The analysis finds significant prominence in social media, stock markets, law, policy making, sociology and even customer service. Machines are faster at responding to events than humans and can process much vaster amount of information without any fatigue. In more volatile markets, people tend to react less strongly to positive news and react more strongly to negative news. Of course, there are situations where sentiment analysis, or sometimes also called News Analytics, works well for a position, while in other cases it fails. The following slide show is a summary of favourable and profitable outcomes of sentiment analysis in trading. Next Steps: Now that you have understood a little about how sentiment analysis works, you would also want to know the pitfalls. For this and other such questions, we have an upcoming webinar on 8220Quantitative Strategies using Sentiment Analysis8221 by Rajib Ranjan Borah. The webinar will give a brief overview of how sentiment analysis works and some historical perspective along with suggestions on how to develop trading strategies. Register for the webinar on this link. Python has emerged as one of the most popular language to code in Algorithmic Trading, owing to its ease of installation, free usage, easy structure, and availability of variety of modules. Globally, Algo Traders and researchers in Quant are extensively using Python for prototyping, backtesting, building their proprietary risk and order management system as well as in optimisation of testing modules. This blog post highlights some of the key steps involved in Algorithmic Trading using Python as the programming language. The screenshots are taken from the webinar of Dr. Yves Hilpisch. in collaboration with QuantInsti. Dr. Hilpisch is world-renowned authority in the world of Python and is the founder of Python Quants GmbH, with several books on the subject under his belt. He also serves as a faculty at QuantInsti, one of Asias pioneer education training firm in Algorithmic Trading. All examples shown are based on the platform and API of oanda. Background information about Python and the libraries used can be found in the OReilly book Hilpisch, Yves (2014): Python for Finance Analyze Big Financial Data. The post is divided in two parts. The current post highlights the basics of connecting with the Oanda platform using python and backtesting the trading strategies. The next post will cover working with streaming data as well as automated trading in real-time. High Frequency Trading (HFT) involves the concept of 8220Order Types8221, which signals a trader to enter or exit a position. According to Reuters, Order types can reach an estimated 2,000 variations as a fully electronic market and more than 50 trading venues have multiplied the possibilities of how, when and with whom to trade. Clearly, the rules of the game are redefined by the Order Types and their correct implementation in the marketplace. Amidst a long list, we touch upon some of the popular ones, frequently used by HFT practitioners. The following Infographic shows 4 HFT Order Types, and examples when a buy or sell order is placed. Introduction Traders in the derivative market often exercise one of the following: Call option or Put Option . Call option is a financial contract between a buyer and seller, whereby the buyer has the right, but not the obligation, to buy an agreed quantity of a financial instrument from the seller of the option at a certain time for a certain price (the strike price). The Put Option serves the opposite. In a Covered Call , the seller of the call options owns the corresponding amount of the underlying instrument. A Covered Call is an income generating option strategy which involves two legs: Buying a stock Selling an Out of the money (OTM) call option If the call is sold simultaneously along with the stock purchase, the strategy is referred to as a buy-write strategy. In a Covered Call, the trader holds a neutral to a bullish outlook. Covered Call is a net debit transaction because you pay for the stock and receive a small premium for the call option sold. The idea of this blog post is to elaborate on the covered call strategy by an example and to plot its payoff using Python. The post also highlights 8220Calendar Call8221 as it is a modification of the Covered Call strategy. To measure the performance of a trading strategy, annualized returns are often a common metric. However comparing two strategies based on annualised returns may not always be a logical way due to several reasons. Some strategies might be directional, some market neutral and some might be leveraged which makes annualized return alone a futile measure of performance measurement. Also, even if two strategies have comparable annual returns, the risk is still an important aspect that needs to be measured. A strategy with high annual returns is not necessarily very attractive if it has a high-risk component we generally prefer better risk-adjusted returns over just better returns. Sharpe Ratio takes care of risk assessment and the problem related to the comparison of strategies. Sharpe ratio is a measure for calculating the risk-adjusted return. It is the ratio of the excess expected return of an investment (over risk-free rate) per unit of volatility or standard deviation. (morehellip)

Comments

Popular Posts