Forex cointegração trading


Cointegration in Forex Pairs Trading.


Cointegration na troca de pares forex é uma ferramenta valiosa. Para mim, a cointegração é a base para uma excelente estratégia de negociação mecânica neutra do mercado que me permite lucrar em qualquer ambiente econômico. Se um mercado está em uma tendência de alta, tendência de baixa ou simplesmente se movendo de lado, a negociação de pares de divisas me permite colher ganhos durante todo o ano.


Uma estratégia de negociação de pares forex que utiliza cointegração é classificada como uma forma de negociação de convergência com base em arbitragem estatística e reversão para significar. Este tipo de estratégia foi popularizado por uma equipe de negociação quantitativa no Morgan Stanley na década de 1980, usando pares de ações, embora eu e outros comerciantes descobrirem que também funciona muito bem para negociação de pares de forex também.


Negociação de pares de Forex com base na cointegração.


O comércio de pares de Forex com base na cointegração é essencialmente uma estratégia de reversão para média. Declarado simplesmente, quando dois ou mais pares forex são cointegrados, significa que o spread de preços entre os pares de divisas separados tende a reverter ao seu valor médio consistentemente ao longo do tempo.


É importante entender que a cointegração não é correlação. A correlação é uma relação de curto prazo em relação a co-movimentos de preços. A correlação significa que os preços individuais se movem juntos. Embora a correlação seja dependente de alguns comerciantes, por si só é uma ferramenta não confiável.


Por outro lado, a cointegração é um relacionamento de longo prazo com co-movimentos de preços, nos quais os preços se movem juntos, mesmo dentro de certos intervalos ou spreads, como se estivessem amarrados. Descobri que a cointegração era uma ferramenta muito útil na troca de pares de forex.


Durante a minha troca de pares forex, quando o spread se alarga para um valor limiar calculado pelos meus algoritmos de negociação mecânica, eu "curto" o spread entre os preços dos pares. Em outras palavras, eu aposto que o spread reverterá em direção a zero devido à sua cointegração.


As estratégias básicas de negociação de pares de forex são muito simples, especialmente quando se utilizam sistemas de negociação mecânica: escolho dois pares de moedas diferentes que tendem a se mover de forma semelhante. Compre o par de moedas insuficientes e venda o par de desempenho. Quando a propagação entre os dois pares converge, eu fechar minha posição com lucro.


A troca de pares de Forex com base na co-integração é uma estratégia razoavelmente neutra para o mercado. Como exemplo, se um par de moedas cair, o comércio provavelmente resultará em uma perda no lado longo e um ganho compensatório no lado curto. Assim, a menos que todas as moedas e instrumentos subjacentes subitamente percam valor, o comércio líquido deve ser próximo de zero no pior cenário.


Do mesmo jeito, as negociações de pares em muitos mercados são uma estratégia de negociação de autofinanciamento, uma vez que o produto de vendas curtas às vezes pode ser usado para abrir a posição longa. Mesmo sem esse benefício, a troca de pares de divisas com cointegração ainda funciona muito bem.


Entendendo a co-integração para negociação de pares forex.


Cointegration é útil para mim na troca de pares forex porque me permite programar meu sistema de negociação mecânica com base em desvios de curto prazo dos preços de equilíbrio, bem como expectativas de preços a longo prazo, pelo que quero dizer correções e retorno ao equilíbrio.


Para entender como a negociação de negociação de pares de divisas orientadas pela cointegração, é importante primeiro definir a cointegração e depois descrever como ela funciona em sistemas de negociação mecânica.


Como eu disse acima, a cointegração refere-se à relação de equilíbrio entre conjuntos de séries temporais, como os preços de pares de divisas separados que, por si só, não estão em equilíbrio. Declarado no jargão matemático, a cointegração é uma técnica para medir a relação entre variáveis ​​não estacionárias em uma série temporal.


Se duas ou mais séries temporais tiverem um valor de raiz igual a 1, mas sua combinação linear é estacionária, então é dito que estão cointegradas.


Como um exemplo simples, considere os preços de um índice de bolsa e seu contrato de futuros relacionado: embora os preços de cada um desses dois instrumentos possam vagar aleatoriamente em breves períodos de tempo, eles retornarão ao equilíbrio e seus desvios serão estacionário.


Aqui está outra ilustração, declarada em termos do exemplo clássico de "caminhada aleatória": digamos que há dois bêbados individuais caminhando para casa depois de uma noite de carousing. Vamos continuar a assumir que esses dois bêbados não se conhecem, então não há uma relação previsível entre seus caminhos individuais. Portanto, não há cointegração entre seus movimentos.


Em contraste, considere a idéia de que um bêbado individual está vagando para casa enquanto acompanha seu cão em uma coleira. Neste caso, há uma conexão definitiva entre os caminhos dessas duas criaturas pobres.


Embora cada um dos dois ainda esteja em um percurso individual durante um curto período de tempo, e mesmo que um dos pares possa aleatoriamente levar ou atrasar o outro em qualquer ponto no tempo, ainda assim, eles sempre serão encontrados juntos. A distância entre eles é bastante previsível, pelo que o par é considerado cointegrado.


Voltando agora a termos técnicos, se houver duas séries temporais não estacionárias, como um conjunto hipotético de pares de moeda AB e XY, que se tornam estacionários quando a diferença entre eles é calculada, esses pares são chamados de série de primeira ordem integrada - também ligue para uma série I (1).


Mesmo que nenhuma dessas séries permaneça em um valor constante, se houver uma combinação linear de AB e XY estacionada (descrita como I (0)), então AB e XY são cointegradas.


O exemplo simples acima consiste em apenas duas séries temporais de pares de forex hipotéticos. No entanto, o conceito de cointegração também se aplica a séries temporais múltiplas, usando ordens de integração mais altas ... Pense em termos de um bêbado errante acompanhado por vários cães, cada um em uma coleira de comprimento diferente.


Na economia do mundo real, é fácil encontrar exemplos que mostrem cointegração de pares: renda e gastos, ou a dureza das leis criminais e o tamanho da população prisional. Na troca de pares forex, meu foco é capitalizar a relação quantitativa e previsível entre pares de moedas cointegradas.


Por exemplo, vamos assumir que estou assistindo esses dois pares de moeda hipotéticos cointegrados, AB e XY, e a relação cointegrada entre eles é AB & # 8211; XY = Z, onde Z é igual a uma série estacionária com uma média de zero, isto é, eu (0).


Isso parece sugerir uma estratégia de negociação simples: quando AB - XY & gt; V e V é o meu preço de gatilho limiar, então o sistema de negociação de pares forex venderia AB e compraria XY, uma vez que a expectativa seria AB para diminuir o preço e XY para aumentar. Ou, quando AB-XY & lt; - V, eu esperaria comprar AB e vender XY.


Evite a regressão espúria na troca de pares forex.


No entanto, não é tão simples como sugeriria o exemplo acima. Na prática, um sistema de negociação mecânica para troca de pares de forex precisa calcular a cointegração em vez de apenas confiar no valor R-quadrado entre AB e XY.


Isso ocorre porque a análise de regressão normal é baixa ao lidar com variáveis ​​não estacionárias. Provoca a chamada regressão espúria, o que sugere relacionamentos entre variáveis, mesmo quando não existe.


Suponhamos, por exemplo, que eu regredisse 2 séries temporais de "caminhada aleatória" separadas uma contra a outra. Quando eu teste para ver se há uma relação linear, muitas vezes eu vou encontrar valores altos para R-quadrado, bem como baixos valores de p. Ainda assim, não há relacionamento entre esses 2 passeios aleatórios.


Fórmulas e testes para cointegração na negociação de pares forex.


O teste mais simples para cointegração é o teste de Engle-Granger, que funciona assim:


Verifique que AB t e XY t sejam ambos I (1) Calcule a relação de cointegração [XY t = aAB t + et] usando o método de mínimos quadrados Verifique se os resíduos de cointegração e estão estacionários usando um teste de raiz de unidade como o Teste avaliado Dickey-Fuller (ADF).


Uma equação Granger detalhada:


I (0) descreve a relação de cointegração.


XY t-1 - βAB t-1 descreve a extensão do desequilíbrio longe do longo prazo, enquanto αi é tanto a velocidade como a direção em que a série temporal do par de moedas se corrige do desequilíbrio.


Ao usar o método Engle-Granger na negociação de pares forex, os valores beta da regressão são usados ​​para calcular os tamanhos comerciais para os pares.


Ao usar o método Engle-Granger na negociação de pares forex, os valores beta da regressão são usados ​​para calcular os tamanhos comerciais para os pares.


Correção de erros para cointegração em troca de pares forex:


Ao usar cointegração para negociação de pares de divisas, também é útil explicar como as variáveis ​​cointegradas se ajustam e retornam ao equilíbrio de longo prazo. Então, por exemplo, aqui estão as duas séries temporais de pares de forex mostrados de forma autoregressiva:


Negociação de pares de Forex com base na cointegração.


Quando uso o meu sistema de negociação mecânica para negociação de pares de divisas, a configuração e a execução são bastante simples. Primeiro, acho dois pares de moedas que parecem ser cointegradas, como EUR / USD e GBP / USD.


Então, eu calculo os spreads estimados entre os dois pares. Em seguida, eu verificar a estacionaridade usando um teste de raiz unitária ou outro método comum.


Tenho certeza de que meu feed de dados de entrada está funcionando adequadamente, e eu deixo meus algoritmos de negociação mecânica criar os sinais comerciais. Supondo que eu tenha executado back-tests adequados para confirmar os parâmetros, finalmente estou pronto para usar cointegração na minha troca de pares forex.


Encontrei um indicador MetaTrader que oferece um excelente ponto de partida para construir um sistema de negociação de pares de divisas de cointegração. Parece um indicador Bollinger Band, no entanto, o oscilador mostra o diferencial de preços entre os dois pares de moedas diferentes.


Quando este oscilador se move em direção ao extremo alto ou baixo, indica que os pares estão se desacoplando, o que sinaliza os negócios.


Ainda assim, para ter certeza de sucesso, confio no meu sistema de comércio mecânico bem construído para filtrar os sinais com o teste Augmented Dickey-Fuller antes de executar os negócios apropriados.


Claro, qualquer pessoa que queira usar cointegração para a negociação de pares forex, ainda que não tenha as necessárias habilidades de programação, pode contar com um programador experiente para criar um consultor especialista vencedor.


Através da magia da negociação algorítmica, programo meu sistema de negociação mecânica para definir os spreads de preços com base na análise de dados. Meu algoritmo monitora os desvios de preços, então compra e vende automaticamente pares de moedas para reduzir as ineficiências do mercado.


Riscos a ter em conta ao usar cointegração com troca de pares forex.


O comércio de pares de Forex não é totalmente livre de riscos. Acima de tudo, eu tenho em mente que a negociação de pares forex usando a cointegração é uma estratégia de reversão média, que se baseia no pressuposto de que os valores médios serão os mesmos no futuro como eram no passado.


Embora o teste Augmented Dickey-Fuller mencionado anteriormente seja útil na validação das relações cointegradas para o comércio de pares de forex, isso não significa que os spreads continuarão a ser cointegrados no futuro.


Confio em fortes regras de gerenciamento de risco, o que significa que meu sistema de negociação mecânica sai de negociações não lucrativas se ou quando a reversão-a-média calculada é invalidada.


Quando os valores médios mudam, é chamado de deriva. Eu tento detectar a deriva o mais rápido possível. Em outras palavras, se os preços dos pares Forex previamente cointegrados começam a se mover em uma tendência em vez de reverter para a média previamente calculada, é hora de os algoritmos do meu sistema de negociação mecânica recalcular os valores.


Quando uso o meu sistema de negociação mecânica para negociação de pares de divisas, uso a fórmula autorregressiva mencionada anteriormente neste artigo para calcular uma média móvel para prever o spread. Então, eu saio do comércio em meus limites de erro calculados.


Cointegration é uma ferramenta valiosa para minha troca de pares forex.


O uso da cointegração na negociação de pares forex é uma estratégia de negociação mecânica neutra do mercado que me permite negociar em qualquer ambiente de mercado. É uma estratégia inteligente que se baseia na reversão, mas isso me ajuda a evitar as armadilhas de algumas das outras estratégias de negociação forex de reversão para média.


Devido ao seu uso potencial em sistemas de negociação mecânica rentáveis, a cointegração para troca de pares de divisas atraiu o interesse tanto de comerciantes profissionais como de pesquisadores acadêmicos.


Há muitos artigos recentemente publicados, como esse artigo de blog focado em quantos, ou essa discussão acadêmica sobre o assunto, bem como uma grande discussão entre os comerciantes.


Cointegration é uma ferramenta valiosa no meu comércio de pares forex, e eu recomendo que você olhe para ele mesmo.


Diz Tommaso Sillian.


Muito bom artigo. É inspirador. Obrigado por escrevê-lo!


Harish Nachnani diz.


A correlação também é aplicada em ações (ações). Qual é a diferença? O processo acima pode ser aplicado às ações?


Eddie Flower diz.


Sim, o mesmo processo pode ser aplicado aos estoques, bem como aos derivados. Uma vez que existe um grande universo de estoques em comparação com os pares de divisas, deve haver uma maior quantidade de oportunidades potenciais para negociação. Com o poder de cruzamento dos sistemas comerciais de hoje, muitos conjuntos de relacionamentos podem ser examinados rapidamente, em tempo real. Cointegration também pode ser usado por comerciantes de opções; pode-se esperar que produza resultados como os populares spreads da Coca Cola-Pepsi, nos quais as relações de preços entre certos estoques / opções permitem que os comerciantes se envolvam em jogos de baixo risco com uma boa chance de ganhar.


Harish Nachnani diz.


Você troca intra dia ou durante semanas usando esta estratégia? Além disso, que linguagem de programação você recomendaria. R leva tempo para executar cálculos e se é comércio intra-dia, a latência entra em jogo.


A linguagem de programação não é importante para o comércio no final do dia. Qualquer linguagem importante como Perl, Python, C / C ++ e C # está bem. R pode ser extremamente rápido, mas retarda se for forçado a alocar dinamicamente a memória.


Eu troco usando gráficos diários, e eu permaneço na maioria dos negócios por alguns dias para algumas semanas. Shaun é um programador experiente, e sempre confio no seu julgamento para usar a melhor linguagem de programação para obter os melhores resultados para uma determinada estratégia de negociação. Na verdade, Shaun pode criar um programa bem equilibrado e vencedor para alavancar a co-integração e outros fatores também. Se você gostou de uma citação, entre em contato com ele diretamente em infoonestepremoved.


Chris Zimmer diz.


Existe algum interesse em uma implementação deste para o MT4. Se você pode fornecer algumas especificações sobre a implementação desta estratégia no código, envie para czimmeronestepremoved.


Estou fazendo um pequeno projeto sobre estratégias de co-integração no FX para meu mestrado. Eu acredito que você executou testes de cointegração em muitos pares de moedas. Quais as quais você achou ser estatisticamente significativamente cointegrado?


Eu não acho que Eddie realmente correu os números. O artigo pretende ser um guia geral para o conceito, mas não é o ponto de ser uma estratégia de boa-fé.


1) USD / JPY e EUR / CHF.


2) EUR / PLN e EUR / HUF.


3) USD / TRY e USD / ZAR.


4) AUD / USD e NZD / USD.


5) EUR / NOK e EUR / SEK.


Eu sei que estes estão bastante correlacionados, mas isso não significa cointegração.


Camilo Romero diz.


Existem bons pares de forex cointegrados:


Eu não acho que USDJPY / EURCHF seja um par cointegrado porque não haverá uma estratégia neutra do mercado.


Obrigado por compartilhar.


Camilo Romero diz.


Alguém implementou um código de retorno usando a estratégia de reversão média?


Eu deveria ajustar os valores do pip entre dois pares de divisas?


Alguém adicionou custo de comissão ao código de retorno e obteve resultados lucrativos?


Tenho certeza de que alguém tem, mas não é algo em que você encontrará uma resposta óbvia em gráficos de curto prazo. Você pode encontrar cointegrações de longo prazo, mas a pesquisa não foi feita pela I & # 8217;


A única cointegração é entre EUR e CHF e entre AUD e NZD, uma vez que o único comércio e economia íntima entre esses países e os bancos centrais estão criando essa cointegração.


Não EUR e GBP?


Robert J Armagost diz.


Olá Eddie. Excelente artigo. Voltei a testar 10 anos de gráficos pensando e # 8221; Eu não posso ser a primeira pessoa a ter pensado nisso! & # 8221; quando encontrei este site. Muito obrigado por escrever isso. Eu não me sinto tão sozinho. 🙂 Apenas me perguntando qual corretor você usa ou você usa vários corretores. Obrigado pelo seu tempo.


Sinceramente Robert J. Armagost.


O corretor principal que eu uso é Pepperstone e STO (via TopTradr).


Olá Shaun eu tenho negociado esta estratégia manualmente. Tem software para automatizar isso? (Então, eu não tenho mais que acordar no meio da noite) Obrigado pelo seu tempo.


Não fora da prateleira, mas é algo que podemos construir. Me tire um email com suas regras de entrada e saída para obter uma estimativa. infoonestepremoved.


Robert & # 8212; Obrigado pelo seu bom feedback. Shaun tem as ferramentas certas para implementar este tipo de estratégia de negociação, e eu concordo inteiramente com as recomendações do corretor, Agradeço novamente por comentar! EF.


Forex Mecânico.


Negociação no mercado FX usando estratégias mecânicas de negociação.


Cointegration no mercado Forex.


A partir dos diferentes tipos de arbitragem estatística disponível, o comércio de pares é talvez um dos mais populares. Em pares, a negociação de um comerciante tentará explorar a relação linear entre os valores de dois instrumentos, tentando comprá-los / vendê-los quando a relação entre seus valores aumentar / diminuir para valores que ofereçam potencial de lucro suficiente. No entanto, a negociação de pares não exige apenas uma correlação linear, mas também exige que os instrumentos sejam cointegrados, uma propriedade fundamental que assegura uma conexão fundamental entre os instrumentos que diminui a probabilidade de propagação entre os dois instrumentos # 8220; explodindo e # 8221; (ampliando muito além do que é esperado estatisticamente). Embora o comércio de pares seja geralmente descrito em ações / commodities, raramente vemos algum estudo de cointegração no mercado FX. Hoje, vamos analisar algumas cointegrações potenciais no mercado FX, por que elas existem e como elas podem ser exploradas.


Comecemos por definir o que queremos dizer por cointegração. Duas séries são cointegradas quando compartilham uma deriva estocástica comum. O exemplo típico para explicar a cointegração fala sobre um homem que vai a um bar com seu cachorro. Depois de ficar bêbado e deixar o bar, tanto o homem quanto o cão caminham pelo mesmo caminho para casa, embora sua deriva estocástica e # 8211; qual é o modo aleatório em que o homem caminha e o cachorro se pergunta ao longo do caminho; são diferentes. Quando isso acontece, seus caminhos estão de fato correlacionados, mas não estão cointegrados. Se o homem, em vez disso, decide colocar uma coleira no cão, seus caminhos se tornam cointegrados porque agora compartilham uma deriva estocástica comum determinada pelo comprimento da trela. O homem e o cão não podem ser separados além do que a sua trela permite, o que faz todos os movimentos aleatórios que eles fazem além de um certo comprimento comum a ambos (como eles se puxariam um para o outro). Em estatísticas, podemos avaliar a cointegração usando vários testes diferentes, dos quais o teste Augmented Dickey-Fuller (ADF) é mais popularmente usado. Observe que este teste avalia apenas a estacionança & # 8211; não exatamente cointegração & # 8211; então é necessário um outro teste, como um teste de Johansen, para confirmar a cointegração.


Ao analisar exemplos clássicos de cointegração em séries de tempo financeiro, você notará que os instrumentos que são cointegrados geralmente têm alguns dos principais motivos fundamentais para serem cointegrados. A & # 8220; leash & # 8221; é uma relação fundamental entre ambos os instrumentos, sua deriva estocástica comum. Esse relacionamento geralmente é muito forte, por exemplo, duas empresas produtoras de petróleo que compartilham refinarias em países amplamente iguais e têm os mesmos clientes; eles são tão bem juntos que é muito improvável que qualquer evento aleatório afete um sem afetar o outro. Isto é o que torna os desvios tão tentadores para explorar. No Forex no entanto, a história é um pouco diferente porque os países têm dificuldade em ser tão fundamentalmente semelhantes.


Você pode realmente ver isso facilmente quando você olha o último ano de dados para vários pares FX que geralmente vemos como correlacionados. Por exemplo, o EUR / USD e GBP / USD tradicionalmente têm uma grande correlação. Um gráfico normalizado que mostra o último ano de dados mostra que ambos os pares realmente tendem a se mover na mesma direção, mas é claro que esse relacionamento não segue a mesma deriva estocástica. Um teste ADF usando o último ano de dados para esses dois pares lhe dará um valor de 0.28 que é simplesmente muito grande para rejeitar a hipótese nula. Olhar para outros pares semelhantes revela resultados muito semelhantes, pares como AUDUSD | NZDUSD & # 8211; que são ainda mais correlacionados do que o EURUSD | GBPUSD revelam-se também não cointegrados.


Então, há cointegrações no mercado FX? Na verdade, a resposta é sim. A decisão do Banco Nacional Suíço de criar um piso no EURCHF em 1.20 gerou um & # 8220; leash & # 8221; que fez vários pares compartilhar uma deriva estocástica. Por exemplo, o EURUSD e o CHFUSD estão agora cointegrados devido a esse fato. Um teste ADF lhe dará um valor inferior a 0,01 para este par, sugerindo que eles são realmente cointegrados (confirmados pelo teste de Johansen também). Todos os pares que contêm CHF também apresentam cointegrações, como o EURJPY | CHFJPY e o EURAUD | AUDCHF. Estas cointegrações surgem do pino EURCHF, algo que é evidente quando você olha o valor de propagação como uma função do tempo entre qualquer um desses pares. A terceira imagem mostra o spread do par EURUSD | CHFUSD em função do tempo, não é surpresa que este seja exatamente o mesmo gráfico que o EURCHF no ano passado. Como o comprimento da & # 8220; leash & # 8221; varia, assim como o valor da propagação nos pares cointegrados.


Podemos aproveitar essas cointegrações? Bem, você certamente pode. Há várias maneiras pelas quais a cointegração pode ser negociada, mas com uma correção variável # 82201; Um bom caminho é provavelmente trocar as bandas de bollinger pela propagação. Você pode negociar em qualquer prazo, mas mesmo quando você comercializa o prazo diário, você pode ganhar algum dinheiro. A quarta imagem mostra uma simulação muito simples em R, onde troquei os 3 pares mencionados acima, usando alavancagem 1:10, em uma média móvel de 10 períodos usando 1 desvio padrão para distâncias de banda. As simulações mostram um lucro de 25% com uma redução de 10% no ano passado, não muito grande, mas também muito ruim. É possível que outros aprimoramentos e entradas / saídas em prazos inferiores possam de fato aumentar essas margens.


Uma coisa importante a lembrar aqui é que a trela é uma presilha de um banco central. Se essa peg por algum motivo parar de existir, é possível que essa cointegração simplesmente desapareça. Por conseguinte, é aconselhável observar os desenvolvimentos fundamentais e interromper a negociação da cointegração se isso ocorrer. Também é importante repetir constantemente os testes estatísticos de cointegração à medida que novos dados chegam para que você possa parar de negociar qualquer um desses pares assim que a cointegração mostrar a quebrar. Se você quiser saber mais sobre o comércio FX e como você também pode projetar suas próprias estratégias de negociação, considere se juntar ao Asirikuy, um site repleto de vídeos educacionais, sistemas de negociação, desenvolvimento e uma abordagem sólida, honesta e transparente para negociação automatizada em geral. Espero que tenha gostado deste artigo ! : o)


6 Respostas à Cointegration no Mercado Forex e # 8201;


& # 8221; Nas estatísticas, podemos avaliar a cointegração usando três testes diferentes dos quais o teste Augmented Dickey-Fuller (ADF) é o mais popular. & # 8221;


Eu, este é um cheque de estacionaria. não implica co-integração.


Isso é verdade, no entanto, quando o resultado deste teste é positivo para as séries financeiras, eles são sempre cointegrados, é por isso que é tão popularmente usado para esse propósito, eu acredito. Você pode, no entanto, realizar um teste de Johansen também ou um teste de duas etapas Engle-Granger. Nos exemplos usados ​​neste artigo, todas as séries que passam o teste ADF também passam o teste de Johansen, mostrando que estão cointegradas.


Eu ficarei mais do que feliz se você pudesse compartilhar seu código r para aprender a fazer esse processo.


A propagação da negociação no EURUSD | CHFUSD parece equivalente à negociação do próprio EURCHF, que, como é realmente diretamente possível na maioria dos corretores, deve ser preferido (pagar apenas metade dos custos de spread / comissão). Um spread EURUSD | CHFUSD é de fato um instrumento sintético para EURCHF.


Então, como essa propagação se comercializa de forma diferente (para melhor)?


Obrigado por comentar: o) Você está claramente certo, é o mesmo que negociar uma estratégia de banda bollinger no EUR / CHF. Conforme mencionado no artigo, o spread é realmente o mesmo gráfico que o EUR / CHF. A co-integração do EURUSD | CHFUSD é realmente refletida como uma tendência para retornar à média no EUR / CHF. Se você fosse negociar isso na prática, você realmente usaria o EUR / CHF para economizar custos comerciais ao invés de comprar / vender EURUSD e USDCHF.


Grande artigo em geral, mas confuso em alguns lugares. Como um comentário & # 8217; ou apontou, o teste ADF é um teste de raiz unitária. É um teste formal usado para determinar se uma série de preços está estacionária ou não. Se você conseguir um valor de P de mais de 1%, 5% ou 10%, você só pode deixar de rejeitar o nulo da raiz da unidade com base no nível de significância com o qual você se sente confortável. Isso não infere a presença de co-integração.


O poder do ADF também é documentado para ser baixo, de modo que a maioria dos pesquisadores agora vá para a verificação cruzada com um teste complementar, como o KPSS.


Será interessante ver o código R para que possamos também executá-lo e ver os resultados. Você menciona que o teste de Johansen confirma a presença de co-integração, de modo que, em geral, acredito que suas descobertas estejam em condições sólidas.


Algumas perguntas interessantes que surgiram são como é estável o relacionamento de co-integração? Com que frequência a estimativa da relação de longo prazo muda e quão grande são essas mudanças quando ocorrem.


No geral, excelente artigo, mantenha-os próximos e compartilhe algum código R.


Análise da série de tempo Cointegrated para negociação de reversão média com R.


Análise da série de tempo Cointegrated para negociação de reversão média com R.


Um tempo atrás, consideramos um modelo de negociação baseado na aplicação dos modelos da série temporal ARIMA e GARCH aos dados diários S & amp; P500. Mencionamos nesse artigo, bem como em outros artigos anteriores de análises de séries temporais, que eventualmente considerariamos as estratégias de negociação de reversão e a forma de construí-los.


Neste artigo, eu quero discutir um tópico chamado cointegração, que é um conceito de séries temporais que nos permite determinar se conseguimos formar um meio de reversão de ativos. Vamos abordar a teoria das séries temporais relacionadas à cointegração aqui e no próximo artigo, vamos mostrar como aplicar isso às estratégias comerciais reais usando a nova estrutura de backtesting de código aberto: QSTrader.


Vamos prosseguir discutindo a reversão média na tradicional estrutura de "negociação de pares". Isso nos levará ao conceito de estacionariedade de uma combinação linear de ativos, levando-nos finalmente a cointegração e testes de raiz unitária. Uma vez que esboçamos esses testes, simularemos várias séries temporais no ambiente estatístico R e aplicaremos os testes para avaliar a cointegração.


Estratégias de negociação de reversão média.


A idéia tradicional de um "comércio de pares" de reversão média é simultaneamente curtos e curtos dois ativos separados compartilhando fatores subjacentes que afetam seus movimentos. Um exemplo do mundo das ações pode ser longo McDonald's (NYSE: MCD) e Short Burger King (NYSE: BKW - antes da fusão com Tim Horton).


A razão para isso é que os preços das ações a longo prazo provavelmente estarão em equilíbrio devido aos amplos fatores do mercado que afetam a produção e o consumo de hambúrgueres. Uma interrupção de curto prazo para um indivíduo no par, como uma interrupção da cadeia de suprimentos que afete apenas o McDonald's, levaria a uma deslocação temporária em seus preços relativos. Isso significa que um comércio longo-curto realizado neste ponto de interrupção deve se tornar rentável, pois os dois estoques retornam ao seu valor de equilíbrio uma vez que a interrupção é resolvida. Esta é a essência do clássico "comércio de pares".


Na medida em que estamos interessados ​​em realizar a negociação de reversão média não apenas em um par de ativos, mas também cestas de ativos que estão separadamente interligados.


Para conseguir isso, precisamos de uma estrutura matemática robusta para identificar pares ou cestas de ativos que significam reverter da maneira descrita acima. É aqui que surge o conceito de séries de tempo cointegradas.


A idéia é considerar um par de séries temporais não estacionárias, como os ativos de MCD e BKW de forma aleatória, e formar uma combinação linear de cada série para produzir uma série estacionária, que tem uma média e variância fixas.


Esta série estacionária pode ter interrupções de curto prazo onde o valor vagueia longe da média, mas devido à sua estacionaridade, este valor retornará eventualmente à média. As estratégias de negociação podem fazer uso disso aniquilando / diminuindo o par no ponto de interrupção apropriado e apostando em uma reversão de longo prazo da série para sua média.


As estratégias de reversão médias, como esta, permitem uma ampla gama de instrumentos para criar as séries de tempo estacionárias "sintéticas". Certamente, não estamos restritos a ações de "baunilha". Por exemplo, podemos fazer uso do Exchange Traded Funds (ETF) que acompanha os preços das commodities, como petróleo bruto e cestas de empresas produtoras de petróleo. Portanto, há muitos marcos para identificar tais sistemas de reversão significativos.


Antes de aprofundar a mecânica das estratégias de negociação reais, que serão objeto do próximo artigo, devemos primeiro entender como identificar estatisticamente tais séries cointegradas. Para isso, utilizaremos técnicas da análise de séries temporais, continuando o uso da linguagem estatística R como em artigos anteriores sobre o tema.


Cointegração.


Agora que motivamos a necessidade de um quadro quantitativo para realizar a negociação média de reversão, podemos definir o conceito de cointegração. Considere um par de séries temporais, ambas não-estacionárias. Se tomarmos uma combinação linear específica dessas séries, às vezes pode levar a uma série estacionária. Esse par de séries seria então denominado cointegrado.


A definição matemática é dada por:


Cointegração.


Deixe $ \ $ e $ \ $ ser duas séries temporais não estacionárias, com constantes $ a, b \ in \ mathbb $, constantes. Se a série combinada $ a x_t + b y_t $ estiver estacionada, dizemos que $ \ $ e $ \ $ são cointegrados.


Embora a definição seja útil, não nos fornece diretamente um mecanismo para determinar os valores de $ a $ e $ b $, nem se essa combinação é, de fato, estatisticamente estacionária. Para este último, precisamos utilizar testes para raízes unitárias.


Teste de raiz unitária.


Em nossa discussão anterior de modelos de AR (p) autorregressivos, explicamos o papel da equação característica. Observamos que era simplesmente um modelo autorregressivo, escrito em forma de mudança para trás, definido como igual a zero. Resolver esta equação nos deu um conjunto de raízes.


In order for the model to be considered stationary all of the roots of the equation had to exceed unity. An AR(p) model with a root equal to unity - a unit root - is non-stationary. Random walks are AR(1) processes with unit roots and hence they are also non-stationary.


Thus in order to detect whether a time series is stationary or not we can construct a statistical hypothesis test for the presence of a unit root in a time series sample.


We are going to consider three separate tests for unit roots: Augmented Dickey-Fuller (AFD), Phillips-Perron and Phillips-Ouliaris. We will see that they are based on differing assumptions but are all ultimately testing for the same issue, namely stationarity of the tested time series sample.


Let's now take a brief look at all three tests in turn.


Augmented Dickey-Fuller Test.


Dickey and Fuller [2] were responsible for introducing the following test for the presence of a unit root. The original test considers a time series $z_t = \alpha z_ + w_t$, in which $w_t$ is discrete white noise. The null hypothesis is that $\alpha = 1$, while the alternative hypothesis is that $\alpha < 1$.


Said and Dickey [6] improved the original Dickey-Fuller test leading to the Augmented Dickey-Fuller (ADF) test, in which the series $z_t$ is modified to an AR(p) model from an AR(1) model. I've discussed the test in a previous article where we've used Python to calculate it. In this article we will carry out the same test using R.


Phillips-Perron Test.


The ADF test assumes an AR(p) model as an approximation for the time series sample and uses this to account for higher order autocorrelations. The Phillips-Perron test [5] does not assume an AR(p) model approximation. Instead a non-parametric kernel smoothing method is utilised on the stationary process $w_t$, which allows it to account for unspecified autocorrelation and heteroscedasticity.


Phillips-Ouliaris Test.


The Phillips-Ouliaris test [4] is different from the previous two tests in that it is testing for evidence of cointegration among the residuals between two time series. The main idea here is that tests such as ADF, when applied to the estimated cointegrating residuals, do not have the Dickey-Fuller distributions under the null hypothesis where cointegration isn't present. Instead, these distributions are known as Phillips-Ouliaris distributions and hence this test is more appropriate.


Difficulties with Unit Root Tests.


While the ADF and Phillips-Perron test are equivalent asymptotically they can produce very different answers in finite samples [7] . This is because they handle autocorrelation and heteroscedasticity differently. It is necessary to be very clear which hypotheses are being tested for when applying these tests and not to simply apply them blindly to arbitrary series.


In addition unit root tests are not great at distinguishing highly persistent stationary processes from non-stationary processes. One must be very careful when using these on certain forms of financial time series. This can be especially problematic when the underlying relationship being modelled (i. e. mean reversion of two similar pairs) naturally breaks down due to regime change or other structural changes in the financial markets.


Simulated Cointegrated Time Series with R.


Let's now apply the previous unit root tests to some simulated data that we know to be cointegrated. We can make use of the defiition of cointegration to artificially create two non-stationary time series that share an underlying stochastic trend, but with a linear combination that is stationary.


Our first task is to define a random walk $z_t = z_ + w_t$, where $w_t$ is discrete white noise. Take a look at the previous article on white noise and random walks if you need to brush up on these concepts .


With the random walk $z_t$ let's create two new time series $x_t$ and $y_t$ that both share the underlying stochastic trend from $z_t$, albeit by different amounts:


\begin x_t &=& p z_t + w_ \\ y_t &=& q z_t + w_ \end.


If we then take a linear combination $a x_t + b y_t$:


\begin a x_t + b y_t &=& a (p z_t + w_ ) + b (q z_t + w_ ) \\ &=& (ap + bq) z_t + a w_ + b w_ \end.


We see that we only achieve a stationary series (that is a combination of white noise terms) if $ap + bq = 0$. We can put some numbers to this to make it more concrete. Suppose $p=0.3$ and $q=0.6$. After some simple algebra we see that if $a=2$ and $b=-1$ we have that $ap +bq = 0$, leading to a stationary series combination. Hence $x_t$ and $y_t$ are cointegrated when $a=2$ and $b=-1$.


Let's simulate this in R in order to visualise the stationary combination. Firstly, we wish to create and plot the underlying random walk series, $z_t$:


Realisation of a random walk, $z_t$


If we plot both the correlogram of the series and its differences we can see little evidence of autocorrelation:


Correlograms of $z_t$ and the differenced series of $z_t$


Hence this realisation of $z_t$ clearly looks like a random walk. The next step is to create $x_t$ and $y_t$ from $z_t$, using $p=0.3$ and $q=0.6$, and then plot both:


Plot of $x_t$ and $y_t$ series, each based on underlying random walk $z_t$


As you can see they both look similar. Of course they will be by definition - they share the same underlying random walk structure from $z_t$. Let's now form the linear combination, comb , using $p=2$ and $q=-1$ and examine the autocorrelation structure:


Plot of comb - the linear combination series - and its correlogram.


It is clear that the combination series comb looks very much like a stationary series. This is to be expected given its definition.


Let's try applying the three unit root tests to the linear combination series. Firstly, the Augmented Dickey-Fuller test:


The p-value is small and hence we have evidence to reject the null hypothesis that the series possesses a unit root. Now we try the Phillips-Perron test:


Once again we have a small p-value and hence we have evidence to reject the null hypothesis of a unit root. Finally, we try the Phillips-Ouliaris test (notice that it requires matrix input of the underlying series constituents):


Yet again we see a small p-value indicating evidence to reject the null hypothesis. Hence it is clear we are dealing with a pair of series that are cointegrated.


What happens if we instead create a separate combination with, say $p=-1$ and $q=2$?


Plot of badcomb - the "incorrect" linear combination series - and its correlogram.


In this case we do not have sufficient evidence to reject the null hypothesis of the presence of a unit root, as determined by p-value of the Augmented Dickey-Fuller test. This makes sense as we arbitrarily chose the linear combination of $a$ and $b$ rather than setting them to the correct values of $p=2$ and $b=-1$ to form a stationary series.


Próximos passos.


In this article we examined multiple unit root tests for assessing whether a linear combination of time series was stationary, that is, whether the two series were cointegrated.


In future articles we are going to consider full implementations of mean reverting trading strategies for daily equities and ETFs data using QSTrader based on these cointegration tests.


In addition we will extend our analysis to cointegration across more than two assets leading to trading strategies that take advantage of cointegrated portfolios.


Referências.


A Quantcademy.


Junte-se ao portal de adesão da Quantcademy que atende à comunidade de comerciantes de varejo de varejo em rápido crescimento e saiba como aumentar a rentabilidade da sua estratégia.


Comércio Algoritmo bem sucedido.


Como encontrar novas ideias de estratégia de negociação e avaliá-las objetivamente para seu portfólio usando um mecanismo de backtesting personalizado em Python.


Negociação Algorítmica Avançada.


Como implementar estratégias de negociação avançadas usando análise de séries temporais, aprendizado de máquinas e estatísticas bayesianas com R e Python.


Gekko Quant - Negociação Quantitativa.


Comércio Quantitativo, Arbitragem Estatística, Aprendizado de Máquinas e Opções Binárias.


Pós-navegação.


Arbitragem estatística & # 8211; Trading a cointegrated pair.


In my last post gekkoquant/2012/12/17/statistical-arbitrage-testing-for-cointegration-augmented-dicky-fuller/ I demonstrated cointegration, a mathematical test to identify stationary pairs where the spread by definition must be mean reverting.


In this post I intend to show how to trade a cointegrated pair and will continue analysing Royal Dutch Shell A vs B shares (we know they’re cointegrated from my last post). Trading a cointegrated pair is straight forward, we know the mean and variance of the spread, we know that those values are constant. The entry point for a stat arb is to simply look for a large deviation away from the mean.


A basic strategy is:


If spread(t) >= Mean Spread + 2*Standard Deviation then go Short If spread(t) <= Mean Spread – 2*Standard Deviation then go Long.


If spread(t) >= nDay Moving Average + 2*nDay Rolling Standard deviation then go Short If spread(t) <= nDay Moving Average – 2*nDay Rolling Standard deviation then go long.


If spread(t) <= Mean Spread + 2*Std AND spread(t-1)> Mean Spread + 2*Std If spread(t) >= Mean Spread – 2*Std AND spread(t-1)< Mean Spread – 2*Std Advantage is that we only trade when we see the mean reversion, where as the other models are hoping for mean reversion on a large deviation from the mean (is the spread blowing up?)


This post will look at the moving average and rolling standard deviation model for Royal Dutch Shell A vs B shares, it will use the hedge ratio found in the last post.


Sharpe Ratio Shell A & B Stat Arb Shell A.


Annualized Sharpe Ratio (Rf=0%):


Shell A&B Stat Arb 0.8224211.


Shell A 0.166307.


The stat arb has a Superior Sharpe ratio over simply investing in Shell A. At a first glance the sharpe ratio of 0.8 looks disappointing, however since the strategy spends most of it’s time out of the market it will have a low annualized sharpe ratio. To increase the sharpe ratio one can look at trading higher frequencies or have a portfolio pairs so that more time is spent in the market.


22 pensamentos sobre & ldquo; Arbitragem estatística & # 8211; Trading a cointegrated pair ”


it also means that when identified the maximum divergence i can take position in derivatives like options?


-selling ATM Call option on first stock.


-buy Call option on the second one.


or with a BacKSpreadCall on the first and a BackSpreadPut on the second so I can set the protections and I can roll them if they go out control…


The short positions should be moneyness ATM or lightly OTM in my opinion.


What do yo think about?


Did you tried using Johansen’s testing approach in order to perform a more rigorous testing of cointegration? What do you think about combining Engle-Granger with Johansen?


The spread in the above does not oscillate around it mean, ideally, a cointegrated pair should trade sideways not in a trending manner as shown above….your write-up was perfect on proper cointegration you demonstrated. but this spread is not a perfect spread.


I 100% agree with you.


However for practical purposes as long as the mean reversion happens faster than the mean changes then you’ll do well.


I guess that’s something I’ve missed, how to quantify the half life/reversion speed.


Please note that in the above demo the look back period is 90days. This is fairly short. Choosing 200 days will result in a mean that is less responsive / changes direction. It will most likely increase the size of the standard deviation bands and result in less trades per year. This usually results in a lower Sharpe ratio.


Very interesting post. Would love to see the implementation on a basket of pairs.


I do some changes in your programme to calculate the bollinger bands and I wanna know why you’re put the Standard deviation to the right? (movingStd = rollapply(spread, lookback, sd, align=”right”, na. pad=TRUE))


OK thank you for answering!


Your blog give me the chance to implement and build more quickly my stat arb strategy.


I am going to test different models for statistical arbitrage. I keep all the visitors in the loop!


In your program, the martingale effect is not here. How can I add this effect?


I am running my iwn backtests with differents programs (Excel, R et ProRealTime (a french platform)) and in order to do some comparison, I need to add the martingale effect.


Obrigado pelo esclarecimento. By the same argument, rollmean has to have the same: rollmean(spread, lookback, na. pad=TRUE, align=’right’)


With this new modification the Sharpe ratio drops dramatically ..


Great stuff!! I think there are two bugs in your code, though. First one is in calculation of moving average. You forgot to set align parameter to “right” (like you do for standard deviation). Function uses default “center” and your data – spread and moving average are not aligned. You can see this from the plot as well. Moving average ends 45 days before the spread. Second bug is in calculation of trading returns. I think you should take return from the next day as we enter the position at the closing price.


Thanks for your elegant code. I noticed that your line of code:


is meant to apply the function shortPositionFunc to (-1*aboveUpperBand+belowMAvg).


However, the function shortPositionFunc takes two arguments x and y.


Is there any typo in the code?


Thank you for your clarification!


Thanks Gekko for the backtesting code. É muito útil. Couple of comments below:


1) Another reader has already commented about this above. movingAvg needs to be amended by adding align=”right” in order to have the first moving avg number on day 90:


movingAvg = rollmean(spread, lookback, align=”right”, na. pad=TRUE)


2) since we enter trades at end of day, the return on trade date shouldn’t count. we can simply shift every element in the “positions” vector down by using the “shift” function in the taRifx library.


Also, I don’t believe daily return is (aRet – stockPair$hedgeRatio*bRet). Imagine if you had a large hedge ratio, i. e. if stock A is priced at $100 and stock B is priced at $10, then the hedgeRatio would be in the neighborhood of 10. Since aRet and bRet are in % terms, the formula won’t work. Daily return should be aRet – bRet * (ratio between dollar neutral ratio vs hedge ratio).


#Calculate spread daily ret.


dailyRet <- aRet – bRet*hedgeRatioOVERdollarNeutralRatio.


tradingRet <- dailyRet * shift(positions,-1)


I am looking for new strategies in equity pair trading that improve the standard cointegration approach (for instance I started looking into the pair trading with copulas, which still seems an “unstable” alternative to cointegration). Do you have any new paper to suggest me? Thank you very much and congrats for the great blog.


The second half of the book goes through lots of more advanced techniques for hedging a portfolio / finding stationary pairs.


i am a bit confused in this step.


when i plotted the longPositions and ShortPositions along with the spread, bands and moving average lines found then there are consecutive long signals and short signals. According to my understanding.


longPostions <- if spread is below lowerband.


longExit <- if spread is above movAvg while long.


shortPostions <- if spread is above upperband.


shortExit <- if spread is below movAvg while short.


is this same thing your code is doing. Please help me understand this part.


Hi Gekko, I read the books of EP Chan that talks about this topic and I a little bit confused about mean reservion. When two assets ara cointegrated we are supposing that they will come back to their mean, but their moving average or their total mean in a fixed period? I’m giving better results using static parameters than using bollinger bands. I will show you an image with my doubt. prntscr/51jofw Could you write another article of mean reversion! Thanks for all.


Hi Gekko. Great Code. Could you closer explain an idea behind this cappedCumSum function ? I do not understand the moment when you are specifing two input variables, but in Reduce() function is only one parameter, – is it because of 0?


There is a mistake. Your algorithm looks in the future, the problem in rollmean function. Algorithm using moving average from future days to close position.


Riqueza do robô.


Posted on January 2, 2016 by Kris Longmore.


In the first post in this series, I explored mean reversion of individual financial time series using techniques such as the Augmented Dickey-Fuller test, the Hurst exponent and the Ornstein-Uhlenbeck equation for a mean reverting stochastic process. I also presented a simple linear mean reversion strategy as a proof of concept. In this post, I’ll explore artificial stationary time series and will present a more practical trading strategy for exploiting mean reversion. Again this work is based on Ernie Chan’s Algorithmic Trading , which I highly recommend and have used as inspiration for a great deal of my own research.


In presenting my results, I have purposefully shown equity curves from mean reversion strategies that go through periods of stellar performance as well as periods so bad that they would send most traders broke. Rather than cherry pick the good performance, I want to demonstrate what I think is of utmost importance in this type of trading, namely that the nature of mean reversion for any financial time series is constantly changing. At times this dynamism can be accounted for by updating the hedge ratios or other strategy parameters. At other times, the only solution is to abandon the mean reversion approach altogether, perhaps in favour of a trend following approach. As this post will demonstrate, finding or constructing mean reverting price series is a relatively simple matter. The real key to profitably exploiting such series is the much more difficult matter of understanding, in real time, whether to continue a strategy as is, update its parameters or put it on ice temporarily or permanently.


Cointegração.


A collection of non-stationary time series variables are said to be cointegrated if there exists a linear combination of those variables that creates a stationary time series. This implies that we can artificially construct a mean reverting time series through the appropriate combination of non-stationary time series. For example, we can construct a portfolio of assets whose market value is a stationary time series and thus amenable to profitable exploitation through mean-reversion techniques, even through the price series of the constituent assets are not themselves mean reverting. A pairs trading strategy, where we buy one asset and short another with an appropriate allocation of capital to each, is an example of this method for exploiting the concept of cointegration, but we can also create more complex portfolios of three or more assets.


We can test whether a given combination of assets forms a stationary process using the stationarity tests described in the previous post. However, it is impossible to know a priori the coefficients (or hedge ratios) that form a stationary portfolio. How then does one test for cointegration? I’ll explore two approaches: the Cointegrated Augmented Dickey-Fuller test and the Johansen test.


Cointegrated Augmented Dickey-Fuller Test.


The Cointegrated Augmented Dickey-Fuller Test (CADF test) involves firstly performing a linear regression between two price series to determine the portfolio’s optimal hedge ratio and then conducting a stationarity test on the portfolio’s price series. The example below illustrates this concept using the currencies of Australia and New Zealand since they seem likely to cointegrate given that the economies of both countries are commodity-based and are affected by similar geopolitical forces. This extends the example in the first post, which explored the mean reverting tendencies of the foreign exchange pair AUD/NZD. In that example, the hedge ratio is always one since equal amounts of AUD and NZD are always being bought and sold. In this example, we allow for a flexible hedge ratio and attempt its optimization. In order to achieve this, we need to introduce a common quote currency, the more liquid the better. It makes sense to choose the US dollar. Therefore, the example below seeks to exploit a stationary portfolio of AUD/USD and NZD/USD.


Firstly, the price series of both exchange rates for the period 2009 to mid-2015, which look like they may cointegrate:


A scatter plot further suggests that the price series may cointegrate as the price pairs fall on a roughly straight line:


We can use least squares regression to find the optimal hedge ratio and plot the residual of AUD/USD-beta*NZD/USD, which admittedly does not look overly stationary:


NZDUSD . Close , data = closes )


Next we apply the ADF test to the spread (see the previous post for a brief description of the urca package, and why its implementation of the ADF test is suitable for this application):


z . lag . 1 + 1 + z . diff . lag )


In this case, the test statistic we are interested in is -0.94, which is greater than the 10% critical value of -2.57. Therefore, we unfortunately can’t reject the null hypothesis that the portfolio is not mean reverting. However, the negative value of the test statistic indicates that the portfolio is not trending.


One shortcoming of the ordinary least squares approach is that it is assymetrc: switching the dependent and independent variables in the regression results in a different hedge ratio. Good practice would dictate that both options be tested and the arrangement that results in the more negative test statistic be selected. Another approach is to use total least squares regression, which can be used to derive a symmetric hedge ratio. In a geometrical sense, total least squares minimizes the orthogonal distance to the regression line (as opposed to the vertical distance in the case of ordinary least squares) and thus takes into account variance of both the dependent and independent variables. The total least squares solution is easily computed in R using principal component analysis and is not limited to a two-asset portfolio:


AUDUSD . Close + NZDUSD . Close , data = closes )


z . lag . 1 + 1 + z . diff . lag )


This results in a more negative test statistic and a visually more stationary spread (at least for the period 2009 – 2012, see the figure below), but we are still unable to reject the null hypothesis that the spread obtained through total least squares regression is mean reverting.


Johansen test.


The Johansen test allows us to test for cointegration of more than two variables. Recall from the previous post, using a linear model of price changes:


Δy(t) = λy(t − 1) + β t + μ + α1Δy(t − 1) + … + αkΔy(t − k) + εt.


that if λ ≠ 0 , then Δy(t) depends on the current level y(t − 1) and therefore is not a random walk. We can generalize this equation for the multivariate case by using vectors of prices y(t) and coefficients λ and α, denoted Y(t), Λ and Α respectively. The Johansen test calculates the number of independent, stationary portfolios that can be formed by various linear combinations of the price series based on the eignevector decomposition of Λ. The urca package contains an implementation of the Johansen test that provides critical values that we can use to test whether we can reject the null hypothesis that there exist 0, 1, 2, …, n-1 cointegrating relationships, where n is the number of constituent time series. Conveniently, the eigenvectors can be used as the hedge ratios of individual price series to form a stationary portfolio. This process is illustrated below for the AUD/USD-NZD/USD portfolio. A third currency pair – USD / CAD & # 8211; is added in the next section to attempt to create a stationary portfolio of three currencies.


In this case, we can’t reject either null hypothesis that r (the number of cointegrating portfolios) is zero or one, since the test statistic in both cases is less than even the 10% critical value. That is, it is unlikely that we can form a stationary portfolio from the price history used in this example. However, it may still be worth pursuing a mean reverting strategy if the half-life of mean reversion is sufficiently low (see the previous post for more details).


As stated above, the eignevectors form the optimal hedge ratio. They are conveniently ordered by maximum likelihood, so in this case we would select a portfolio of 1 lot of AUD/USD long or short and 3.41 lots of NZD/USD in the opposite direction. In this case, unfortunately, the resulting portfolio does not look any more stationary than that constructed using the ordinary least squares and total least squares regression approaches:


Mean reversion of a portfolio of more than two instruments.


We can add a third asset and use the Johansen test to determine the probability that there exists a mean reverting portfolio along with the hedge ratios of such a portfolio. In this case, I will add USD/CAD and take the reciprocal of price so that the quote currencies are consistent (note that when building a trading strategy from this triplet, that the directions signalled for USD/CAD would need to be reversed):


Again, we unfortunately find no significant cointegrating relationship. However, as discussed in the first post, we sometimes don’t need to hold our results to scientifically stringent statistical significance in order to make money, particularly if the half life of mean reversion is sufficiently short. Therefore, we will retain the first eigenvector to form a portfolio of the three instruments for further investigation. First, lets take a look at a time series plot of the portfolio’s value:


The half life of mean reversion of the portfolio is 53.2 days. This is calculated in the same manner as for a single mean reverting time series in the previous post, namely by regressing the value of the portfolio against its value lagged by one time period:


y . lag , data = df )


Recall that in the previous post, we were able to construct a theoretically profitable linear mean reverting strategy from a single time series with a half life of mean reversion of over 300 days, so at first glance, this results holds some promise.


Linear mean reversion on a cointegrated time series.


Below is the equity curve of the linear mean reversion strategy from the previous post on the three-instrument portfolio with the value of the portfolio overlaid on the equity curve:


The strategy suffers significant drawdown and only returns a profit factor of 1.04 and a Sharpe ratio of 0.29.


Obviously, the linear mean reversion strategy presented above and detailed in the previous post would not be suitable for live trading even if the example shown here had generated an impressive backtest. Applied to equities, it would require buying and selling an infinitesimal number of shares when price moves an infinitesimal amount. This is less of a problem when applied to currencies since we can buy and sell in units as small as one-hundredth of a lot. However, the real killer for such a strategy is the trading costs associated with bar-by-bar portfolio rebalancing, as well as the fact that we can’t know the capital required at the outset. Having said that, there is still much value in testing a mean reversion idea with this linear strategy as it shows whether we can extract profits without any data snooping bias as there are no parameters to optimize. Also, a consequence of the bar-by-bar portfolio rebalancing is that the results of the linear strategy backtest are likely to have more statistical significance than other backtests that incorporate more complex entry and exit rules. Essentially, the simple linear strategy presented here can be used as a proof of concept to quickly determine whether a portfolio is able to be exploited using mean reversion techniques.


Practical approach to linear mean reversion.


If the simple linear strategy is not practical for trading, how can we exploit mean reverting portfolios? In Algorithmic Trading , Ernie Chan suggests a Bollinger band approach where trades are entered when price deviates by more than x standard deviations from the mean, where x is a parameter to be optimized. The lookback period for the rolling mean and standard deviation can be optimized or set to the half life of mean reversion. The trade would be exited when price reverts to y standard deviations from the mean where again y is an optimization parameter. For y = 0 the trade is exited when price reverts to the mean. For y = - x the trade is reversed at x standard deviations from the mean. The obvious advantage of this approach is that we can easily control capital allocation and risk. We can also control the holding period and trade frequency. For example, setting x and y to smaller values will result in shorter holding periods and more round-trip trades.


Exploiting the AUD-NZD-CAD portfolio using this simple implementation with x = 2 and y = 1 returns the following equity curve, with transaction costs included:


The equity curve of the Bollinger strategy is of similar shape to the linear mean reversion strategy, but it trades much less and allows for simpler control of risk and exposure.


Pensamentos finais.


This post extended the previous article on the exploitation of individual mean reverting time series by exploring the construction of portfolios whose market value is mean reverting. In addition to the simple linear mean reversion strategy I also presented a more practical approach that could form the basis of an actual trading strategy.


As stated in the introductory paragraphs, I wanted to show the good and the bad of mean reversion trading. The equity curves presented show periods of outstanding performance as well as periods of the polar opposite. Clearly, there are times when mean reversion is highly profitable, and other times when it just doesn’t work (perhaps trend following is more suitable at these times). But how does one determine, in real time, which regime to follow? How does one determine when to switch? I’ve explored several options, including a simple filter based on a trend indicator and a filter based on the actual performance of the strategy in real time. However, due to the lag associated with the filter values, these approaches are of little if any value. Diversification is another option, that is, continuously trade both mean reversion and trend following strategies at the same time in the belief that the profit from the dominant regime will more than make up for the losses of the other.


If you have an idea about how to address this issue, please let me know in the comments. I’d love to hear from you.


Download files and data used in this analysis.


Here you can download the price data and scripts (Zorro and R) used in this post: Mean reversion 2.


Ilya Kipnis.


Knowing when to revert and when to trend follow without the signal lagging is the gazillion dollar question. From my conversations with my mentor, you want a regime changing model for that.


After all, if you have a rangebound instrument, pick your favorite mean reversion indicator and go nuts. If you have a trending market, just buy and hold the trend. But to know which is which? I’d love to see some ideas posted elsewhere. I’ve tried depmix’s default settings and it just gave me garbage.


Kris Longmore.


Regime switching models are a whole new area of research for me. Something I’ve been meaning to tackle for a while now, but haven’t yet gotten around to. This is good motivation to bump it up the to do list. I’ll spend some time learning the first principles and then take a look at the depmix package you mentioned. Although from your experience it sounds like the solution is not a simple one.


Your last suggestion should work fine. Trade a basket of uncorrelated systems with a range of parameters. You’ll get the sum of returns with reduced drawdowns. Some Zorro code is here: financial-hacker/build-better-strategies-part-2-model-based-systems/


Kris Longmore.


Thanks for the suggestion Kevin. I think the key term in your comment is ‘uncorrelated’. I’ve had mixed success with strategy diversification in the past thanks mainly to the correlation between strategies changing over time. But that’s not really a failure of diversification, rather a failure of the trader to properly manage it.


great analysis. I did a lot of stuff there and traded (my website is down) so here are some things I found out.


No need to diversify mean reverting and trading, just find 5-10 cointegrating relationship and your Sharpe ratio will be 2+ as residuals are all uncorrelated. You’ll also need to do a WFO or IS/OOS test as no one will take seriously if you have a look-ahead bias. (there is a 50% performance degradation in out of sample testing from my own experience after doing in sample optimization) I strongly suggest WFO for every parameter as it will adapt to changing market modes. Also try other loading from PCA as the first one has the most variance but also the most likely to contain trends.


As for regime switching some filter to filter out trends is an option if you can find one. No need to waste time as regime switching field is huge.


Additional an execution algo that uses EMA vs SMA was better option for me (probably due to large funds using it also and size moves markets), plus you can use 2 st dev to enter but exit after n days could be a better one as a rule.


Anyhow hope it helps. If you want to talk more feel free to contact me.


Kris Longmore.


Hi D, thanks for sharing your findings! Some great stuff there that hadn’t occurred to me. I’ll definitely be pursuing them. Totally agree regarding walk forward testing; it is an essential part of the evaluation phase of strategy development in my opinion.


I hadn’t considered using the other loadings from the principal components analysis, but I will look into that too. I also like the n-day exit idea. It is appealing in its simplicity and I have found it useful in the past.


Eduardo Gonzatti.


Have you tried to use some kind of dominantPhase analysis from Zorro in the cointegrated spread and then trading it (spread) when the phase indicated so?


Ps: I’ve traded cointegrated equity pairs for some 4 yrs, and have no clue about cointegrated fx pairs =) but they do look way better and more robust for doing such.


Kris Longmore.


Hi Eduardo, no I hadn’t considered extracting phase information from the cointegrated spread. My first reaction to the idea is that this approach would be applicable if some sort of cyclical behaviour was present in the spread. I don’t presently know if that is the case or not, but I will certainly look into it. In your experience, have you found exploitable cycles in the spreads you have traded?


Eduardo Gonzatti.


Actually, I had this idea when fiddling with the Zorro manual a couple days ago.. I was studying about spectral analysis of financial time series returns and stumble upon Zorro’s cycle/phase indicators based in Hilbert Transforms, so it just occurred to me that, IF you assume that a spread (say, a cointegrated ols residue of two equities) is mean reverting (cointegrated and low enough half life with OU equation), you could probably use the same kind of transformation / cycle analysis that Zorro does (i thinks it’s based in John Ehlers books) in those spreads, in order to get “optimized” entry points, assuming those would predict turning points in the spread itself.


Don’t know if my assumption is mathematically sound, but it’s a hunch..


Personally, I never tried something aside from N*sigmas deviations for trading cointegrated spreads, because of the assumption that they are stochastic.


Sorry for any misspellings,


Hi Robot Master,


Thank you for the analysis. One question, is keeping the quote currency constant also necessary for CADF and OU, or it is only for required for Johansen?


Kris Longmore.


If you think about what the tests are doing, the answer to this becomes fairly obvious. The tests mentioned look for a unit root and/or stationarity of the time series in question. In this case, the time series is a spread created by the linear combination of the constituent currency pairs. Would it make much sense to test a spread that consists of, for example:


What would the units of the spread be?


Thank you for answering.


With two pairs with same quote currency, one unit moves have the same dollar values. So what you say is, unless we have this, the tests will not make any sense. Then for example for sgdchf vs zarjpy the pairs to test are sgdusd and zarusd, inverting the quotes or trading signals when necessary.


Am i correct with my interpretation.


Kris Longmore.


Assuming you want to trade a mean reverting spread that consists of SGD and ZAR, yes what you described is how I would approach it.


What about using 10 assets and combining them in groups of 3 with a loop and then calculate the eigenvalues of all those combinantions to get as an output the best cointegration portfolio?


Just a heads up:


You’re missing a negative here:


It should be, '-log(2) / lambda'


And caution to the lag function; I'm unsure which package was used, but you might be erroneously shifting the lag forward to y(t+1) by using '-1' if you're using the base. lag function. I like quantmod. Lag(y, k = 1).


Kris Longmore.


Thanks for pointing that out – you are absolutely correct on both counts. I’ve updated the code accordingly and found that the actual half life should be roughly 53 days, an increase over the 40 days calculated erroneously. I will some day get around to updating the affected results (ie the equity curves of the trading strategies that used the erroneous half life)!


Can you enlighten me as to the meaning, when both eigenvalues for a pair are the same sign? They are normally opposite… so I’m selling one and buying the other. The same sign seems to imply go long (or short) on both… which seems at odds with the pair trading methodology.


Riskmaverick.


Just came across your blog post while searching for the concept around half-life in mean reversion. I would be keen to know your thoughts around using Kalman filter to estimate hedge ratio. Would be even better if you have an example implementation in R.


Kris Longmore.


I think Kalman filtering is a great way to estimate hedge ratios. The optimal hedge ratio is rarely static, and Kalman filtering provides a sensible way to update it in real time taking into account the inherent uncertainty in its calculation.


Is there a easy way to ensure that the cointegration relationship is about to expire?


Kris Longmore.


I’m not sure of any easy way, but one reason these relationships break down is a structural change in the underlying relationship, for example following an earnings announcement that causes a sudden revaluation in one security. In that case, a different cointegrating relationship would probably emerge, once the jump or decline in price settled down to its new level. Another example that relates to the cointegration of ETFs that track the economies of two countries: a relationship could break down when one country’s economy shifts in some fundamental way, for example from a manufacturing to a service base. The two ETFs end up being exposed to different factors and so the cointegration relationship breaks down. In this case, it would happen more slowly.


Analyzing Pairs with Correlation and Cointegration.


Pairs Trading or Market Neutrality have long been seen as complex hedge fund style strategies with limited application for the retail trader. As part of our series on Correlation and Cointegration, we thought it would be beneficial to look at how both regression patterns can be used effectively to identify pair trading opportunities and scenarios, and how to reduce possible pitfalls.


The mystery that surrounds Cointegration and its complexity from a formulation point of view has somewhat put off many traders. Funnily enough, even as I write this post the spell check does not identify Cointegration as a word, which gives you an indication of how often the term is referenced.


Identifying Good Pairs Trades.


Although there are a number of formulas or tests that can be used, one of the most widely adopted is that of the Augmented Dickey Fuller (ADF) Test. Formulating a p-value, the test allows the trader to identify how cointegrated two series are over a specified period in an efficient and simplified way.


To put this into context, if the prices for currency A and currency B are inputted into the model and the p-value comes out at 0.02, then this identifies that 2% of the time the two variables are not stationary or 98% of the time they are cointegrated. Make sure that you use a good number of values (eg 3 years on a daily chart), otherwise the calculation may not give you the most accurate indication.


There are a number of sites where you can download an excel version of the ADF test including quantcode.


The next part in the calculation process is to work out the correlation. It is recommended that multiple time frames are used to also paint a picture of the cycle of the linear regression. To highlight how much of a discrepancy there can be, we ran scans on the EURUSD/GBPUSD and Gold/Silver Pairings. Results were very interesting.


30 Day Correlation: 73.46%


2 Year Correlation: 64.89%


13 Year Correlation: 89.20%


2 Year Cointegration: 13%


The long term correlation indicates that the pairs track a very similar path. However on a short term basis, they will gradually move apart. On a cointegration basis, only 13% of the time over the last two years have the pairs reverted back to the same mean.


30 Day Correlation: 94.98%


2 Year Correlation: 26.99%


13 Year Correlation: 95.3%


2 Year Cointegration: 85%


The two year interval highlights how the prices are statistically out of their long term and short term ranges. According to the cointegration figure, the prices of both Gold and Silver reverted back to the same mean 85% of the time.


Conclusion : Gold and Silver is a better pairs trade than EURUSD and GBPUSD.


Cointegration and Correlation Technicals.


Now that we determined that gold and silver show the highest correlation and cointegration, we need to analyse the technicals for specific entry and exit points. In the below example, there are three specific graphical representations (top chart is the gold price, middle chart is the regression correlation, and the bottom chart is the Silver price). The linear regression period is 360 days with no look back.


A chart showing gold, silver and their correlation.


The diagram had two possible entry and exit points over the one year period. In August, the 360 regression channel indicated that the linear value would revert to its mean after a period above the 3 rd standard deviation.


According to the chart, a Short Gold and Long Silver pair signal would have been triggered. The second trade came in December, with the linear line breaking back through the bottom standard deviation channel.


With reference to the above example, we can see a number of issues that could greatly impact performance. Curve fitting as it is commonly known is best described as a specific series fitting a time variable without giving a true and clear picture of performance.


Strategies that require definitions from future pricing or large historical data are usually curve fitted. On paper it may look great, but in real trade scenario, the results may be completely different.


The 360 regression channel chart did not pass the out of sample (curve fitting) test. As can be seen below, when the look back period is amended to 162 Days, the signal would be completely different.


A moving window for the regression channel provides fewer opportunities for curve fitting.


One of the solutions for curve fitting in pairs trading is to reduce the linear regression period to a shorter window or time frame. Although this can result in sensitivity to volatile movements, this reduces the potential risk to forward looking scenarios. Traders should also be aware of changes in the correlation and cointegration values of the pair, as these can shift quickly due to market mispricing or global economic and political events.

Comments