Wednesday 18 October 2017

Quantstrat Forex Trading


Trading with Bollinger Bands R. The Bollinger Bands będzie ceną akcji W czasach wysokiej zmienności, poszerzają się, podczas gdy w czasach o niskiej lotności, zbliżają się do siebie Więc zasadniczo dostosowują się do ruchu i zmienności rynku Ten filtr o większej lotności jest prawdziwą wartością tego narzędzia. Są dwa warunki, których szukamy w ramach możliwości obrotu. Chcemy kupić pullback w celu wsparcia, gdy rynek jest w trendzie wzrostowym lub sprzedajcie rajd do oporu, gdy rynek jest w trendzie spadkowym Zespoły Bollingera zazwyczaj oferują dobrą oporność i wsparcie dla naszej konfiguracji handlowej, więc po prostu musimy się upewnić, że śledzimy silne pary trendów. Spójrzmy na przykład na wykresie USDCHF Daily Wykresy Wykresów Rynku FXCM 2 0.Wynik jest w górę, jak możemy zobaczyć serię wyższych poziomów i wyższych poziomów niskich, co oznacza szukać zanurzenia w celu wsparcia dolnego pasma dla możliwości zakupowych Mam dwa przykłady zaznaczone na wykresie pierwsze miało miejsce w maju i sekundie odbyło się w czerwcu tego roku Rynek sprzedawał się na niższym pasku Bollinger Band w każdym z przypadków odnotowanych w pudełkach. Niekoniecznie jest to jednak zakup, a raczej tylko sygnał, aby zacząć szukać kupna na odwrocie. Traderzy będą korzystać z różnych metod w celu określenia wpisu, począwszy od używania swojego ulubionego wskaźnika po prostu zakupu, gdy rynek przechodzi przez poprzednie wysokie Jedno popularne podejście polega na zakupie pierwszej świecy, która zamyka się powyżej linii środkowej 20-dniowego Zwykła średnia ruchoma To jest bardziej potwierdzenie odwrotu i zwiększa naszą szansę na sukces w handlu Na powyższym wykresie świecznik kupuje się zieloną strzałką Handlowcy mogą następnie umieścić swój ochronny stop poniżej najniższego knota w pudełku i wygląd za dwukrotne ryzyko w zysku za współczynnik wynoszący 1 2. Chciałbym wspomnieć, że akcje cenowe na USDCHF przesunęły się w dół i dotknęły dolnego pasma Bollingera cztery razy w ciągu ostatnich kilku dni. Oznacza to, że s powinieneś poszukać innej możliwości zakupu. Zamiast kupować teraz teraz, byłby to czas na wykorzystanie twojego podejścia, aby wskazać, że zakup wejścia, aby zwiększyć szanse na sukces w handlu Cena wzrosła od dolnego pasma testowany w zeszłym tygodniu Wykazywał cierpliwość i dyscyplinę i czekał na to, że pierwsze zamknięcie powyżej 20-dniowej prostej Moving Average byłaby sposobem na wejście do tego handlu przy użyciu strategii Bollinger Band, że właśnie dowiedziałem. Nowywszy na rynku walutowym Oszczędź godziny, aby dowiedzieć się co to jest transakcja FOREX? Przetestuj ten darmowy kurs 20 minutowy Kurs FX prezentowany przez DailyFX Education W trakcie omówisz podstawy transakcji FOREX, jaka jest dźwignia i jak ustalić odpowiednią dźwignię dla Twojego trading. Registe r TUTAJ, aby rozpocząć swoją wymianę handlową FOREX. DailyFX dostarcza informacji forex i analizy technicznej na temat trendów, które mają wpływ na globalne rynki walutowe. Ten post wprowadzi autentyczność Pana Johnsona Ehlersa mechanizm oparty na eriodogramie mechanizm zaprojektowany do dynamicznego określania okresu lookbacku Jest to najczęstszy parametr zoptymalizowany pod kątem testów wstecznych to okres zwrotu. Przed rozpoczęciem tego stanowiska muszę udzielić kredytu, jeśli to konieczne, jednemu Fabrizio Maccallini, szefowi strukturyzowanych instrumentów pochodnych na Rynkach Nordea w Londynie Możesz znaleźć resztę repozytorium, które zrobił dla Dr John Ehlers Analytics cyklu dla Handlowców na jego github Jestem wdzięczny i zaszczycony, że takie inteligentne i doświadczone osoby pomagają przynieść niektóre z metod dr Ehlersa do R . Punktem autografii autokorelacyjnej Ehlersa jest dynamiczne określenie okresu między minimalnym a maksymalnym okresem. Podczas gdy ja pozostawię dokładne wyjaśnienie mechanika w książce dr Ehlersa, dla wszystkich praktycznych celów i celów, moim zdaniem, pasklina tej metody polega na próbie usunięcia olbrzymiego źródła nadmiernego dostosowania się do tworzenia systemu handlowego, a mianowicie określenia okresu zwrotu z inwestycji. SMA 50 dni 100 dni 200 dni W ell, ten algorytm ma tę możliwość wyeliminowania Twoich rąk Po prostu określ górną i dolną granicę lookback'u, a resztę robi resztę Jak dobrze to jest temat dyskusji dla osób dobrze zorientowanych metodologii elektrycznych inżynierii Nie jestem, więc czuć się swobodnie pozostawić komentarze, które omawiają, jak dobry algorytm czyni swoją pracę, i niech Cię blog o tym jak dobrze. W każdym razie, o s oryginalny kod algorytmu, dzięki uprzejmości Maccallini. One coś czy zauważyłem, że ten kod używa pętli, która mówi o w filtrze 1 długości, czyli pętli punktów danych O, którą uważam za chorobę w R Kiedy używałem Rcpp wcześniej, to był tylko najbardziej podstawowy pętle, więc jest to zdecydowanie miejsce, w którym algorytm może stać się ulepszony dzięki Rcpp ze względu na nieodłączną pętlę R. Jestem zainteresowanym dokładną logiką algorytmu będzie, po raz kolejny, znajdować ją w raporcie Cycle Analytics Johna Ehlersa dla Handlowców książkę zobaczyć link wcześniej w post. Tak oczywiście pierwszy thi To zrobić, aby sprawdzić, jak dobry algorytm robi to, co zamierza robić, co oznacza dyktowanie okresu lookback'u algorytmu. Jeśli uruchomisz go na niektórych danych. Teraz, jaki jest okres look-up look-up look-up? s w latach 2001-2003, kiedy rynki przeszły przez pewien wstrząs. W tym powiększonym obrazie widać, że szacunki algorytmów wydają się dość jumpy. Oto niektóre z kodów, które podaje szacunki algorytmu n do wskaźnika aby obliczyć wskaźnik z dynamicznym okresem lookboków, ustawionym przez autokorelację okresową Ehlersa. Poniżej znajduje się funkcja stosowana z SMA, aby dostroić się między 120 a 252 dni. Jak widać ten algorytm jest mniej spójny niż chciałbym, przynajmniej jeśli chodzi o korzystanie z prostej średniej ruchomej. Na razie będę opuszczać ten kod i niech ludzie eksperymentują z tym mam nadzieję, że ktoś stwierdzi, że ten wskaźnik jest dla nich przydatny. Cytuj do czytania. NOTES jestem zawsze zainteresowani spotkaniami w północno-wschodnim Filadelfii N YC Ponadto, jeśli uważasz, że Twoja firma skorzysta z moich umiejętności, nie wahaj się do mnie skontaktować Mój linkinowy profil można znaleźć tutaj. Następnie jestem wolontariuszem, aby poświęcić sekcję R dla książek o kwantowości Jeśli masz książkę o R, które mogą mieć zastosowanie do finansów, pamiętaj, aby dać mi znać o tym, aby mogłem go przeanalizować i polecam go Thakn you. This post będzie dogłębnej analizy Alpha Architect s Quantitative Momentum książki Ogólnie, w moim opinia, książka jest wspaniała dla tych, którzy są praktykami w zarządzaniu funduszami w pojedynczym kapitale własnym, i nadal zawiera pomysły warte myślenia o tej przestrzeni. Jednak system opisany w książce przynosi korzyść z zagnieżdżonego rankingu według osi X, top decile, ustawione wzdłuż osi Y w górnej części decilu w X i przyjmują górę decile wzdłuż osi Y, co w zasadzie ogranicza selekcję do 1 wszechświata. Książka ta nie czyni wiele, aby dotknąć elementów zmienności, które mogłyby wzbogacić system znacznie nakreślony. Zanim wejdę do tego stanowiska, chciałbym pozwolić moim czytelnikom wiedzieć, że sformalizowałem moje nakrętki i śruby serii quantstrat postów jako formalne kursy datacamp. Datacamp to bardzo tania sposób, aby nauczyć się grona R, a aplikacje finansowe należą do tych tematów Mój kurs obejmuje podstawowe kwestie dotyczące kwantowania, a jeśli ci, którzy ukończą ten kurs, mogą bardzo dobrze utworzyć bardziej zaawansowane moduły quantstrat na serwerze datacamp Mam nadzieję, że kursy finansowe są dobrze odebrane , ponieważ w RI istnieją tematy finansowe, chcę się nauczyć, że 45 minutowy wykład nie wystarcza, na przykład na punkty magii Dr David Mattesona, na PortfolioAnalytics itd. W każdym razie, tutaj jest link. So, let zaczynają się od podsumowania książki. Część 1 to kilka rozdziałów, które są olbrzymim odkryciem - dlaczego pęd działa lub przynajmniej działa od co najmniej 20 lat od 1993 roku, a mianowicie, że ludzkie uprzedzenia i irracjonalne zachowanie działają w określony sposób anomalii Praca Jest to również ryzyko zawodowe AKA to czynnik ryzyka, a więc jeśli twój benchmark jest SPY i biegnie przez 3-letni okres nieskuteczności, masz poważne ryzyko związane z karierą i zasadniczo całą litanię, dlaczego profesjonalny składnik aktywów menedżer zostanie zwolniony, ale jeśli po prostu trzymasz się anomalii przez wiele wielu lat i przejedźcie przez wiele lat relatywnie niższe wyniki, wyjdziesz naprzód w bardzo długiej run. Generally, I feel like there s pracy należy zrobić, jeśli to najlepsze, co można zrobić, ale w porządku, przyznam się. Część 1 jest dla niewtajemniczonych Dla tych, którzy byli wokół blokady pędów kilka razy, mogą pominąć tę chwilę Niestety, to połowa książka, tak że pozostawia trochę kwaśny smak w ustach. Następne, część druga jest, gdzie, moim zdaniem, prawdziwe mięso i ziemniaki z książki how. Essentially, algorytm można sprowadzić do następujących. Zbiorowanie wszechświata dużych i średnich udziałów, wykonaj następujące czynności: 1 rt zapasy na deciles o 2-12 pędu, czyli na koniec każdego miesiąca, obliczyć moment na podstawie kursu zeszłego miesiąca minus kurs zamknięcia 12 miesięcy temu W zasadzie, badania wskazują, że istnieje efekt odwracania się od 1-miesięcznego tempa Jednak ten efekt nie przenosi się do wszechświata ETF w moim doświadczeniu2. Oto interesująca część, która sprawia, że ​​książka warta samodzielnego wychwytywania według własnego uznania po sortowaniu na decylki, rankingu najwyższej klasy przez kolejne mnożniki znak 2-12 pędu przez następujące równanie negatywne pozytywne pozytywne W zasadzie, idea tutaj jest określenie gładkości pędu Jest to, w najbardziej ekstremalnych sytuacjach, wyobrazić sobie zapas, który nie zrobił nic przez 230 dni, a następnie miał jeden masywny dzień, który dał jej całkowitą aprecjację cen, pomyśl o Google, kiedy miało 10 skoków lepszych od oczekiwań raportów liczbowych, aw drugim skrajnym, zapas, który po prostu miał każdego dnia był mały pozytywny aprecjacja cen Oczywiście, że chcesz drugi typ zapasów To jest ten pomysł Ponownie, sortuj w deciles i weź górę decile Dlatego też, biorąc górę decile top decile pozostawia się z jednego wszechświata zasadniczo to sprawia, że ​​pomysł bardzo trudne do replikacji, ponieważ musisz śledzić masywny wszechświat zapasów, który stwierdził, myślę, że wyrażenie jest w rzeczywistości całkiem dobrym pomysłem jako podstawa dla zmienności. To znaczy, niezależnie od tego, jak zmienny jest aktywa, czy to jako niestabilny jako towar taki jak DBC lub jako nieulotny jako produkt o stałym dochodzie, taki jak SHY, wyrażenie to jest ciekawym sposobem stwierdzenia, że ​​ta ścieżka jest chwiejna, a ta droga jest gładka. Mogę zbadać ten wyraz na moim blogu w przyszłości .3 Wreszcie, jeśli portfel przechodzi kwartał zamiast miesięcznie, najlepsze miesiące na jego odwrót to miesiące poprzedzające koniec miesiąca kwartału, czyli luty, maj, sierpień, listopad, ponieważ wiele amatorskich menedżerów zasobów takich jak do okna dr Ich portfele Mają złe ćwiartki, więc w ostatnim miesiącu, zanim będą musieli wysłać kwartalne oświadczenia, ładują się do niedawnych zwycięzców, aby ich klienci nie uważali się za amatora, tak naprawdę, i tam szaleństwo dla tego Podobnie, styczeń ma pewne sprzedaży anomalie ze względu na utratę podatków zbiorów Jeśli chodzi o praktyczne wdrożenia go, myślę, że to jest bardzo miłe dotyku Przyznając fakt, że zwrotne co miesiąc może być trochę zbyt kosztowne, ja jak to Wes i Jack mówią pewnie, że chcesz cofnąć to co trzy miesiące, ale w jakich miesiącach Jest to bardzo dobre pytanie, aby zapytać, czy oznacza to, że otrzymasz dodatkowy punkt procentowy lub 150 bps rocznie od tego, może pokryć koszty transakcji, a następnie niektóre. Wszystko jest to dość proste do zrozumienia strategii Jednak część tego rodzaju bramek z książki do doskonałej replikacji jest trudność w uzyskaniu CRSP danych. Jednak polecam Alpha Architekt ujawniający t cały algorytm od początku do końca. Poza tym, jeśli podstawowy moment obrotowy w przedziale 2-12 nie wystarcza, znajduje się dodatek, w którym opisane są inne typy momentów pomysłów, zwiększające się do 52 tygodni, absolutny moment historyczny i tak dalej Żadna z tych strategii nie jest tak naprawdę lepsza niż strategia podstawowej dynamiki cenowej, więc są tam dla zainteresowanych, ale wydaje się, że nie ma nic naprawdę przełomowego. Oznacza to, że jeśli sprzedajesz raz w miesiącu, to tylko tak wiele sposobów mówienia hej, myślę, że ta rzecz się skończy. Lubię też, że Wes i Jack doszli do wniosku, że trend poniżej, choć nie poprawia ogólnej CAGR lub Sharpe, robi ogromną kwotę, aby poprawić maksymalny spadek jest, jeśli w obliczu perspektywy utraty 70-80 wszystkiego, a tracąc tylko 30 lat, to jest łatwy wybór, aby trend był dobry, nawet wersja uproszczona. W sumie myślę, że książka osiąga to, co określa poza tym, aby przedstawić dobrze zbadane a algorytm Ostatecznie, punchline znajduje się na stronie Alpha Architektu Myślę, że mają jakiś miesięczny filtr zapasów Ponadto, w książce stwierdzono, że istnieją lepsze zwrotów z uwzględnieniem ryzyka po połączeniu z algorytmem nakreślonym w ilościowej książce wartościowej Z mojego doświadczenia nigdy nie miałem algorytmów wartościowych zaimponować mi w testach backtest I've done, ale mogę kredy, że do mnie jest niedoświadczony ze wszystkimi różnymi metrics. My krytyka książki, jest jednak. Algorytm momentum w książce misses co Czuję, że jest kluczowym czynnikiem wpływającym na zmienność składnika. Po prostu moment, w którym papier objęto moimi hipotezowymi seriami rozwojowymi stanowisk, zasadniczo stwierdza, że ​​zwykła strategia Fama-French jest zdecydowanie lepsza od strategii wynagradzania za ryzyko dzięki delewarowaniu w czasach nadmiernej lotności i unikaniu awarii pędu nie jestem pewien, dlaczego Wes i Jack nie dotknął tego dokumentu, ponieważ wdrożenie jest bardzo prostym celem r zde fi nalizowany współczynnik dźwigni zmienności Uważam, że jeśli Wes lub Jack mogliby mi wysłać strumień powrotu do tej strategii, najlepiej codziennie, ale miesięcznie również działa. Powtarzam, że ta książka jest bardzo obszerna. Myślę jednak, że ma też trochę don nie próbuj tego w domu czuć to ze względu na wymogi dotyczące danych, aby go replikować Z pewnością, jeśli broker obciąża Cię 8 transakcją, nie jest to wykonalna strategia, aby zrezygnować z kilku tysięcy dolarów rocznie na koszty transakcji, które po prostu zwracają się Twój broker Jednak zastanawiam się, czy QMOM ETF z Alpha Architekt jest oczywiście lepszą wersją tej strategii, poza opłatą za zarządzanie. W każdym razie moja ostateczna opinia jest taka, że ​​ta książka pozostawia trochę bit wiedzy na stole, w całości, to, co robi to, jest jasne z jego procedur i oferuje kilka cennych pomysłów Za cenę podręcznika nietechnicznego, aka tych 60 książek na amazon, ta książka jest kradzieże. Czcionki do czytania ing. NOT Podczas gdy jestem obecnie zatrudniony w udanej zdolności analitycznej, jestem zainteresowany wysłuchaniem o stanowiskach pełnoetatowych ściśle związanych z tematami na tym blogu Jeśli masz pełnoetatową pozycję, która może skorzystać z moich obecnych umiejętności, proszę daj mi znać, że moja Linkedin można znaleźć tutaj. Ten post będzie polegał na próbie używania pakietu Depmix do przewidywania stanu online Podczas gdy pakiet depmix jest godny podziwu, jeśli chodzi o opisywanie stanów przeszłości, przy jednokrotnym wprowadzeniu przewidywania, przy założeniu, że jutro stan będzie identyczny z dzisiejszym stanem rzeczy, ukryty model markowa, który znajduje się w opakowaniu, nie spełnia oczekiwań. Zacznijmy od tego, że ten post był motywowany przez Michaela Hallsa-Moore'a, który niedawno wysłał jakiś kod R dotyczący używania biblioteki depmixS4 do używania ukrytych modeli markov Ogólnie nie chcę tworzyć postów na tematy Nie czuję, że mam całkowite zrozumienie front-to-back, ale robię to w nadziei lear ning od innych, w jaki sposób odpowiednio przewidzieć stan przestrzeni kosmicznej w trybie online lub wykrywanie przełączania reżimu, ponieważ można to nazwać bardziej finansową wypowiedzią. Chociaż widziałem zwykłą teorię ukrytych markowych modeli, to znaczy, że może padać lub może być słoneczny dzień, ale można tylko wywnioskować, że pogoda dociera do ubrania, które widzisz na noszach poza oknem, kiedy się obudzisz i pracowałeś z przykładami zabawek w jeździe samochodowej MotoCs Udacity z własnym samochodem, jeśli dobrze sobie przypominam, a może to był kurs AI, pod koniec dnia, teoria jest tak dobra, jak skuteczność może działać na rzeczywistych danych. Na tym eksperymencie zdecydowałem się na podjęcie danych SPY od początku i wykonać pełną próbę wyników w teście na danych Oznacza to, że algorytm HMM z depmiksu dostrzega całą historię powrotu, przy czym ten widok wzroku boga, czy algorytm prawidłowo sklasyfikuje reguły, czy wyniki testów backtest są wskazaniami. Oto kod do tego inspirowane przez dr Halls-Moore'a sE aczkolwiek ja wybrałem trzy stany, zauważyłem, że cokolwiek z przecinkami powyżej zera jest stanem byka, a poniżej zera jest stan opatrznościowy, więc zasadniczo zmniejsza się do dwóch stanów. Z wynikiem. So, a nie szczególnie straszne algorytm działa, rodzaj swego rodzaju, dobrze. Pozwól nam spróbować przewidywania online. Więc co zrobiłem, wzięłam rozwinięcie okna, począwszy od 500 dni od założenia SPY, i dalej rośnie, o jeden dzień w a moja prognoza, była, trywialnie za późno, ostatnim dniem, używając 1 dla stanu byka, a -1 dla stanu niedźwiedzia uruchomiłem ten proces równolegle na klastrze linuksowym, ponieważ biblioteki doParallel w systemie Windows nie wydaje się nawet wiedz, że niektóre pakiety są załadowane, a to bardziej niechlujne, a pierwszym dużym problemem jest to, że proces ten trwał około trzech godzin na siedmiu rdzeniach przez około 23 lata danych. Niekoniecznie zachęcające, ale czas obliczeniowy nie jest tania w dzisiejszych czasach. niech s zobaczyć, czy ten proces rzeczywiście works. First, niech s test jeśli algorytm doe co to jest faktycznie zrobione i użycie jednego dnia przekuwającego się uprzedzenia, czyli algorytm mówi nam stan pod koniec dnia, jak prawidłowe jest nawet dla tego dnia. Z wynikiem. So, rzekomo, algorytm wydaje się robić to, co zostało zaprojektowane, aby sklasyfikować stan dla danego zbioru danych Teraz najważniejsze pytanie, jak dobrze przewiduje się nawet jeden dzień naprzód Myślisz, że przewidywania przestrzeni stanów byłyby oszczędne z dnia z dnia na dzień, biorąc pod uwagę długą historię, correct. With result. That jest, bez prześwitu orientacji, statek kosmiczny algorytm przewidywania jest okropny Dlaczego tak. Najtem, o to stan stanów. W skrócie, hmm online algorytm w pakiecie deplikacji wydaje się bardzo łatwo zmienić jego umysł, z oczywistymi negatywnymi konsekwencjami dla rzeczywistych strategii handlowych. Więc to, że owija to do tego postu Zasadniczo główną przesłanką jest tu ogromna różnica między ładowaniem dokonującym analizy opisowej AKA, dlaczego tak robiłeś co się dzieje z predykcyjną analizą, która jest, jeśli poprawnie przewiduję przyszłość, dostaję dodatnie wynagrodzenie Moim zdaniem, chociaż statystyka opisowa ma swój cel, wyjaśniając, dlaczego strategia mogła się odbyć tak, jak to robi, w końcu zawsze szukamy lepsze narzędzia do przewidywania W takim przypadku, przynajmniej w tej demonstracji, nie wydaje się, aby depmix nie był narzędziem. Jeśli ktoś miałby powodzenie przy użyciu depmiksu lub innego algorytmu przełączania reguł w R, aby przewidzieć, Chciałbym zobaczyć pracę, która szczegółowo opisuje procedurę, ponieważ jest to obszar, w którym chcę rozszerzyć swoją skrzynkę na narzędzia, ale nie mam żadnych szczególnych dobrych przodków. Zasadniczo chciałbym myśleć o tym poście, jak ja opisując moje własne doświadczenia z pakietem. Dzięki za przeczytanie. NOTE 5 października będę w Nowym Jorku W dniu 6 października będę prezentować się na wystawie Trading Show na panelu Programming Wars. Usłona Moja obecna umowa analityczna jest do sprawdzenia na końcu roku, więc oficjalnie szukam dla innych ofert Jeśli masz pełnoetatową rolę, która może korzystać z umiejętności widocznych na moim blogu, skontaktuj się ze mną Mój linkin profilu można znaleźć tutaj. Ten wpisz wprowadzi warunek warunek wartości warunkowej mechaniki ryzyka w PerformanceAnalytics z artykułu napisanego przez Petera, Petera Krisa, Petera Carla Jest to mechanizm, który jest łatwym w obsłudze mechanizmem obliczania spodziewanego niedoboru składowych składowych aktywów w odniesieniu do portfela Podczas gdy dokładna mechanika jest dość złożona , wzrost jest taki, że czas biegu jest niemal natychmiastowy, a ta metoda jest solidnym narzędziem włączenia analizy alokacji aktywów. Dla zainteresowanych pogłębioną analizą intuicji wartości warunkowej elementu zagrożonego, odsyłam do nich papier napisany przez Briana Petersona, Petera Carla i Kris Boudta. Założeniem tego jest, że wszystkie aktywa w danym portfelu mają marginalny wkład w całkowitą wartość warunkową zagrożoną tak zwaną oczekiwaną niedobór, czyli oczekiwana strata, gdy strata przekracza określony próg Na przykład, jeśli chcesz poznać 5 spodziewanego niedoboru, to jest to średnia z najgorszych 5 zwrotów na 100 dni i tak dalej Dla zwrotu przy użyciu rozdzielczości dziennej, idea spodziewanego niedoboru może brzmieć tak, jakby nigdy nie było wystarczająco dużo danych w wystarczająco szybkim przedziale czasowym w ciągu jednego roku lub krócej, formuła oczekiwanego niedoboru w PerformanceAnalytics domyślnie oblicza przybliżenie przy użyciu rozszerzenia Cornish-Fisher, który zapewnia bardzo dobre wyniki, dopóki wartość p nie jest zbyt wysoka, to znaczy, że działa dla względnie zdrowych wartości p, takich jak wartość wariancji warunkowej wartości zagrożonej 1 -10 wynosi dwa razy, przy braku obciążenia wejściowego, stosuje taką samą wagę domyślnie, co pozwala na oszacowanie ryzyka dla każdego indywidualnego składnika aktywów bez obciążania badacza, aby utworzyć własną heurystyczną korelację korelacji Po drugie, po dostarczeniu zestawu ciężarów, t zmiany odzwierciedlające wkład różnych aktywów proporcjonalnie do wagi Oznacza to, że ta metodologia działa bardzo dobrze z takimi strategiami, które wykluczają aktywa na podstawie tempa, ale potrzebują schematów ważenia pozostałych aktywów. Ponadto, przy użyciu tej metodologii, po analizie wkładu ryzyka, aby zobaczyć, które instrumenty przyczyniły się do tego, co ryzykowne. Przede wszystkim demonstruje sposób działania mechanizmu przy użyciu zestawu danych edhec Nie ma tu strategii, tylko demonstracja składni. Przyjmie to wkład równy od wszystkich środków w zestawie danych edhec. Tak tmp jest wkładem w oczekiwany niedobór każdego z różnych menedżerów edhec przez cały ten okres. Oto wynik. Najważniejszą częścią tego jest procentowy wkład ostatniej informacji wyjściowej Zauważ, że może być negatywne, co oznacza, że ​​niektóre fundusze zyskają, gdy inne stracą Przynajmniej miało to miejsce w obecnym zestawie danych Te aktywa dywersyfikują portfel i faktycznie niższe oczekiwany niedobór. W tym przypadku równoważiłem dziesięć pierwszych menedżerów w zestawie danych edhec i zerowy ciężar w ciągu ostatnich trzech Ponadto możemy zobaczyć, co się dzieje, gdy odważniki nie są równe. Na tym czasie zauważmy, że jako ciężar wzrosła w konwerterze arb menedżera, a więc również przyczynił się do maksymalnego oczekiwanego niedoboru. W przypadku przyszłych testów wstecznych, chciałabym podać pewne wnioski o dane, które chciałbym wykorzystać we wszechświecie znalezionym w księdze Global Asset Allocation tej firmy, która mówi, że symulacje w tej książce powraca do 1972 r. i zastanawiałem się, czy ktoś tam ma dzienne zyski za te indeksy aktywów Podczas gdy niektóre ETF wracają na początku lat 2000. Są takie, które zaczynają się raczej późno, jak na przykład towary DBC, na początku 2006 r., złoto GLD , na początku 2004 r., obligacje zagraniczne BWX, pod koniec 2007 r., i FTY NAREIT, na początku 2007 r. Jak osiem lat testów byłby nieco krótki, zastanawiałem się, czy ktoś ma dane z większą historią. pokaz handlowy i rozmowy panel programowania wojny w dniu 6 października. Dziękuję za przeczytanie. UWAGA Podczas gdy jestem obecnie kontraktująca, szukam także stałej pozycji, która może skorzystać z moich umiejętności, gdy zakończy się obecna umowa. Jeśli masz lub jesteś świadomy takiego otwarcia, Z przyjemnością porozmawiam z Tobą. Ten post będzie obejmował funkcję ułatwiającą tworzenie strategii przywracania wartości Harry Long od SeekingAlpha dla zainteresowanych czytelników, jak stwierdził Harry Long, większość, jeśli nie wszystkie jego strategie są bardziej dla celów demonstracji, a nie rzeczywistych rekomendowane inwestycje. Ponieważ Harry Long publikuje kilka artykułów na temat Seeknig Alpha, miałem czytelnika lub dwóch, poprosić mnie o analizę jego strategii ponownie Zamiast tego robię, po prostu będę po prostu umieścił to narzędzie, które jest opakowanie, które automatyzuje gromadzenie danych i symuluje reimansowanie portfela jednym wierszem kodu. Oto narzędzie. Pobiera dane dla Ciebie zazwyczaj z Yahoo, ale wielkie podziękowania dla Helumtha Vollmeiera w sprawie z ZIV i VXX oraz ma możliwość wyświetlenia krzywej kapitału własnego, a niektóre statystyki CAGR, roczne standardowe dev, Sharpe, maks. rozbieżenie, Calmar lub podanie strumienia zwrotnego jako wyjścia, jeśli chcesz przeprowadzić więcej analizy w R Oto przykład prostego gromadzenia danych statystycznych, a 80 XLP SPLV są mniej lub bardziej wymienne i 20 TMF aka 60 TLT, więc 80 60 portfela, z jednego z artykułów Harry Long. Nic niezwykłego możemy oczekiwać od zrównoważonego portfela obligacji skarbowych Ogólnie dobrze, ma największe wycofanie z kryzysu finansowego i inne wstrząsy na drodze, ale generalnie myślę, że dość waniliowa i zapomnieć o tym rodzaju rzeczach. A tutaj byłby sposobem na uzyskanie strumienia indywidualnych dziennych zysków, przy założeniu, że zamiast corocznie zmieniać te dwa instrumenty, zamiast rocznie, tak jak jest to domyślne. A teraz niech się trochę statystycznie. nie mają znaczącego wpływu tutaj, poza tym, aby zarobić na brokera, jeśli uwzględniasz koszty transakcji, co nie robi. Tak więc, jak to działa. Wyniki oczywiście zaczynają się od ostatniego uruchomienia instrumentu. Podstęp, moim zdaniem , jest próba znalezienia zamienników proxy o dłuższych historiach dla nowszych ETF, które są po prostu ulepszonymi ETF, np. przy użyciu wagi 60 w TLT z 80 ciężarami w XLP zamiast 20 w TMF z 80 przydziałami w SPLV. Na przykład, Oto kilka proksies. SPXL XLP SPXL UPRO SPY 3 TMF TLT 3. To powiedziałem, wcześniej pracowałem z Harrym Longem i rozwijał bardziej skomplikowane strategie za kulisami, więc zalecam, aby czytelnicy SeekingAlpha przyjął publicznie wydane strategie jako koncepcję demonstracje, w przeciwieństwie do w pełni rozwiniętych pomysłów inwestycyjnych i skontaktuj się z panem Longiem o bardziej dostosowane, prywatne rozwiązania dla instytucji inwestycyjnych, jeśli jesteś tak zainteresowany. Dziękuję za przeczytanie. NOTAZNIE jestem obecnie na północny wschód Podczas gdy obecnie jestem kontraktem ng, jestem zainteresowany tworzeniem sieci z osobami lub firmami w odniesieniu do potencjalnych możliwości współpracy. Ten post pokaże, jak wziąć pod uwagę obroty podczas przetwarzania danych zwrotnych przy użyciu PerformanceAnalytics i funkcji w R Wykaże to w oparciu o podstawową strategię w odniesieniu do dziewięciu sektorów SPDRs. So, po pierwsze, jest to odpowiedź na pytanie postawione przez Roberta Wages na liście dyskusyjnej R-SIG-Finance Podczas gdy istnieje wiele osób, które mają wiele pytań, z których wiele można znaleźć które mają zostać pokazane na tym blogu już od czasu do czasu, będzie okazjonalnie weteranem w przemyśle, stypendystą z Stanford lub inną bardzo inteligentną osobą, która zadałby pytanie na temat, na który jeszcze nie dotknęłem tego bloga, co skłoni post do wykazania innego technicznego aspektu znalezionego w R To jest jedna z tych chwil. Więc ta demonstracja będzie dotyczyła obliczania obrotów w przestrzeni zwracanej przy użyciu pakietu PerformanceAnalytics S implikuje, poza pakietem PortfolioAnalytics, PerformanceAnalytics z jego funkcją jest pakietem przejściowym R do symulacji zarządzania portfelami, ponieważ może przybrać zestaw odważników, zestaw zwrotów i generować zestaw zwrotów z portfolio do analizy z resztą funkcji PerformanceAnalytics. Co więcej, strategia polega na tym, że trwa trzydzieści sześć sektorów SPDR, ponieważ istnieją obecnie czteroliterowe ETF, a pod koniec każdego miesiąca, jeśli cena skorygowana przekracza 200-dniową średnią ruchową, zainwestuj do tego Normalizuj we wszystkich zainwestowanych sektorach, tj. 1 9, jeśli zainwestowano w sumie 9, 100 na 1, jeśli tylko 1 zainwestowało do 100 środków pieniężnych, oznaczonych wektorem zerowym zwrotem, jeśli nie zainwestowano w nią sektorów, ponieważ strategia nie jest punktem demonstracji. Tutaj jest podstawowym kodem konfiguracji. Więc, weź SPDR, umieść je razem, obliczyć ich zwrot, wygenerować sygnał i utworzyć wektor zerowy, ponieważ traktuje wagi mniej niż 1 jako wycofanie, i wagi powyżej 1 jako dodajemy więcej kapitału o dużym znaczeniu FYI tutaj. Teraz tu chodzi o obliczanie obrotów. Tak, to jest to, kiedy używasz opcji verbose TRUE To tworzy kilka obiektów, wśród nich zwraca, a te oznaczają Początek Okresu, i Koniec okresu Waga. Liczba obrotów obliczana jest po prostu różnicą między sposobem, w jaki dzień powraca z powrotem przenosi przydzielony portfel z poprzedniego punktu końcowego na miejsce, w którym portfel rzeczywiście znajduje się na początku następnego okresu Oznacza to, że waga okresu końcowego jest początkiem dryfu okresowego po uwzględnieniu zwrotu z tytułu bieżącego dnia dla tego składnika Nowy początek okresu jest wagą okresu końcowego wraz z wszelkimi transakcjami, które zostałyby wykonane W celu znalezienia rzeczywistych transakcji lub obrotu, jeden z nich odejmuje poprzedni koniec okresu od początku wagi. Jakie są tego typu transakcje dla tej strategii. Coś, co możemy zrobić z tymi danymi, to roczne obroty co oznacza, że ​​roczne obroty dwukierunkowe to znaczy, że sprzedaż zupełnie zainwestowanego portfela to 100 obrotów, a zakup zupełnie nowego zestawu aktywów to kolejne 100, a następnie obroty dwukierunkowe wynoszą 200 na maksymalnie 800 To może być dość wysokie dla niektórych osób. Teraz, gdy chodzi o aplikację, gdy nakładasz kary za koszty transakcji w wysokości 20 punktów bazowych na procentowy punkt obrotu, to znaczy, że kosztuje 20 centów do transakcji 100. Tak więc, w 20 punktach bazowych na kosztach transakcji, które zajmują około jednego procenta zysku rocznie z tej, co prawda, strasznej strategii Jest to znikome. Tak, to w jaki sposób rzeczywiście obliczasz obroty i koszty transakcji W tym przypadku transakcja 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 2017 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 2017 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, 2017 , 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, 2017, 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.

No comments:

Post a Comment