Cointegration trading forex


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. Tire-me com as 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.

Cointegration trading forex
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.
Pairs Trading & # 8211; Confirmação do Ponto de Entrada Usando Indicadores Técnicos.
Os pares comerciais sem confirmação adequada são como construir uma casa sem um engenheiro estrutural. No curto prazo, o design pode ser estável e seguro, no entanto, durante um período de tempo mais longo, a sensibilidade às condições climáticas e outros fatores podem ser perigosos.
Os sistemas baseados em um único fator, invariavelmente, terão uma vida útil e precisarão ser treinados para acomodar mudanças nas condições do mercado. Conforme discutido em nosso artigo anterior sobre cointegração, o grau em que um comerciante não adere a essas diretrizes rígidas, pode afetar grandemente sua rentabilidade.
Indicadores técnicos para sinais de entrada em um comércio de pares.
Alguns dos principais indicadores técnicos e padrões que podem funcionar bem para confirmar sinais de entrada incluem o Índice de Força Relativa (RSI), Índice de Facilidade de Mercado (MFI) e gráficos de Candlestick. Cada um tem um atributo exclusivo e pode ajudar a definir pontos de entrada e saída de chave.
Índice de Força Relativa (RSI)
Embora este seja um indicador relativamente comum que não suporta o teste do tempo por si só, o RSI pode ser uma ferramenta eficaz na negociação de pares. Definida como a mudança de impulso, este indicador técnico variará de 100 (extremamente sobre-comprado) a 0 (extremamente sobrevendido). Traditionally the trigger points are 70 for a short and 30 for a long. With respect to pairs trading, this strength index allows the trader to confirm overbought and oversold scenarios.
RSI shows how a technical indicator can be used to spot entry opportunities.
The sppread between Gold and Silver is considerable, with the cointegration still above the required 80 mark (according to catalyst corner). The relative strength index has confirmed that silver is trading in the oversold bracket (at 75), providing the trader with a valid entry for a short position .
Market Facilitation Index (MFI)
Invented by technical analyst Bill Williams, the MFI identifies the momentum of a movement based on the volume. Depending on the strength of the buying and selling pressure, the indicator will price in an estimate of whether the trend is strong or weak.
Commonly used with longer time frames, the Market Facilitation Index is calculated by using the high, low and volume bars. Unlike RSI, the indicator is represented by a bar graph with coloration. Green highlights strong volume and momentum, whilst blue, brown and light brown indicate indecisive volume reactions. In pairs trading, the MFI can identify long term momentum patterns and which cross to buy or short.
Included below is a table from Wikipedia, which visually highlights the degree to which an adjust in volume can influence the market facilitation index.
The money flow index uses basic bar information to create a colored graph.
Gold has crossed below silver on a linear regression basis. The Market Facilitation Index however has indicated that volume and momentum are rising, and there will be a rebound in the price. The trader would look at going long gold and short silver.
Castiçais.
Candlesticks are an extremely efficient way of determining the trend of a price. Different patterns defined by the open high low and close price can supply the trader with efficient entry and exit points. From a pairs trading point of view, it is important to only open a position based on a strong buy or sell pattern. Bullish signals include a piercing pattern, inverted hammer, morning star and abandoned baby. For more information on each of these patterns it is recommended to visit stockcharts.
During the month of April, the spread between Gold and Silver is relatively tight. A morning star formation appears on the Gold price, indicating a potential bullish reversal. The trader in this case, would open a Long Gold, Short Silver to capitalize on a sudden breakout in the price.
Pairs Trading Case Study: Gold / Silver.
Finding a pair of currencies or commodities that can stand up to the cointegration test on both a short term and long term basis can be quite difficult. It is common for pairings to have some degree of distance or long term deviation away from the linear regression and this can greatly affect performance.
Several high profile market neutral hedge funds have been victim to this regression breakout. Long Term Capital Management (LTCM) is the most famous example. The fund lost several billion dollars in 1998 during the Russian financial crisis. Nearly every position in its bonds and derivative pairings went off the rails all at the same time.
Trading pairs is not full proof and strict risk management and cointegration retraining must be implemented. As discussed in our previous posts on correlation and cointegration, we are looking for the degree to which two variables will return to their common mean. This will determine our entry and exit strategy, and where we will place our stops.
In one of our previous articles – ‘Analysing Pairs with Correlation and Cointegration’, we identified Gold and Silver as a good potential trading pair due to its statistically high long term percentage levels. We calculated the cointegration using a free tool from the website – Catalyst Corner catalystcorner.
30 Day Correlation: 94.98%
2 Year Correlation: 26.99%
13 Year Correlation: 95.3%
2 Year Cointegration: 85%
Silver (Black) Gold (Orange Green) 30 Minute Chart.
Setting up Charts.
Setting up a pairs template in MetaTrader is relatively simple and requires two free indicators (these have been included with the tutorial). The first indicator is that of the FX Correlator and the second is the overlay chart. Highlighted below are the step by step instructions on adding each to your chart.
1. Open Metatrader and Choose Chart.
2. Drag the Overlay Chart onto the open chart window, and specify default settings. Clique OK.
3. Attach the FX Correlator to the chart, click INPUTS and change all currencies to FALSE except for USD and AUD. The reason why we are keeping these two as TRUE is outlined in the trade setup section. Clique OK.
Trade Setup.
You will now see two indicators positioned on the chart window. The top overlay chart will highlight the price of silver in comparison to gold. You will notice that the general trend direction is quite similar (correlation), however there are points along the timeline where the prices widen and then regress (cointegration). These are the points that we are looking to profit from.
The FX correlator is a unique indicator that calculates a spread between the main chart window and specified other crosses. When we added the indicator to the chart, we only specified the AUD and USD currencies. Hence we can only see two coloured linear regression points along the time line. The reason we chose the Aussie dollar, was because of its susceptibility to commodity prices movements and the US dollar is the natural base cross with Gold and Silver.
• Long Gold and Short Silver when the USD crosses above the AUD on the FX Correlator.
• Short Gold and Long Silver when the USD crosses below the AUD on the FX Correlator.
In the diagram above, we have circled a number of trade setups. On the 14th of May at 4:00, the USD crossed higher than the AUD, triggering a potential Short Silver/Long Gold scenario. According to the chart, Silver regressed back to the mean and overlapped Gold at 12:00. The second possible trade scenario occured on the 15th of May at 20:00. As the AUD crossed above the USD, a Long Silver / Short Gold trade was triggered with the spread widening.
Gerenciamento de riscos.
• Tight Stops on both crosses.
• Calculate the correlation and cointegration of Gold and Silver regularly (daily basis). If the cointegration breaks down (below 80%) do not trade.
• Position size should be based on underlying value and may not be equal.
Charting a Linear Regression.
Linear Regression can be an effective tool when defining the overall momentum or trend of a series of prices. It can be adapted to all data. Fields outside of trading, including risk management and statistics, use the same statistical technique. Insurance providers will commonly plot the relationship between claims and age groups to determine premium levels.
To put it into perspective, if there were five people in a group who each owned two television sets, one person who owned no tv and two people that owned four tv sets, then the linear regression on a rough basis would indicate the trend is just slightly above the two sets. The standard error or deviation in this case would be the two outside samples of no tv and four televisions.
Can regression be an effective tool for trading on a longer term basis or is it too susceptible to market volatility and future pricing? To understand how linear regression really works, we need to chart the channel and its standard deviation levels.
The first tutorial below looks at a scatter graph in excel and how to plot a linear regression. Please note that it does not include the standard deviation channels.
Charting a Simple Regression in Excel.
Open your Metatrader platform and click on TOOLS, HISTORY CENTER. Choose the relevant pair for your regression analysis. Once you have chosen the time frame, click on EXPORT and SAVE the spread sheet. Open the spread sheet and highlight the two relevant columns you would like to use in the scatter chart. In the diagram above we used time (minutes) and price. Click INSERT and choose SCATTER. A drop down menu will appear. To get a true reflection, click on SCATTER WITH ONLY MARKERS. A chart will appear with dots representing the distribution of pricing data. To decipher the linear regression, highlight the chart and click on LAYOUT in the excel menu. Navigate to TREND LINE. A drop down menu will appear with several options. Choose LINEAR TREND LINE. The regression line will now appear.
Excel draws a linear regression of the EURSUD prices using data from MetaTrader M5 charts.
As discussed previously, the excel chart will only give a basic trend and will not supply the user with detailed standard deviations. It is also recommended that you do not highlight too much data for a realistic short term interpretation.
We specified eight hours of five minute data on the EURUSD cross in the above diagram.
Charting Linear Regression in Metatrader.
Open the desired chart and time frame in Metatrader Click on INSERT and CHANNELS. You will then be provided with a list. Choose LINEAR REGRESSION. Hold down your left mouse button and drag the linear regression over the desired time period. In the above diagram, we chose a linear regression with a starting date of the 13th May at 10:30. You will notice that the regression line will appear and adjust according to the data. One standard deviation will also appear. If you would like a second deviation channel on your chart, navigate back to the top of the terminal menu and click on INSERT – CHANNELS and choose Standard Deviation. You will then need to drag the standard deviation channel using your left mouse button and specify the same time period.
MetaTrader interprets the price movements and draws a liner regression.
Recomendação.
It is recommended when trading using regression, that you specify a shorter range so as to manage the volatility. As prices shift, so will the channel, and profit potentials could quickly turn to losses.
It is important to always keep stops tight in case of violent swing backs in the price.
Correlation vs. Cointegration.
Correlation and cointegration are two regression based concepts that are commonly misused by the trading community. Complex in their formulation, both are inter related and are used to calculate the relationships between two or more products (ie commodities, forex, stock prices) over a specific time period.
Correlação.
A value of +1 (positive correlation) or -1 (negative correlation) is assigned based on the how efficiently the two prices react to each other. Correlation identifies pairs that move in either tandem or opposing directions .
A good example of a long term correlation pairing is that of the EURUSD and the USDCHF crosses, which trade in a similar direction. On the other side of the coin, the EURGBP and the AUDNZD trade in opposing directions. They show a negative correlation of -0.81.
Although this figure indicates that the crosses moved against each other, there is a slight degree of uncertainty over the long term sustainability of this negative result. Professional traders commonly set the entry benchmark for pairs above or below 0.9 or -0.9.
Correlation does have a significant drawback, which can greatly affect profitability. Although two pairs may be correlated, they are still not in complete unison, which can cause a slight drift in the prices. In the case of the EURGBP and the AUDNZD, it is a drift -0.19.
Read the post on forex correlation for more details on the topic.
Image credit: Vassia Atanassova.
The left box shows a strong correlation. The middle shows a weak correlation. The far right shows an image with no correlation.
Cointegration.
Cointegration analyses the movements in prices and identifies the degree to which two values are sensitive to the same mean or average price over a given time period. It doesn’t say anything about the direction that the pairs will move. Cointegration only measures whether or not the distance between them remains stable over time.
If we look at gold and silver, for example, we may find that they track a common average value. They may trade in opposite directions from day to day. At some unknown point in the future, they should revert back towards that average and hence they are cointegrated. Hedge funds commonly use this formula to program statistical arbitrage models to identify pairs to trade.
Another important factor to keep in mind is the look back period of the mean and standard deviation. In essence, if you make the look back value 700, then the regression channel will calculate what the average price is over 700 periods. This can be too inefficient and will limit the sensitivity to changes in the market dynamic.
On the other hand, if you set a short look back period, then it will cause a whipsaw effect and will be far too sensitive. It is important to get a balanced look back within the range of 200-350.
Gold / Silver Example.
• Top Section: Standard Deviation and Linear Regression.
• Middle Section: Relative Performance Gold (dark blue) and Silver (light/ turquoise blue)
• Bottom Section: Gold Daily Chart and Time Line.
The above chart highlights the overall correlation of Gold and Silver and the degree to which breakouts could trigger trade opportunities. I have circled a number of different cointegration scenarios and referenced these on the second section with P1, P2, P3 and P4 labels.
Silver Spike – Marcha.
A significant spike in the price of Silver in March sent the linear regression value below the lower standard deviation channel of -2.0. To capitalize on the significant discrepancy in prices, the trader would have looked at shorting silver and going long gold. Performance wise, this would have resulted in an overall profit as silver weakened heavily, crossing below gold in May.
Silver Oversold – July.
The silver price continues to weaken on a relative level to gold. In June and July, the regression value passes above the top standard deviation channel, indicating that silver is oversold and the price will have to revert back to its mean. The trader decides to open a long position in silver and short gold. As forecast, it returns to its mean and the gap between both spot prices closes quickly.
Silver Overshoots – December.
Once again the silver price overshoots gold. This sets up a long gold, short silver opportunity. On a performance level, the trader would capitalize on.
the spread and profit from the position.
Silver Selloff – April.
Puncturing the second standard deviation channel, the gold price stabilises whilst silver weakens heavily. This has now supplied the trader with a long.
silver, short gold opportunity.
Forex Correlation.
Correlation strategies appeal to forex traders because it removes the stress associated with picking market direction. When two correlated pairs diverge from one another, the idea is to simply buy one pair and sell the other.
What are correlated currency pairs?
Correlation offers a mathematical probability of two “time series” moving in the same direction. Applying the idea to forex, it means that we need to pick two currency pairs. EURUSD and USDCHF are two popular choices due to their extremely high correlation, so we’ll use those.
Now we ask a simple question: “If the EURUSD rises, what is the probability of that the USDCHF will also rise”? Our calculations will pump out a simple a number between -1 and +1. +1 means that that if Currency A rose in value, then it is 100% certain that Currency B rose in value. -1 means that if Currency A increased in value, then it is 100% certain that Currency B decreased in value. A value of 0 means that the movement of Currency A exercises no effect at all on Currency B.
Traders generally consider a correlation significant whenever the number is greater than 70%. EURUSD and USDCHF are so popular because they hold the strongest correlation among the major currency pairs. When market volatility was very low a few years ago, it was around -93%. Today, the correlation tends to hang around -80%. The European debt problems and Swiss National Bank’s intervention have a lot to do with the decrease in this number. Their trading relationships are far less stable.
Risks of correlation strategies.
Let’s move back into familiar territory with my favorite example, the moving average. If you take the average over the past 20 bars, you know from experience that the average will differ if you study a 50 period versus a 200 period average. If you look at the average on a 5 minute chart versus an hourly chart, the number will vary yet again.
The take-away here is that the correlations work the same way. The correlation between EURUSD and USDCHF might even be positive if you look at a short enough time scale. As you back away in time, you will notice that the further out you go, the more steady the correlation numbers look. If the weekly correlation of the EURUSD and USDCHF is -80%, you would expect the numbers to get more wild and erratic as you scale all the way down to a tick chart.
The same problem with the moving average also appears. Studying the correlation over 50 periods provides a responsive number, but it is also far less consistent than the 200 period correlation. What a short period gains in responsiveness, it loses in stability.
You should also consider whether the correlation that you’re studying makes fundamental sense. Just because the temperature change in Mongolia predicted the direction of USDJPY for the past week does not make it a good idea to use in the future. The same goes with pair trading.
EURUSD and USDCHF should be highly correlated for two reasons. They both contain the same currency in the pair (USD), which half weights them with the same instrument. Additionally, the EUR and CHF both have strong trading relationships with the US. You would expect both the Euro Zone and Switzerland to share a need for buying and selling US dollars. They need them for buying oil, importing and exporting to the US, etc. Anyone with a cursory understanding of macroeconomics could explain why this relationship makes sense.
Correlation traders typically settle on pairs that share a common currency. The EURUSD and USDCHF trade both share the US dollar. When you buy EURUSD and buy USDCHF, you are really:
Buying EUR and selling USD.
Buying USD and selling CHF.
Notice that the USD cancels itself out. What you are really doing is buying EUR and selling CHF. This is commonly known as the EURCHF pair. Assuming that the spread is not outrageous, it makes more sense to simply buy or sell EURCHF directly rather than going through the convoluted process of managing two open trades.
If you decide to pursue the two pair approach, you must consider the need to balance the trade sizes against each other. Using standard lots as the example, 100,000 EUR is 137,500 USD. 100,000 USD is 90,900 CHF. If you buy one standard lot of EURUSD, you are buying $137,500 of it. When you buy a standard lot of USDCHF, you are only buying $100,000.
$137,500 obviously does not equal $100,000. Unless you intentionally decided to trade different sizes, you may want to consider equalizing them.
€100,000 / $137,500 = x * (₣90,900/$100,000)
x = €100,000 / ₣90,00 * $100,000 / $137,500 = 0.803.
You would need your EURUSD trade to be 80% of the size of the USDCHF trade.
What correlation is not.
Correlation only provides insight into the probability of direction. It says absolutely nothing about the strength of a particular move. A few months ago the USDCHF climbed 1,000 points in value within a single day. The EURUSD only moved a few hundred pips. The USDCHF moved dramatically further than the EURUSD both in terms of pips, but more importantly, as a percentage of price.
Consider if you were short EURUSD that day and short USDCHF. You lost a ton of money. On the flip side, if you were long EURUSD and long USDCHF, then you got lucky and earned the move. Regardless of what happened, correlation told you nothing about the outcome when they move in the same direction. For that reason, I prefer looking at a less intuitive method called cointegration.
Cointegration.
Conintegration turns the problem on its head. Rather than asking whether or not two pairs move in the same direction, it asks how likely are they to remain a certain distance apart. Naturally, that distance tends to vary with time. What you want the cointegration formula to tell you is how likely two pairs are to come back to a standard distance. If you see two pairs spread unusually far apart and the numbers tell you that they usually come back together, then it makes sense to consider a pair trade.
Ernest Chan has a friendly introduction to cointegration that I highly recommend. A much uglier, math intensive introduction to the subject, albeit one that is also far more thorough, is in the book Pairs Trading by Ganapathy Vidyamurthy.

QuantStart.
Junte-se ao portal de membros privados da Quantcademy que atende à comunidade de comerciantes de varejo de varejo em rápido crescimento. Você encontrará um grupo bem informado de mentalistas quant pronto para responder suas perguntas comerciais mais importantes.
Confira meu ebook sobre o comércio de quant, onde eu ensino você como criar estratégias de negociação sistemáticas lucrativas com ferramentas Python, desde o início.
Dê uma olhada no meu novo ebook sobre estratégias de negociação avançadas usando análise de séries temporais, aprendizado de máquina e estatísticas bayesianas, com Python e R.
By Michael Halls-Moore on June 2nd, 2016.
A while back we considered a trading model based on the application of the ARIMA and GARCH time series models to daily S&P500 data. We mentioned in that article as well as other previous time series analysis articles that we would eventually be considering mean reverting trading strategies and how to construct them.
In this article I want to discuss a topic called cointegration, which is a time series concept that allows us to determine if we are able to form a mean reverting pair of assets. We will cover the time series theory related to cointegration here and in the next article we will show how to apply that to real trading strategies using the new open source backtesting framework: QSTrader.
We will proceed by discussing mean reversion in the traditional "pairs trading" framework. This will lead us to the concept of stationarity of a linear combination of assets, ultimately leading us to cointegration and unit root tests . Once we have outlined these tests we will simulate various time series in the R statistical environment and apply the tests in order to assess cointegration.
Mean Reversion Trading Strategies.
The traditional idea of a mean reverting "pairs trade" is to simultaneously long and short two separate assets sharing underlying factors that affect their movements. An example from the equities world might be to long McDonald's (NYSE:MCD) and short Burger King (NYSE:BKW - prior to the merger with Tim Horton's).
The rationale for this is that their long term share prices are likely to be in equilibrium due to the broad market factors affecting hamburger production and consumption. A short-term disruption to an individual in the pair, such as a supply chain disruption solely affecting McDonald's, would lead to a temporary dislocation in their relative prices. This means that a long-short trade carried out at this disruption point should become profitable as the two stocks return to their equilibrium value once the disruption is resolved. This is the essence of the classic "pairs trade".
As quants we are interested in carrying out mean reversion trading not solely on a pair of assets, but also baskets of assets that are separately interrelated.
To achieve this we need a robust mathematical framework for identifying pairs or baskets of assets that mean revert in the manner described above. This is where the concept of cointegrated time series arises.
The idea is to consider a pair of non-stationary time series, such as the random-walk like assets of MCD and BKW, and form a linear combination of each series to produce a stationary series, which has a fixed mean and variance.
This stationary series may have short term disruptions where the value wanders far from the mean, but due to its stationarity this value will eventually return to the mean. Trading strategies can make use of this by longing/shorting the pair at the appropriate disruption point and betting on a longer-term reversion of the series to its mean.
Mean reverting strategies such as this permit a wide range of instruments to create the "synthetic" stationary time series. We are certainly not restricted to "vanilla" equities. For instance, we can make use of Exchange Traded Funds (ETF) that track commodity prices, such as crude oil, and baskets of oil producing companies. Hence there is plenty of scope for identifying such mean reverting systems.
Before we delve into the mechanics of the actual trading strategies, which will be the subject of the next article, we must first understand how to statistically identify such cointegrated series. For this we will utilise techniques from time series analysis, continuing the usage of the R statistical language as in previous articles on the topic.
Cointegration.
Now that we've motivated the necessity for a quantitative framework to carry out mean reversion trading we can define the concept of cointegration. Consider a pair of time series, both of which are non-stationary. If we take a particular linear combination of theses series it can sometimes lead to a stationary series. Such a pair of series would then be termed cointegrated .
The mathematical definition is given by:
Cointegration.
Let $\ $ and $\ $ be two non-stationary time series, with $a, b \in \mathbb $, constants. If the combined series $a x_t + b y_t$ is stationary then we say that $\ $ and $\ $ are cointegrated .
While the definition is useful it does not directly provide us with a mechanism for either determining the values of $a$ and $b$, nor whether such a combination is in fact statistically stationary. For the latter we need to utilise tests for unit roots .
Unit Root Tests.
In our previous discussion of autoregressive AR(p) models we explained the role of the characteristic equation . We noted that it was simply an autoregressive model, written in backward shift form, set to equal zero. Solving this equation gave us a set of roots .
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.
Apenas iniciando o comércio quantitativo?
3 razões para se inscrever na QuantStart List:
1. Quant Trading Lessons.
Você terá acesso instantâneo a um curso gratuito de 10 partes, com sugestões e dicas para ajudá-lo a começar a negociação quantitativa!
2. Todo o conteúdo mais recente.
Todas as semanas, vou enviar-lhe um envoltório de todas as atividades no QuantStart para que você nunca mais perca uma postagem novamente.
Real, dicas de negociação viáveis, sem tonturas.

Forex Mecânico.
Negociação no mercado FX usando estratégias mecânicas de negociação.
Cointegration in the Forex market.
From the many different types of statistical arbitrage available, pairs trading is perhaps one of the most popular. In pairs trading a trader will attempt to exploit the linear relationship between the values of two instruments, attempting to buy/sell them when the relationship between their values increases/decreases to values that offer enough profit potential. However pairs trading does not only require a linear correlation to exist but it also requires the instruments to be cointegrated, a fundamental property that ensures a fundamental connection between the instruments that diminishes the probability of the spread between both instruments “blowing up” (widening far beyond what is statistically expected). Although pairs trading is usually described in stocks/commodities, we rarely see any study of cointegration in the FX market. Today we’re going to look at some potential cointegrations in the FX market, why they exist and how they might be exploited.
Let us begin by defining what we mean by cointegration. Two series are cointegrated when they share a common stochastic drift. The typical example to explain cointegration talks about a man who goes to a bar with his dog. After getting drunk and leaving the bar both the man and the dog walk the same path home, although their stochastic drift – which is the random way in which the man walks and the dog wonders along the way – are different. When this happens their paths are in fact correlated but they are not cointegrated. If the man instead decides to put a leash on the dog their paths become cointegrated because they now share a common stochastic drift that is determined by the length of the leash. The man and the dog cannot be separated further than their leash allows, which makes any random movements they make beyond a certain length common to both (as they would pull on each other). In statistics we can evaluate for cointegration using several different tests from which theВ Augmented Dickey-Fuller (ADF) test is most popularly used. Note that this test evaluates only stationarity – not exactly cointegration – so another test such as a Johansen test is necessary to confirm cointegration.
When looking at classic examples of cointegration in financial time series you’ll notice that instruments that are cointegrated generally have some strong fundamental reasons to be cointegrated. The “leash” is a fundamental relationship between both instruments, their common stochastic drift. This relationship is usually very strong, for example two oil producing companies that share refineries in broadly the same countries and have the same clients, they are so tightly put together that it is very improbable for any random event to affect one without affecting the other. This is what makes deviations so tantalizing to exploit. В In Forex however, the story is a bit different because countries have a very hard time being so fundamentally similar.
You can actually see this easily when you look at the last year of data for several FX pairs that we usually view as correlated. For example the EUR/USD and GBP/USD traditionally have a large correlation. A normalized plot showing the last year of data shows you that both pairs indeed tend to move in the same direction but it is clear that this relationship does not follow the same stochastic drift. An ADF test using the last year of data for these two pairs will give you a value of 0.28 which is simply far too large to reject the null hypothesis. Looking at other similar pairs reveals very similar results, pairs like AUDUSD|NZDUSD – which are even more correlated than the EURUSD|GBPUSD turn out to also not be cointegrated.
So are there any cointegrations in the FX market? Actually the answer is yes. The Swiss National Bank’s decision to create a floor on the EURCHF at 1.20 generated a “leash” that made several pairs share a stochastic drift. For example the EURUSD and the CHFUSD are now cointegrated due to this fact. An ADF test will give you a value less than 0.01 for this pair, suggesting that they are indeed cointegrated (confirmed by the Johansen test as well). All similar CHF containing pairs also show cointegrations, such as the EURJPY|CHFJPY and the EURAUD|AUDCHF. This cointegrations all arise from the EURCHF peg, something which is evident when you look at the spread value as a function of time between any of these pairs. The third image shows you the spread of the EURUSD|CHFUSD pair as a function of time, it is no surprise that this is the exact same graph as the EURCHF for the past year. As the length of the “leash” varies, so does the value of the spread on the cointegrated pairs.
Could we take advantage of these cointegrations? Well, you certainly can. There are several ways in which cointegration can be traded but with a varying “leash” a good way is probably to trade the bollinger bands around the spread. You can trade on any timeframes but even when trading the daily timeframe you can make some money. The fourth image shows a very simple simulation in R where I traded the 3 pairs mentioned above, using 1:10 leverage, on a 10 period moving average using 1 standard deviation for band distances. The simulations show a 25% profit with a 10% drawdown within the past year, not too great but not too bad either. It is possible that further refinements and entries/exits on lower timeframes can indeed increase these margins.
One important thing to remember here is that the leash is a peg from a central bank. If this peg for some reason stops existing it is possible that this cointegration will simply vanish. It is therefore advisable to keep an eye on fundamental developments and stop trading the cointegration if this arises. It is also important to constantly repeat the statistical tests for cointegration as new data comes in so that you can stop trading any of these pairs as soon as the cointegration does show to break. If you would like to learn more about FX trading and how you too can design your own trading strategiesВ please consider joiningВ Asirikuy, a website filled with educational videos, trading systems, development and a sound, honest and transparent approach towards automated trading in general . Espero que tenha gostado deste artigo ! : o)
6 Responses to “Cointegration in the Forex market”
& # 8221; In statistics we can evaluate for cointegration using three different tests from which the Augmented Dickey-Fuller (ADF) test is the most popular.”
Yo, this is a stationarity check. it does not imply cointegration.
This is true, however when the result of this test is positive for financial series they are always cointegrated, this is why it is so popularly used for this purpose I believe. You can however perform a Johansen test as well or a Engle–Granger two step test. In the examples used on this article all series that pass the ADF test also pass the Johansen test, showing they are cointegrated.
i will be more than happy if you could share your r code in order to learn how to do this process.
Spread trading on EURUSD|CHFUSD sounds equivalent to trading EURCHF itself, which, as is actually directly possible at most brokers, should be preferred (pay only half the spread/commission costs). An EURUSD|CHFUSD spread is in fact a synthetic instrument for EURCHF.
So how is this spread trading any different (for the better)?
Thanks for commenting :o) You’re clearly right, it’s the same as trading a bollinger band strategy on the EUR/CHF. As mentioned on the article the spread is actually the same chart as the EUR/CHF. The cointegration of the EURUSD|CHFUSD is actually reflected as a tendency to return to the mean on the EUR/CHF. If you were going to trade this in practice you would indeed use the EUR/CHF to save trading costs instead of buying/selling EURUSD and USDCHF.
Great article overall but confusing in some places. As one comment’or has pointed out, ADF test is a unit root test. It is a formal test used to establish whether a price series is stationary or not. If you get a P value of more than 1%, 5% or 10% you can only fail to reject the null of unit root based on the significance level you are comfortable with. This does not infer the presence of co-integration.
The power of the ADF is also documented to be low so most researchers now go ahead to cross check with a complementary test such as KPSS.
It will be interesting to see the R code so we can also run it and see the results. You do mention that the Johansen test confirms the presence of co-integration, so all in all I believe your findings are on solid ground.
Some interesting questions that come up is how stable is the co-integration relationship? How frequently does the long run relationship estimate change and how big are these changes when they do occur.
Overall great article, keep them coming and do share some R code.

Comments

Popular Posts