Cointegration combina estratégia de negociação sobre derivativos


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; Negociando um par cointegrado.
Na minha última publicação gekkoquant / 2018/12/17 / statistics-arbitrage-testing-for-cointegration-aumentated-dicky-fuller / Eu demonstrou cointegração, um teste matemático para identificar pares estacionários onde a propagação por definição deve ser reversa média.
Nesta publicação, pretendo mostrar como negociar um par cointegrado e continuarei a analisar as ações Royal Dutch Shell A vs B (sabemos que eles estão cointegrados da minha última publicação). Negociar um par cointegrado é direto, sabemos a média e variância da propagação, sabemos que esses valores são constantes. O ponto de entrada para uma stat arb é simplesmente procurar um grande desvio para longe da média.
Uma estratégia básica é:
Se spread (t) & gt; = Diferença média + 2 * Desvio padrão, então vá curto Se propagação (t) & lt; = Distribuição média & # 8211; 2 * Desvio padrão, então vá Long.
Se spread (t) & gt; = nDay Moving Average + 2 * nDay Rolling Desvio padrão, então vá Curto Se spread (t) & lt; = nDay Moving Average & # 8211; 2 * nDay Rolling Desvio padrão, então vá longo.
Se spread (t) & lt; = spread médio + 2 * std AND spread (t-1) & gt; Distribuição média + 2 * Std Se propagação (t) & gt; = Distribuição média & # 8211; 2 * Std AND spread (t-1) & lt; Mean Spread & # 8211; 2 * Std Advantage é que só trocamos quando vemos a reversão média, onde, como os outros modelos esperam a reversão média em um grande desvio da média (a propagação é explodida?)
Esta publicação analisará a média móvel eo modelo de desvio padrão de rolamento para as ações Royal Dutch Shell A vs B, usará a relação de cobertura encontrada na última publicação.
Sharpe Ratio Shell A & amp; B Stat Arb Shell A.
Razão Annual Sharpe (Rf = 0%):
Shell A & amp; B Stat Arb 0.8224211.
Shell A 0.166307.
O stat arb tem uma relação de Sharpe superior ao simplesmente investir na Shell A. De uma primeira olhada, a proporção de sharpe de 0,8 parece decepcionante, no entanto, uma vez que a estratégia gasta a maior parte do tempo fora do mercado, terá uma baixa anualização proporção de sharpe. Para aumentar a proporção de sharpe, pode-se olhar para negociar freqüências mais altas ou ter pares de portfólio de modo que mais tempo seja gasto no mercado.
22 pensamentos sobre & ldquo; Arbitragem estatística & # 8211; Negociando um par cointegrado & rdquo;
Isso também significa que, quando identificado, a divergência máxima eu posso tomar posição em derivadas, como opções?
- opção de chamada de ATM no primeiro estoque.
- Opção de compra de compra no segundo.
ou com um BacKSpreadCall no primeiro e um BackSpreadPut no segundo para que eu possa definir as proteções e posso rolo se eles sairem do controle & # 8230;
As posições curtas devem ser dinheiro ATM ou levemente OTM na minha opinião.
Sobre o que você pensa?
Você tentou usar a abordagem de teste de Johansen para realizar um teste mais rigoroso da cointegração? O que você acha de combinar Engle-Granger com Johansen?
A propagação no acima não oscila em torno dele significa, idealmente, um par cointegrado deve trocar de lado, de forma não aberta, como mostrado acima. O seu artigo foi perfeito na cointegração adequada que você demonstrou. mas esta propagação não é uma propagação perfeita.
Eu concordo 100% com você.
No entanto, para fins práticos, desde que a reversão média ocorra mais rapidamente do que as mudanças médias, então você vai fazer bem.
Eu acho que é algo que eu perdi, como quantificar a velocidade de semi-vida / reversão.
Por favor, note que, na demonstração acima, o período de retrocesso é de 90 dias. Isso é bastante curto. Escolher 200 dias resultará em uma direção menos sensível / de mudanças. Provavelmente aumentará o tamanho das bandas de desvio padrão e resultará em menos negócios por ano. Isso geralmente resulta em uma proporção Sharpe mais baixa.
Postagem muito interessante. Adoraria ver a implementação em uma cesta de pares.
Eu faço algumas mudanças no seu programa para calcular as bandas bollinger e eu quero saber por que você colocou o desvio Padrão para a direita? (movingStd = rollapply (spread, lookback, sd, align = & # 8221; right & # 8221 ;, na. pad = TRUE))
OK, obrigado por responder!
Seu blog me dá a chance de implementar e desenvolver mais rapidamente minha estratégia de arbítrio estatístico.
Eu vou testar diferentes modelos de arbitragem estatística. Eu mantenho todos os visitantes no circuito!
No seu programa, o efeito martingale não está aqui. Como posso adicionar esse efeito?
Estou executando meus backtests com diferentes programas (Excel, R et ProRealTime (uma plataforma francesa)) e, para fazer alguma comparação, preciso adicionar o efeito martingale.
Obrigado pelo esclarecimento. Pelo mesmo argumento, rollmean deve ter o mesmo: rollmean (spread, lookback, na. pad = TRUE, align = 'right')
Com esta nova modificação, a relação Sharpe cai drasticamente ...
Coisas boas!! Penso que existem dois erros no seu código, no entanto. O primeiro é o cálculo da média móvel. Você esqueceu de ajustar o parâmetro de alinhamento para & # 8220; direita & # 8221; (como você faz para o desvio padrão). A função usa o padrão & # 8220; center & # 8221; e seus dados & # 8211; A propagação e a média móvel não estão alinhadas. Você também pode ver isso da trama. A média móvel termina 45 dias antes da propagação. O segundo bug está no cálculo dos retornos comerciais. Eu acho que você deveria retornar no dia seguinte quando entramos na posição no preço de fechamento.
Obrigado pelo seu código elegante. Notei que sua linha de código:
é destinado a aplicar a função shortPositionFunc a (-1 * aboveUpperBand + belowMAvg).
No entanto, a função shortPositionFunc leva dois argumentos x e y.
Existe algum erro de digitação no código?
Obrigado pelo seu esclarecimento!
Obrigado Gekko pelo código de resposta. É muito útil. Um par de comentários abaixo:
1) Outro leitor já comentou sobre isso acima. moveAvg precisa ser alterado adicionando align = "right" para ter o primeiro número de avg em movimento no dia 90:
movingAvg = rollmean (spread, lookback, align = "right", na. pad = TRUE)
2) uma vez que entramos em negociações no final do dia, o retorno na data de negociação não deve contar. podemos simplesmente deslocar cada elemento no vetor "posições" para baixo usando a função "shift" na biblioteca taRifx.
Além disso, não acredito que o retorno diário é (aRet - stockPair $ hedgeRatio * bRet). Imagine se você tivesse um grande índice de cobertura, ou seja, se o estoque A tiver um preço de US $ 100 e o estoque B for de US $ 10, então o hedgeRatio ficaria no bairro de 10. Como aRet e bRet estão em%, a fórmula não trabalhos. O retorno diário deve ser aRet - bRet * (relação entre relação dólar neutro versus relação hedge).
#Calculate spread daily ret.
DailyRet & lt; - aRet - bRet * hedgeRatioOVERdollarNeutralRatio.
tradingRet & lt; - dailyRet * shift (posições, -1)
Estou à procura de novas estratégias de negociação de par de equidade que melhorem a abordagem de co-integração padrão (por exemplo, comecei a procurar o par de negociação com copulas, o que ainda parece uma alternativa instável e instável à cointegração). Você tem algum artigo novo para me sugerir? Muito obrigado e felicidades pelo excelente blog.
A segunda metade do livro passa por muitas técnicas mais avançadas para proteger um portfólio / encontrar pares estacionários.
Estou um pouco confuso nesta etapa.
quando traçei as longas Publicações e Pequenos Posicionamentos juntamente com a propagação, bandas e linhas de média móvel encontradas, então há sinais longos consecutivos e sinais curtos. De acordo com o meu entendimento.
longPostions & lt; - se spread for abaixo da banda baixa.
longExit & lt; - se o spread estiver acima de movAvg enquanto estiver longo.
ShortPostions & lt; - se spread for acima da banda alta.
shortExit & lt; - se o spread estiver abaixo de movAvg enquanto curto.
é a mesma coisa que seu código está fazendo. Por favor, ajude-me a entender essa parte.
Oi Gekko, eu leio os livros do EP Chan que fala sobre este assunto e eu um pouco confuso sobre a reserva média. Quando dois ativos estão cointegrados, estamos supondo que eles voltem ao seu alcance, mas sua média móvel ou sua média total em um período fixo? I & # 8217; m dando melhores resultados usando parâmetros estáticos do que usar bandas de bollinger. Vou mostrar-lhe uma imagem com minha dúvida. Prntscr / 51jofw Você poderia escrever outro artigo de reversão média! Obrigado por todos.
Oi Gekko. Grande Código. Você poderia explicar mais uma idéia por trás dessa função cappedCumSum? Não entendo o momento em que você está especificando duas variáveis ​​de entrada, mas na função Reduzir () é apenas um parâmetro, & # 8211; é por causa de 0?
Há um erro. Seu algoritmo parece no futuro, o problema na função rollmean. Algoritmo usando a média móvel dos dias futuros para fechar a posição.

Estratégia de negociação de pares de co-integração em derivativos
Página atualizada pela última vez.
16 de fevereiro de 2003.
Estratégias de negociação baseadas em co-integração:
Uma nova abordagem para rastreamento de índice aprimorado e arbitragem estatística.
A busca de técnicas quantitativas adequadas para a construção de estratégias de capital de longo prazo não é um desenvolvimento do último momento nos mercados financeiros. Os recém-chegados neste jogo estão constantemente se juntando aos jogadores tradicionais e, atualmente, os pesquisadores mais fervorosos em estratégias quantitativas são os hedge funds envolvidos na negociação de ações. A sua flexibilidade operacional e a falta de restrições são ideais para que possam se beneficiar da aplicação desses tipos de estratégias de negociação.
Nesta linha de pesquisa, estamos propondo várias estratégias comerciais de "cointegração", como o rastreamento de índices e a arbitragem estatística. A primeira estratégia visa replicar uma referência em termos de retorno e volatilidade, enquanto a outra busca gerar retornos estáveis ​​em todas as circunstâncias do mercado. Ao contrário de outras estratégias comerciais tradicionais, a otimização de portfólio é baseada na cointegração e não na correlação. Quando aplicados às ações da DJIA, essas estratégias de negociação produziram resultados muito estáveis. Por exemplo, entre janeiro de 1995 e dezembro de 2001, as estratégias de arbitragem estatística de autofinanciamento mais bem-sucedidas retornaram (líquidas de custos de transação e repo) aproximadamente 10% com volatilidade anual aproximada de 2% e correlação insignificante com o mercado (Alexander e Dimitriu, 2002). As estratégias financiadas discutidas nesse artigo retornam muito mais, é claro, mas têm volatilidade ligeiramente maior. Na maioria dos anos, nossas estratégias apresentaram índices de Sharpe próximos de um.
A aplicabilidade da técnica de cointegração à alocação de ativos foi pioneira por Lucas (1997) e Alexander (1999). Suas principais características, isto é, o erro de rastreamento médio de reversão, a maior estabilidade dos pesos e o melhor uso das informações incluídas nos preços das ações, permitem um projeto flexível de várias estratégias de negociação financiadas e autofinanciadas, do índice e rastreamento indexado aprimorado, até longo prazo técnicas de transferência neutra do mercado e alfa.
Por que usar cointegração no gerenciamento de portfólio?
O conceito de cointegração tem sido amplamente aplicado na econometria financeira em conexão com análises de séries temporais e macroeconomia. Ele evoluiu como uma técnica estatística extremamente poderosa porque permite a aplicação de métodos simples de estimativa (como o mínimo de mínimos quadrados e a máxima probabilidade) a variáveis ​​não estacionárias. Ainda assim, sua relevância para a análise de investimentos tem sido bastante limitada até agora, principalmente devido ao fato de que o padrão de gerenciamento de portfólio e mensuração de risco é a análise de correlação dos retornos de ativos.
No entanto, a análise de correlação é válida apenas para variáveis ​​estacionárias. Isso requer a destruição dos preços e de outras variáveis ​​financeiras de nível, que geralmente são integradas da ordem um ou superior. Tomar a primeira diferença nos preços do registro é o procedimento padrão para garantir a estacionaria e leva todas as outras inferências a serem baseadas em retornos. Este procedimento, entretanto, é a desvantagem de perder informações valiosas. Em particular, modificar as variáveis ​​antes da análise remove qualquer possibilidade de detectar tendências comuns nos preços. Em contrapartida, o objetivo da análise de cointegração é detectar qualquer tendência estocástica nos dados de preços e usar essas tendências comuns para uma análise dinâmica de correlação em retornos (Alexander, 2001).
A observação fundamental que justifica a aplicação do conceito de cointegração, por exemplo, a análise dos preços das ações, é que um sistema de preços de estoque não estacionários no nível pode compartilhar tendências estocásticas comuns (Stock e Watson, 1991). De acordo com Beveridge e Nelson (1981), uma variável tem uma tendência estocástica, se sua diferença tiver uma representação ARMA (p, q) invertível estacionária mais um componente determinista. Como os modelos ARIMA (p, 1, q) parecem caracterizar muitas variáveis ​​financeiras, segue-se que o crescimento dessas variáveis ​​pode ser descrito por tendências estocásticas.
Quando aplicado aos preços das ações em um índice de mercado de ações, a cointegração existe quando existe pelo menos um portfólio de ações que tem um erro de rastreamento estacionário (usamos o termo erro de rastreamento como fazem os estatísticos, para denotar a diferença entre o índice e o portfólio) . Em outras palavras, a cointegração existe quando há reversão média no spread de preços entre o portfólio e o índice. Esta descoberta não fornece nenhuma informação para prever os preços individuais no sistema, ou a posição do sistema em algum momento no futuro, mas fornece informações valiosas que, independentemente da sua posição, os preços da carteira e do índice permanecerão juntos em longo prazo.
Esboço das estratégias de negociação.
Considerando o que precede, encontrar uma relação de cointegração, ou seja, uma combinação linear estacionária do índice de mercado e uma série de ações de seus componentes (normalmente especificados como preços de log) é equivalente a um spread inverso médio entre o índice de mercado e um portfólio de rastreamento . Nessas circunstâncias, por meio da construção, os retornos na carteira de rastreamento serão iguais aos retornos no índice, em longo prazo.
Além disso, sendo construídos em uma história de preços bastante longa, os pesos da carteira tendem a ignorar os movimentos de curto prazo nos preços das ações, como bolhas ou apenas o ruído, e se concentrar no comportamento de longo prazo dos preços. Como já mostramos, o fato de que o erro de rastreamento é, por construção, significa reverter, garante que o portfólio de rastreamento permanecerá "vinculado" com o índice no longo prazo, independentemente dos movimentos de curto prazo nos preços individuais das ações. No entanto, pode haver des-correlações de curto prazo entre o portfólio de rastreamento e o índice. Na verdade, esta é uma fonte potencial de "alfa", ou seja, o excesso de retorno, nas carteiras de rastreamento.
Uma série de estratégias comerciais podem ser construídas com base nas relações de cointegração:
A. Acompanhamento do índice.
A primeira estratégia de negociação baseada em cointegração investigada é um rastreamento de índices clássicos com o objetivo de replicar uma referência em termos de retorno e volatilidade. Um processo de rastreamento de índice envolve dois estágios igualmente importantes: primeiro, selecionar os estoques a serem incluídos no portfólio de rastreamento e, em seguida, determinar as participações da carteira em cada ação com base em uma técnica de otimização de cointegração.
A primeira etapa, a seleção de ações, pode ser o resultado de modelos de seleção proprietários, análise técnica ou apenas habilidades de escolha de estoque de um gerente de portfólio. O grau de co-integração e conseqüentemente o desempenho de rastreamento dependerá muito do processo de seleção. Por mais crítico, o processo de seleção não possui características especiais em uma técnica de rastreamento baseada em cointegração. Isso constitui uma variável de controle na identificação da estratégia de rastreamento mais apropriada.
A segunda etapa do rastreamento do índice diz respeito à determinação das participações da carteira em cada uma das ações selecionadas na etapa anterior. Os pesos das ações em cada carteira são estimados com base nos coeficientes do menor quadrado ordinário (OLS) da equação de cointegração, regressando o índice de índice de estoque nos preços de estoque das ações do portfólio em um determinado período de calibração antes do momento de construção da carteira. Observamos que a aplicação de OLS a variáveis ​​dependentes não estacionárias, como log (índice), é válida apenas no caso especial de uma relação de cointegração. A não ser que os resíduos da regressão da cointegração sejam estacionados, os coeficientes OLS serão inconsistentes e uma inferência adicional com base neles será inválida. Portanto, o teste de cointegração é um passo essencial na construção de portfólios de rastreamento baseados em cointegração.
Além da estimativa, os coeficientes OLS são normalizados para somar até um, fornecendo assim os pesos de cada estoque no portfólio de rastreamento.
Como mostrado em Alexander e Dimitriu (2002), mesmo usando regras simples de seleção de ações, como classificar as ações pelo seu peso no índice, as carteiras de rastreamento construídas com base nessa metodologia podem replicar com precisão o índice de mercado.
B. Acompanhamento de índice aprimorado e arbitragem estatística.
Tendo construído a estratégia de rastreamento simples, uma extensão natural para explorar o potencial de rastreamento das carteiras cointegradas seria a replicação de índices artificiais, "plus" ou "menos", construídos para superar ou subavaliar linearmente o índice de mercado por um quantidade dada por ano. Em seguida, as estratégias de autofinanciamento longo e curto podem ser configuradas ao ser curtas em um portfólio que rastreie o benchmark "menos", e há muito tempo em um portfólio que rastreie o benchmark 'plus'.
Este tipo de estratégia de arbitragem estatística deve gerar retornos de acordo com o spread "plus" / "menos" (ou seja, alfa dupla) com bastante baixa volatilidade e nenhuma correlação significativa com os retornos do mercado. Esperamos tornar-se cada vez mais difícil encontrar carteiras cointegradas à medida que a magnitude do spread entre os benchmarks rastreados aumenta. A relação de cointegração entre o índice de mercado e seus estoques de componentes tem uma sólida lógica, mas isso não é necessariamente o caso das carteiras que seguem benchmarks artificiais, que podem ser escolhidos para superar o índice de mercado em 50%, por exemplo. A dificuldade em encontrar uma relação de cointegração apropriada leva a uma maior instabilidade dos pesos de ações, maiores custos de transação e maior volatilidade dos retornos. Para evitar isso, é essencial garantir que todas as carteiras que rastreiam os índices "plus" ou "menos" passem no teste de cointegração.
C. Combinando rastreamento de índice com arbitragem estatística.
Caso a neutralidade do mercado não seja um requisito e se deseje uma exposição a um índice de mercado, outra possibilidade seria transportar o alfa obtido na estrutura neutra do mercado para um índice, através do uso de derivativos (por exemplo, futuros de índice). Ou, em vez de derivativos, um procedimento de rastreamento de índice baseado em cointegração aprimorado pode ser implementado.
Este tipo de estratégia, combinando rastreamento de índice aprimorado com arbitragem estatística, deve ter uma correlação elevada com o índice de mercado, ao mesmo tempo em que ganha alfa a partir de duas fontes: primeiro, o retorno excessivo do rastreamento indexado aprimorado e, em seguida, o alfa duplo da arbitragem estatística. Ao aplicar estratégias de transferência alfa para os estoques no DJIA, Alexander e Dimitriu (2002) obtiveram índices Sharpe significativamente melhores que o mercado, mesmo depois de contabilizar os custos de transações e retomadas.
Como já apontado, o conceito de cointegração possui uma série de características atraentes na modelagem dos preços dos ativos, que o recomendam como uma alternativa significativamente melhor para a análise clássica de correlação na gestão de portfólio. As principais características, isto é, o erro de rastreamento do retorno, a maior estabilidade dos pesos e o melhor uso das informações contidas nos preços das ações, permitem um projeto flexível de estratégias de negociação, desde o rastreamento de índice aprimorado até a arbitragem estatística. Além disso, sua aplicação na construção de estratégias de negociação dentro dos estoques DJIA produziu resultados encorajadores, que podem ser aprimorados.
Alexander, C. O. (1999) "Cobertura óptima usando cointegração" Transações filosóficas da Royal Society A 357, pp. 2039-2058.
Alexander, C. O. (2001) Modelos de mercado: um guia para análise de dados financeiros, John Wiley, pp. 347-388.
Alexander, C. O. e A. Dimitriu (2002), The Cointegration Alpha: Estratégias de Neutro de Rastreamento de Índice de Mercado Melhorado e Long-Short Equity ", Documento de Discussão 2002-08, Documentos de Discussão do Centro ISMA em Série Financeira.
Beveridge, S. e C. R. Nelson (1981) "Uma nova abordagem para a decomposição de séries temporais econômicas em componentes permanentes e transitórios com especial atenção à mensuração do ciclo comercial", Journal of Economics Monetary 7, pp. 151-74.
Lucas, A. (1997) "Alocação Estratégica e Tática de Ativos e o Efeito das Relações de Equilíbrio Long-Run", Memorando de Pesquisa 1997-42, Vrije Universiteit Amsterdam.

Pairs Trading para o Mercado de Futuros de Mercadorias Usando o Método de Cointegração.
Revista Internacional de Comércio e Finanças, Vol. 1, edição 1, 2018, 25-38.
14 Páginas Publicado: 15 Jan 2017.
Cuneyt Ungever.
Istambul Commerce University, Estudantes.
Data escrita: 9 de janeiro de 2017.
Este artigo investiga estratégia de negociação de pares usando o método de cointegração entre os 10 mercados futuros agrícolas mais populares. Verifica-se que apenas em 2 pares mostra sinal comercial. A estratégia de negociação de pares é realizada em duas etapas que são o período de formação eo período de negociação com os dados diários de futuros de 2004 a 2018. Após o período de formação foi construído, presume-se que o erro de cointegração continua a manter o período de negociação o mesmo que ele faz para o período de formação. A estratégia de negociação de pares é criada pela posição longa do algodão e pelo café de posição curta e também pela posição longa do algodão e pela posição curta da livecattle. Verificou-se que a rentabilidade desta estratégia funcionou bem tanto no período de formação como no período de negociação.
Palavras-chave: Pairs Trading, Cointegration Approach, Futures Market, Commodities, Statistical Arbitrage.
Classificação JEL: g11, g12, g13, q02, c58.
Cuneyt Ungever (Autor do Contato)
Universidade de Comércio de Istambul, Estudantes (email)
Estatísticas de papel.
Jornais relacionados.
Fundos Mútuos, Hedge Funds e Indústria de Investimento eJournal.
Assine este boletim de taxas para mais artigos com curadoria sobre este tópico.
EJournal de derivativos.
Assine este boletim de taxas para mais artigos com curadoria sobre este tópico.
Modelagem econométrica: eJournal de derivativos.
Assine este boletim de taxas para mais artigos com curadoria sobre este tópico.
Modelagem econométrica: eJournal Mercados de Mercadorias.
Assine este boletim de taxas para mais artigos com curadoria sobre este tópico.
Papéis recomendados.
Links Rápidos.
Sobre.
Os cookies são usados ​​por este site. Para recusar ou aprender mais, visite nossa página Cookies. Esta página foi processada por apollo8 em 0.156 segundos.

Tutoriais.
Consulte também documentação, vídeos e bate-papo.
Jing é um desenvolvedor quantitativo na QuantConnect. Ela tem um mestrado em Matemática Financeira por John Hopkins e a anterior trabalhou no Northeast Securities fazendo pesquisas quantitativas.
Artigos recentes.
Pairs Trading & # 8211; Copula vs Cointegration.
Em Tutoriais de Estratégia, publicado em 13 de junho de 2017.
Nós investigamos dois métodos de troca de pares e comparamos os resultados. O intercâmbio de pares envolve investigar a estrutura de dependência entre dois ativos altamente correlacionados. Com o pressuposto de que a reversão média ocorrerá, posições longas ou curtas são inseridas na direção oposta quando há uma divergência de preço. Normalmente, a distribuição de preços dos ativos é modelada por uma distribuição gaussiana das séries de retorno, mas a distribuição normal das juntas pode deixar de capturar algumas características-chave da dependência do preço dos pares de ações, como a dependência da cauda. Nós investigamos o uso da teoria da copula para identificar essas oportunidades comerciais.
Neste tutorial, vamos discutir o quadro básico de copula a partir da perspectiva matemática e explicar como aplicar a abordagem na negociação de pares. A implementação do algoritmo baseia-se no papel Estratégias de negociação com copulas [1] Stander Y, Marais D, Botha I. Estratégias comerciais com copulas [J]. Revista de Ciências Econômicas e Financeiras, 2018, 6 (1): 83-107. Cópia online de Stander Y, Marais D, Botha I (2018). Comparamos o desempenho da estratégia de negociação de pares de cópula com o método de negociação de pares de co-integração com base no papel das estratégias de negociação de arbitragem estatística e negociação de alta freqüência de Hanson TA, Hall J R. (2018) [2] Hanson TA, Hall J R. Estratégias de negociação de arbitragem estatística e negociação de alta freqüência [J]. 2018.. A técnica de co-integração assume uma relação de co-integração entre as ações emparelhadas para identificar oportunidades comerciais lucrativas. Os resultados empíricos sugerem que a estratégia baseada em cópula é mais rentável do que as técnicas tradicionais de negociação de pares.
Estrutura da Copula.
1. Definição.
Dado um vetor aleatório, suas funções marginais de distribuição cumulativa (CDFs) são. Ao aplicar a transformada integral de probabilidade a cada componente, as distribuições marginais são uniformes (da Wikipédia).
Então a copula de é definida como a função de distribuição cumulativa conjunta de, para a qual a distribuição marginal de cada variável U é uniforme como.
A função Copulas contém todas as características de dependência das distribuições marginais e descreve melhor a relação linear e não linear entre as variáveis, usando a probabilidade. Eles permitem que as distribuições marginais sejam modeladas independentemente uma da outra, e não é necessária nenhuma suposição no comportamento das juntas dos marginais. [3] Rad H, Low R K Y, Faff R. A rentabilidade das estratégias de negociação de pares: distância, cointegração e métodos de cópula [J]. Finanças quantitativas, 2018, 16 (10): 1541-1558.aplica on-line.
2. Copulas Bivariadas.
Uma vez que esta pesquisa se concentra em copulas bivariadas (para troca de pares, temos 2 variáveis ​​aleatórias), algumas propriedades probabilísticas são especificadas.
Seja X e Y duas variáveis ​​aleatórias com função de probabilidade cumulativa e. que são uniformemente distribuídos. Então a função copula é. Tomar a derivada parcial da função da copula sobre U e V daria a função de distribuição condicional da seguinte maneira:
3. Arquimedes Copulas.
Existem muitas funções de copula que nos permitem descrever estruturas de dependência entre variáveis, além da suposição Gaussiana. Aqui vamos concentrar três desses; as fórmulas Clayton, Gumbel e Frank Copula da classe Archimedean.
Copulas de Arquimedes [4] Mahfoud M, Michael M. Bivariate Copas de Arquimedes: uma aplicação para dois índices do mercado de ações [J]. BMI Paper, 2018. A cópia on-line é baseada nas transformações de Laplace φ das funções de distribuição univariada. Eles são construídos por uma função de gerador particular [5] LANDGRAF N, SCHOLTUS K, DIRIS D R B. Casos baseados em copula de alta freqüência negociando em estoques Goldmine dos EUA [J]. 2018..
A função de densidade de probabilidade é:
Onde é o inverso da segunda derivada da função do gerador.
Genest, MacKay (1986) [6] Genest, C. e MacKay, J., 1986, The Joy of Copulas: Distribuições Bivariadas com Margenes Uniformes, o Statistician Americano, 40, 280-283, provou que a relação entre a função geradora de cópula e a correlação de classificação de Kendall no caso bivariante pode ser dada por:
Então, podemos calcular facilmente o parâmetro nas copulas de Archimedean se conhecemos a medida de classificação de tau de Kendall e a função de gerador. Consulte o passo 3 para ver as fórmulas.
Parte I: Método Copula.
Os ETFs têm vários setores de ações e classes de ativos que nos fornecem uma ampla gama de pares de candidatos comerciais. Nosso conjunto de dados consiste em dados diários dos ETFs negociados no NASDAQ ou NYSE.
Utilizamos os primeiros 3 anos de dados para escolher o copula e o par de ativos mais adequados ("período de treinamento formação"). Em seguida, usamos um período de 5 anos a partir de 2018 até 2017 ("período de negociação"), para executar a estratégia. Durante o período de negociação, usamos uma janela de 12 meses para obter os parâmetros da copula ("período de formação contínua").
Passo 1: Selecionando os estoques emparelhados.
O método geral de seleção de pares é baseado em análise tanto fundamental como estatística. [7] Jean Folger. Pairs Trading Example Online Copy.
1) Montar uma lista de pares potencialmente relacionados.
Todos os pares aleatórios podem ser correlacionados. É possível que essas variáveis ​​não sejam causalmente relacionadas entre si, mas por causa de uma relação espúria devido a coincidência ou a presença de um certo terceiro fator não visto. Assim, é importante para nós começar com uma lista de títulos que têm algo em comum. Para esta demonstração, escolhemos alguns dos ETFs mais líquidos negociados no Nasdaq ou na NYSE. O relacionamento para esses pares potencialmente relacionados pode ser devido a uma sobreposição de índice, setor ou classe de ativos. por exemplo. QQQ e XLK são dois ETFs que acompanham os índices líderes no mercado.
2) Filtre o par de negociação com correlação estatística.
Para determinar quais pares de ações incluir na análise, as correlações entre os pares ETF pré-selecionados são analisadas. Abaixo estão três tipos de medidas de correlação que geralmente usamos em estatísticas:
= número de concordantes.
= número de discordantes.
= a diferença entre as classificações dos valores correspondentes e.
Podemos obter esses coeficientes em Python usando funções da biblioteca de estatísticas no SciPy. As correlações foram calculadas usando retornos diários do preço do estoque de registro durante o período de formação. Encontramos as 3 técnicas de correlação que dão aos ETFs pareados a mesma classificação de coeficientes de correlação. A correlação de Pearson pressupõe que ambas as variáveis ​​devem ser normalmente distribuídas. Assim, aqui usamos a classificação de Kendall como a medida de correlação e escolhemos os pares com a maior correlação de classificação de Kendall para implementar a negociação de pares.
Recebemos o preço de fechamento histórico diário do nosso par ETF usando a função História e convertendo os preços em uma série de retorno de registro. Deixe e denote as séries históricas dos preços das ações para estoque x e estoque y. Os retornos de log para o par ETFs são fornecidos por:
t = 1,2. n onde n é o número de dados de preços.
Passo 2: Estimativa de distribuições marginais de log-return.
Para construir a copula, precisamos transformar a série log-return e dois valores uniformemente distribuídos u e v. Isso pode ser feito estimando as funções de distribuição marginal e conectando os valores de retorno em uma função de distribuição. Como não fazemos suposições sobre a distribuição das duas séries log-return, aqui utilizamos a função de distribuição empírica para abordar a distribuição marginal e. A função Python ECDF da biblioteca statsmodel nos dá o CDF empírico como uma função de etapa.
Passo 3: Estimando Parâmetros Copula.
Conforme discutido acima, estimamos o parâmetro de copula theta pela relação entre a copula e a medida de dependência do tau de Kendall, para cada uma das copulas de Arquimedes.
Passo 4: Seleção da melhor copula de montagem.
Uma vez que obtemos a estimativa de parâmetros para as funções copula, usamos os critérios AIC para selecionar a copula que fornece o melhor ajuste na inicialização do algoritmo.
onde é a função log-verossimilhança e k é o número de parâmetros, aqui k = 1.
As funções de densidade de cada função de copula são as seguintes:
A copula que fornece o melhor ajuste é aquela que corresponde ao menor valor do critério AIC. O par escolhido é "QQQ" e amp; "XLK".
Etapa 5: Gerando os Sinais de Negociação.
As funções de copula incluem todas as informações sobre as estruturas de dependência de duas séries de retorno. De acordo com Stander Y, Marais D, Botha I (2018) [8] Stander Y, Marais D, Botha I. Estratégias comerciais com copulas [J]. Revista de Ciências Econômicas e Financeiras, 2018, 6 (1): 83-107. Copia on-line, a copula ajustada é usada para derivar as bandas de confiança para a função de distribuição marginal condicional e, isto é, os índices de preços errados. Quando as observações do mercado ficam fora da faixa de confiança, é uma indicação de que a oportunidade de negociação de pares está disponível. Aqui escolhemos 95% como a banda de confiança superior, 5% como a menor banda de confiança como indicado no documento. O nível de confiança foi selecionado com base em uma análise de back-test no documento que mostra que o uso de 95% parece levar a oportunidades comerciais apropriadas para serem identificadas.
Given current returns of stock X and stock Y, we define the "mis-pricing indexes" are:
For further mathematical proof , please refer to Xie W, Wu Y(2018) [9] Xie W, Wu Y. Copula-based pairs trading strategy[C]//Asian Finance Association (AsFA) 2018 Conference. doi. 2018, 10.
The conditional probability formulas of bivariate copulas can be derived by taking partial derivatives of copula functions shown in Table 1. The results are as follows:
After selection of trading pairs and the best-fitted copulas, we take the following steps for trading. Please note we implement the Steps 1, 2, 3 and 4 on the first day of each month using the daily data for the last 12 months, which means our empirical distribution functions and copula parameters theta estimation are updated once a month. In summary each month:
During the 12 months' rolling formation period, daily close prices are used to calculate the daily log returns for the pair of ETFs and then compute Kendall's rank correlation. Estimate the marginal distribution functions of log returns of X and Y, which are ecdf_x and ecdf_y separately. Plug Kendall's tau into copula parameter estimation functions to get the value of theta. Run linear regression over the two price series. The coefficient is used to determine how many shares of stock X and Y to buy and sell. For example, if the coefficient is 2, for every X share that is bought or sold, 2 units of Y are sold or bought.
Finally during the trading period, each day we convert today's returns to u and v by using empirical distribution functions ecdf_x and ecdf_y. After that, two mispricing indexes are calculated every trading day by using the estimated copula C. The algorithm constructs short positions in X and long positions in Y on the days that and . It constructs short position in Y and long positions in X on the days that and .
Part II: Cointegration Method.
For the cointegration pairs trading method, we choose the same ETF pair "GLD" & "DGL". There is no need to choose a copula function so there is only a 12 month rolling formation period. The trading period is 5 years from January 2018 to May 2017.
Step 1: Generate the Spread Series.
At the start of each month, we generate the log price series of two ETFs with the daily close. Then the spread series is estimated using regression analysis based on log price series data.
For equities X and Y, we run linear regression over the log price series and get the coefficient β.
Step 2: Compute the Threshold.
Using the standard deviation of spread during the rolling formation period, a threshold of two standard deviations is set up for the trading strategy as indicated in the paper.
Step 3: Set up the Trading Signals.
On each trading day, we enter a trade whenever the spread moves more than two standard deviations away from its mean. In other words, we construct short positions in X and long positions in Y on the day that spread>mean+2*std. We construct short positions in Y and long positions in X on the day that spread<mean-2*std. The trade is exited if the spread reverts to its equilibrium (defined as less than half a standard deviation from zero spread).
The value of mean and standard deviation are calculated from the rolling formation period and will be updated once a month.
Conclusão.
Ultimately pairs trading intends to capture the price divergence of two correlated assets through mean reversion. Our results demonstrate that the copula approach for pairs trading is superior to the conventional cointegration method because it is based on the probability of the dependence structure, vs cointegration which relies on simple linear regression variance from normal pricing. We found through testing the performance of the copula method less sensitive to the starting parameters. Because the cointegration method relies on standard distribution and the ETF pairs had low volatility there were few trading opportunities.
Generally, ETFs are not very volatile and so mean-reversion did not provide many trading opportunities. There are only 39 trades during 5 years for cointegration method.
It is observed that the use of copula in pairs trading provides more trading opportunities as it does not require any rigid assumptions [10] Liew R Q, Wu Y. Pairs trading: A copula approach[J]. Journal of Derivatives & Hedge Funds, 2018, 19(1): 12-30. .
Backtest for copula method.
Colaboradores.
Referências.
`Hi Jing Wu. Thank you for an excellent article. I have a question, but it might be because I am misunderstanding your Python code (my background is in C#). The theory states that the log return series is given by ln(P_x, t / P_x, t-1), however in your code it seems that you are returning only ln(P_x, t), in the following line of code: np. log([float(z) for z in close_price]). Please let me know what I am missing. Obrigado.
Are you talking about the cointegration? Theoretically ln(Pt) should be used instead if log returns.
Sorry, a typo for my last reply:
Please ignore my previous comment/question, I realize the “diff” function takes care of this – Maths 101.
Hi Jing Wu, I have backtested your strategy from the period of 2018-01-01 to 2017-09-11. However, from around Sep 2018 onward, beta, net holdings and leverage seem to be constant. Is there any intuition to that? I don’t think the code is broken, but I am just curious to see what the intuition would be to cause such an outcome.
That might because there is no new trade at that time. For pairs trading that means the trading condition is not triggered.
Thank you very much for this very interesting post. It’s very helpful to have all the reasoning and formula so clearly explained and synthesized.
I have 2 remarks regarding the algo though:
+ the Gumbel fit done on the calibration set [2006 – 2009] does not work. This does not stop the algo though and the latter chooses the Frank copula in the end but it only decides using AIC for Frank and Clayton. The reason why the fit on Gumbel does not work comes from 2 divisions by 0, owing to the u or v values.
+ a post above mentions the very high beta of the algo and I agree it’s surprising for a pair strategy. This high beta is particularly stricking when simply comparing the algo results and the S&P. Local corrections of US Stocks in Q3-2018 and Q1-2018 are visible on the copula strat as if the latter was simply long equities. I took the liberty to compute the day by day net position in each component of the selected pair [i. e. XLK and QQQ]. It appears that from end 2018 until the end the algo is LONG BOTH ETFs and barely changes the position. I might be totally wrong but I think this explains the beta, the net holdings and the suddenly dropping size of trades.
Hi Jing Wu, I have backtested your strategy but I don’t seem to grasp how exactly the positions are made. According to Trade tab only small quantities of underlying assets are traded.
My reasoning is this. Suppose I have $100 000 and there’s a signal from the copulas to buy A (currently prices at $10) and short B (currently priced at $20) . Do I buy 10 000 shares of A and short 5 000 shares of B?
How long will I be in this position? Till the end of the day/next day or until another signal occurs? Obrigado.
Hi Fraty, yes here I allocate 40% capital in each stock. But the ratio of stock A and B are based on the regression coefficient of the historical price of two assets, not just the price at the trading day. The position is changed until another signal occurs.
Hello Jing, Thank you ver much for your excellent article and for presenting the method applying Copula to pair trading 🙂
Regarding the trading signals you mentioned that “we construct short positions in X and long positions in Y on the day that spread>mean+2*std. We construct short positions in Y and long positions in X on the day that spread<mean-2*std."
Since we are regressing Y on X, then if the "normalized"spread, (spread-mean)/sd, is wider than two standard deviations, this means that Y is out-performing X and hence we would want to short the spread, meaning we go short on Y (which is the outperforming stock) and Long X (which is the undersperforming stock).
Hello I am a student study pair trading, and I’m only beginner,
I wanna Run your code and understand the logic, but I can’t see.
all of your code.. if you mind ask you send to me complete code.
I’m not so good at english because I’m Korean Sorry about that !
I hope that your reply. obrigado.
The code is at the end of the page. Just click the ‘code’ tab of the attached backtest or clone the algorithm you will see the code.

Pairs trading: A copula approach.
Rong Qi Liew Yuan Wu.
Pairs trading is a technique that is widely practiced in the financial industry. Its relevance has been constantly tested with updated samples, and its profitability is acknowledged among practitioners and academics. Yet in pairs trading, the notion of correlation is central, and the use of correlation or cointegration as a measure of dependency is ultimately its Achilles’ heel. To overcome this limitation, this article employs the use of copulas, which is much more realistic and robust, to develop trading rules for pairs trading. Copulas are useful extensions and generalizations of approaches for modeling joint distributions and dependence between financial assets. A trading strategy that involves the use of copulas has been compared against two most commonly applied conventional strategies. The empirical results suggest that the proposed strategy is a potentially powerful analytical alternative to the traditional pairs trading techniques.
INTRODUÇÃO.
Pairs trading is a well-acknowledged speculative investment strategy in the financial markets that is popularized back in the 1980s. Today, pairs trading is commonly applied by hedge funds and institutional investors as a long/short equity investment strategy. ( Vidyamurthy, 2004 ) Recent researchers ( Gatev et al, 2006 ; Do and Faff, 2018 ) have extended the initial analysis of pairs trading to more updated samples, and documented economically and statistically significant profits using simple pairs trading rule.
Generally perceived as a form of technical analysis, the objective of pairs trading is to identify the relative overvalued and undervalued positions between two stocks that are closely related, with a long-run relationship. Such relative mispricing occurs if the spread between the two stocks deviates from its equilibrium, and excess returns will be generated if the pair is mean-reverting (that is, any deviations are temporary, and will return to its equilibrium after a period of adjustment). In this situation, the stategy will simultaneously short the relatively overvalued stock and long the relatively undervalued. The formation of pairs ensues from a cointegration analysis or maximum correlation criteria of the historical prices. Thereafter, pairs trading strategy is implemented to identify the trading signals.
However, a significant shortcoming in the technique is the fundamental assumption of linear association and its use of correlation coefficient or cointegration as a measure of dependency. These basic assumptions may be convenient and useful in application, but they can cause the simple pairs trading signals to be inaccurate. If the data is normally distributed, then linear correlation completely describes dependency. But it is widely acknowledged that financial data are rarely normally distributed in reality, therefore correlation cannot completely describe the dependency. In fact, negative skewness and/or excess kurtosis are frequently observed in most financial assets ( Kat, 2003 ; Crook and Moreira, 2018 ), resulting in upper and lower tail dependence of different extent. As such, correlation and cointegration are not sufficient in describing the association between financial assets and predicting their future movements.
The objective of this article is to link the use of copula with pairs trading to develop a trading strategy. Because copulas separate marginal distributions from dependence structures, the appropriate copula for a particular application is one that best captures dependence features of the data. ( Trivedi and Zimmer, 2007 ) Hence, the use of copula is able to capture the co-movement between stocks accurately enough to identify trading signals, which standard linear correlation analysis is not robust enough to accomplish ( Ferreira, 2008 ). Therefore, it is hypothesized that a trading strategy involving the use of copula will bring about more trading opportunities, and potentially more profit than conventional strategies. The proposed strategy will be explored, and compared against conventional strategies.
The rest of the article will be organized as follow. The next section will provide a brief overview of pairs trading. The section ‘Trading strategies’ will describe the trading strategies studied in this article, and the empirical results will be demonstrated in the section ‘Empirical results’. The section ‘Conclusion’ will conclude the article and provide directions for future studies.
FOUNDATIONS OF PAIRS TRADING STRATEGIES.
The general idea for investing in the marketplace from a valuation point of view is to sell overvalued securities and buy the undervalued. As the true values of the securities in absolute terms are rarely known, pairs trading techniques attempt to resolve this by looking at stock pairs with similar characteristics. Its objective is to identify the relative positions whenever an inefficient market results in the mispricing of securities. This mutual mispricing between two securities is theoretically captured by the notion of spread ( Vidyamurthy, 2004 ).
Currently, there are several different pairs trading techniques applied in the modern financial industry. The two most commonly established techniques are the distance strategy ( Gatev et al, 2006 ; Perlin, 2009 ; Do and Faff, 2018 ) and cointegration strategy ( Vidyamurthy, 2004 ; Lin et al, 2006 ; Galenko et al, 2018 ).
Generally, pairs are selected based on a cointegration analysis or minimum distance (equivalently, maximum correlation) criteria. When a suitable pair is identified, the traditional technique will engage in a simultaneous purchase of relatively undervalued stock and sale of relatively overvalued stock in an attempt to create a market-neutral trading system. This is to take advantage of the price divergence in terms of the spread that is expected to revert eventually, known as the mean-reverting behavior ( Bock and Mestel, 2008 ). Hence, pairs trading is also known as a form of long/short equity investment as the market-neutral strategy holds two stocks of different positions with equal market risk exposure at all times.
It is important to note that all the conventional techniques are essentially found on the assumption of linear association and its use of correlation coefficient or cointegration as a measure of dependency. In addition, the use of correlation and cointegration in pairs trading assumes a symmetric distribution of spread around the mean value of 0. Therefore, pairs trading has its limitations, and these may result in issues where the traditional pairs trading approach produces wrong trading signals or fail to identify profit opportunities ( Bock and Mestel, 2008 ).
On the other hand, copulas provide a powerful framework for modeling dependence structure without rigid assumptions ( Ferreira, 2008 ). It can potentially resolve the concerns mentioned earlier as it separates the estimation of individual marginal behavior and dependence structure into two different procedures. This separation of procedure is extremely valuable and useful in many different aspects. From an economic perspective, it gives analyst the opportunity to use different marginal distributions to account for the diversity in financial risks (or assets) ( Ane and Kharoubi, 2003 ). Hence, copula can be applied regardless of the form of marginal distributions, providing much greater flexibility for practical application. From a modeling position, the lower the dimensionality of a model or the cardinality of its parameters, the higher the reliability of the estimates. Hence, applying the best-fitting marginal distribution before estimating its joint distribution ensures that all information regarding the dependence structure between random variables are accurately captured without rigid assumptions.
Unlike the conventional approaches, employing a copula-based approach results in a far richer set of information, such as the shape and nature of the dependency between the stock pairs ( Ferreira, 2008 ). This advantage is resulted because of the variety of copula choices that measures upper and lower tail dependencies of different extent, in an environment that considers both linear and non-linear relationship. For example, Gumbel copula produces more correlation at the two extremes of the correlated distribution but has its highest correlation in the maxima tails, whereas Clayton copula produces a tight correlation at the low end of each variable. In addition, copulas possess an attractive property of being invariant under strictly monotone transformations of random variables. In other words, the same copula will be obtained regardless of whether the analyst or researcher is using price series or log price series ( Hu, 2003 ).
As a whole, copula is unique as it allows modeling dependence structure to be split into two separate procedures. First, the choice of best-fitting marginal distribution is provided to describe the variables. Subsequently, a suitable copula is applied to establish the dependence structure. This two-step approach provides more alternatives in model specification, and an explicit dependence function obtained will provide more delicate description of dependence ( Hu, 2003 ). These functionalities of copula ensure high accuracy and reliability of estimations, both of which are essential for financial analysis and application. Hence, the concept of copula will be explored as an alternative in this article where non-linear environment can be considered. For more details about copula, please refer Appendix A .
TRADING STRATEGIES.
In this section, the trading rules customized for three approaches, namely, copula, distance and cointegration, will be elaborated. In all three approaches, there are two different time periods, the formation period and trading (or backtesting) period. Historical data during formation period are used to observe price behavior and estimate the distribution and relevant parameters required for each approach. Using the estimated distributions and parameters from formation period, strategies are implemented during the trading period to test for profitability. There is no fixed guideline to the length of each time period, hence this article will use a 2-year and a subsequent 1-year phase as the formation and trading period, respectively.
Ultimately, all three approaches aim to identify the relative positions of the stock pairs and simultaneously long the undervalued stocks and short the overvalued, in attempt to establish a market-neutral trading system. The use of same formation period, trading period and stock pairs are maintained throughout the three approaches in this article due to the intention to make a comparison between the three.
Copula approach.
The objective of the pairs trading technique using copula approach is to apply the optimal copula between two stock returns, and identify the relative positions between stock pairs. In general, application of the strategy for copula approach will require the marginal distributions, the relevant copula function and the conditional probability distribution functions, which can be functions of copula.
Using data of the stocks during formation period, marginal distribution functions and the respective parameters are estimated based on the value of its cumulative log-returns. This can be done using any standard statistical analysis software that estimates the best-fitting marginal distribution. After applying the marginal distributions and relevant estimated parameters for each stock returns, the cumulative distribution function values obtained of each stock, u and v , provides the information for a relevant copula function to be selected.
As a general guideline, stocks are identified as being relatively undervalued if the conditional probability is less than 0.5 and relatively overvalued if the conditional probability is greater than 0.5. In addition, the values of the conditional probabilities are also an indication of its certainty or confidence regarding the position of stocks ( Ferreira, 2008 ). Therefore, the execution of trade should be done when one of the conditional probabilities is close to 1. Hence, the use of conditional probability functions is essential for the strategy. For more information on the formulas of conditional probability functions, please refer Appendix B (Table B1).
For demonstration purposes, this article selects the upper bound of 0.95 and lower bound of 0.05 for the threshold of conditional probabilities as trading triggers in this approach. A position is opened during the trading period when one of the conditional probability values is above the upper bound, whereas the other is below the lower bound. Subsequently, exit position is assumed once the positions revert (that is, when the conditional probabilities cross the boundary of 0.5).
Distance approach.
In this article, we implemented the same trading strategy framework as described in Gatev et al (2006) for the distance approach. Upon finding two stocks that move together, long/short positions are taken when the stocks diverge abnormally. This divergence is determined by the difference between standardized price gap of the two securities, often known as spread. It acts as a signal to the open and close positions of the pairwise stocks. During the trading period, position is opened when the spread widens by more than two historical standard deviations, as estimated during the formation period. Thereafter, the positions are closed when spread of the stocks reverts. If reversion does not occur before the end of the trading period, profits or losses are calculated at the end of the last trading day of the trading period.
Cointegration approach.
Similar to the previous trading strategy, the main concern of this aproach is the movement of spread. However, instead of emphasizing on the distance between the standardized prices of stock pairs, the spread considered is based on the notion of error correction. The idea of error correction is based on the long-run equilibrium in a cointegrated system; that is, the long-run mean of the linear combination of two time series ( Vidyamurthy, 2004 ). If there is a deviation from the long-run mean, then it is expected for one or both the time series to adjust in order for the long-run equilibrium to be restored.
Using cointegration as a theoretical basis, the general framework of cointegration approach in pairs trading consist of two parts. First is to generate the spread based on the actual cointegration error term of long-run relationship. This is estimated using regression analysis based on log-price series data from the formation period. Using the standard deviation of spread during formation period, a threshold of two standard deviation is set up for the trading strategy. Once the spread deviates from its long-term equilibrium and exceeds the threshold during the trading period, long/short positions are taken. Thereafter, positions are closed after the spread converges to its long-run equilibrium value of 0. For more details of the strategy framework conducted in this article, please refer Vidyamurthy (2004) .
EMPIRICAL RESULTS.
This section will provide details of the actual implementation by demonstrating the three strategies using the pairs that have been applied. For reasons of space, only one example of Brookdale Senior Living Inc. and Emeritus Corporation ( BKD-ESC ) will be illustrated in detail. The stock pair is verified as one that is highly correlated and cointegrated. It is also one of the stock pairs listed on pairslog in the healthcare sector, specifically in long-term care facilities.
This article investigates the time period from 1 December 2009 to 30 November 2018. Data from the first 24 months are used to find the relevant parameters, and information obtained is applied on the trading period, which is the subsequent 12 months. The trading strategies of different approaches are studied and demonstrated, without the procedure of pairs selection. Hence, only stock pairs that are widely discussed online or speculated in several literatures have been considered. Each stock pair has the same Schwarz Information Criterion (SIC) code to ensure industrial neutrality, or at least to reduce the industrial risk as well.
Distance approach.
A detailed figure for the conventional distance strategy is featured below to illustrate the standardized prices and spread of the values.
Distance trading strategy.
Cointegration approach.
Cointegration trading strategy.
Figure 2(a) shows a plot of the log-price series of the stock pair BKD-ESC during formation period and Figure 2(b) displays the spread during the same time period. The same applies for Figure 2(c) and Figure 2(d) , respectively, but the values plotted are data from trading period.
Note that the spread of concern in this approach is obtained from the actual cointegration error term of the long-run relationship between the two log-price series, estimated using regression. Hence, the spread itself is a linear combination of the two log-price series. As the stock pair is verified to be cointegrated, it implies that the spread should thereotically be a stationary time series that is randomly distributed about the long-term mean value of 0. However, this is not illustrated in Figures 2(b) and (d) . In fact, the spread behavior from the two time periods are distintively different, with an asymmetric distribution. Hence, linear association and its use of cointegration as a measure of dependence in this approach is insufficient in capturing the association between the financial assets. This results in an inconsistency of spread values obtained during the two time periods. Note that the possibility of a structural change cannot be dismissed, but the limitatons of the approach itself seems more reasonable. The limitations of this conventional trading strategy could in turn result in an inaccurate perspective of the association between the assets concerned, possibly causing the lack of trading opportunities and therefore a lower profit in the trading strategy.
Copula approach.
As mentioned in the section ‘Distance approach’, this approach will first require the marginal distributions of each variable; in this case, the cumulative log returns of BKD and ESC from the historical data. Using standard statistical analysis software, the marginal distributions fitted to the cumulative log returns of BKD and ESC are Error and Generalized Logistic distributions, respectively. Using the distribution functions and parameters estimated, the values of u and v are computed.
SIC, AIC and HQIC test values of copulas using formation period data.
As shown in Table 1 , the dependence structure of Gumbel copula fits the formation period data best as it has the lowest SIC, AIC and HQIC test values among the tested.
Plots of u and v values of formation period data and copulas fitted.
Note that extreme tail dependencies of different extent can be captured by copulas as seen from the different options provided by the copulas displayed in Figure 3 . On the other hand, these crucial characteristics cannot be captured by correlation and cointegration as both indicators only measure the linear association and assumes that observations follow a symmetrical pattern. Hence, copula will be able to make estimations and predictions that are closer to the reality.
SIC, AIC and HQIC test values of copulas using trading period data.
Results of the trading strategies.
Correlation coefficient of log-price series during formation period.
Correlation coefficient of log-price series during trading period.
Kendall's τ of log-price series during formation period.
Kendall's τ of log-price series during trading period.
Spearman ρ of log-price series during trading period.
Spearman ρ of log-price series during trading period.
Panel A: Trading strategy based on thresholds designated in the section ‘Empirical results’
Profit (Capital: 10 000)
Number of transactions.
Returns of trading period.
Panel B: Trading strategy in Panel A with 1-day waiting period.
Profit (Capital: 10 000)
Number of transactions.
Returns of trading period.
Plots of u and v values of trading period data and copulas fitted.
Summary results of the trading strategies based on thresholds designated in the section ‘Empirical results’
Panel A: Trading strategies executed on BKD-ESC.
Panel B: Trading strategies executed on APA-DVN.
Panel C: Trading strategies executed on BOH-CYN.
Transactions costs.
In real-world applications, it is certain that transaction costs have to be taken into consideration. Hence, this article will address the issues regarding bid-ask spreads and short sales lost.
According to Gatev et al (2006) , the use of same prices for the start of trading and returns may be biased upward because of the fact that transactions executed in the study are implicitly buying at bid quotes (losers) and selling at ask quotes (winners). Hence, to address this concern, this article has done the same as Gatev et al (2006) for the example on stock pair BKD-ESC , and initiated positions on the day following the divergence and liquidates on the day following the convergence. The values of profits, number of transactions and returns are computed and illustrated in Panel B of Table 3 . However, the authors understand that it is meaningless to carry out such precaution on a few stock pairs. In order for the precaution to be effective in addressing the issue of bid-ask spread, it is essential for the research to be extended to an entire market. Yet this is currently out of the scope of this article, thus it can be one of the aspects that the authors are considering for future studies.
On the other hand, the concerns regarding cost of short-selling is dismissed in this article as it has been verified by Gatev et al (2006) that pairs trading profits are robust to short-selling costs. Hence, it is presumed that the impact of short-selling costs is mitigated by the use of liquid stocks that trade every day over a period of 1 year and it is therefore viewed as insiginificant.
CONCLUSÃO.
Pairs trading is a technique that is commonly applied in the financial industry. In this article, the concept of copulas in pairs trading is explored to overcome the limitations of traditional pairs trading strategies. The use of copulas in constructing joint distributions separates the estimation of individual marginal distributions from the dependence structure. This brings about much greater flexibility in the framework when specifying joint distributions, while providing richer information regarding the dependency between financial assets. Hence, copulas will bring about estimations that are more realistic and of better precision.
The empirical results demonstrate that the copula approach for pairs trading is superior to the conventional. It is observed that the use of copula in pairs trading provides more trading opportunities in practical application, and with greater confidence, as it does not require any rigid assumptions. The use of correlation or cointegration as a measure of dependency is also disregarded, thus the proposed strategy offers a potentially powerful analytical alternative to the traditional pairs trading techniques.
Despite the overall superiority of results obtained from copulas, this is only a preliminary study, and it is certainly imperfect. Copulas provide flexibility, and the strategy based on copula is considered relatively easy to implement for such a sophisticated approach. However, it is still a new approach in the trading area after all. There is much more discovery and further improvements to be done to overcome the limitations of the current work. Furthermore, the use of copulas may also be explored in the selection of stock pairs. Pairs selection is the first and most essential step to pairs trading, thus improving the conventional selection process will be a new leap forward in this area.
Appendix A.
Copula and Sklar's Theorem.
In the statistics literature, the idea of a copula arose as early as the nineteenth century in the context of discussions regarding non-normality in multivariate cases ( Hu 2003 ). Currently, copulas are known as tools used in probability theory and statistics for modeling dependence between random variables.
Under this construction, C is a distribution function of two random variables with uniform unit values. Such a function is formally defined as a copula. In general sense, copulas are known as functions that combine individual one-dimensional marginal distributions to form a multivariate distribution function that describes both the linear and non-linear relationship between variables. It ensures that the dependency between variables are accurately captured and described in terms of a function.
The word ‘copula’ was first employed in a statistical sense by Sklar (1959) , in the theorem that now bears his name. His idea was to separate a joint distribution function into one part that describes the dependence structure (the copula) and the other that describes marginal behavior.
If F ( x ) and G ( y ) are continuous then C is unique; otherwise C is uniquely determined on Ran( F ) × Ran( G ), where Ran denotes range. Conversely, if C is a copula, and F ( x ) and G ( y ) are distribution functions then the function H ( x , y ) defined by the above equation is a joint distribution function with margins F ( x ) and G ( y ). Certainly, the notion of copula can be extended to higher dimensions: n - dimensional copulas are joint distribution functions of n random variables with unit uniform marginal. Formal proofs can be found in Nelsen (2006) .
In words, the Sklar's theorem translates that every copula is a joint distribution function with margins that are uniform in the domain of the copula. An essential implication is that a copula can be constructed from any joint distribution function with continuous marginal distributions. This is ultimately Sklar's idea of the concept of copula where the best-fitting marginal distributions are estimated before a joint distribution function that describes the dependence structure (a copula) is estimated and then applied.
Appendix B.
Conditional probability formulas of commonly applied copulas.
Appendix C.
GRAPHS OF STOCK PAIR APA-DVN.
Distance trading strategy.
Cointegration trading strategy.
Conditional probabilities of copula trading strategy.
Appendix D.
GRAPHS OF STOCK PAIR BOH-CYN.
Distance trading strategy.
Cointegration trading strategy.
Conditional probabilities of copula trading strategy.
Referências.
Informações sobre direitos autorais.
Autores e afiliações.
Rong Qi Liew 1 Yuan Wu 1. Nanyang Technological University (NTU) Singapore.
Sobre este artigo.
Recomendações personalizadas.
Cite o artigo.
.RIS Papers Reference Manager RefWorks Zotero.
.BIB BibTeX JabRef Mendeley.
Compartilhe o artigo.
Cite o artigo.
.RIS Papers Reference Manager RefWorks Zotero.
.BIB BibTeX JabRef Mendeley.
Compartilhe o artigo.
Índice.
Mais de 10 milhões de documentos científicos ao seu alcance.
Switch Edition.
&cópia de; 2017 Springer International Publishing AG. Parte de Springer Nature.

Comments