суббота, 12 мая 2018 г.

John ehlers trading system


Melhor comerciante do sistema.


Better System Trader é o podcast e o blog dedicado a comerciantes sistemáticos, fornecendo dicas práticas de especialistas em comércio em todo o mundo.


048 & # 8211; Indicadores, DSP & # 038; Ciclos com John Ehlers.


O comércio pode ser difícil, os mercados são barulhentos e encontrar sinais no mercado, o ruído pode ser um desafio. Além disso, a aplicação de indicadores para estratégias de negociação pode trazer atraso, no entanto, muitos comerciantes nem sequer percebem o atraso que seus indicadores estão introduzindo ou o impacto que ele pode ter na negociação. Na verdade, o convidado em nossa conversa hoje, John Ehlers disse que "um dos maiores inimigos dos comerciantes é o atraso".


Então, qual a solução?


John Ehlers é bem conhecido na arena de futuros de commodities como o Criador da MESA, tendo sido pioneiro no método MESA de análise do ciclo no final de 1970 e se tornou o fundador do software MESA.


Ele é autor de quatro livros, incluindo Rocket Science for Traders, Cycle Analytics for Traders, Cybernetic Analysis for Stocks and Futures e MESA e Trading Market Cycles.


Ele também tem sido um editor contribuinte de Stocks & amp; Commodities, ganhando uma série de prêmios por seu trabalho.


Na nossa conversa com John, discutimos a questão do atraso nos indicadores, o impacto que pode ter sobre o comércio e algumas soluções. Também falamos sobre aplicações de processamento de sinal digital na negociação, abordagem MESA, mudança de regime, ciclos e os erros que as pessoas fazem nos ciclos de negociação.


Tópicos discutidos.


MESA e sua aplicação para negociação Alternativas para a abordagem MESA e qual é o melhor para os mercados Como o comprimento do ciclo pode determinar o comprimento do indicador Erros comuns que as pessoas fazem com os ciclos Ciclos e técnicas de DSP como filtros de regime Os problemas causados ​​pelo atraso do indicador e soluções para reduzir o atraso O Melhor filtro de baixo nível e oscilador disponível Começando com Ciclos e DSP.


Recursos mencionados neste episódio.


Para saber mais sobre John e seu trabalho, faça o check-out do website do mesassoftware. Também pode ser contatado no ehlers @ mesasoftware. Livros mencionados no show:


Workshop de Desenvolvimento do Sistema de Negociação de Ciclos MESA.


Como John mencionou no final do nosso bate-papo, ele realizará uma oficina exclusiva de 3 dias sobre técnicas de Processamento de Sinal Digital e Ciclos na negociação.


Desde conceitos básicos até técnicas avançadas, incluindo código para uma série de estratégias de negociação, John vai compartilhar todas as suas pesquisas.


Ele mesmo vai divulgar os segredos por trás do algoritmo MESA, juntamente com o código, que ele NUNCA fez antes! (você será obrigado a assinar um NDA)


Este é um evento único e os números são limitados devido ao tamanho do local, então se você estiver interessado, verifique a página de informações da oficina clicando na caixa azul abaixo.


Transcrição.


Tem uma pergunta, tópico ou convidado que deseja ver no podcast?


Você tem uma pergunta específica, tópico ou convidado que você gostaria de ver em um futuro episódio de podcast?


Clique aqui e envie sua sugestão para ter a chance de apresentá-lo em um próximo episódio de podcast.


Inscreva-se no Better System Trader e nunca perca outro episódio!


Por favor, suporte o podcast, dando uma classificação / revisão honesta para o show no iTunes!


Episódio Lançado:


Posts Relacionados.


Apenas começando?


Finalmente, acabar com a frustração e a confusão de começar na negociação do sistema.


Breakout Trading.


Obtenha este relatório GRATUITO sobre '7 Dicas comprovadas para criar estratégias de Breaking rentáveis ​​rapidamente'


Saiba como iniciar a criação de estratégias de desdobramento rentáveis ​​em menos de 2 semanas - sem gastar mais de 35 minutos por dia.


Você está procurando uma solução comprovada para CUT DRAWDOWNS e melhorar significativamente o desempenho de suas estratégias de negociação?


O que pro comerciantes estão falando sobre o BST.


"Profissional, até o ponto e conteúdo relevante. O Better System Trader deve ser seguido por qualquer pessoa interessada em nosso campo".


"Andrew é um mestre em fazer perguntas difíceis e relevantes".


"Ouvir BST é um requisito para todos na nossa equipe".


"Recebo algumas das minhas melhores idéias de ouvir outros participantes do mercado e Better System Trader é um ótimo recurso de conversas com comerciantes profissionais".


"Eu realmente gosto de ouvir os podcasts do Better System Trader. Mesmo que eu esteja na indústria há mais de 15 anos, sempre há algo de novo a aprender com isso. Obrigado!"


"O Better System Trader é um recurso inestimável que recebi enormes quantidades de informações ao longo dos anos. Eu não seria o comerciante que estou hoje sem ter encontrado esse recurso. Mantenha o ótimo trabalho".


"Este podcast fornece informações exclusivas, de comerciantes reais, entrevistados por um comerciante experiente".


"Os podcasts do Better System Trader tornaram-se um recurso inestimável. Não há nenhum outro podcast em torno do que cobre o assunto em tanta amplitude e profundidade".


"As perguntas certas para as pessoas certas no momento certo".


"Se você estava procurando por esse pequeno nugget extra para transformar sua negociação, você vai encontrá-lo no Better System Trader".


"Se eu tivesse que ouvir apenas um podcast comercial, seria o Better System Trader. Estou sempre aprendendo coisas novas e obtendo idéias de pesquisa dos convidados de Andrew".


"Convidados experientes e confiáveis ​​falam sobre tópicos úteis em uma discussão interessante e envolvente. O que não gosta?"


"O que realmente faz com que o podcast do BST se destaque é que Andrew também é um comerciante experiente e, portanto, pode fornecer qualidade e profundidade incomparáveis ​​em qualquer entrevista. Obrigado por uma infinita inspiração".


"Andrew parece ter uma habilidade para obter os comerciantes mais famosos do mundo para compartilhar informações valiosas sobre como eles comercializam para o benefício da comunidade comercial".


"Eu realmente gosto da grande variedade de tópicos e perspectivas compartilhados nos podcasts e com as entrevistas feitas por alguém com experiência comercial real"


"Andrew ama os comerciantes e desenha as respostas mais informativas e envolventes deles".


"Andrew entrevistou algumas pessoas fantásticas e recebi alguns novos conceitos úteis. Sua integridade, conhecimento comercial, atitude alegre, curiosidade e entusiasmo brilham e melhoram cada um dos seus podcasts. Dada a qualidade da informação e do preço ( livre!) qualquer comerciante sério teria que ser um tolo para não aproveitar. Mantenha meu amigo ".


A negociação de ações, opções, futuros e divisas envolve um risco significativo de perda e não é adequado para todos. O desempenho passado não é necessariamente indicativo de resultados futuros.


Oh sim! Não se esqueça dos nossos serviços!


Incluindo algumas coisas excelentes GRATUITAS.


Serviços personalizados: enquanto meus produtos são projetados e destinados a ser o comerciante auto-dirigido, se você precisar de uma vantagem, posso ajudar!


MESA Lifetime Support (FREE!)


Você possui sua licença para MESA Phasor ou MESA Intraday, ao contrário dos sistemas de negociação oferecidos pela assinatura. Isso significa que eu fico atrás dele 100%, incluindo atualizações gratuitas (se aplicável) e suporte vitalício.


Coaching StockSpotter (GRÁTIS)


Estou com prazer em oferecer um treinamento individualizado do StockSpotter para você. Esta é uma excelente maneira de otimizar os recursos do StockSpotter para suas necessidades comerciais e estilo.


Documentos técnicos e amp; Seminários (GRÁTIS!)


Você tem acesso total aos meus documentos técnicos e seminários PPT slides. Estes são basicamente relatórios de pesquisa para ajudá-lo a manter-se atualizado sobre as últimas descobertas de análise técnica.


Suporte MESA (GRÁTIS!)


Às vezes você só precisa de um empurrão para fazer você passar de um lugar que você não entende. Sobretudo, há conforto e segurança, sabendo que estou aqui para apoiá-lo.


Coaching StockSpotter (GRÁTIS)


O StockSpotter tem uma série de ferramentas para ajudar com a negociação de ações, que vão desde indicadores de configuração de swing até relatórios transparentes de resultados. Posso ajudar a organizar apenas as ferramentas que você precisa.


Documentos técnicos e seminários (GRÁTIS!)


Para os tecnicamente inclinados, estou encantado de compartilhar minhas pesquisas avançadas com você.


Por que a experiência é importante!


O que os meus colegas dizem!


"É refrescante encontrar novas idéias em um negócio que se tornou tão competitivo e muitas vezes preenchido com variações nos mesmos temas".


Algo mais meus colegas dizem!


"Se John Ehlers escreveu, eu leio. Ele é tão brilhante".


Palavras amáveis, pessoas gentis!


"John Ehlers classifica com Art Merrill como o melhor analista técnico quantitativo do vigésimo e, provavelmente, do século XXI"


Ainda mais de meus colegas!


"John é uma daquela rara raça de analistas que mergulha no porquê e na forma de coisas e não na abordagem superficial frequentemente utilizada".


AVISO LEGAL.


A negociação de curto prazo envolve RISCOS ALTA e VOCÊ PODE PERDER muito dinheiro. Não arrisque nenhum dinheiro que você não pode perder. A negociação de curto prazo não é adequada para todos os investidores. Não somos consultores de investimentos registrados. Nós fornecemos pesquisa quantitativa impessoal. Não oferecemos consultoria de negociação ou de investimento. As informações aqui contidas não devem ser consideradas uma solicitação para comprar ou vender qualquer garantia ou se envolver em uma estratégia de investimento específica. Os resultados de desempenho são hipotéticos e todos os negócios são simulados. O desempenho passado não é necessariamente indicativo de resultados futuros. O uso deste site constitui aceitação dos Termos desta Disclaimer.


Sobre a nossa empresa.


O software MESA é especializado na análise de dados de mercado no domínio da frequência. Tomamos a abordagem científica no desenvolvimento de filtros, indicadores e sistemas de negociação e, em seguida, usamos estatísticas para verificar o desempenho.


QuantStrat TradeR.


Comércio, QuantStrat, R e muito mais.


Arquivos da categoria: Dr. John Ehlers.


Ehlers & # 8217; s Autocorrelation Periodogram.


Esta publicação irá introduzir o mecanismo de Periodograma de Autocorrelação do John Ehlers & # 8217; # 8211; um mecanismo projetado para encontrar dinamicamente um período de lookback. Ou seja, o parâmetro mais comum otimizado em backtests é o período de lookback.


Antes de começar esta publicação, devo dar crédito em relação ao Sr. Fabrizio Maccallini, chefe de derivativos estruturados da Nordea Markets em Londres. Você pode encontrar o resto do repositório que ele fez para o Dr. John Ehlers's Analytics de Ciclo para Traders em seu github. Sou grato e honrado que indivíduos tão inteligentes e experientes ajudem a trazer alguns dos métodos do Dr. Ehlers em R.


O ponto do Periodograma de Autocorrelação Ehlers é definir dinamicamente um período entre um comprimento de período mínimo e máximo. Enquanto eu deixo a explicação exata do mecânico para o livro do Dr. Ehlers, para todas as intenções práticas, na minha opinião, o punchline deste método é tentar remover uma fonte maciça de superação da criação do sistema de negociação e # 8211, especificando um período de lookback.


SMA de 50 dias? 100 dias? 200 dias? Bem, esse algoritmo leva essa possibilidade de superação de suas mãos. Simplesmente, especifique um limite superior e inferior para o seu lookback, e ele faz o resto. Quão bem faz isso é um tema de discussão para aqueles bem versados ​​nas metodologias de engenharia elétrica (I & # 8217; m não), então sinta-se livre para deixar comentários que discutem o quão bem o algoritmo faz o seu trabalho e sinta-se livre para blog sobre isso também.


Em qualquer caso, aqui é o código do algoritmo original, cortesia do Sr. Maccallini:


Uma coisa que eu aviso é que este código usa um loop que diz para (i in 1: length (filt)), que é um loop O (pontos de dados), que eu vejo como a praga em R. Enquanto I & # 8217; Já usou o Rcpp antes, ele foi apenas para os loops mais básicos, então este é definitivamente um lugar onde o algoritmo pode ser melhorado com Rcpp devido ao loop insuficiente inerente de R & # 8217 ;.


Aqueles interessados ​​na lógica exata do algoritmo, mais uma vez, encontrarão no livro Ciclo analítico para comerciantes de John Ehlers & # 8217; veja o link anterior na publicação).


Claro, a primeira coisa a fazer é testar o quão bem o algoritmo faz o que pretende fazer, o que é para ditar o período de lookback de um algoritmo.


Deixe-o executá-lo em alguns dados.


Agora, como o período de lookback do algoritmo-set parece?


Deixe o zoom aumentar em 2001 até 2003, quando os mercados passaram por alguma agitação.


Nesta imagem ampliada, podemos ver que as estimativas do algoritmo parecem ser bastante nervosas.


Aqui é algum código para alimentar as estimativas do algoritmo de n em um indicador para calcular um indicador com um período de lookback dinâmico conforme estabelecido pelo períodoograma de autocorrelação de Ehlers & # 8217;


E aqui está a função aplicada com um SMA, para sintonizar entre 120 e 252 dias.


Como visto, esse algoritmo é menos consistente do que eu gostaria, pelo menos quando se trata de usar uma média móvel simples.


Por enquanto, eu vou deixar este código aqui e deixar as pessoas experimentarem isso. Espero que alguém ache que esse indicador seja útil para eles.


Obrigado pela leitura.


NOTAS: Estou sempre interessado em redes / encontros no nordeste (Philadelphia / NYC). Além disso, se você acredita que sua empresa se beneficiará das minhas habilidades, não hesite em contactar-me. O meu perfil associado pode ser encontrado aqui.


Por fim, sou voluntário para curar a seção R para livros sobre a importância. Se você tem um livro sobre R que pode se candidatar a financiamentos, não deixe de me informar sobre isso, para que eu possa revisá-lo e possivelmente recomendá-lo. Thakn você.


Um oscilador John Ehlers & # 8212; Ciclo RSI (2)


Uma vez que eu acertei uma rotina na tendência seguinte (como você quantifica o aumento / queda / plano? O que até mesmo define esses três termos em definição precisa da máquina? Como você evita comprar tops enquanto não está sendo cortado por whipsaws?), Eu decidi olhar para o outro lado, com osciladores. Certamente, eu não estou pronto para desistir do Dr. Ehlers ainda. Então, nesta publicação, apresentarei uma inovação recente do RSI pelo Dr. John Ehlers.


O indicador é o RSI modificado por Dr. Ehlers & # 8217; do Capítulo 7 do Cycle Analytics for Traders.


Para iniciantes, aqui é como o Ehlers RSI é diferente dos habituais: ele é filtrado com um filtro passa-alto e depois suavizado com um filtro supersmoother. Enquanto Michael Kapler também abordou este assunto há algum tempo, eu acho que não pode machucar se eu tentei tocá-lo sozinho.


Aqui está o filtro de passagem alta e o super smoother, do arquivo utility. R em DSTrading. Eles não são exportados desde o momento, eles são simplesmente componentes de outros indicadores.


Em poucas palavras, ambas as funções servem para fazer um alisamento exponencial nos dados usando algumas quantidades trigonométricas calculadas estaticamente, cuja fundamentação simplesmente me adiantarei para o livro do Dr. Ehlers (link aqui).


Aqui, os ehlers modificados RSI, que eu chamo CycleRSI, do livro no qual ele definiu:


Aqui é uma imagem que compara quatro RSI separados.


O primeiro é o RSI apresentado nesta publicação (ciclo RSI) em azul. O próximo é o RSI básico (2) em vermelho. Aquele depois é o Connors RSI de Larry Connors, que pode ser abordado no futuro, e o último, em roxo, é o Laguerre RSI generalizado, que é mais uma vez a criação do Dr. Ehlers (que I & # 8217 ; terei que testar em algum momento no futuro).


Para começar as coisas com o Cycle RSI, eu decidi jogar uma estratégia simples em torno disso:


Compre quando o CycleRSI (2) cruza abaixo de 10 quando o fechamento está acima do SMA200, que está na veia de uma estratégia de negociação de Larry Connors a partir de & # 8220; Estratégias de Negociação ETF de curto prazo que funcionam & # 8221; (se eles trabalham ou não permanecem discutíveis), e vendem quando o CicloRSI (2) cruza acima de 70, ou quando o fechamento cai abaixo do SMA200 para que a estratégia não fique presa em uma tendência de queda desenfreada.


Uma vez que a estratégia vem de uma ETF Trading, decidi usar o meu antigo conjunto de dados ETF, de 2003 a 2018.


Aqui, o código da estratégia, como de costume:


E aqui estão os resultados:


No geral, as estatísticas não parecem ruins. No entanto, os retornos anualizados de 1: 1 para a redução máxima não são particularmente agradáveis, pois isso significa que essa estratégia pode ser efetivamente alavancada para continuar obtendo retornos exagerados nesse estado. Muito irritante. Aqui é a curva de equidade.


Em suma, como acontece com outros vencedores médios, quando os levantamentos acontecem, eles ocorrem de forma relativamente rápida e brutal.


Aqui é um gráfico de posição de instrumento individual.


Pelo aspecto das coisas, a estratégia é melhor em um mercado que motiva para cima, ao invés de um mercado paralelo completamente agitado.


Finalmente, aqui é algum código para traçar todos os diferentes negócios.


E a trama resultante:


Uma última coisa a notar # 8230: esse comércio de $ 50,000 no canto superior esquerdo? Esse era um problema de dados do Yahoo e é uma impressão falsa. Além disso, mais uma vez, isso parece uma tarifa padrão para um reverter e # 8211, quando os negócios são ruins, eles realmente são ruins, mas o enigma de onde parar é uma questão completamente diferente, já que geralmente significa bloquear muitas perdas que diminuem em magnitude, juntamente com possivelmente girando vencedores em perdedores. Do outro lado, aqui é o gráfico de excursão máximo favorável.


Em suma, definitivamente há negócios que poderiam ter sido interrompidos para um lucro que se transformou em perdedores.


Em conclusão, enquanto o sistema comercial inicial parece ser um bom começo, está longe de ser completo.


Obrigado pela leitura.


Outra Volatilidade Desaparecida Histeresis: Ehlers & # 8217; S Own Idea.


Esta semana, tentei usar a ideia da Ehlers & # 8217's nessa apresentação.


Essencialmente, a idéia é que quando um indicador é plano, os cruzamentos de linha podem produzir whipsaws, então adicione uma fração do alcance diário ao indicador defasado e veja se o indicador não retardado cruza o limite. Neste caso, é um intervalo diário exponencialmente alisado que usou para calcular as bandas. Eu corri isso de 2018 até o presente no momento desta escrita (14 de julho de 2018), como o link original passa pela maioria dos anos 2000. (Além disso, certifique-se de usar o meu pacote IKTrading mais atualizado, pois atualizei a função QuandClean para lidar com alguns problemas de dados confusos intraday que passaram despercebidos antes).


As configurações que usei foram as configurações originais de John Ehlers & # 8217; ou seja, um período de análise de 20 dias, um suavização de banda exponencial de 10 dias (ou seja, a banda é calculada como banda .1 * (alta-baixa) + .9 *), inserida na porcentagem B (ou seja, a corrente FRAMA menos a faixa baixa sobre a diferença das bandas), e a fração é 1/10 da faixa diária.


Aqui, o indicador utilizado é:


E aqui é o código da estratégia:


Aqui estão os resultados:


Em suma, é um perdedor nos últimos três anos. Aqui, a curva de equidade:


Agora, embora possa ter funcionado no passado (ou algo parecido com isso, usando o indicador de filtro de Ehlers & # 8217;), não parece fazer isso em frente.


I & # 8217; deixarei isso aqui por enquanto como uma demonstração de como fazer as bandas Ehlers.


Obrigado pela leitura.


Volatilidade Histeresis: uma primeira tentativa.


Assim, a última vez que uma estratégia de FRAMA foi tentada com crossovers de preços, o problema era que, devido a falhas contra-tendências, o filtro que foi adicionado perdeu muitas boas negociações e acabou perdendo muito dinheiro em mercados planos que passaram o filtro arbitrário.


Esse sistema de negociação tenta corrigir essas questões ao negociar um FRAMA crescente, filtrado em uma taxa de desvio padrão de 5 dias.


A hipótese é a seguinte: o FRAMA sobe em mercados legitimamente tendenciosos e permanece imóvel em mercados agitados. Portanto, a proporção de desvios padrão (isto é, um desvio padrão correto do FRAMA em relação ao desvio padrão do fechamento do mercado) deve ser maior durante os mercados de tendências e menor durante os mercados agitados. Além disso, à medida que esta proporção termina em zero e, geralmente, é superior a 1 (raramente fica mais alta), ela pode ser usada como um indicador através de instrumentos de propriedades muito diferentes.


Os dados que serão utilizados serão o arquivo de dados futuros (sem fundos federais, café ou açúcar, devido a problemas de dados).


Aqui está o arquivo de dados:


Aqui está a estratégia:


Observe que a saída devido ao filtro de volatilidade teve que ter sido comentada (pois causou que a estratégia perca toda a sua vantagem). Em qualquer caso, o FRAMA é o habitual FRAMA de 126 dias e o desvio padrão de execução é de 5 dias, a fim de tentar reduzir o atraso. O limite da taxa de desvio padrão será de 0,2 ou superior. Aqui estão os resultados:


Em outras palavras, os resultados típicos do seguidor da tendência. 40/60 errado para a direita, com um índice de perda para perda de 2: 1. Longe de ser espetacular.


Em suma, os vencedores duram mais do que os perdedores, o que faz sentido dado que há muitos whipsaws e que esta é uma estratégia de tendência.


38%. Então, como ele funcionou?


Como isso. Não particularmente excelente, considerando-se um ganho de 60% ao longo de 11 anos. Aqui estão as estatísticas específicas:


Em outras palavras, cerca de 10 pontos base de retorno por por cento da exposição ao mercado, ou um retorno anual de 10%. O problema é? A redução é muito maior do que o retorno anualizado, o que significa que alavancagem só piorará as coisas. Basicamente, pelo baixo retorno da exposição e alta redução do retorno anualizado, essa estratégia é uma falha. Embora a curva de equidade constante e ascendente seja boa, não tem sentido quando as piores perdas levam mais de um ano para se recuperar.


Em qualquer caso, aqui é um olhar sobre alguns instrumentos individuais.


Aqui é a curva de equidade para o E-minis.


Então, primeiro, podemos ver uma pequena característica desta estratégia, uma vez que a entrada e a saída não são simétricas (ou seja, é preciso duas condições para inserir um FRAMA crescente e uma razão de desvio padrão acima de .2 & # 8211; e apenas sai em um deles (queda de FRAMA), a ação de preço que exibe uma moagem constante para cima, devido à rápida mudança de ATR (é uma figura de 10 dias) pode, na verdade, ser ligeiramente piramidal de tempos em tempos. Este é um bom recurso na minha opinião, uma vez que pode adicionar-se a uma posição vencedora. No entanto, em tempos de extrema volatilidade, quando mesmo um indicador adaptativo pode ser rebaixado em torno da perseguição e # 8220; mini-tendências & # 8221 ;, podemos ver as perdas se acumulam.


Em seguida, vamos ver uma situação muito pior. Aqui, a curva de equidade para o spread Eurodollar / TED.


Nesse caso, é claramente visível que a estratégia tem problemas de contra-tendência, bem como o fato de que a taxa de desvio padrão de 5 dias pode ser relativamente miope quando se trata de instrumentos que possuem períodos prolongados de inatividade completa e # 8211; Ou seja, o mercado nem sequer é agitado, assim como ainda.


Vou deixá-lo aqui, e passar para outras tentativas de contornar esse tipo de roadblock em seguida.


Obrigado pela leitura.


FRAMA Parte V: Conclusão no Indicador de Confirmação / Amostra de Teste.


Portanto, é possível criar um sistema comercial que possa isolar corretamente as desacelerações severas e prolongadas, sem tomar (demais) sinais falsos.


Aqui estão as regras:


126 dias FRAMA, FC = 4, SC = 300 (ainda estamos modificando a estratégia original ETFHQ).


Uma mediana de corrida (em algum lugar entre 150 dias e 252 dias e # 8211, aparentemente, todas essas configurações funcionam).


Tanto o FRAMA como a mediana de confirmação devem estar se movendo na mesma direção (para um longo comércio, para baixo para um curto comércio, a ascensão mediana é a nova regra aqui), e o preço deve atravessar o FRAMA nessa direção para entrar em um comércio, enquanto saia quando o preço cruza abaixo do FRAMA. Apresentado como um conjunto de regras de quantstrat, fica bastante longo, uma vez que uma regra precisa especificar as três condições de configuração, uma regra para vinculá-las e uma regra de saída (5 regras de cada lado).


A estratégia funciona em fins longos e curtos, embora a versão curta parece mais uma estratégia de seguro do que qualquer outra coisa. Aqui, a curva de equidade para uma mediana de 150 dias:


Basicamente, ganha dinheiro em períodos terríveis, mas dá algo de volta durante quase qualquer outro momento. Está lá apenas para colocá-lo lá fora, como algo que finalmente pode tentar isolar as condições verdadeiramente desprezíveis e dar-lhe um pop naqueles tempos. Além disso? Usá-lo dependeria da frequência com que alguém acredita que esses tipos de condições de retirada ocorressem, ou seja, um indicador adaptativo descendente, uma medição descendente de 7 a 12 meses.


Aqui estão as estatísticas de comércio e portfólio:


Em outras palavras, não é absolutamente uma estratégia autônoma, mas mais um pouco para dar um impulso a uma estratégia de longa duração durante os maus momentos. Certamente, não é tão espetacular quanto é. Por exemplo, aqui a curva de equidade para XLK no final de 2008-2009. Principalmente, o problema com a estratégia do ETFHQ (I & # 8217; m ainda sobre isso, sim) é que não leva em consideração a magnitude da direção do indicador. Isso significa que, em um mercado reversível, essa estratégia pode perder uma grande quantidade de dinheiro desnecessariamente.


Basicamente, essa estratégia é altamente conservadora, o que significa que ela tem uma tendência a perder boas negociações, tomar desnecessárias e geralmente é falho porque não tem como realmente estimar a inclinação do FRAMA.


Como a solução possível para isso envolve uma estratégia de John Ehlers, acho que I & # 8217; deixarei essa estratégia aqui por agora.


Então, para enviar esta estratégia de cruzamento de preço original da ETFHQ fora, eu testarei isso fora da amostra usando uma mediana de 200 dias, usando lados longos e curtos (a partir de 2018-03-01 para obter a mediana de 200 dias queimada em, até a data atual no momento da redação, 2018-06-20).


Aqui estão as estatísticas comerciais e as estatísticas do portfólio:


Com a curva de equidade correspondente:


Em suma, definitivamente não é bom. Por quê?


Aqui é um bom sintoma de por que:


Esta é a curva de ações fora da amostra de SHY & # 8211, ou seja, o ETF de títulos de curto prazo. A tendência terminou, mas o sistema de negociação não se retirou disso.


Neste caso, você pode ver que a magnitude da tendência não faz diferença para a estratégia # 8211, que é um grande problema. Embora o comércio de contra-tendências tenha sido eliminado, forçando a ação não era, e tentando permanecer leal ao preço que atravessava a estratégia do indicador, mantendo-se a métodos mais convencionais (um indicador de confirmação) se revela falho. Aqui está outro sintoma lateral de um sistema defeituoso:


Neste caso, usar um indicador de confirmação tão conservador para o curto comércio e simplesmente usar esse mesmo indicador para o lado longo indica que pode haver muito superação no sistema. Em uma nota mais geral, no entanto, esta imagem faz pensar se um indicador de confirmação era mesmo necessário. Por exemplo, houve certamente períodos prolongados durante os quais houve uma longa tendência que foi interrompida devido à média de corrida ser ligeiramente negativa. Houve ocasiões longas e curtas.


Na minha opinião, acho que isso coloca o kibosh em algo como um ator de mão como um indicador confirmatório de longa duração. Por quê? Porque eu acho que ele corrige demais para um sistema de lógica de ordem defeituosa que não leva em consideração a magnitude da inclinação do indicador. Obviamente, negociar em uma contra-tendência (indicador descendente) é uma idéia terrível. Mas e quanto a uma ligeira mudança de sinal direcional como parte de uma contra-tendência maior? De repente, um indicador de confirmação robusto e deliberadamente retardado já não parece uma idéia tão ruim. No entanto, como você pode ver, a desvantagem de um indicador de atraso é que pode muito bem atrasar seu indicador primário em uma boa parte dos casos. E não faz nada para eliminar o comércio paralelo.


Certamente, existe uma solução mais elegante que tenta quantificar o fato de que às vezes, o FRAMA suave e ainda adaptável pode avançar rapidamente (e esses negócios devem ser postos em uso), e também podem ficar planas. Em última análise, acho que, embora as configurações do indicador do ETFHQ tenham algum mérito, a lógica da ordem simplista por conta própria pode certamente machucar e # 8211; juntamente com uma função de dimensionamento de pedidos que diminui as ordens em tempos de tendência, ampliando-as em tempos de calma (um efeito colateral da ATR, que foi criado para igualar o risco em todos os instrumentos, mas com a conseqüência não desejada de não compensar o risco em condições de mercado) pode causar problemas.


A próxima estratégia tentará corrigir esses problemas.


Obrigado pela leitura.


FRAMA Parte IV: continuando a Pesquisa de Filtro Longo / Curto.


Esta publicação examina um filtro mediano de nove dias para duas propriedades desejáveis: robustez a outliers e uma tendência inerente de confirmação. Embora este seja um filtro incompleto (ou talvez até mesmo inferior), ele oferece algumas idéias fundamentais para melhorar o sistema de negociação.


A estratégia será assim:


Em primeiro lugar, esta será uma estratégia de curto prazo, devido ao longo período de tempo dentro do período de amostra, de modo que o teste de estresse do sistema será tentar capturar a tendência não-dominante (e somente quando apropriado).


Aqui a estratégia: continuaremos a usar o mesmo FRAMA de 126 dias com a constante rápida ajustada em 4 e uma constante lenta em 300 (isto é, pode oscilar em qualquer lugar entre um EMA4 e EMA300). Só entraremos em uma posição curta quando este indicador estiver descendo, abaixo da mediana de 126 dias da ação de preço e quando a ação de preço for menor que esse indicador (geralmente isso significa uma cruz, e não em todos os casos). Nós sairemos quando a ação de preço subir de cima do indicador.


Aqui está a estratégia no código R:


Os resultados não são bonitos, o que significa que o filtro ainda está incompleto. Aqui estão as estatísticas comerciais:


Neste ponto, por uma questão de brevidade, deixarei as curvas de equidade e as estatísticas de portfólio (eles, obviamente, serão ruins). No entanto, vamos ver algumas imagens do que exatamente está acontecendo com os negócios individuais.


Aqui está a curva de equidade full-backtest e indicadores correspondentes para XLP. O FRAMA está em roxo, com a mediana de 126 dias em laranja, juntamente com a ATR de 10 dias (atrasada por dia) na parte inferior.


E aqui podemos ver imediatamente certas propriedades:


1) O tamanho da ordem do ATR não é um tipo de ordem de fim-de-dia final. Foi criado para um propósito, que é igualar o risco em todos os instrumentos (a ideia original do qual, eu adoro o artigo de Andreas Clenow & # 8217; s). No entanto, essa é apenas uma base para começar, usando outros procedimentos de dimensionamento de ordem dimensionados que podem tentar quantificar a confiança em qualquer comércio específico. Como está atualmente, para estratégias curtas em ações, as melhores oportunidades acontecem nas profundezas da rápida queda de ação de preço, durante a qual ATR aumentará. Pode-se considerar aumentar a função de dimensionamento da ordem ATR para realizar esta tarefa (ou simplesmente aplicar alavancagem no momento adequado, através da modificação do parâmetro pctATR).


2) Enquanto a mediana de corrida certamente tem valor como um filtro para evitar negociações obviamente sem cérebro (por exemplo, no meio de uma tendência de alta), uma vez que o FRAMA atravessa a mediana, qualquer coisa pode acontecer, pois a única lógica é que o FRAMA atual é apenas ligeiramente inferior ao dia anterior # 8217; s. Isso pode significar que a própria mediana de execução ainda está subindo, ou que o FRAMA é efetivamente plano, e o que está sendo negociado é puramente ruído. Além disso, com o dimensionamento da ordem ATR ampliando as conseqüências desse ruído, esse caso de borda pode ter conseqüências desastrosas em uma curva de equidade.


Aqui é um zoom em 2005, onde vemos uma redução bastante severa (séries de séries de gráficos recolhidas para clareza).


Como pode ser visto, mesmo que o FRAMA pareça aumentar ligeiramente, um cruzamento de preços quando o FRAMA é menor do que o dia anterior, até mesmo uma quantidade invisivelmente pequena (compare o roxo & # 8211; o FRAMA, o vermelho e o # 8211; mesma quantidade atrasada por dia) é suficiente para desencadear um comércio que irá comprar um número considerável de ações, mesmo quando a volatilidade é muito pequena para justificar esse comércio. Essencialmente, a maioria das perdas neste sistema de negociação surge como resultado da negociação durante esses períodos planos durante os quais o sistema tenta forçar a ação.


Esse padrão se repete. Aqui está a curva de equidade para XLB.


Novamente, além de talvez um comércio ruim no final, graças a qualquer negociação sendo tomada uma vez que as três condições se alinham (diminuindo FRAMA, FRAMA inferior à mediana, preço inferior ao FRAMA) muito tarde devido a uma relação FRAMA / mediana plana, a maioria dos os perdedores parecem ser feitos por meio de uma ação de mercado muito plana e calma, mesmo quando a mediana de corrida pode estar indo na direção oposta do FRAMA, durante o qual a função de dimensionamento de ordem ATR tentou forçar a ação. Um segundo filtro que serve para capturar essas situações de caixa de borda (ou talvez um filtro que substitua a mediana de execução inteiramente) será investigado no futuro.


Então, para recapitular esta publicação:


O filtro mediano de corrida é um indicador intrinsecamente retardado, mas robusto, escolhido deliberadamente para essas duas propriedades. É capaz de filtrar negócios que obviamente vão contra a tendência. No entanto, devido a alguns casos de ponta, ainda havia uma grande quantidade de perdas que foram incorridas, o que afogou a oportunidade de curto prazo durante esse período de amostragem. Este é um problema que precisa ser endereçado.


Obrigado pela leitura.


FRAMA Part III: Avoiding Countertrend Trading — A First Attempt.


This post will begin to experiment with long-term directional detection using relationships between two FRAMA indicators. By observing the relationship between two differently parametrized FRAMAs and the relationship by virtue of the ATR, it will be possible to avoid counter-trend trading on both sides. We will see this example later:


As with TVI, when the signals and rules were swapped for the short end, the equity curve was an unmitigated disaster. Unlike the flat-during-bull-runs-and-permanently-popping-up equity curve of ETFHQ, this equity curve was a disaster. For those that read the final TVI post, the equity curve looked almost identical to that–just a monotonous drawdown until the crisis, at which point the gains aren’t made up, and then the losses continue. In short, there’s no need to go into depth of those statistics.


As the link to ETFHQ suggests, we will use a longer-term FRAMA (the n=252, FC=40, SC=252 version). The market will be in an uptrend when the fast FRAMA (the FRAMA from the previous post) is above this slower FRAMA, and vice versa. Furthermore, in order to avoid some whipsaws, the fast FRAMA will have to be ascending (or descending, during a downtrend), and the entry signal will be when the price crosses over (under) the faster FRAMA, with the exit being the reverse.


In the interest of brevity, since the sample period was an uptrend, then a great deal of strategies will look good on the upside. The question is whether or not the strategy does well on the short side, as the litmus test in testing a confirming indicator is whether or not it can create a positive expectation in a strategy that is counter-trend to the dominant trend in the sample data. As this is a replication of an implied idea by ETFHQ (rather than my own particular idea), let’s look at the code for the strategy. In this instance, both the long and short end of this symmetric strategy are included, and in RStudio, commenting or uncommenting one half or the other is as simple as highlight+ctrl+shift+C.


First, a quick little side-note: since many indicators look for the word “low”, my usage of the label “slow” would cause a bug if I added the lagATR indicator after that point. So try to avoid labels such as “high”, “low”, “open”, and “close” in your indicators, or at least declare all indicators that would look for the word “low” before declaring the indicator you label in part as “slow”, if you must go this route. Low is probably the easiest one for which to overlook this, since “slow” has so many applications to confirmatory indicators. (EG: SMA fast vs. SMA slow, etc.)


Again, to reiterate, the system will take a long position when price crosses over (under) a rising (falling) fast FRAMA that’s higher (lower) than the slow FRAMA, and exit that position when the price crosses back under (over) the fast FRAMA. The cross must happen when the other two conditions are intact, as opposed to a trade being entered when all three conditions come together, which may be in the middle of a trend.


As the majority of the sample data was in an uptrend (and the fact that the Andreas Clenow-inspired ATR order-sizing function pays enormous dividends in protecting for a limited time in a counter-trend), I decided to put the (slightly modified–with the one condition of rising in an uptrend or falling in a downtrend) system to the test by testing it on the non-dominant trend in the sample–that is, to see if the system can stay out at all points aside from the crisis.


Here are the (not-so-flattering) results:


In other words, we can already see that the proposed confirmatory indicator is a dud. To display the raw instrument daily stats at this point would also be uninteresting, so we’ll move past that.


Basically, we can see that there are some really long trades that win, but between this table and the previous trade stats output, that is more than swamped by the legions of losers. Here is the market exposure:


In other words, even though the market exposure is rather small, the system still manages to hemorrhage a great deal during those small exposures, which does not sing many praises for the proposed system.


Here is the code for a cash sharpe and the equity curve comparisons:


Which gives us the following results:


In short, the idea of using a “slower” FRAMA does not seem to hold much water. And here are the portfolio statistics to confirm it:


For that, we’ll look at a picture of the equity curve of an individual instrument, complete with overlaid indicators.


Which produces the following plot:


The primary indicator is in purple, while the confirmatory indicator is in orange. And now we see the reason why: because although the FRAMA (n=252, FC=40, SC=252) is a seemingly fine parametrization in and of itself, as a “big-picture/long-term-trend/greater smoothing” indicator, it does not seem like the best choice, at least in the conventional sense as using something such as the SMA200, ROC200 > 0, or RS Rank (see this post from SystemTraderSuccess).


Por quê? Because from my intuition, adaptive moving average indicators all aim to do the same thing–they aim to be a more accurate way of aggregating lots of data in order to tell you what is happening to as close as current time as they can get. That is, if you look at the presentation by Dr. John Ehlers (see this link), you’ll notice how similar all of the indicators are. All of them effectively aim to maximize near-term smoothness and eliminate as much lag as possible. That is, if you’re looking to make short-term momentum trades that last five days, if your indicator has a five-day lag (EG a 10-day running median), well, your indicator isn’t of much use in that case, because by the time you receive the signal, the opportunity is over!


However, while eliminating lag is usually desirable, in one case, it isn’t. To go off on a tangent, the Japanese trading system called Ichimoku Kinko Hyo (which may be investigated in the future), created by Goichi Hosoda, deliberately makes use of lagging current price action to create a cloud. That is, if you want a confirmatory indicator, you want something robust (especially to the heightened volatility during corrections, bear markets, downtrends, etc.), and something that *has* a bit of lag to it, to confirm the relationship between the more up-to-date indicator (E. G. an adaptive moving average, a short-term oscillator such as RSI2, etc.), and the overarching, long-term trend.


The failure to do so in this case results in problematic counter-trend trades before the financial crisis. While the trading during the financial crisis had a very choppy equity curve during the height of the crisis itself, this was for an individual instrument, and note, that by the end of the crisis, the strategy had indeed made money. The greater problem was that due to the similarities in kind of the confirmatory indicator with the one used for entries and exits, then occasionally, the confirmatory indicator would overtake the indicator it was supposed to confirm, even in a sideways or upwards market, which resulted in several disastrous trades.


And while the indicator used for entries and exits should be as up-to-date as possible so as to get in and out in as timely a fashion as possible, a confirmatory indicator, first and foremost, should not reverse the entire system’s understanding of the market mode on a whim, and secondly, should try to be more backward looking, so as to better do its job of confirmation. Thus, in my opinion, the recommendation of this “slower” FRAMA to be used as a confirmatory indicator by ETFHQ was rather ill-advised. Thus, the investigation will continue into finding a more suitable confirmatory indicator.


Obrigado pela leitura.


FRAMA Part II: Replicating A Simple Strategy.


This post will begin the investigation into FRAMA strategies, with the aim of ultimately finding a FRAMA trading strategy with less market exposure, fewer whipsaw trades, and fewer counter-trend trades. This post will also introduce new analytics regarding trade duration.


To begin the investigation into developing strategies based on the previously-introduced FRAMA, I’m going to replicate the simple strategy from ETFHQ — use a 126 day FRAMA with a fast constant of 4 (that is, an EMA that goes as fast as a 4-day EMA), and all the way up to a slow constant of 300. For my ATR order-sizing, which, once again, was inspired by Andreas Clenow in the post on leverage being pointless, I’m going to use 2 percent of notional capital, with a 10 day ATR for my order sizing (ATR 20 and 30 display slightly weaker results, but nevertheless, are very close in performance).


Once again, let’s start by looking at the strategy, using our same 30 instruments as with our TVI demos (I thought about testing on mutual funds, but due to the obnoxious fees that mutual funds charge for trying to trade with them, I feel that I’d have to employ too much magical thinking to neglect their obscene trading transaction costs):


It’s a fairly simple strategy–buy the next day’s open when the price crosses above the indicator, and vice versa. In other words, it’s about as simple a strategy as you can get as its sole purpose was to demonstrate the effectiveness of the indicator. And while someone interested can peruse through ETFHQ to find all of the indicator relative tests, the general gist is that adaptive moving averages work very well, and the FRAMA (the fractal adaptive moving average) works slightly better than the rest. Ultimately though, if one believes ETFHQ’s analysis (and I do), then even one good trend-following indicator will be sufficient.


Here are the trade statistics:


And the aggregate trade statistics:


Far from spectacular. Less than 50% hit rate, the profit factor definitely indicates that there is massive room for improvement as well.


Here are the daily statistics:


Now, I’d like to introduce some new analytics found in my IKTrading package–namely, trade duration statistics. This is a simple little function that breaks down the trades by duration, in aggregate, winners, and losers, using the usual five-number summary and the mean time. It’s programmed under the assumption that the units are days. Once you start drilling into more frequent trading, one would likely need a bit more refined analysis. However, as most freely available data occurs at the daily frequency, this function should be sufficient for most analyses.


Here is the input and output for this strategy:


From top to bottom in this transposed table (or left to right in the original), we have aggregate trade duration statistics, the same statistics on winners, and finally, losers. This paints a picture of this current strategy as having a profile of a classic trend follower: let your winners run, and cut your losses. Or, to set it to a higher standard, the occasional winner at the price of plenty of small whipsaws, with the occasional long-duration loser. Note that this loser may not have been a loser the entire time–it could very well have been a trade that was going sideways for a long time and finally sunk into negative territory near the end, but it seems that every instrument has had at least one somewhat long-running trade that wound up losing at least a penny.


On the winning side of the trade, the winning trades stay in the market for long berths, with the best ones riding waves that last for around half a year. Ultimately, this is the appeal of trend following–the idea of just getting in once, and just having the market pay you. The goal of investigating the FRAMA (and potentially other trend indicators), is to try and locate those long profit waves while avoiding the whipsaws, countertrends, and so on.


One other interesting piece of analytics I’m incorporating into this demo is the idea of market exposure–or what percentage of the time that the strategy is actually *in* the market. Here is the code and the results:


Essentially, this little piece of code takes advantage of the daily statistics output to compute market exposure. Here’s the output:


So basically, around 60-66% of the time spent in the market, most of which are short, sporadic, losing trades, with the occasional long winner.


Here’s what the equity curve looks like:


As can be seen during the crisis, this baseline strategy is taking lots of trades…for no reason at all.


And here are the three aggregate portfolio statistics:


The largest drawdown occurs during the crisis, but beyond that, the annualized returns are solid. What I find most impressive is that the annualized Sharpe Ratio over the course of this backtest, even with what seems to be a period of drawdowns that can be removed with what seems to be relative ease (most market timing trend-followers seem to do a decent job of avoiding most of the brunt of the crisis).


And finally, to demonstrate the indicator and investigate areas for improvement, here’s the equity curve of XLF (not XLB this time), since XLF lost eight dollars over the course of the backtest.


One advantage that I think the FRAMA has over the Trend Vigor is that as it is an indicator that’s superimposed directly on the price action, it’s easier to understand visually. (Also, the math is definitely more intuitive.) As we can see from the XLF equity curve, the base strategy presented by ETFHQ could certainly use a confirmatory, slower-moving indicator to keep out counter-trend trading. After all, while the tiny little whipsaw trades are undoubtedly a nuisance, correcting counter-trend trading is a lower-hanging fruit, and would seem to be more profitable in addressing.


Obrigado pela leitura.


The Continuing Search For Robust Momentum Indicators: the Fractal Adaptive Moving Average.


Following from the last post and setting aside the not-working-as-advertised Trend Vigor indicator, we will turn our attention to the world of adaptive moving averages. In this case, I will be working with the FRAMA–the FRactal Adaptive Moving Average. The reason I am starting off with this one is that according to ETFHQ in this post, FRAMA is an indicator that seems to have very strong performance, even using what definitely seems to be a very simple strategy (long if the price crosses over the indicator, exit vice versa), which would most likely leave one open to whipsaws.


But before then, I’d like to make an introduction to the FRAMA, by linking to the original Dr. John Ehlers paper, here.


While I won’t attempt to give a better formal explanation than the man that created the indicator (which is why the paper is there), the way I intuitively think about the FRAMA (or the adaptive moving average family of indicators, found here) is that they are improvements of the exponential moving average that attempt to smooth the indicator during cyclical market periods to avoid whipsaws, and to have a faster response during periods of strong trends, so as to minimize the damage done due to an ending trend.


The FRAMA itself compares two periods of n/2 days (the last n/2 days, and the last n/2 days before those last n/2 days) to the total period (n days). Intuitively, if there is a straight trend upwards, then the expression (log(N1+N2)-log(N3))/log(2), where N1 is the difference of highest high and lowest low over the last n/2 days and N2 is identical except for the previous n/2 days before the last n/2 days, and N3 is the same quantity over all n days, will be equal to zero, and thus, the exponent of that would be equal to 1, which is analogous to an EMA of 1 day. Similarly, when there is a great deal of congestion, then the expression log(N1+N2) will be greater than log(N3), and so the exponent (that is, the fractal dimension) of the exponent would be closer to 2 (or greater, since I implemented the modified FRAMA).


Let’s look at the code:


Essentially, from the second chunk of code, this is an advanced form of the exponential moving average that takes into account the amount of movement over a greater time period relative to the swing at two finer intervals in the two halves of that period. The methodology for the modified FRAMA is thanks to ETFHQ (once again), found here.


And while words can make for a bit of explanation, in this case, a picture (or several) is worth far more. Here is some code I wrote to plot an EMA, and three separate FRAMA computations (the default John Ehlers settings, the best ETFHQ settings, and the slower ETFHQ settings) on XLB from 2003 through 2018 (yes, the same XLB from our Trend Vigor backtest, because it was the go-to instrument for all our individual equity curves).


This produces the following plot:


From this perspective, the improvements are clear. Essentially, the long-term FRAMA (FC 40, n 252, SC 252) possesses much of the smoothness of the 126 day EMA, while being far more responsive to the turns in price action to keep open equity at the end of a trend. The two faster FRAMAs, on the other hand, hug the price action more closely, yet still retain a degree of smoothness.


Here’s the code to zoom in on 2007-2008.


And, the corresponding plot.


Here, we can see some more properties. While the default John Ehlers settings (blue) seemingly tracks price action very closely, the indicator usually finds itself right in the middle of the price action, but still has the occasional trend following property when price action breaks through it at the start of the financial crisis. In other words, it seems that it can hurt you both as a trend follower (whipsaws), and as a mean reverting indicator (as seen when XLB starts falling in the crisis), so this gives rise to the idea that an indicator can track the price too well.


On the other hand, the 126 day FRAMA (the ETFHQ settings, in green) seems to look like a dynamic support and resistance indicator that the talking heads go on and on about (yet give very little advice on how to actually objectively compute), in that the price action seems to touch it every so often, but not oscillate around it. It breaks in one direction and manages to stay in that direction, until it breaks in the other direction, and sustain a move to that direction. This seems like a foundation of a future trading strategy.


Finally, the 252 day FRAMA (the ETFHQ settings for the long-term FRAMA indicator, in red) looks like a confirmatory indicator or filter.


Notice that by comparison, the 126 day EMA seems to lag as much if not more than the 252 day FRAMA, and from this vantage point, it seems that the results are not as good for the same amount of data processed.


Overall, it seems that by trading off smoothness and responsiveness, one can see the foundations of a possible system.


The potential trading systems here will be explored in the future.


Obrigado pela leitura.


Trend Vigor Part IV: Shorting and Walk Forward Test.


While Trend Vigor has potential on the long end (as seen in part III of this investigation here), as Andreas Clenow has stated in his article “Trend Following Does Not Work On Stocks”, the short side of trend following gets killed in equities. And, since by far and away most of the securities in this backtest were equity-based ETFs (most of the ones available before 2003 were equity index ETFs), the results can basically be summed up as “buying insurance for Black Swans”. On the plus side, Trend Vigor at very high period settings (longer than 120) is able to capture some of the upside from being short in the depths of the financial crisis, but unfortunately gives most of it back.


To begin, here’s the code for this strategy, starting off at the previous settings of a period of 20 and delta 0 with ATR order sizing. The demo data has slightly changed in that the initialization, from, and to parameters are now found in the demo scripts, rather than the file itself, which, as a result, is no longer a standalone file.


And here is the output:


So, already, we can see that it’s pretty much a bloodbath–namely because throughout 2003 through 2018, the general trend was upwards, and also, because of the use of constant ATR order sizing, when the moves are largest (during the heightened volatility), our position size is smallest, relative to it. Which isn’t to say that this is a particularly bad idea considering that a short position can get whipsawed badly, but that such a short-term detection system has no sense of the overall larger trend.


Here are some more portfolio statistics.


In other words, this strategy simply costs you an annualized 4% a year, just to get the pop-up during the financial crisis, and then proceed to give that all back to the market anyway. In other words, it’s a really silly form of insurance, especially considering that due to the heightened volatility in times of extreme crisis, the ATR order sizing function *already* functions as a massive hedge. For the sake of completeness, here’s the equity curve of this strategy.


And here’s the usual equity curve of XLB.


Note that just when all the blood is in the water, the ATR order-sizing function actually works *against* the strategy. This is due to the fact that with equities, that are bought in the expectation of price appreciation as an investment (rather than, say, a commodity, whose prices need to fluctuate, and whose price appreciation perhaps means adverse consequences outside of the investment universe, or an exchange rate, which is by nature long in one instrument, short another, so may not be marked by severe volatility to the downside), and thus, trends to the upside are more sustained, while moves to the downside happen much more quickly, and by the time there is “sufficient evidence” (at any level of evidence) of a move to the downside, the largest part of the move already happened, and it’s much more likely that a short trade would get whipsawed for a loss.


If the other extreme is tried–that is, a more conservative delta parameter (.1), and a much larger period (greater than 120 days, to attempt to implement this more as a filter, in this case, 140), these are the results:


The NaN means that one or more of the instruments had so few trades that there were no losers (most likely 1 or 2 trades that just so happened to get lucky), E. G. XLU had 1 trade.


Again, nothing worth writing home over. Even after I tried several different settings (for instance, if the delta parameter is too high, most of the move to the downside in the crisis will be missed, and any profit will get consumed by the recovery, and then some), when the best result barely breaks even in a once-in-a-lifetime crisis, and so many other configurations either bite too easily on minor dips in an uptrend, or the converse, are too afraid to enter even in a once-in-a-lifetime opportunity, it’s best to not even try to fit this square peg into a round hole, and just not even think about trying Trend Vigor on the short end in equities.


For the record, here’s the equity curve.


So even when the indicator gets the once-in-a-lifetime black swan opportunity, it still manages to do little noteworthy. To put it into perspective, let’s once again look at XLB.


Basically, enter late, exit late (meaning there’s a lot of lag to this computation) on the filter end, and bite too easily on the short-term trading end.


In other words, as a standalone indicator, I’d be careful with it. Originally, this indicator was meant to be a predictor of trending vs. cycling. And essentially, at least when it comes to equities, it fails miserably, taking many trades it shouldn’t in an environment that steadily grinds upwards. This makes me believe that in a trend that grinds downwards, that a long strategy would be similarly disastrous. In short, in my opinion, the Trend Vigor indicator fails its original stated purpose, which is to partition markets into trending/cycling/trending downwards.


This all in mind, let’s see what happened to our holdout data–that is, from 2018 onwards using the long-only ATR position-sizing strategy through 2018 to present day (that is, the current date as of the time of this writing, which is June 9th, 2018, or “2018-06-09”).


Nothing spectacular, that’s for certain. Aqui estão os resultados:


Overall, it still was profitable, but definitely not impressively so. For the first time, the 50% mark got broken, which essentially contradicted the uniqueness of the indicator to begin with.


Here are the daily stats:


Basically, it seems that while the domestic side of equities seemed to do fairly well, the international side of the trade really hurt. For once, the perils of diversification are apparent. Here are the portfolio statistics:


So, ho-hum annualized returns, but the Sharpe Ratio at this point is far from stellar, and the drawdowns are definitely disappointing. Here is the resultant equity curve comparison.


In other words, it kept pace with the S&P 500 up until the beginning of 2018 (when in fact, their performance was just about equal), with less violent (but longer-lasting) drawdowns. Unfortunately, starting in mid-2018, the S&P 500 roared away, while the strategy just seemed to be flat, at the new equity high. This would probably anger quite a few investors. Let’s check out an equity curve from a losing security and see what happened.


In short, Trend Vigor as an entry indicator seems to be like the rest of the usual trend following indicators. Susceptible to buying tops and getting caught in cycles, gives back open equity (see that long trade in 2018-2018), takes counter-trend trades, but essentially at the price of incorporating a bunch of mathematics far more complex than the usual SMAs and EMAs, and at best, to marginally better results.


So does this mean that there was absolutely nothing to take away from this?


Bem não. Trend Vigor is something that can be added to a repertoire of indicators. Unlike the usual SMA and EMA fare, the advantage that Trend Vigor has is that over longer time horizons, assuming gradual trends (as opposed to the steep drops in things such as equities), is that it still can get things right more often than not, and when it does, the average win to loss profile is usually impressive. However, a marginal improvement over the basics isn’t what trend vigor was originally advertised to be, so much as a reliable market mode indicator. And in a trending environment, even your basic SMA crossovers will make money. In an oscillating environment, even the most basic RSI plug-and-chug will make money. The key, of course, is to try and find an indicator that will tell you what to deploy when. And for that purpose, unlike what was advertised in the original John Ehlers presentation, Trend Vigor, as far as this investigation has led me, is *not* that.


My Stochastic Oscillator – John Ehlers.


In his article, “Predictive And Successful Indicators,” author John Ehlers presents two new indicators: the SuperSmoother filter , which is superior to moving averages for removing aliasing noise, and the MESA Stochastic oscillator , a stochastic successor that removes the effect of spectral dilation through the use of a roofing filter.


To demonstrate the effects of using the new indicators, Ehlers introduces a simple countertrend system that goes long when MESA Stochastic crosses below the oversold value and reverses the trade by taking a short position when the oscillator exceeds the overbought threshold.


This stochastic oscillator eliminate noises a lot and then make reading of this oscillator more convenient with a clearer view. Because of smoothing / lag phenomena, this indicator must be used in convergence with other indicator to give good signals. Another ways of using it for counter trend trades would be to directly enter trade when the oscillator cross the oversold area for a buy order and the overbought area for a short sell order.


Compartilhar isso.


Nenhuma informação neste site é um conselho de investimento ou uma solicitação para comprar ou vender qualquer instrumento financeiro. O desempenho passado não é indicativo de resultados futuros. A negociação pode expô-lo ao risco de perda maior do que seus depósitos e é apenas adequado para investidores experientes que tenham meios financeiros suficientes para suportar esse risco.


Arquivos ITF ProRealTime e outros anexos:


Novo! O PRC também está no YouTube, inscreva-se no nosso canal para conteúdo exclusivo e tutoriais.


Hy Nicolas, I have downloaded this oscillator, but i see only the two horizontal lines (0.2 and 0.8).The oscillator line don’t go. (maybe in your script missing the “close” data?)


Sorry for my previous post, your indicato all right!!


it runs well, but on Germany 30 (CFD) time frame 15 minutes don’t go.. (for every other time frame runs good..)i do not know why…


Hi Nicolas, Thanks for posting Ehler’s My Oscillator (a combination of his Optimal Tacking Filter and the Universal Oscillator (Supersmoother)), I just saw your MESA stochastic for prorealtime post #15940. You mentioned “This indicator reflects short term variations of price within the “bandedge” parameter as a frequency” on the Universal Oscillator page. What does that exactly mean? I was also wondering how best to determine what Bandedge setting to use in Ehler’s Oscillators, or is it a case of optimising it for one currency pair and then seeing how it performs for other pairs?


Re: Trading systems, I’m still working with different Ehler indicators. When the Supersmoother Oscillator is set to be >= the zero line as a long entry (and <= for short trades) using a Kaufman KAMA as the exit long (Period = 4, FastPeriod = 2, SlowPeriod = 30) works well on different markets like forex, gold, even Credit Agricole. As usual it is a balancing act with getting acceptable lower drawdowns with the % winner and a good gain/loss ratio. Is there any way to do Monte Carl testing of results, fortunately it’s built into the Trading Blox s/ware I have but I didn’t manage to figure out how to use the Excel s/ware approach? Cheers again for your help.


Nice to hear you make good trades with Ehler’s indicators so far. About the “bandedge” statement, where did I mentioned that?


About Monte Carlo analysis, there are already good threads on forums to make your excel report of prorealtime backtest results:


The bandedge was part of the Universal Oscillator: prorealcode/prorealtime-indicators/universal-oscillator-john-ehlers/Thanks for the Monte Carlo links, I will take a look. (I’m using Firefox and the page is jumping to the bottom when I click on insert link…)


Hi Nicolas, Thanks for your help with the Monte Carlo links and these Ehler’s indicators, they really are good, particularly the Universal Oscillator with 0.7 and -0.7 crosses using a trend definition like two 200 mov averages, the present compared to it’s 5 or 10 day previous value to determine trade direction and using a shorter period exit stop. Oddly Cythia Kase’s Dev Stops didn’t seem to work as well… I will test the Univ. Osc with the Kaufman KAMA soon.


I’m going to see how they then compare with the Goertzel Algo if I can ever get those indicators to load properly without “syntax issues… The function called from Example A, called from Example B, is called with 1 parameter(s) instead of 0 expected. “? I think I’m, missing an indicator – pls see screenshot: The image isn’t showing as attached to this comment? I will try again below this comment if necessary. I’m trying to figure out though how you determine the best bandedge setting for the Universal Oscillator? It’d be great if it could have been an optimised parameter so it could then be optimised and “let loose” on an out of sample data set. Is there a simple way like trying to match the oscillations to the price/chart oscillations? Cheers Brad.


Yes, the Univ Osc with a KAMA used as a trend filter instead of a simple mov ave. (for long or short trades – comparing the present with it’s value 10 days ago) doubled the profits to 78% over 4 years with drawdown dropping from 21.6% to 13.7%. (-;


80: John Ehlers on Multi Time Frame, Fully Automated, Cycle Trading Success.


From California, USA, John is a veteran trader. With 35 years trading experience he has seen it all. John has an engineering background that led to his technical approach to trading ignoring fundamental analysis (with one important exception).


John strongly believes in cycles. He’d rather exit a trade when the cycle ends or a new one starts. He uses the MESA principle to make predictions about cycles in the market and trades one hundred percent automatically.


In the show John reveals:


What is more appropriate than trading individual stocks The one thing he relies upon in his approach to the market The detail surrounding his unique trading style What important thing underpins the market and gives every trader an edge.


Pré-visualização de entrevista.


Pré-visualização de entrevista.


Uau! @bobdesaedeleer:disqus, where is that info from? Norton told me that mesasoftware is a “known dangerous site.” Sometimes it just flags foreign sites, this one is out of Canada but I thought John was in California. Pensamentos? Anyone else have any comments thoughts?


The illustration of John’s adapted strategy shows 14 trades over a period of about 6 months (7 short, 7 long). However a standard 9 period RSI (1D Bars) has only crossed the 20/80 RSI levels for the S&P 500 about 3 times in total over the last 18 months. Why the difference?


I suspect it’s because of the SuperSmoother filter he uses.


Hi Cam… it is the same with a 6 period super smoother applied too. The super smother (aka Butterworth filter) reduces noise so if anything is likely to reduce the number of spurious 20/80 crossovers. I was wondering whether John has used one of his adaptive RSI indicators, or an RSI fed through an inverse Fisher transform. I can’t get anywhere close to replicating the strategy as described – so must be missing something! Cheers….


Get 13 FREE Trader Interviews.


& All Previews.


Ótimo! Você está dentro de Verifique seu email para seus detalhes de login e link.


Acesse todas as pré-visualizações.


& 13 entrevistas FREE Trader.


Ótimo! Você está dentro de Verifique seu email para seus detalhes de login e link.


Digite seu e-mail e obtenha acesso instantâneo.


52 entrevistas acionáveis!


Odeio o SPAM e promete manter seu endereço de e-mail seguro. Aqui está a nossa Política de privacidade.

Комментариев нет:

Отправить комментарий