Trading mit Bollinger Bands R. Die Bollinger Bands werden Klammer Preis Aktion In Zeiten der hohen Volatilität, sie erweitern, während in Zeiten der geringen Volatilität, sie bewegen sich näher zusammen Also grundsätzlich passen sie auf die Bewegung und Volatilität des Marktes Diese zusätzliche Volatilität Filter Ist der wirkliche Wert dieses Werkzeugs. Es gibt zwei Bedingungen, die wir in einer Handelsmöglichkeit suchen Wir wollen einen Pullback kaufen, um zu unterstützen, wenn der Markt in einem Aufwärtstrend ist oder eine Rallye bis zum Widerstand verkaufen, wenn der Markt in einem Abwärtstrend ist Bollinger Bands bieten in der Regel gute Resistenz und Unterstützung für unsere Handels-Setup, so müssen wir nur sicherstellen, dass wir den starken Trending-Paaren folgen. Lassen Sie sich ein Beispiel auf diesem USDCHF Tages-Chart. Created von FXCM Marketscope Charts 2 0.Der Trend Ist da, wie wir eine Reihe von höheren Höhen und höheren Tiefen sehen können, was bedeutet, nach einem Dip nach unten zu suchen, um die untere Band für eine Kaufgelegenheit zu unterstützen. Ich habe zwei Beispiele, die auf dem Diagramm erwähnt wurden, das erste fand im Mai und das zweite statt Fand im Juni dieses Jahres statt Der Markt handelte an die untere Bollinger Band in jedem der in den Boxen aufgeführten Instanzen. Allerdings ist dies nicht unbedingt der Kauf selbst, sondern nur das Signal, um zu beginnen, nach einem Kauf auf einer Umkehr zu suchen. Trader werden eine Vielzahl von Methoden verwenden, um den Eintrag zu bestimmen, von der Verwendung ihrer Lieblings-Indikator, um nur zu kaufen, wie der Markt bewegt sich durch die vorherige hoch Ein beliebter Ansatz ist es, auf der ersten Kerze, die über die mittlere Linie der 20-Tage schließt zu kaufen Simple Moving Average Dies dient als weitere Bestätigung der Umkehrung und erhöht unsere Chance auf Erfolg auf dem Handel Auf der obigen Grafik wird die Kaufkerze durch einen grünen Pfeil identifiziert. Trader könnten dann ihren Schutzstopp unter den untersten Docht in die Box legen und schauen Für das Doppelte dieses Risiko im Gewinn für ein 1 2 Risiko-Belohnungsverhältnis. Ich möchte erwähnen, dass Preis-Aktion auf der USDCHF nach unten und berührte die untere Bollinger Band viermal in den letzten Tagen Dies bedeutet, dass wir s Ich würde auf der Suche nach einer anderen Kaufgelegenheit sein. Aber anstatt nur gerade zu kaufen, wäre dies die Zeit, um Ihren Ansatz zu nennen, dass Kaufeintrag, um Ihre Chance auf Erfolg auf den Handel zu erhöhen Preis hat sich verschoben, da die untere Band war Getestet letzte Woche Durch die Ausübung Geduld und Disziplin und warten auf diese erste Nähe über die 20-Tage-Simple Moving Average wäre ein Weg, um diesen Handel mit der Bollinger Band Strategie, die Sie gerade gelernt haben. Neu zum FX-Markt Sparen Sie Stunden in herauszufinden Was FOREX-Handel ist alles über. Take diese kostenlose 20 Minuten New to FX Kurs von DailyFX Education präsentiert In der Kurs werden Sie lernen, über die Grundlagen einer FOREX-Transaktion, welche Hebelwirkung ist, und wie man eine angemessene Menge an Hebelwirkung für Ihre zu bestimmen Trading. Registe r HIER, um Ihre FOREX Trading jetzt starten. DailyFX bietet Forex News und technische Analyse über die Trends, die Einfluss auf die globalen Devisenmärkte. Dieser Post wird John Ehlers s Autocorrelation P vorstellen Erodogramm-Mechanismus ein Mechanismus entworfen, um dynamisch eine Rückblick-Periode zu finden Das ist, der häufigste Parameter, der in Backtests optimiert ist, ist die Lookback-Periode. Bevor ich diesen Beitrag beginne, muss ich Kredit geben, wo es s fällig ist, zu einem Herrn Fabrizio Maccallini der Leiter der strukturierten Derivate Bei Nordea Markets in London Sie finden den Rest des Repositoriums, das er für Dr. John Ehlers s Cycle Analytics für Trader auf seinem Github gemacht hat. Ich bin dankbar und geehrt, dass solche intelligenten und erfahrenen Personen dazu beitragen, einige von Dr. Ehlers Methoden in R zu bringen. Der Punkt des Ehlers Autokorrelations-Periodogramms besteht darin, einen Zeitraum zwischen einer minimalen und einer maximalen Periodenlänge dynamisch festzulegen. Während ich die genaue Erklärung des Mechanikers auf Dr. Ehlers s Buch, für alle praktischen Absichten und Zwecke, meiner Meinung nach, die Punchline verlasse Von dieser Methode ist zu versuchen, eine massive Quelle der Überfüllung von Trading-System-Erstellung zu entfernen, nämlich die Angabe einer Rückblickperiode. SMA von 50 Tagen 100 Tage 200 Tage W Ell, dieser Algorithmus nimmt diese Möglichkeit der Überfüllung aus Ihren Händen Einfach, geben Sie eine obere und untere Schranke für Ihren Lookback, und es macht den Rest Wie gut es ist es ein Thema der Diskussion für die gut versierten in den Methoden der elektrischen Ingenieurwesen Ich bin nicht, also fühlen Sie sich frei, Kommentare zu hinterlassen, die besprechen, wie gut der Algorithmus seinen Job macht, und fühlen sich frei, über ihn auch zu bloggen. In jedem Fall ist hier der ursprüngliche Algorithmuscode, Höflichkeit von Herrn Maccallini. One Sache ich Bemerken ist, dass dieser Code eine Schleife verwendet, die für i in 1 Längenfilet sagt, was eine O-Datenpunktschleife ist, die ich als die Pest in R sehe. Während ich Rcpp vorher benutzt habe, war es für nur die einfachste von Loops, also ist dies definitiv ein Ort, an dem der Algorithmus mit Rcpp aufgrund von R s inhärenten schlechten Looping verbessert werden kann. Das Interessierte an der genauen Logik des Algorithmus wird es noch einmal in John Ehlers s Cycle Analytics For Traders finden Buch sehen Link früher in der Post. Natürlich, die erste thi Ng zu tun ist zu testen, wie gut der Algorithmus tut, was es vorbringt zu tun, was ist, um die Lookback-Periode eines Algorithmus zu diktieren. Lassen Sie es auf einige Daten laufen. Jetzt, was macht die Algorithmus-Set Lookback-Periode aussehen. Let S Zoom in 2001 bis 2003, als die Märkte durch einige Umwälzungen ging. In diesem vergrößerten Bild, können wir sehen, dass die Schätzungen des Algorithmus scheinen ziemlich jumpy. Here s einige Code, um die Algorithmen s Schätzungen von n in einen Indikator zu füttern Um einen Indikator mit einer dynamischen Lookback-Periode zu berechnen, wie sie von Ehlers s Autokorrelations-Periodogramm gesetzt wird. Und hier ist die Funktion, die mit einem SMA angewendet wird, um zwischen 120 und 252 Tagen abzustimmen. Wie man sieht, ist dieser Algorithmus weniger konsistent als ich es möchte Wenn es darum geht, einen einfachen gleitenden Durchschnitt zu verwenden. Für jetzt werde ich diesen Code hier verlassen, und lassen Sie die Leute mit ihm experimentieren Ich hoffe, dass jemand feststellen wird, dass dieser Indikator für sie hilfreich ist. Danke für das Lesen. NOTES Ich bin immer Interessiert an Networking-Treffen im Nordosten von Philadelphia N YC Darüber hinaus, wenn Sie glauben, dass Ihre Firma von meinen Fähigkeiten profitieren wird, zögern Sie bitte nicht, mich zu erreichen Mein linkedin Profil finden Sie hier. Lastly, ich bin freiwillig, um die R-Abteilung für Bücher auf Quantokratie zu kuratieren Wenn Sie ein Buch haben Über R, die für die Finanzierung gelten können, achten Sie darauf, lassen Sie mich darüber wissen, so dass ich es überprüfen kann und möglicherweise empfehlen es Thakn you. This Post wird eine eingehende Überprüfung von Alpha Architect s Quantitative Momentum Buch Insgesamt in meinem Englisch: www. goethe. de/wis/bib/thm/mop/en360869.htm Das Buch ist für diejenigen, die Praktizierende im Fondsmanagement im individuellen Eigenkapitalraum sind, und ist immer noch Ideen, die es sich lohnt, außerhalb des Raumes zu denken Top-Decile, Rang entlang der Achse Y innerhalb der oberen Dezile in X, und nehmen Sie die obere Dezile entlang der Achse Y, im Wesentlichen beschränken Auswahl auf 1 des Universums Darüber hinaus ist das Buch nicht viel zu tun, um Volatilitätskontrollen, die möglicherweise verbessert haben Das System skizzierte sehr. Bevor ich in die Hauptlast dieses Beitrags zu bekommen, ich möchte meine Leser wissen lassen, dass ich meine Nüsse und Schrauben von quantstrat Reihe von Posten als formalen Datacamp Kurs formatiert Datacamp ist ein sehr billiger Weg, um einen Haufen zu lernen Von R, und Finanzanwendungen gehören zu diesen Themen Mein Kurs deckt die Grundlagen von quantstrat ab, und wenn diejenigen, die den Kurs wie es vervollständigen, kann ich sehr gut erweiterte quantstrat Module auf datacamp Ich hoffe, dass die Finanzkurse gut aufgenommen werden , Da gibt es finanzielle Themen in RI Ich mag mich selbst lernen, dass eine 45-minütige Vorlesung nicht wirklich genügt, wie zB Dr. David Matteson s ändern Punkte Magie, PortfolioAnalytics, und so weiter In jedem Fall hier ist die Link. So, let S beginnt mit einer Zusammenfassung des Buches. Part 1 ist mehrere Kapitel, die die riesige expose sind - warum Impuls arbeitet oder zumindest seit mindestens 20 Jahren seit 1993 gearbeitet hat, nämlich dass menschliche Vorurteile und irrationale Verhaltensweisen in gewisser Weise handeln Die Anomalie Arbeit Dann gibt es auch die Karriere Risiko AKA es sa Risikofaktor, und so, wenn Ihr Benchmark ist SPY und Sie laufen über eine 3-Jahres-Zeitraum der Underperformance, haben Sie eine schwere Karriere Risiko und im Wesentlichen eine ganze Litanei, warum ein professionelles Vermögen Manager würde gefeuert werden, aber wenn Sie nur mit der Anomalie über viele viele Jahre bleiben und reiten aus mehreren Jahr Abschnitten der relativen Underperformance, werden Sie kommen auf der Vorwärts auf die sehr lange run. Generally, ich fühle mich wie es Arbeit zu tun, wenn Dies ist das Beste, was getan werden kann, aber okay, ich werde es akzeptieren. Essentiell, Teil 1 ist für die Uneingeweihten Für diejenigen, die um die Impulsblock ein paar Mal gewesen sind, können sie direkt über diese hinausgehen. Leider ist es halb so Das Buch, so dass ein wenig von einem sauren Geschmack in den Mund verlässt. Next, Teil zwei ist, wo meiner Meinung nach das echte Fleisch und Kartoffeln des Buches, wie. Essentiell, kann der Algorithmus in die folgenden gekocht werden. Verwenden Sie das Universum von großen und Mid-Cap-Aktien, machen Sie die folgenden.1 So Rt die Aktien in Dezile um 2-12 Impuls, das ist, am Ende eines jeden Monats, berechnen Impuls bis zum letzten Monat s Schlusskurs abzüglich der Schlusskurs vor 12 Monaten Im Wesentlichen sagt die Forschung, dass es eine Reversion Wirkung auf die 1-Monats-Momentum Allerdings geht dieser Effekt nicht in das ETF-Universum in meiner Erfahrung.2 Hier ist der interessante Teil, der das Buch lohnt sich auf eigene Faust auf eigene Faust nach dem Sortieren in Dezile, Rang der Top-Decile durch die folgende Metrik multiplizieren die Zeichen des 2-12 Impulses durch die folgende Gleichung negative Rückkehr positiv Im Wesentlichen ist die Idee hier, um die Glätte des Impulses zu bestimmen Das ist, in der extremsten Situation, stellen Sie sich eine Aktie, die absolut nichts für 230 Tage und dann hatte ein massives Tag, der ihm seine ganze Preisschätzung gab, glaube Google, als es einen 10 Sprung von besser als erwarteten Zahlen Berichte hatte, und im anderen Extrem ein Lager, der einfach jeden einzelnen Tag ein kleines positives war Preis-Aufwertung Offensichtlich wollen Sie die zweite Art von Lager, dass s diese Idee Wieder, in Dekaden sortieren, und nehmen Sie die Top-Decile Daher nehmen die Top-Decile der Top-Decile verlässt Sie mit 1 des Universums Im Wesentlichen macht dies die Idee Sehr schwer zu replizieren, da Sie brauchen, um ein riesiges Universum von Aktien aufzuspüren Das heißt, ich denke, der Ausdruck ist eigentlich eine ziemlich gute Idee als Stand-in für die Volatilität Das ist, egal wie flüchtig ein Vermögenswert ist, ob es s als Flüchtig wie eine Ware wie DBC oder als nicht-flüchtig wie ein Fixed-Income-Produkt wie SHY, ist dieser Ausdruck eine interessante Art zu sagen, dass dieser Weg ist choppy vs dieser Weg ist glatt Ich könnte diesen Ausdruck auf meinem Blog weiter in der Zukunft zu untersuchen .3 Schließlich, wenn das Portfolio vierteljährlich statt monatlich umdreht, sind die besten Monate, um es umzukehren, die Monate vor dem Ende des Quartalsmonats, das ist, Februar, Mai, August, November, weil ein Haufen von Amateur-Asset-Managern wie Zum Fenster dr Ihre Portfolios Das heißt, sie hatten ein verrücktes Viertel, also im letzten Monat, bevor sie vierteljährliche Aussagen aussenden müssen, laden sie auf einige jüngste Gewinner, so dass ihre Kunden nicht glauben, dass sie als Amateur sind, wie sie wirklich anlassen, Und da ist ein Stoß für dieses Ähnlich hat Januar einige verkaufende Anomalien wegen der Steuerverlust-Ernte Soweit praktische Implementierungen gehen, denke ich, dass dieses eine sehr nette Note ist, dass die Umdrehung jeden Monat ein bisschen zu teuer sein kann, ich So dass Wes und Jack sicher sagen, du willst es einmal alle drei Monate umdrehen, aber bei welchen Monaten ist es eine sehr gute Frage zu fragen, ob es bedeutet, dass du einen zusätzlichen Prozentpunkt oder 150 Bps pro Jahr davon bekommst Könnte die Transaktionskosten abdecken und dann irgendwie. Es ist ein ziemlich einfach zu verstehende Strategie Allerdings ist der Teil, der die Art von Gates aus dem Buch zu einer perfekten Replikation macht, die Schwierigkeit, die CRSP-Daten zu erhalten. Jedoch lerne ich Alpha Architekt zur Offenlegung von t Er ganzer Algorithmus von Anfang bis Ende. Darüber hinaus, wenn die grundlegende 2-12 Impuls ist nicht genug, gibt es einen Anhang detailliert andere Arten von Impuls Ideen Ergebnis Impuls, Ranking nach Entfernung zu 52-Wochen-Highs, absolute historische Impuls, und so weiter Keiner dieser Strategien ist wirklich so viel besser als die grundlegende Preisdynamikstrategie, also sind sie dort für die Interessierten, aber es scheint dort s nichts wirklich bahnbrechend dort Das heißt, wenn du einmal im Monat handelst, gibt es nur so Viele Möglichkeiten zu sagen, hey, ich denke, diese Sache geht nach oben. Ich mag auch, dass Wes und Jack auf die Tatsache, dass Trend-Follow, während es doesn t verbessern insgesamt CAGR oder Sharpe, macht eine massive Menge zu verbessern auf max Drawdown Das Ist, wenn sie mit der Aussicht, 70-80 von allem zu verlieren, und verlieren nur 30, das ist eine einfache Wahl, um Trend-Follow ist gut, sogar eine simplen Version. All in allen, ich glaube, das Buch vollbringt, was es setzt Zu tun, was eine gut recherchierte a Lgorithm Letztlich ist die Punchline auf Alpha Architect s Website Ich glaube, sie haben eine Art von monatlichen Lager Filter Darüber hinaus gibt das Buch, dass es bessere risikoadjustierte Renditen in Kombination mit dem Algorithmus in der quantitativen Wert Buch In meiner Erfahrung, ich Ich habe niemals Wert-Algorithmen beeindruckt mich in den Backtests, die ich getan habe, aber ich kann Kreide, dass bis zu mir unerfahren mit all den verschiedenen Bewertungs-Metriken. Meine Kritik an dem Buch ist jedoch das ist. Der Momentum Algorithmus in dem Buch vermisst was Ich fühle, ist eine Schlüsselkomponente Volatilität Targeting Control Einfach, die Papier-Dynamik hat seine Momente, die ich in meiner Hypothese-getriebenen Entwicklung Reihe von Posts im Wesentlichen besagt, dass die üblichen Fama-Französisch Impuls-Strategie weit besser aus einer Risiko-Belohnung-Strategie durch Deleveraging In Zeiten von übermäßiger Volatilität und Vermeidung von Impulsabstürzen Ich bin mir nicht sicher, warum Wes und Jack dieses Papier nicht anfassen, da die Umsetzung sehr einfaches Ziel ist Ealisierte Volatilität Hebel-Faktor Idealerweise habe ich lieben, wenn Wes oder Jack mir den Strom von Renditen für diese Strategie vorzugsweise täglich schicken könnte, aber monatlich auch funktioniert. Essentiell, ich glaube, dieses Buch ist sehr umfangreich Aber ich denke, es hat auch eine etwas don T Versuchen Sie dies zu Hause fühlen, um es aufgrund der Daten Anforderung, um es zu replizieren Sicherlich, wenn Ihr Broker lädt Sie 8 eine Transaktion, ist es nicht eine machbare Strategie, um mehrere tausend Dollar pro Jahr auf Transaktionskosten fallen, die nur geben Sie Ihre Rückkehr zu Ihr Broker aber ich frage mich, ob die QMOM ETF von Alpha Architect, natürlich ist in der Tat eine bessere Version dieser Strategie, außerhalb der Management-Gebühr. In jedem Fall ist meine endgültige Meinung dies, während dieses Buch ein wenig verlässt Ein bisschen Wissen auf dem Tisch, im Ganzen, es vollbringt, was es zu tun macht, ist klar mit seinen Verfahren, und bietet mehrere lohnende Ideen Für den Preis eines nicht-technischen Lehrbuch aka diese 60 Bücher auf amazon, ist dieses Buch Ein steal. Thanks für lesen Ing. NOTE Während ich derzeit in einer erfolgreichen Analytik-Kapazität beschäftigt bin, bin ich interessiert an Anhörung über Vollzeitstellen, die eng mit den Themen auf diesem Blog verwandt sind. Wenn Sie eine Vollzeit-Position haben, die von meinen aktuellen Fähigkeiten profitieren kann, bitte Lassen Sie mich wissen, dass mein Linkedin hier gefunden werden kann. Dieser Beitrag wird über das Versuchen sein, das Depmix-Paket für die Online-Vorhersage zu verwenden. Während das Depmix-Paket bewundernswert ist, wenn es darum geht, die Zustände der Vergangenheit zu beschreiben, wenn es für einen Schritt voraus ist Vorhersage, unter der Annahme, dass morgen s Zustand wird identisch mit heute s, die versteckten markov Modell Prozess innerhalb des Pakets gefunden wird nicht auf Erwartungen. So, um zu beginnen, wurde dieser Beitrag von Michael Halls-Moore, die vor kurzem gepostet wurde Einige R-Code über die Verwendung der depmixS4-Bibliothek, um versteckte markov-Modelle zu verwenden Im Allgemeinen bin ich nicht geneigt, Beiträge zu Themen zu erstellen Ich glaube, ich habe ein absolut front-to-back Verständnis von, aber ich mache dies in der Hoffnung auf Lear Ning von anderen auf, wie man passend Online-State-Space-Vorhersage oder Regime Switching-Erkennung, wie es in mehr finanzielle parlance. While ich habe die übliche Theorie der versteckten markov Modelle, die es ist, kann es regnen oder es kann sein Sonnig, aber man kann nur das Wetter beurteilen, das von den Kleidern beurteilt wird, die man Leute sieht, die sich außerhalb des Fensters befinden, wenn man aufwacht und mit Spielzeugbeispielen in MOOCs gearbeitet hat. Udacity s Selbstfahrender Auto Kurs beschäftigt sich mit ihnen, wenn ich mich richtig erinnere oder vielleicht Es war der AI-Kurs, am Ende des Tages ist die Theorie nur so gut, wie gut eine Implementierung an realen Daten arbeiten kann. Für dieses Experiment habe ich beschlossen, SPY-Daten seit Auflegung zu nehmen und einen vollen in-Probe-Backtest zu machen Auf die Daten Das ist, da der HMM-Algorithmus von depmix die ganze Geschichte der Renditen sieht, mit diesem Gott s Auge Blick auf die Daten, macht der Algorithmus korrekt klassifizieren die Regime, wenn die Backtest-Ergebnisse sind irgendwelche Anzeichen. Hier ist der Code Um dies zu tun, inspiriert von Dr. Halls-Moore sE Ssentially, während ich drei Staaten ausgewählt habe, stellte ich fest, dass irgendetwas mit einem Intercept über null ein Stierzustand ist und unter Null ein Bärenstaat ist, also im Wesentlichen, es reduziert sich auf zwei states. With das result. So, nicht besonders schrecklich Das Algorithmus funktioniert, Art von, Art von, right. Well, lassen Sie uns versuchen Online-Vorhersage now. So, was ich hier gemacht wurde, nahm ich ein erweitertes Fenster, beginnend von 500 Tagen seit SPY s Anfang, und hielt es, um einen Tag an Eine Zeit Meine Vorhersage war, trivial genug, der jüngste Tag, mit einem 1 für einen Stier-Zustand, und ein -1 für einen Bärenstaat Ich lief diesen Prozess parallel auf einem Linux-Cluster, weil Windows s doParallel Bibliothek scheint nicht Sogar wissen, dass bestimmte Pakete geladen sind, und es ist mehr chaotisch, und das erste große Problem ist, dass dieser Prozess dauerte etwa drei Stunden auf sieben Kerne für etwa 23 Jahre Daten Nicht gerade ermutigend, aber Rechenzeit ist nicht tekt in diesen Tagen. So Lassen Sie s sehen, ob dieser Prozess tatsächlich funktioniert. Erstens, lassen Sie s testen, wenn der Algorithmus doe S was es eigentlich eigentlich zu tun und verwenden Sie einen Tag der Look-Ahead Bias, die ist, sagt der Algorithmus uns den Staat am Ende des Tages, wie richtig ist es sogar für diesen Tag. Mit dem Ergebnis. So, angeblich, die Algorithmus scheint zu tun, was es entworfen wurde, um zu tun, was ist, einen Staat für einen gegebenen Datensatz zu klassifizieren Nun, die wichtigste Frage, wie gut diese Vorhersagen sogar einen Tag voraus tun Sie d denken, dass Zustand Raumvorhersagen würde sparsam von Tag sein Zu Tag, angesichts der langen Geschichte, korrekt. Mit dem Ergebnis. That ist, ohne die Lookahead Bias, ist der Zustand Raum Vorhersage Algorithmus grauenhaft Warum ist das. Well, hier ist die Handlung der Staaten. In kurz, die Online-Hmm-Algorithmus In der depmix-Paket scheint, seinen Verstand sehr leicht zu ändern, mit offensichtlichen negativen Implikationen für tatsächliche Handelsstrategien. So, dass wraps es für diesen Beitrag Im Wesentlichen ist die wichtigste Botschaft hier ist ein großer Unterschied zwischen Laden, die beschreibende Analyse AKA wo haben Du warst, warum hat es getan Geschehen vs prädiktive analyse, das ist, wenn ich die künftig richtig voraussagen werde, bekomme ich eine positive auszahlung Meiner Meinung nach, während beschreibende Statistiken ihren Zweck haben, um zu erklären, warum eine Strategie durchgeführt haben könnte, wie es war, letztlich suchen wir immer auf der Suche nach Bessere Vorhersage-Tools In diesem Fall, depmix, zumindest in dieser Out-of-the-Box-Demonstration scheint nicht das Werkzeug für das zu sein. Wenn jemand Erfolg mit der Verwendung von Depmix oder anderen Regime-Switching-Algorithmus in R für die Vorhersage hatte, Ich würde gerne die Arbeit sehen, die die Prozedur beschreibt, da es ein Bereich ist, den ich in der Lage bin, meine Toolbox zu erweitern, aber don t haben irgendwelche besonderen guten Leads Im Wesentlichen möchte ich an diesen Beitrag denken, wie ich meine eigenen Erfahrungen beschreibe Mit dem package. Thanks für reading. NOTE Am 5. Oktober werde ich in New York City sein Am 6. Oktober werde ich bei The Trading Show auf dem Programming Wars Panel präsentieren. HINWEIS Mein aktueller Analytics-Vertrag ist für die Überprüfung am Ende Des Jahres, also bin ich offiziell suchen Für andere Angebote auch Wenn Sie eine Vollzeit-Rolle haben, die von den Fähigkeiten profitieren kann, die Sie auf meinem Blog sehen, treten Sie bitte in Verbindung mit mir Mein linkedin Profil kann hier gefunden werden. Dieser Pfosten stellt Bestandteilbedingungswert an der Risikomechanik vor, die gefunden wird In PerformanceAnalytics aus einem Papier von Brian Peterson, Kris Boudt und Peter Carl Dies ist ein Mechanismus, der ein einfach zu rufender Mechanismus für die Berechnung der Komponente erwarteten Fehlbetrag in Asset-Renditen, wie sie für ein Portfolio gelten Während die genaue Mechanik sind ziemlich komplex , Die Oberseite ist, dass die Laufzeit fast sofort ist, und diese Methode ist ein solides Werkzeug für die Einbeziehung in Asset Allocation Analyse. Für diejenigen, die sich für eine eingehende Analyse der Intuition der Komponente Bedingungswert in Gefahr, ich verweise sie auf die Papier geschrieben von Brian Peterson, Peter Carl und Kris Boudt. Essentiell, hier ist die Idee alle Vermögenswerte in einem bestimmten Portfolio haben einen marginalen Beitrag zu seinem gesamten bedingten Wert in Gefahr auch bekannt als erwartet Defizit ist der erwartete Verlust, wenn der Verlust eine bestimmte Schwelle übertrifft. Zum Beispiel, wenn du deinen 5 erwarteten Fehlbetrag kennen möchtest, dann ist es der Durchschnitt der schlechtesten 5 Renditen pro 100 Tage und so weiter Für Rücksendungen mit täglicher Auflösung, Die Idee des erwarteten Fehlbetrags kann klingen, als ob es nie genug Daten in einem ausreichend schnellen Zeitrahmen auf ein Jahr oder weniger geben wird, die Formel für erwarteten Fehlbetrag in der PerformanceAnalytics standardisiert eine Annäherungsberechnung mit einer Cornish-Fisher-Erweiterung, die sehr liefert Gute Ergebnisse so lange, wie der p-Wert isn t zu extrem ist, das ist, es funktioniert für relativ sane p Werte wie der 1 -10 rangeponent Conditional Value at Risk hat zwei Verwendungen zuerst aus, da keine Eingangsgewichte, verwendet es ein gleiches Gewicht Standard, die es erlaubt, eine Risikoabschätzung für jeden einzelnen Vermögenswert vorzusehen, ohne den Forscher zu belasten, um seine eigene Korrelationskovarianzheuristiken zu erstellen. Zweitens, wenn er mit einem Satz von Gewichten versehen ist, ist das Outpu T ändert sich, um den Beitrag verschiedener Vermögenswerte im Verhältnis zu diesen Gewichten zu reflektieren. Dies bedeutet, dass diese Methodik sehr gut mit Strategien arbeitet, die Vermögenswerte auf der Grundlage von Impuls ausschließen, aber ein Gewichtungsschema für die verbleibenden Vermögenswerte benötigen. Darüber hinaus ermöglicht diese Methode auch eine Ex - Post-Analyse der Risikobeitrag zu sehen, welches Instrument dazu beigetragen hat, was zu riskieren. Erstens, eine Demonstration, wie der Mechanismus arbeitet mit dem edhec Datensatz Es gibt keine Strategie hier, nur eine Demonstration der Syntax. Dies wird ein gleichberechtigter Beitrag von allen Der Fonds im edhec-Datensatz. So tmp ist der Beitrag zu erwartetem Fehlbetrag von jedem der verschiedenen edhec-Manager über den gesamten Zeitraum Hier ist die Ausgabe. Der herausragende Teil davon ist der prozentuale Beitrag der letzte Ausgabe Beachten Sie, dass es kann Negativ sein, was bedeutet, dass bestimmte Fonds gewinnen, wenn andere verlieren Mindestens das war der Fall über den aktuellen Datensatz Diese Vermögenswerte diversifizieren ein Portfolio und tatsächlich niedriger Erwarteter Fehlbetrag. In diesem Fall habe ich auch die ersten zehn Manager im edhec-Datensatz gewichtet und in den letzten drei null Gewicht gelegt. Außerdem können wir sehen, was passiert, wenn die Gewichte nicht gleich sind. Diese Zeit bemerken, dass das Gewicht Erhöhte sich in der Cabrio-Arb-Manager, so auch seinen Beitrag zu maximal erwarteten Fehlbetrag. Für einen zukünftigen Backtest, würde ich gerne einige Datenanfragen Ich möchte das Universum in Faber s Global Asset Allocation Buch verwenden Das sagte, die Simulationen In diesem Buch gehen zurück zu 1972, und ich frage mich, ob jemand da draußen hat tägliche Renditen für diese Vermögenswerte Indizes Während einige ETFs gehen in die frühen 2000er Jahre, gibt es einige, die ziemlich spät beginnen, wie DBC Rohstoffe, Anfang 2006, GLD Gold , Anfang 2004, BWX ausländische Anleihen, Ende 2007 und FTY NAREIT, Anfang 2007 Als ein achtjähriger Backtest wäre ein bisschen kurz, ich frage mich, ob jemand Daten mit mehr Geschichte hatte. Eine andere Sache, werde ich in New York für Die Handelsausstellung und das Sprechen auf Die Programmierkriegs-Panel am 6. Oktober. Danke für das Lesen. HINWEIS Während ich derzeit vertrage, bin ich auch auf der Suche nach einer dauerhaften Position, die von meinen Fähigkeiten profitieren kann, wenn mein aktueller Vertrag endet Wenn Sie eine solche Eröffnung kennen oder kennen, Ich werde glücklich sein, mit Ihnen zu sprechen. Dieser Beitrag wird eine Funktion abdecken, um die Erstellung von Harry Long-Typ-Rebalancing-Strategien von SeekingAlpha für interessierte Leser zu vereinfachen. Wie Harry Long gesagt hat, sind die meisten, wenn nicht alle seine Strategien eher für demonstrative Zwecke als für tatsächliche Zwecke Empfohlene investitionen. So, seit Harry Long hat noch einige Artikel auf Seeknig Alpha, ich habe einen Leser oder zwei fragen mich, um seine Strategien wieder zu analysieren, anstatt das zu tun, aber ich werde einfach dieses Tool hier, was ist ein Wrapper, der die Erfassung von Daten automatisiert und simuliert Portfolio-Rebalancing mit einer Zeile Code. Hier s das Tool. It holt die Daten für Sie in der Regel von Yahoo, aber ein großes Dankeschön an Herrn Helumth Vollmeier in dem Fall Von ZIV und VXX, und hat die Möglichkeit, entweder einfach eine Eigenkapitalkurve und einige Statistiken CAGR, annualisierte Standard dev, Sharpe, max Drawdown, Calmar, oder geben Sie den Rücklauf als Ausgabe, wenn Sie mehr Analyse in R wollen. Hier ist ein Beispiel für einfach nur die Statistiken, mit einem 80 XLP SPLV sie mehr oder weniger austauschbar und 20 TMF aka 60 TLT, so ein 80 60 Portfolio, von einem von Harry Long s Artikeln. Nichts aus dem gewöhnlichen von was Wir könnten von einem ausgewogenen Aktienanleihen-Portfolio erwarten Im Allgemeinen ist gut, hat seinen größten Drawdown in der Finanzkrise, und einige andere Beulen in der Straße, aber insgesamt, ich dachte, eine ziemlich Vanille setzen sie und vergiss es Art der Sache. Und hier Wäre der Weg, um den Strom der einzelnen täglichen Renditen zu bekommen, vorausgesetzt, Sie wollten diese beiden Instrumente wöchentlich neu ausbalancieren, anstatt jährlich wie ist die default. And jetzt lassen Sie sich einige Statistiken. Turns aus, bewegen die Rebalancing von jährlich auf wöchentlich didn Ich habe viel Wirkung Hier geben Sie dem Broker einen Bündel Geld, wenn Sie in den Transaktionskosten fakturiert haben, was das tut, das ist, wie das Werkzeug funktioniert. Die Ergebnisse beginnen natürlich von der neuesten Instrumentenstellung. Der Trick, meiner Meinung nach , Ist zu versuchen, Proxy-Ersatzstoffe mit längeren Geschichten für neuere ETFs, die einfach gehebelte ETFs, wie die Verwendung eines 60 Gewicht in TLT mit einem 80 Gewicht in XLP statt einer 20 Gewicht in TMF mit 80 Zuweisung in SPLV. Für Beispiel, Hier sind einige Proxies. SPXL XLP SPXL UPRO SPY 3 TMF TLT 3.Das sagte, ich habe mit Harry Lange vorher gearbeitet und er entwickelt anspruchsvollere Strategien hinter den Kulissen, also ich empfehle, dass SeekingAlpha Leser seine öffentlich veröffentlichten Strategien als Konzept nehmen Demonstrationen, im Gegensatz zu vollwertigen Investitionsideen und kontaktieren Sie Herrn Long selbst über mehr maßgeschneiderte, private Lösungen für Investmentinstitute, wenn Sie so interessiert sind. Danke für das Lesen. NOTE Ich bin derzeit im Nordosten Während ich derzeit Vertrag bin Ng, ich interessiere mich für die Vernetzung mit Einzelpersonen oder Firmen in Bezug auf potenzielle Kooperationsmöglichkeiten. Dieser Beitrag wird zeigen, wie man den Umsatz bei der Umgang mit Renditen-basierten Daten mit PerformanceAnalytics und die Funktion in R zu berücksichtigen. Dies wird dies auf einer grundlegenden Strategie zu demonstrieren Auf der neun Sektor SPDRs. So, zuerst aus, dies ist als Antwort auf eine Frage von einem Robert Wages auf der R-SIG-Finance Mailing-Liste gestellt, während es viele Personen gibt es mit einer Fülle von Fragen, von denen viele gefunden werden können Auf diesem Blog bereits gezeigt werden, gelegentlich wird es ein Industrie-Veteran, ein Doktorand Student von Stanford, oder andere sehr intelligente Person, die eine Frage zu einem Thema, dass ich habe noch nicht auf diesem Blog berührt, die wird auffordern Ein Posten, um einen weiteren technischen Aspekt zu demonstrieren, der in R gefunden wird. Dies ist einer jener Zeiten. So wird diese Demonstration über die Berechnung des Umsatzes im Rendite-Raum mit dem PerformanceAnalytics-Paket S sein Implizit außerhalb des PortfolioAnalytics-Pakets ist PerformanceAnalytics mit seiner Funktion das Go-to-R-Paket für Portfoliomanagement-Simulationen, da es eine Reihe von Gewichten, eine Reihe von Renditen und eine Reihe von Portfolio-Renditen für die Analyse mit dem Rest zu machen Von PerformanceAnalytics s Funktionen. Again, die Strategie ist dies nehmen die 9 Drei-Buchstaben-Sektor SPDRs, da gibt es vier-Buchstaben ETFs jetzt, und am Ende eines jeden Monats, wenn der bereinigte Preis über seinem 200-Tage gleitenden Durchschnitt ist, investieren In sie Normalisierung über alle investierten Sektoren, die ist, 1 9., wenn investiert in alle 9, 100 in 1, wenn nur 1 investiert in, 100 Bargeld, mit einem Null-Return-Vektor bezeichnet, wenn keine Sektoren in Es sa einfach, Spielzeug-Strategie investiert sind, Wie die Strategie ist nicht der Punkt der Demonstration. Hier s die grundlegende Setup-Code. So, erhalten Sie die SPDRs, setzen sie zusammen, berechnen ihre Renditen, generieren das Signal, und erstellen Sie die Null-Vektor, da behandelt Gewichte weniger als 1 als Entzug und Gewichte über 1 als die Hinzufügen von mehr Kapital große FYI hier. Jetzt, hier s, wie man Umsatz zu berechnen. So, der Trick ist dies, wenn Sie nennen die verbose TRUE Option Dies schafft mehrere Objekte, darunter Renditen, und diese stehen für Anfang von Period Weight, und Ende des Periodengewichts. Die Art und Weise, wie der Umsatz berechnet wird, ist einfach der Unterschied zwischen dem, wie der Tag s zurückführt, das zugeteilte Portfolio von seinem vorherigen Endpunkt zu dem, wo dieses Portfolio tatsächlich zu Beginn des nächsten Zeitraums steht. Das ist das Ende des Periodengewichts Ist der Beginn der Periode Drift nach Berücksichtigung der Tag s Drift Rendite für diesen Vermögenswert Der neue Anfang des Periodengewichts ist das Ende des Periodengewichts plus alle Transaktionen, die getan worden wäre So, um die tatsächlichen Transaktionen oder Umsatz zu finden, Man subtrahiert das vorherige Ende des Periodengewichts vom Anfang des Periodengewichts. Dies ist, was solche Transaktionen für diese Strategie aussehen. Vieles, was wir mit solchen Daten machen können, ist ein einjähriger rollender Umsatz, a Ccomplished mit dem folgenden code. It sieht aus wie this. This im Wesentlichen bedeutet, dass ein Jahr im Wert von Zwei-Wege-Umsatz, der ist, wenn der Verkauf eines vollständig investierten Portfolios ist 100 Umsatz, und den Kauf eines völlig neuen Satz von Vermögenswerten ist ein weiterer 100, dann Zwei-Wege-Umsatz ist 200 ist etwa 800 am Maximum Das kann ziemlich hoch für einige Leute. Jetzt, hier ist die Anwendung, wenn Sie die Transaktionskosten bei 20 Basispunkten pro Prozentpunkt gehandelt, das ist, kostet es 20 Cent, um 100 zu tätigen. Also, zu 20 Basispunkten auf Transaktionskosten, das dauert etwa ein Prozent in Renditen pro Jahr aus dieser zugegebenermaßen, schreckliche Strategie Das ist weit von vernachlässigbar. So, das ist, wie Sie tatsächlich berechnen Umsatz und Transaktionskosten In diesem Fall die Transaktion cost model was very simple However, given that returns transactions at the individual asset level, one could get as complex as they would like with modeling the transaction costs. Thanks for reading. NOTE I will be giving a lightning talk at R Fi nance, so for those attending, you ll be able to find me there. This post will outline an easy-to-make mistake in writing vectorized backtests namely in using a signal obtained at the end of a period to enter or exit a position in that same period The difference in results one obtains is massive. Today, I saw two separate posts from Alpha Architect and Mike Harris both referencing a paper by Valeriy Zakamulin on the fact that some previous trend-following research by Glabadanidis was done with shoddy results, and that Glabadanidis s results were only reproducible through instituting lookahead bias. The following code shows how to reproduce this lookahead bias. First, the setup of a basic moving average strategy on the S P 500 index from as far back as Yahoo data will provide. And here is how to institute the lookahead bias. These are the results. Of course, this equity curve is of no use, so here s one in log scale. As can be seen, lookahead bias makes a massive difference. Here are the numeric al results. Again, absolutely ridiculous. Note that when using the function in PerformanceAnalytics , that package will automatically give you the next period s return, instead of the current one, for your weights However, for those writing simple backtests that can be quickly done using vectorized operations, an off-by-one error can make all the difference between a backtest in the realm of reasonable, and pure nonsense However, should one wish to test for said nonsense when faced with impossible-to-replicate results, the mechanics demonstrated above are the way to do it. Now, onto other news I d like to thank Gerald M for staying on top of one of the Logical Invest strategies namely, their simple global market rotation strategy outlined in an article from an earlier blog post. Up until March 2015 the date of the blog post , the strategy had performed well However, after said date. It has been a complete disaster, which, in hindsight, was evident when I passed it through the hypothesis-dri ven development framework process I wrote about earlier. So, while there has been a great deal written about not simply throwing away a strategy because of short-term underperformance, and that anomalies such as momentum and value exist because of career risk due to said short-term underperformance, it s never a good thing when a strategy creates historically large losses, particularly after being published in such a humble corner of the quantitative financial world. In any case, this was a post demonstrating some mechanics, and an update on a strategy I blogged about not too long ago. Thanks for reading. NOTE I am always interested in hearing about new opportunities which may benefit from my expertise, and am always happy to network You can find my LinkedIn profile here. This post will shed light on the values of R 2s behind two rather simplistic strategies the simple 10 month SMA, and its relative, the 10 month momentum which is simply a difference of SMAs, as Alpha Architect showed in th eir book DIY Financial Advisor. Not too long ago, a friend of mine named Josh asked me a question regarding R 2s in finance He s finishing up his PhD in statistics at Stanford, so when people like that ask me questions, I d like to answer them His assertion is that in some instances, models that have less than perfect predictive power EG R 2s of 4, for instance , can still deliver very promising predictions, and that if someone were to have a financial model that was able to explain 40 of the variance of returns, they could happily retire with that model making them very wealthy Indeed 4 is a very optimistic outlook to put it lightly , as this post will show. In order to illustrate this example, I took two staple strategies buy SPY when its closing monthly price is above its ten month simple moving average, and when its ten month momentum basically the difference of a ten month moving average and its lag is positive While these models are simplistic, they are ubiquitously talked about, a nd many momentum strategies are an improvement upon these baseline, out-of-the-box strategies. Here s the code to do that. And here are the results. In short, the SMA10 and the 10-month momentum aka ROC 10 aka MOM10 both handily outperform the buy and hold, not only in absolute returns, but especially in risk-adjusted returns Sharpe and Calmar ratios Again, simplistic analysis, and many models get much more sophisticated than this, but once again, simple, illustrative example using two strategies that outperform a benchmark over the long term, anyway. Now, the question is, what was the R 2 of these models To answer this, I took a rolling five-year window that essentially asked how well did these quantities the ratio between the closing price and the moving average 1, or the ten month momentum predict the next month s returns That is, what proportion of the variance is explained through the monthly returns regressed against the previous month s signals in numerical form perhaps not the best framing, as the signal is binary as opposed to continuous which is what is being regressed, but let s set that aside, again, for the sake of illustration. Here s the code to generate the answer. And the answer, in pictorial form. In short, even in the best case scenarios, namely, crises which provide momentum trend-following call it what you will its raison d etre, that is, its risk management appeal, the proportion of variance explained by the actual signal quantities was very small In the best of times, around 20 But then again, think about what the R 2 value actually is it s the percentage of variance explained by a predictor If a small set of signals let alone one was able to explain the majority of the change in the returns of the S P 500, or even a not-insignificant portion, such a person would stand to become very wealthy More to the point, given that two strategies that handily outperform the market have R 2s that are exceptionally low for extended periods of time, it goes to sho w that holding the R 2 up as some form of statistical holy grail certainly is incorrect in the general sense, and anyone who does so either is painting with too broad a brush, is creating disingenuous arguments, or should simply attempt to understand another field which may not work the way their intuition tells them. Thanks for reading. This review will review the Adaptive Asset Allocation Dynamic Global Portfolios to Profit in Good Times and Bad book by the people at ReSolve Asset Management Overall, this book is a definite must-read for those who have never been exposed to the ideas within it However, when it comes to a solution that can be fully replicated, this book is lacking. Okay, it s been a while since I reviewed my last book, DIY Financial Advisor from the awesome people at Alpha Architect This book in my opinion, is set up in a similar sort of format. This is the structure of the book, and my reviews along with it. Part 1 Why in the heck you actually need to have a diversified p ortfolio, and why a diversified portfolio is a good thing In a world in which there is so much emphasis put on single-security performance, this is certainly something that absolutely must be stated for those not familiar with portfolio theory It highlights the example of two people one from Abbott Labs, and one from Enron, who had so much of their savings concentrated in their company s stock Mr Abbott got hit hard and changed his outlook on how to save for retirement, and Mr Enron was never heard from again Long story short a diversified portfolio is good, and a properly diversified portfolio can offset one asset s zigs with another asset s zags This is the key to establishing a stream of returns that will help meet financial goals Basically, this is your common sense story humans love being told stories so as to motivate you to read the rest of the book It does its job, though for someone like me, it s more akin to a big wait for it, wait for it and there s the reason why we should read on, as expected. Part 2 Something not often brought up in many corners of the quant world because it s real life boring stuff is the importance not only of average returns, but when those returns are achieved Namely, imagine your everyday saver At the beginning of their careers, they re taking home less salary and have less money in their retirement portfolio or speculation portfolio, but the book uses retirement portfolio As they get into middle age and closer to retirement, they have a lot more money in said retirement portfolio Thus, strong returns are most vital when there is more cash available to the portfolio, and the difference between mediocre returns at the beginning and strong returns at the end of one s working life as opposed to vice versa is astronomical and cannot be understated Furthermore, once in retirement, strong returns in the early years matter far more than returns in the later years once money has been withdrawn out of the portfolio though I d hope that a po rtfolio s returns can be so strong that one can simply live off the interest Or, put more intuitively when you have 10,000 in your portfolio, a 20 drawdown doesn t exactly hurt because you can make more money and put more into your retirement account But when you re 62 and have 500,000 and suddenly lose 30 of everything, well, that s massive How much an investor wants to avoid such a scenario cannot be understated Warren Buffett once said that if you can t bear to lose 50 of everything, you shouldn t be in stocks I really like this part of the book because it shows just how dangerous the ideas of a 50 drawdown is unavoidable and other stay invested for the long haul refrains are Essentially, this part of the book makes a resounding statement that any financial adviser keeping his or her clients invested in equities when they re near retirement age is doing something not very advisable, to put it lightly In my opinion, those who advise pension funds should especially keep this section o f the book in mind, since for some people, the long-term may be coming to an end, and what matters is not only steady returns, but to make sure the strategy doesn t fall off a cliff and destroy decades of hard-earned savings. Part 3 This part is also one that is a very important read First off, it lays out in clear terms that the long-term forward-looking valuations for equities are at rock bottom That is, the expected forward 15-year returns are very low, using approximately 75 years of evidence Currently, according to the book, equity valuations imply a negative 15-year forward return However, one thing I will take issue with is that while forward-looking long-term returns for equities may be very low, if one believed this chart and only invested in the stock market when forecast 15-year returns were above the long term average, one would have missed out on both the 2003-2007 bull runs, and the one since 2009 that s just about over So, while the book makes a strong case for caution, r eaders should also take the chart with a grain of salt in my opinion However, another aspect of portfolio construction that this book covers is how to construct a robust assets for any economic environment and coherent asset classes balanced in number universe for implementation with any asset allocation algorithm I think this bears repeating universe selection is an extremely important topic in the discussion of asset allocation, yet there is very little discussion about it Most research topics simply take some conventional universe , such as all stocks on the NYSE , or all the stocks in the S P 500 , or the entire set of the 50-60 most liquid futures without consideration for robustness and coherence This book is the first source I ve seen that actually puts this topic under a magnifying glass besides finger in the air pick and choose. Part 4 and here s where I level my main criticism at this book For those that have read Adaptive Asset Allocation A Primer this section of the book is basically one giant copy and paste It s all one large buildup to momentum rank min-variance optimization All well and good, until there s very little detail beyond the basics as to how the minimum variance portfolio was constructed Namely, what exactly is the minimum variance algorithm in use Is it one of the poor variants susceptible to numerical instability inherent in inverting sample covariance matrices Or is it a heuristic like David Varadi s minimum variance and minimum correlation algorithm The one feeling I absolutely could not shake was that this book had a perfect opportunity to present a robust approach to minimum variance, and instead, it s long on concept, short on details While the theory of maximize return for unit risk is all well and good, the actual algorithm to implement that theory into practice is not trivial, with the solutions taught to undergrads and master s students having some well-known weaknesses On top of this, one thing that got hammered into my head in t he past was that ranking also had a weakness at the inclusion exclusion point E G if, out of ten assets, the fifth asset had a momentum of say, 10 9 , and the sixth asset had a momentum of 10 8 , how are we so sure the fifth is so much better And while I realize that this book was ultimately meant to be a primer, in my opinion, it would have been a no-objections five-star if there were an appendix that actually went into some detail on how to go from the simple concepts and included a small numerical example of some algorithms that may address the well-known weaknesses This doesn t mean Greek mathematical jargon Just an appendix that acknowledged that not every reader is someone only picking up his first or second book about systematic investing, and that some of us are familiar with the whys and are more interested in the hows Furthermore, I d really love to know where the authors of this book got their data to back-date some of these ETFs into the 90s. Part 5 some more formal research on topics already covered in the rest of the book namely a section about how many independent bets one can take as the number of assets grow, if I remember it correctly Long story short You easily get the most bang for your buck among disparate asset classes, such as treasuries of various duration, commodities, developed vs emerging equities, and so on, as opposed to trying to pick among stocks in the same asset class though there s some potential for alpha there just a lot less than you imagine So in case the idea of asset class selection, not stock selection wasn t beaten into the reader s head before this point, this part should do the trick The other research paper is something I briefly skimmed over which went into more depth about volatility and retirement portfolios, though I felt that the book covered this topic earlier on to a sufficient degree by building up the intuition using very understandable scenarios. So that s the review of the book Overall, it s a very solid piece of writing, and as far as establishing the why , it does an absolutely superb job For those that aren t familiar with the concepts in this book, this is definitely a must-read, and ASAP. However, for those familiar with most of the concepts and looking for a detailed how procedure, this book does not deliver as much as I would have liked And I realize that while it s a bad idea to publish secret sauce, I bought this book in the hope of being exposed to a new algorithm presented in the understandable and intuitive language that the rest of the book was written in, and was left wanting. Still, that by no means diminishes the impact of the rest of the book For those who are more likely to be its target audience, it s a 5 5 For those that wanted some specifics, it still has its gem on universe construction. Overall, I rate it a 4 5.Thanks for reading. Happy new year This post will be a quick one covering the relationship between the simple moving average and time series momentum The implication is that one can potentially derive better time series momentum indicators than the classical one applied in so many papers. Okay, so the main idea for this post is quite simple. I m sure we re all familiar with classical momentum That is, the price now compared to the price however long ago 3 months, 10 months, 12 months, etc E G P now P 10 And I m sure everyone is familiar with the simple moving average indicator, as well E G SMA 10.Well, as it turns out, these two quantities are actually related. It turns out, if instead of expressing momentum as the difference of two numbers, it is expressed as the sum of returns, it can be written for a 10 month momentum as. MOM10 return of this month return of last month return of 2 months ago return of 9 months ago, for a total of 10 months in our little example. This can be written as MOM10 P 0 P 1 P 1 P 2 P 9 P 10 Each difference within parentheses denotes one month s worth of returns. Which can then be rewritten by associative arithmetic as P 0 P 1 P 9 P 1 P 2 P 10.In other words, momentum aka the difference between two prices, can be rewritten as the difference between two cumulative sums of prices And what is a simple moving average Simply a cumulative sum of prices divided by however many prices summed over. Here s some R code to demonstrate. With the resulting number of times these two signals are equal. In short, every time. Now, what exactly is the punchline of this little example Here s the punchline. The simple moving average is fairly simplistic as far as filters go It works as a pedagogical example, but it has some well known weaknesses regarding lag, windowing effects, and so on. Here s a toy example how one can get a different momentum signal by changing the filter. With the following results. While the difference of EMA10 strategy didn t do better than the difference of SMA10 aka standard 10-month momentum , that s not the point The point is that the momentum signal is derived from a simple moving average filter, and that by using a different filter, one can still use a momentum type of strategy. Or, put differently, the main general takeaway here is that momentum is the slope of a filter, and one can compute momentum in an infinite number of ways depending on the filter used, and can come up with a myriad of different momentum strategies. Thanks for reading. NOTE I am currently contracting in Chicago, and am always open to networking Contact me at my email at or find me on my LinkedIn here. Post navigation. Category Archives Trading. This post will introduce John Ehlers s Autocorrelation Periodogram mechanism a mechanism designed to dynamically find a lookback period That is, the most common parameter optimized in backtests is the lookback period. Before beginning this post, I must give credit where it s due, to one Mr Fabrizio Maccallini the head of structured derivatives at Nordea Markets in London You can find the rest of the repository he did for Dr John Ehlers s Cycle Analytics for Traders on his github I am grateful and honored that such intelligent and experienced individuals are helping to bring some of Dr Ehlers s methods into R. The point of the Ehlers Autocorrelation Periodogram is to dynamically set a period between a minimum and a maximum period length While I leave the exact explanation of the mechanic to Dr Ehlers s book, for all practical intents and purposes, in my opinion, the punchline of this method is to attempt to remove a massive source of overfitting from trading system creation namely specifying a lookback period. SMA of 50 days 100 days 200 days Well, this algorithm takes that possibility of overfitting out of your hands Simply, specify an upper and lower bound for your lookback, and it does the rest How well it does it is a topic of discussion for those well-versed in the methodologies of electrical engineering I m not , so feel free to leave comments that discuss how well the algorithm does its job, and feel free to blog about it as well. In any case, here s the orig inal algorithm code, courtesy of Mr Maccallini. One thing I do notice is that this code uses a loop that says for i in 1 length filt , which is an O data points loop, which I view as the plague in R While I ve used Rcpp before, it s been for only the most basic of loops, so this is definitely a place where the algorithm can stand to be improved with Rcpp due to R s inherent poor looping. Those interested in the exact logic of the algorithm will, once again, find it in John Ehlers s Cycle Analytics For Traders book see link earlier in the post. Of course, the first thing to do is to test how well the algorithm does what it purports to do, which is to dictate the lookback period of an algorithm. Let s run it on some data. Now, what does the algorithm-set lookback period look like. Let s zoom in on 2001 through 2003, when the markets went through some upheaval. In this zoomed-in image, we can see that the algorithm s estimates seem fairly jumpy. Here s some code to feed the algorithm s estimates of n into an indicator to compute an indicator with a dynamic lookback period as set by Ehlers s autocorrelation periodogram. And here is the function applied with an SMA, to tune between 120 and 252 days. As seen, this algorithm is less consistent than I would like, at least when it comes to using a simple moving average. For now, I m going to leave this code here, and let people experiment with it I hope that someone will find that this indicator is helpful to them. Thanks for reading. NOTES I am always interested in networking meet-ups in the northeast Philadelphia NYC Furthermore, if you believe your firm will benefit from my skills, please do not hesitate to reach out to me My linkedin profile can be found here. Lastly, I am volunteering to curate the R section for books on quantocracy If you have a book about R that can apply to finance, be sure to let me know about it, so that I can review it and possibly recommend it Thakn you. This post will be about attempting to use the Depmix pack age for online state prediction While the depmix package performs admirably when it comes to describing the states of the past, when used for one-step-ahead prediction, under the assumption that tomorrow s state will be identical to today s, the hidden markov model process found within the package does not perform to expectations. So, to start off, this post was motivated by Michael Halls-Moore, who recently posted some R code about using the depmixS4 library to use hidden markov models Generally, I am loath to create posts on topics I don t feel I have an absolutely front-to-back understanding of, but I m doing this in the hope of learning from others on how to appropriately do online state-space prediction, or regime switching detection, as it may be called in more financial parlance. While I ve seen the usual theory of hidden markov models that is, it can rain or it can be sunny, but you can only infer the weather judging by the clothes you see people wearing outside your window when you wake up , and have worked with toy examples in MOOCs Udacity s self-driving car course deals with them, if I recall correctly or maybe it was the AI course , at the end of the day, theory is only as good as how well an implementation can work on real data. For this experiment, I decided to take SPY data since inception, and do a full in-sample backtest on the data That is, given that the HMM algorithm from depmix sees the whole history of returns, with this god s eye view of the data, does the algorithm correctly classify the regimes, if the backtest results are any indication. Here s the code to do so, inspired by Dr Halls-Moore s. Essentially, while I did select three states, I noted that anything with an intercept above zero is a bull state, and below zero is a bear state, so essentially, it reduces to two states. With the result. So, not particularly terrible The algorithm works, kind of, sort of, right. Well, let s try online prediction now. So what I did here was I took an expanding window, starting from 500 days since SPY s inception, and kept increasing it, by one day at a time My prediction, was, trivially enough, the most recent day, using a 1 for a bull state, and a -1 for a bear state I ran this process in parallel on a linux cluster, because windows s doParallel library seems to not even know that certain packages are loaded, and it s more messy , and the first big issue is that this process took about three hours on seven cores for about 23 years of data Not exactly encouraging, but computing time isn t expensive these days. So let s see if this process actually works. First, let s test if the algorithm does what it s actually supposed to do and use one day of look-ahead bias that is, the algorithm tells us the state at the end of the day how correct is it even for that day. With the result. So, allegedly, the algorithm seems to do what it was designed to do, which is to classify a state for a given data set Now, the most pertinent question how well do these predictions do even one day ahead You d think that state space predictions would be parsimonious from day to day, given the long history, correct. With the result. That is, without the lookahead bias, the state space prediction algorithm is atrocious Why is that. Well, here s the plot of the states. In short, the online hmm algorithm in the depmix package seems to change its mind very easily, with obvious negative implications for actual trading strategies. So, that wraps it up for this post Essentially, the main message here is this there s a vast difference between loading doing descriptive analysis AKA where have you been, why did things happen vs predictive analysis that is, if I correctly predict the future, I get a positive payoff In my opinion, while descriptive statistics have their purpose in terms of explaining why a strategy may have performed how it did, ultimately, we re always looking for better prediction tools In this case, depmix, at least in this out-of-the-box demonstrati on does not seem to be the tool for that. If anyone has had success with using depmix or other regime-switching algorithm in R for prediction, I would love to see work that details the procedure taken, as it s an area I m looking to expand my toolbox into, but don t have any particular good leads Essentially, I d like to think of this post as me describing my own experiences with the package. Thanks for reading. NOTE On Oct 5th, I will be in New York City On Oct 6th, I will be presenting at The Trading Show on the Programming Wars panel. NOTE My current analytics contract is up for review at the end of the year, so I am officially looking for other offers as well If you have a full-time role which may benefit from the skills you see on my blog, please get in touch with me My linkedin profile can be found here. This post will demonstrate how to take into account turnover when dealing with returns-based data using PerformanceAnalytics and the function in R It will demonstrate this on a basic strategy on the nine sector SPDRs. So, first off, this is in response to a question posed by one Robert Wages on the R-SIG-Finance mailing list While there are many individuals out there with a plethora of questions many of which can be found to be demonstrated on this blog already , occasionally, there will be an industry veteran, a PhD statistics student from Stanford, or other very intelligent individual that will ask a question on a topic that I haven t yet touched on this blog, which will prompt a post to demonstrate another technical aspect found in R This is one of those times. So, this demonstration will be about computing turnover in returns space using the PerformanceAnalytics package Simply, outside of the PortfolioAnalytics package, PerformanceAnalytics with its function is the go-to R package for portfolio management simulations, as it can take a set of weights, a set of returns, and generate a set of portfolio returns for analysis with the rest of PerformanceAnalytics s fun ctions. Again, the strategy is this take the 9 three-letter sector SPDRs since there are four-letter ETFs now , and at the end of every month, if the adjusted price is above its 200-day moving average, invest into it Normalize across all invested sectors that is, 1 9th if invested into all 9, 100 into 1 if only 1 invested into, 100 cash, denoted with a zero return vector, if no sectors are invested into It s a simple, toy strategy, as the strategy isn t the point of the demonstration. Here s the basic setup code. So, get the SPDRs, put them together, compute their returns, generate the signal, and create the zero vector, since treats weights less than 1 as a withdrawal, and weights above 1 as the addition of more capital big FYI here. Now, here s how to compute turnover. So, the trick is this when you call use the verbose TRUE option This creates several objects, among them returns, and These stand for Beginning Of Period Weight, and End Of Period Weight. The way that turnover is computed is simply the difference between how the day s return moves the allocated portfolio from its previous ending point to where that portfolio actually stands at the beginning of next period That is, the end of period weight is the beginning of period drift after taking into account the day s drift return for that asset The new beginning of period weight is the end of period weight plus any transacting that would have been done Thus, in order to find the actual transactions or turnover , one subtracts the previous end of period weight from the beginning of period weight. This is what such transactions look like for this strategy. Something we can do with such data is take a one-year rolling turnover, accomplished with the following code. It looks like this. This essentially means that one year s worth of two-way turnover that is, if selling an entirely invested portfolio is 100 turnover, and buying an entirely new set of assets is another 100 , then two-way turnover is 200 is around 800 at maxim um That may be pretty high for some people. Now, here s the application when you penalize transaction costs at 20 basis points per percentage point traded that is, it costs 20 cents to transact 100.So, at 20 basis points on transaction costs, that takes about one percent in returns per year out of this admittedly, terrible strategy This is far from negligible. So, that is how you actually compute turnover and transaction costs In this case, the transaction cost model was very simple However, given that returns transactions at the individual asset level, one could get as complex as they would like with modeling the transaction costs. Thanks for reading. NOTE I will be giving a lightning talk at R Finance, so for those attending, you ll be able to find me there. This post will outline an easy-to-make mistake in writing vectorized backtests namely in using a signal obtained at the end of a period to enter or exit a position in that same period The difference in results one obtains is massive. T oday, I saw two separate posts from Alpha Architect and Mike Harris both referencing a paper by Valeriy Zakamulin on the fact that some previous trend-following research by Glabadanidis was done with shoddy results, and that Glabadanidis s results were only reproducible through instituting lookahead bias. The following code shows how to reproduce this lookahead bias. First, the setup of a basic moving average strategy on the S P 500 index from as far back as Yahoo data will provide. And here is how to institute the lookahead bias. These are the results. Of course, this equity curve is of no use, so here s one in log scale. As can be seen, lookahead bias makes a massive difference. Here are the numerical results. Again, absolutely ridiculous. Note that when using the function in PerformanceAnalytics , that package will automatically give you the next period s return, instead of the current one, for your weights However, for those writing simple backtests that can be quickly done using vectorized operations, an off-by-one error can make all the difference between a backtest in the realm of reasonable, and pure nonsense However, should one wish to test for said nonsense when faced with impossible-to-replicate results, the mechanics demonstrated above are the way to do it. Now, onto other news I d like to thank Gerald M for staying on top of one of the Logical Invest strategies namely, their simple global market rotation strategy outlined in an article from an earlier blog post. Up until March 2015 the date of the blog post , the strategy had performed well However, after said date. It has been a complete disaster, which, in hindsight, was evident when I passed it through the hypothesis-driven development framework process I wrote about earlier. So, while there has been a great deal written about not simply throwing away a strategy because of short-term underperformance, and that anomalies such as momentum and value exist because of career risk due to said short-term underperformanc e, it s never a good thing when a strategy creates historically large losses, particularly after being published in such a humble corner of the quantitative financial world. In any case, this was a post demonstrating some mechanics, and an update on a strategy I blogged about not too long ago. Thanks for reading. NOTE I am always interested in hearing about new opportunities which may benefit from my expertise, and am always happy to network You can find my LinkedIn profile here. Happy new year This post will be a quick one covering the relationship between the simple moving average and time series momentum The implication is that one can potentially derive better time series momentum indicators than the classical one applied in so many papers. Okay, so the main idea for this post is quite simple. I m sure we re all familiar with classical momentum That is, the price now compared to the price however long ago 3 months, 10 months, 12 months, etc E G P now P 10 And I m sure everyone is familia r with the simple moving average indicator, as well E G SMA 10.Well, as it turns out, these two quantities are actually related. It turns out, if instead of expressing momentum as the difference of two numbers, it is expressed as the sum of returns, it can be written for a 10 month momentum as. MOM10 return of this month return of last month return of 2 months ago return of 9 months ago, for a total of 10 months in our little example. This can be written as MOM10 P 0 P 1 P 1 P 2 P 9 P 10 Each difference within parentheses denotes one month s worth of returns. Which can then be rewritten by associative arithmetic as P 0 P 1 P 9 P 1 P 2 P 10.In other words, momentum aka the difference between two prices, can be rewritten as the difference between two cumulative sums of prices And what is a simple moving average Simply a cumulative sum of prices divided by however many prices summed over. Here s some R code to demonstrate. With the resulting number of times these two signals are equal. In short, every time. Now, what exactly is the punchline of this little example Here s the punchline. The simple moving average is fairly simplistic as far as filters go It works as a pedagogical example, but it has some well known weaknesses regarding lag, windowing effects, and so on. Here s a toy example how one can get a different momentum signal by changing the filter. With the following results. While the difference of EMA10 strategy didn t do better than the difference of SMA10 aka standard 10-month momentum , that s not the point The point is that the momentum signal is derived from a simple moving average filter, and that by using a different filter, one can still use a momentum type of strategy. Or, put differently, the main general takeaway here is that momentum is the slope of a filter, and one can compute momentum in an infinite number of ways depending on the filter used, and can come up with a myriad of different momentum strategies. Thanks for reading. NOTE I am currently contracting in Chicago, and am always open to networking Contact me at my email at or find me on my LinkedIn here. This post will outline a first failed attempt at applying the ensemble filter methodology to try and come up with a weighting process on SPY that should theoretically be a gradual process to shift from conviction between a bull market, a bear market, and anywhere in between This is a follow-up post to this blog post. So, my thinking went like this in a bull market, as one transitions from responsiveness to smoothness, responsive filters should be higher than smooth filters, and vice versa, as there s generally a trade-off between the two In fact, in my particular formulation, the quantity of the square root of the EMA of squared returns punishes any deviation from a flat line altogether although inspired by Basel s measure of volatility, which is the square root of the 18-day EMA of squared returns , while the responsiveness quantity punishes any deviation from the time series of the real ized prices Whether these are the two best measures of smoothness and responsiveness is a topic I d certainly appreciate feedback on. In any case, an idea I had on the top of my head was that in addition to having a way of weighing multiple filters by their responsiveness deviation from price action and smoothness deviation from a flat line , that by taking the sums of the sign of the difference between one filter and its neighbor on the responsiveness to smoothness spectrum, provided enough ensemble filters say, 101, so there are 100 differences , one would obtain a way to move from full conviction of a bull market, to a bear market, to anything in between, and have this be a smooth process that doesn t have schizophrenic swings of conviction. Here s the code to do this on SPY from inception to 2003.And here s the very underwhelming result. Essentially, while I expected to see changes in conviction of maybe 20 at most, instead, my indicator of sum of sign differences did exactly as I had hoped it wouldn t, which is to be a very binary sort of mechanic My intuition was that between an obvious bull market and an obvious bear market that some differences would be positive, some negative, and that they d net each other out, and the conviction would be zero Furthermore, that while any individual crossover is binary, all one hundred signs being either positive or negative would be a more gradual process Apparently, this was not the case To continue this train of thought later, one thing to try would be an all-pairs sign difference Certainly, I don t feel like giving up on this idea at this point, and, as usual, feedback would always be appreciated. Thanks for reading. NOTE I am currently consulting in an analytics capacity in downtown Chicago However, I am also looking for collaborators that wish to pursue interesting trading ideas If you feel my skills may be of help to you, let s talk You can email me at or find me on my LinkedIn here. This review will be about Inovance Tech s TRAIDE system It is an application geared towards letting retail investors apply proprietary machine learning algorithms to assist them in creating systematic trading strategies Currently, my one-line review is that while I hope the company founders mean well, the application is still in an early stage, and so, should be checked out by potential users venture capitalists as something with proof of potential, rather than a finished product ready for mass market While this acts as a review, it s also my thoughts as to how Inovance Tech can improve its product. A bit of background I have spoken several times to some of the company s founders, who sound like individuals at about my age level so, fellow millennials Ultimately, the selling point is this. Systematic trading is cool Machine learning is cool Therefore, applying machine learning to systematic trading is awesome And a surefire way to make profits, as Renaissance Technologies has shown. While this may sound a bit snarky, it s also , in some ways, true Machine learning has become the talk of the town, from IBM s Watson RenTec itself hired a bunch of speech recognition experts from IBM a couple of decades back , to Stanford s self-driving car invented by Sebastian Thrun, who now heads Udacity , to the Netflix prize, to god knows what Andrew Ng is doing with deep learning at Baidu Considering how well machine learning has done at much more complex tasks than create a half-decent systematic trading algorithm , it shouldn t be too much to ask this powerful field at the intersection of computer science and statistics to help the retail investor glued to watching charts generate a lot more return on his or her investments than through discretionary chart-watching and noise trading To my understanding from conversations with Inovance Tech s founders, this is explicitly their mission. However, I am not sure that Inovance s TRAIDE application actually accomplishes this mission in its current state. Here s how it works. Users select one asset at a time, and select a date range data going back to Dec 31, 2009 Assets are currently limited to highly liquid currency pairs, and can take the following settings 1 hour, 2 hour, 4 hour, 6 hour, or daily bar time frames. Users then select from a variety of indicators, ranging from technical moving averages, oscillators, volume calculations, etc Mostly an assortment of 20th century indicators, though the occasional adaptive moving average has managed to sneak in namely KAMA see my DSTrading package, and MAMA aka the Mesa Adaptive Moving Average, from John Ehlers to more esoteric ones such as some sentiment indicators Here s where things start to head south for me, however Namely, that while it s easy to add as many indicators as a user would like, there is basically no documentation on any of them, with no links to reference, etc so users will have to bear the onus of actually understanding what each and every one of the indicators they select actually does, and wheth er or not those indicators are useful The TRAIDE application makes zero effort thus far to actually get users acquainted with the purpose of these indicators, what their theoretical objective is measure conviction in a trend, detect a trend, oscillator type indicator, etc. Furthermore, regarding indicator selections, users also specify one parameter setting for each indicator per strategy E G if I had an EMA crossover, I d have to create a new strategy for a 20 100 crossover, a 21 100 crossover, rather than specifying something like this. short EMA 20-60 long EMA 80-200.Quantstrat itself has this functionality, and while I don t recall covering parameter robustness checks optimization in other words, testing multiple parameter sets whether one uses them for optimization or robustness is up to the user, not the functionality in quantstrat on this blog specifically, this information very much exists in what I deem the official quantstrat manual , found here In my opinion, the option of cov ering a range of values is mandatory so as to demonstrate that any given parameter setting is not a random fluke Outside of quantstrat, I have demonstrated this methodology in my Hypothesis Driven Development posts, and in coming up for parameter selection for volatility trading. Where TRAIDE may do something interesting, however, is that after the user specifies his indicators and parameters, its proprietary machine learning algorithms WARNING COMPLETELY BLACK BOX determine for what range of values of the indicators in question generated the best results within the backtest, and assign them bullishness and bearishness scores In other words, looking backwards, these were the indicator values that did best over the course of the sample While there is definite value to exploring the relationships between indicators and future returns, I think that TRAIDE needs to do more in this area, such as reporting P-values, conviction, and so on. For instance, if you combine enough indicators, your ru le is a market order that s simply the intersection of all of the ranges of your indicators For instance, TRAIDE may tell a user that the strongest bullish signal when the difference of the moving averages is between 1 and 2, the ADX is between 20 and 25, the ATR is between 0 5 and 1, and so on Each setting the user selects further narrows down the number of trades the simulation makes In my opinion, there are more ways to explore the interplay of indicators than simply one giant AND statement, such as an OR statement, of some sort E G select all values, put on a trade when 3 out of 5 indicators fall into the selected bullish range in order to place more trades While it may be wise to filter down trades to very rare instances if trading a massive amount of instruments, such that of several thousand possible instruments, only several are trading at any given time, with TRAIDE, a user selects only one asset class currently, one currency pair at a time, so I m hoping to see TRAIDE create more functionality in terms of what constitutes a trading rule. After the user selects both a long and a short rule by simply filtering on indicator ranges that TRAIDE s machine learning algorithms have said are good , TRAIDE turns that into a backtest with a long equity curve, short equity curve, total equity curve, and trade statistics for aggregate, long, and short trades For instance, in quantstrat, one only receives aggregate trade statistics Whether long or short, all that matters to quantstrat is whether or not the trade made or lost money For sophisticated users, it s trivial enough to turn one set of rules on or off, but TRAIDE does more to hold the user s hand in that regard. Lastly, TRAIDE then generates MetaTrader4 code for a user to download. And that s the process. In my opinion, while what Inovance Tech has set out to do with TRAIDE is interesting, I wouldn t recommend it in its current state For sophisticated individuals that know how to go through a proper research process , TRAIDE is too stringent in terms of parameter settings one at a time , pre-coded indicators its target audience probably can t program too well , and asset classes again, one at a time However, for retail investors, my issue with TRAIDE is this. There is a whole assortment of undocumented indicators, which then move to black-box machine learning algorithms The result is that the user has very little understanding of what the underlying algorithms actually do, and why the logic he or she is presented with is the output While TRAIDE makes it trivially easy to generate any one given trading system, as multiple individuals have stated in slightly different ways before, writing a strategy is the easy part Doing the work to understand if that strategy actually has an edge is much harder Namely, checking its robustness, its predictive power, its sensitivity to various regimes, and so on Given TRAIDE s rather short data history 2010 onwards , and coupled with the opaqueness that the user oper ates under, my analogy would be this. It s like giving an inexperienced driver the keys to a sports car in a thick fog on a winding road Nobody disputes that a sports car is awesome However, the true burden of the work lies in making sure that the user doesn t wind up smashing into a tree. Overall, I like the TRAIDE application s mission, and I think it may have potential as something for the retail investors that don t intend to learn the ins-and-outs of coding a trading system in R despite me demonstrating many times over how to put such systems together I just think that there needs to be more work put into making sure that the results a user sees are indicative of an edge, rather than open the possibility of highly-flexible machine learning algorithms chasing ghosts in one of the noisiest and most dynamic data sets one can possibly find. My recommendations are these.1 Multiple asset classes 2 Allow parameter ranges, and cap the number of trials at any given point E G 4 indicators with ten settings each 10,000 possible trading systems blow up the servers To narrow down the number of trial runs, use techniques from experimental design to arrive at decent combinations I wish I remembered my response surface methodology techniques from my master s degree about now 3 Allow modifications of order sizing E G volatility targeting, stop losses , such as I wrote about in my hypothesis-driven development posts 4 Provide some sort of documentation for the indicators, even if it s as simple as a link to investopedia preferably a lot more 5 Far more output is necessary, especially for users who don t program Namely, to distinguish whether or not there is a legitimate edge, or if there are too few observations to reject the null hypothesis of random noise 6 Far longer data histories 2010 onwards just seems too short of a time-frame to be sure of a strategy s efficacy, at least on daily data may not be true for hourly 7 Factor in transaction costs Trading on an hourly time frame w ill mean far less P L per trade than on a daily resolution If MT4 charges a fixed ticket price, users need to know how this factors into their strategy 8 Lastly, dogfooding When I spoke last time with Inovance Tech s founders, they claimed they were using their own algorithms to create a forex strategy, which was doing well in live trading By the time more of these suggestions are implemented, it d be interesting to see if they have a track record as a fund, in addition to as a software provider. If all of these things are accounted for and automated, the product will hopefully accomplish its mission of bringing systematic trading and machine learning to more people I think TRAIDE has potential, and I m hoping that its staff will realize that potential. Thanks for reading. NOTE I am currently contracting in downtown Chicago, and am always interested in networking with professionals in the systematic trading and systematic asset management allocation spaces Find my LinkedIn here. EDIT Today in my email Dec 3, 2015 , I received a notice that Inovance was making TRAIDE completely free Perhaps they want a bunch more feedback on it. This post will demonstrate a method to create an ensemble filter based on a trade-off between smoothness and responsiveness, two properties looked for in a filter An ideal filter would both be responsive to price action so as to not hold incorrect positions, while also be smooth, so as to not incur false signals and unnecessary transaction costs. So, ever since my volatility trading strategy, using three very naive filters all SMAs completely missed a 27 month in XIV I ve decided to try and improve ways to create better indicators in trend following Now, under the realization that there can potentially be tons of complex filters in existence, I decided instead to focus on a way to create ensemble filters, by using an analogy from statistics machine learning. In static data analysis, for a regression or classification task, there is a trade-off betwe en bias and variance In a nutshell, variance is bad because of the possibility of overfitting on a few irregular observations, and bias is bad because of the possibility of underfitting legitimate data Similarly, with filtering time series, there are similar concerns, except bias is called lag, and variance can be thought of as a whipsawing indicator Essentially, an ideal indicator would move quickly with the data, while at the same time, not possess a myriad of small bumps-and-reverses along the way, which may send false signals to a trading strategy. So, here s how my simple algorithm works. The inputs to the function are the following. A The time series of the data you re trying to filter B A collection of candidate filters C A period over which to measure smoothness and responsiveness, defined as the square root of the n-day EMA 2 n 1 convention of the following a Responsiveness the squared quantity of price filter 1 b Smoothness the squared quantity of filter t filter t-1 1 aka R s f unction D A conviction factor, to which power the errors will be raised This should probably be between 5 and 3 E A vector that defines the emphasis on smoothness vs emphasis on responsiveness , which should range from 0 to 1.Here s the code. This gets SPY data, and creates two utility functions xtsApply, which is simply a column-based apply that replaces the original index that using a column-wise apply discards, and sumIsNa, which I use later for counting the numbers of NAs in a given row It also creates my candidate filters, which, to keep things simple, are just SMAs 2-250.Here s the actual code of the function, with comments in the code itself to better explain the process from a technical level for those still unfamiliar with R, look for the hashtags. The vast majority of the computational time takes place in the two xtsApply calls On 249 different simple moving averages, the process takes about 30 seconds. Here s the output, using a conviction factor of 2.And here is an example, lo oking at SPY from 2007 through 2011.In this case, I chose to go from blue to green, orange, brown, maroon, purple, and finally red for smoothness emphasis of 0, 5 , 25 , 50 , 75 , 95 , and 1, respectively. Notice that the blue line is very wiggly, while the red line sometimes barely moves, such as during the 2011 drop-off. One thing that I noticed in the course of putting this process together is something that eluded me earlier namely, that naive trend-following strategies which are either fully long or fully short based on a crossover signal can lose money quickly in sideways markets. However, theoretically, by finely varying the jumps between 0 to 100 emphasis on smoothness, whether in steps of 1 or finer, one can have a sort of continuous conviction, by simply adding up the signs of differences between various ensemble filters In an uptrend , the difference as one moves from the most responsive to most smooth filter should constantly be positive, and vice versa. In the interest of brev ity, this post doesn t even have a trading strategy attached to it However, an implied trading strategy can be to be long or short the SPY depending on the sum of signs of the differences in filters as you move from responsiveness to smoothness Of course, as the candidate filters are all SMAs, it probably wouldn t be particularly spectacular However, for those out there who use more complex filters, this may be a way to create ensembles out of various candidate filters, and create even better filters Furthermore, I hope that given enough candidate filters and an objective way of selecting them, it would be possible to reduce the chances of creating an overfit trading system However, anything with parameters can potentially be overfit, so that may be wishful thinking. All in all, this is still a new idea for me For instance, the filter to compute the error terms can probably be improved The inspiration for an EMA 20 essentially came from how Basel computes volatility if I recall, correct ly, it uses the square root of an 18 day EMA of squared returns , and the very fact that I use an EMA can itself be improved upon why an EMA instead of some other, more complex filter In fact, I m always open to how I can improve this concept and others from readers. Thanks for reading. NOTE I am currently contracting in Chicago in an analytics capacity If anyone would like to meet up, let me know You can email me at or contact me through my LinkedIn here. This post will deal with a quick, finger in the air way of seeing how well a strategy scales namely, how sensitive it is to latency between signal and execution, using a simple volatility trading strategy as an example The signal will be the VIX VXV ratio trading VXX and XIV, an idea I got from Volatility Made Simple s amazing blog particularly this post The three signals compared will be the magical thinking signal observe the close, buy the close, named from the ruleOrderProc setting in quantstrat , buy on next-day open, and buy on ne xt-day close. Let s get started. So here s the run-through In addition to the magical thinking strategy observe the close, buy that same close , I tested three other variants a variant which transacts the next open, a variant which transacts the next close, and the average of those two Effectively, I feel these three could give a sense of a strategy s performance under more realistic conditions that is, how well does the strategy perform if transacted throughout the day, assuming you re managing a sum of money too large to just plow into the market in the closing minutes and if you hope to get rich off of trading, you will have a larger sum of money than the amount you can apply magical thinking to Ideally, I d use VWAP pricing, but as that s not available for free anywhere I know of, that means that readers can t replicate it even if I had such data. In any case, here are the results. Log scale for Mr Tony Cooper and others. My reaction The execute on next day s close performance being vas tly lower than the other configurations and that deterioration occurring in the most recent years essentially means that the fills will have to come pretty quickly at the beginning of the day While the strategy seems somewhat scalable through the lens of this finger-in-the-air technique, in my opinion, if the first full day of possible execution after signal reception will tank a strategy from a 1 44 Calmar to a 92, that s a massive drop-off, after holding everything else constant In my opinion, I think this is quite a valid question to ask anyone who simply sells signals, as opposed to manages assets Namely, how sensitive are the signals to execution on the next day After all, unless those signals come at 3 55 PM, one is most likely going to be getting filled the next day. Now, while this strategy is a bit of a tomato can in terms of how good volatility trading strategies can get they can get a lot better in my opinion , I think it made for a simple little demonstration of this techniq ue Again, a huge thank you to Mr Helmuth Vollmeier for so kindly keeping up his dropbox all this time for the volatility data. Thanks for reading. NOTE I am currently contracting in a data science capacity in Chicago You can email me at or find me on my LinkedIn here I m always open to beers after work if you re in the Chicago area. NOTE 2 Today, on October 21, 2015, if you re in Chicago, there s a Chicago R Users Group conference at Jaks Tap at 6 00 PM Free pizza, networking, and R, hosted by Paul Teetor, who s a finance guy Hope to see you there. This post deals with an impossible-to-implement statistical arbitrage strategy using VXX and XIV The strategy is simple if the average daily return of VXX and XIV was positive, short both of them at the close This strategy makes two assumptions of varying dubiousness that one can observe the close and act on the close , and that one can short VXX and XIV. So, recently, I decided to play around with everyone s two favorite instruments on this blog VXX and XIV, with the idea that hey, these two instruments are diametrically opposed, so shouldn t there be a stat-arb trade here. So, in order to do a lick-finger-in-the-air visualization, I implemented Mike Harris s momersion indicator. And then I ran the spread through it. In other words, this spread is certainly mean-reverting at just about all times. And here is the code for the results from 2011 onward, from when the XIV and VXX actually started trading. Here are the equity curves. With the following statistics. In other words, the short side is absolutely amazing as a trade except for the one small fact of having it be impossible to actually execute, or at least as far as I m aware Anyhow, this was simply a for-fun post, but hopefully it served some purpose. Thanks for reading. NOTE I am currently contracting and am looking to network in the Chicago area You can find my LinkedIn here. Post navigation. Financial Mathematics and Modeling II FINC 621 is a graduate level class that is current ly offered at Loyola University in Chicago during the winter quarter FINC 621 explores topics in quantitative finance, mathematics and programming The class is practical in nature and is comprised of both a lecture and a lab component The labs utilize the R programming language and students are required to submit their individual assignments at the end of each class The end goal of FINC 621 is to provide students with practical tools that they can use to create, model and analyze simple trading strategies. Some useful R links. About the Instructor. Harry G is a senior quantitative trader for an HFT trading firm in Chicago He holds a master s degree in Electrical Engineering and a master s degree in Financial Mathematics from the University of Chicago In his spare time, Harry teaches a graduate level course in Quantitative Finance at the Loyola University in Chicago He is also the author of Quantitative Trading with R. The folks at Rstudio have done some amazing work with the shiny package From the shiny homepage, Shiny makes it super simple for R users like you to turn analyses into interactive web applications that anyone can use Developing web applications has always appealed to me, but hosting, learning javascript, html, etc made me put this pretty low on my priority list With shiny, one can write web applications in R. This example uses the managers dataset with calls to and from the PerformanceAnalytics package to display a plot and table in the shiny application. Below is a screenshot of the application. You need to have shiny and Performance Analytics packages installed to run the application Once those are installed, open your R prompt and run. There is a great shiny tutorial from Rstudio as well as examples from SystematicInvestor for those interested in learning more. The past few posts on momentum with R focused on a relatively simple way to backtest momentum strategies In part 4, I use the quantstrat framework to backtest a momentum strategy Using quantstrat open s the door to several features and options as well as an order book to check the trades at the completion of the backtest. I introduce a few new functions that are used to prep the data and compute the ranks I won t go through them in detail, these functions are available in my github repo in the rank-functions folder. This first chunk of code just loads the necessary libraries, data, and applies the ave3ROC function to rank the assets based on averaging the 2, 4, and 6 month returns Note that you will need to load the functions in Rank R and monthly-fun R. The next chunk of code is a critical step in preparing the data to be used in quantstrat With the ranks computed, the next step is to bind the ranks to the actual market data to be used with quantstrat It is also important to change the column names to e g because that will be used as the trade signal column when quantstrat is used. Now the backtest can be run The function qstratRank is just a convenience function that hides the quantst rat implementation for my Rank strategy. For this first backtest, I am trading the top 2 assets with a position size of 1000 units. Changing the argument to gives the flexibility of scaling in a trade In this example, say asset ABC is ranked 1 in the first month I buy 500 units In month 2, asset ABC is still ranked 1 I buy another 500 units. In the previous post, I demonstrated simple backtests for trading a number of assets ranked based on their 3, 6, 9, or 12 i e lookback periods month simple returns While it was not an exhaustive backtest, the results showed that when trading the top 8 ranked assets, the ranking based 3, 6, 9, and 12 month returns resulted in similar performance. If the results were similar for the different lookback periods, which lookback period should I choose for my strategy My answer is to include multiple lookback periods in the ranking method. This can be accomplished by taking the average of the 6, 9, and 12 month returns, or any other n-month returns This gives us the benefit of diversifying across multiple lookback periods If I believe that the lookback period of 9 month returns is better than that of the 6 and 12 month, I can use a weighted average to give the 9 month return a higher weight so that it has more influence on determining the rank This can be implemented easily with what I am calling the WeightAve3ROC function shown below. The function is pretty self explanatory, but feel free to ask if you have any questions. Now to the test results The graph below shows the results from using 6, 9, and 12 month returns as well as an average of 6, 9, and 12 month returns and weighted average of 6, 9, and 12 month returns. Case 1 simple momentum test based on 6 month ROC to rank. Case 2 simple momentum test based on 9 month ROC to rank. Case 3 simple momentum test based on 12 month ROC to rank. Case 4 simple momentum test based on average of 6, 9, and 12 month ROC to rank. Case 5 simple momentum test based on weighted average of 6, 9, and 12 month ROC to rank Weights are 1 6, 2 3, 1 6 for 6, 9, and 12 month returns. Here is a table of the returns and maximum drawdowns for the test. This test demonstrates how it may be possible to achieve better risk adjusted returns higher CAGR and lower drawdowns in this case by considering multiple lookback periods in the ranking method. Full R code is below I have included all the functions in the R script below to make it easy for you to reproduce the tests and try things out, but I would recommend putting the functions in a separate file and using source to load the functions to keep the code cleaner. Many of the sites I linked to in the previous post have articles or papers on momentum investing that investigate the typical ranking factors 3, 6, 9, and 12 month returns Most not all of the articles seek to find which is the best look-back period to rank the assets Say that the outcome of the article is that the 6 month look-back has the highest returns A trading a strategy that just uses a 6 month look-back period to rank the assets leaves me vulnerable to over-fitting based on the backtest results The backtest tells us nothing more than which strategy performed the best in the past, it tells us nothing about the future duh. Whenever I review the results from backtests, I always ask myself a lot of what if questions Here are 3 what if questions that I would ask for this backtest are. What if the strategy based on a 6 month look-back under performs and the 9 month or 3 month starts to over perform. What if the strategies based on 3, 6, and 9 month look-back periods have about the same return and risk profile, which strategy should I trade. What if the assets with high volatility are dominating the rankings and hence driving the returns. The backtests shown are simple backtests meant to demonstrate the variability in returns based on look-back periods and number of assets traded. The graphs below show the performance of a momentum strategy using 3, 6, 9, and 12 month returns and tradin g the Top 1, 4, and 8 ranked assets You will notice that there is significant volatility and variability in returns only trading 1 asset The variability between look-back periods is reduced, but there is still no one clear best look-back period There are periods of under performance and over performance for all look back periods in the test. Here is the R code used for the backtests and the plots Leave a comment if you have any questions about the code below. Time really flies it is hard to believe that it has been over a month since my last post Work and life in general have consumed much of my time lately and left little time for research and blog posts Anyway, on to the post. This post will be the first in a series of to cover a momentum strategy using R. One of my favorite strategies is a momentum or relative strength strategy Here are just a few of the reasons why I like momentum. Simple to implement. Long only or long short portfolios. Many ways to define the strength or momentum measur e. It just works. Also, a momentum strategy lends itself well to potential for diversification The universe of instruments can be infinite, but the instruments traded are finite Think about it this way Investor A looks at 10 instruments and invests 1000 in the top 5 instruments ranked by momentum Investor B looks at 100 instruments and invests 1000 in the top 5 instruments ranked by momentum Investor A is limiting his potential for diversification by only having a universe of 10 instruments Investor B has a much larger universe of instruments and can in theory be more diversified Theoretically speaking, you can trade an infinite number of instruments with a finite amount of trading capital using a momentum or relative strength strategy. Check out these links for further reading. In this first post of the series on momentum, I will go over some of the basic setup and functions we will be using. The first step is to get data from yahoo. Note that the for loop converts the data to monthly and s ubsets the data so that the only column we keep is the adjusted close column We now have four objects XLY, XLP, XLE, XLF that have the Adjusted Close price. The next step is to merge these four objects into a single object holding the Adjusted Close price We can do this in a simple one-liner in R. For the factor that will be ranked, I will use the 3 period rate of change ROC.
Comments
Post a Comment