Saturday 3 March 2018

Estratégia de negociação de garch


Estratégias de Negociação de Volatilidade Dinâmica no Mercado de Opções de Moeda.


Dajiang Guo.


A volatilidade condicional das taxas de câmbio pode ser prevista usando modelos GARCH ou volatilidade implícita extraída de opções de moeda. Este artigo investiga se essas previsões são economicamente significativas nas estratégias de negociação que são projetadas apenas para negociar o risco de volatilidade. Primeiro, este artigo fornece novas evidências sobre a questão do conteúdo da informação da volatilidade implícita e da volatilidade do GARCH na previsão da variação futura. Em um mundo artificial sem custos de transação, tanto as estratégias de negociação neutras quanto distantes dota conduzem a lucros positivos significativos, independentemente do método de previsão de volatilidade. Especificamente, o agente que usa o método de Regressão de Volatilidade Estocástica Implícita (ISVR) ganha lucros maiores do que o agente usando o método GARCH. Em segundo lugar, sugere que o mercado de opções de moeda seja eficiente de forma informativa. Depois de contabilizar os custos de transação, que assumem igual a um por cento dos preços das opções, os lucros observados não são significativamente diferentes de zero na maioria das estratégias de negociação. Finalmente, essas estratégias oferecidas apresentaram maior índice de Sharpe e menor correlação com várias classes de ativos principais. Conseqüentemente, os hedge funds e os investidores institucionais que procuram métodos de investimento alternativos "marketneutral" podem usar a negociação de volatilidade para melhorar o perfil de risco e retorno de sua carteira através da diversificação.


Esta versão revisada foi publicada on-line em novembro de 2006 com correções na Data da capa.


Referências.


Informações sobre direitos autorais.


Autores e afiliações.


Dajiang Guo 1 2 1. Grupo Centro Zurich Financial Service Nova Iorque U. S. A. 2. Instituto de Análise de Políticas Universidade de Toronto Toronto Canadá.


Sobre este artigo.


Recomendações personalizadas.


Cite o artigo.


.RIS Papers Reference Manager RefWorks Zotero.


.BIB BibTeX JabRef Mendeley.


Compartilhe o artigo.


Acesso ilimitado ao artigo completo Download instantâneo Inclua o imposto de vendas local, se aplicável.


Cite o artigo.


.RIS Papers Reference Manager RefWorks Zotero.


.BIB BibTeX JabRef Mendeley.


Compartilhe o artigo.


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.


Quintuitiva.


Visualizações Quantitativamente Intuitivas sobre Mercados.


Modelos ARMA para negociação.


Neste tutorial, vou compartilhar meu R & # 038; D e experiência comercial usando o conhecido modelo estatístico de modificação autoregressiva (ARMA). Há muito escrito sobre esses modelos, no entanto, eu recomendo a série de tempo introdutória com R, que eu acho que é uma combinação perfeita entre fundo teórico leve e implementações práticas em R. Outra boa leitura é o e-book on-line Previsão: princípios e prática escrita por Rob Hyndman, um especialista em previsão estatística e autor do excelente pacote R de previsão.


Começando.


Em R, estou usando principalmente o pacote fArma, que é um bom invólucro com funcionalidade estendida em torno da função arima do pacote stats (usado no livro acima mencionado). Aqui está uma sessão simples de montagem de um modelo ARMA para os retornos diários S & # 038; P 500:


Para mais detalhes, consulte a literatura e os pacotes, eu só quero enfatizar em alguns pontos:


Modelamos os retornos diários em vez dos preços. Existem múltiplos motivos: desta forma, as séries financeiras geralmente se tornam estacionárias, precisamos de alguma maneira para "normalizar" e # 8221; uma série, etc. Usamos a função diff e log para calcular os retornos diários em vez de porcentagens. Não só isso é uma prática padrão em estatísticas, mas também fornece uma boa aproximação aos retornos discretos.


A abordagem que vou apresentar aqui é uma forma de backtesting walk-forward. Ao caminhar a série dia a dia, usaremos uma história de certo comprimento para encontrar o melhor modelo. Então, usaremos esse modelo para prever o retorno do dia seguinte. Se a predição é negativa, assumimos posição curta, caso contrário, assumimos uma posição longa.


Um exemplo tornará as coisas mais claras: após o encerramento de 11 de junho de 2018, calculamos os últimos 500 retornos diários. Usando esses retornos, procuramos pelo espaço dos modelos ARMA e selecionamos o modelo de melhor ajuste (em relação a algumas métricas e alguns requisitos). Finalmente, usamos esse modelo para calcular a previsão do retorno do futuro e use o sinal do retorno para decidir a posição apropriada.


Escolhendo um bom modelo.


O primeiro obstáculo para este método antes que ele possa ser útil para nós, é selecionar os parâmetros do modelo. No caso do ARMA, existem dois parâmetros. Em outras palavras, há um número infinito de escolhas: (0,1), (1,0), (1,1), (2,1), etc. Como sabemos quais parâmetros usar?


Uma abordagem comum em estatísticas para quantificar o teste de bondade de ajuste é a estatística AIC (para Akaike Information Criteria). Uma vez que o ajuste está pronto, o valor das estatísticas do AIC é acessível através de:


Existem outras estatísticas, é claro, no entanto, geralmente os resultados são bastante semelhantes.


Para resumir, tudo o que precisamos é um loop para passar por todas as combinações de parâmetros que consideramos razoáveis, por exemplo, de (0,0) a (5,5), inclusive, para cada par de parâmetros, ajuste o modelo e, finalmente, escolha o modelo com o AIC mais baixo ou alguma outra estatística.


Observe que, por vezes, o armaFit não consegue encontrar um ajuste e retorna um erro, deixando assim o loop imediatamente. O armaSearch lida com esse problema usando a função tryCatch para capturar qualquer erro ou aviso e retornar um valor lógico (FALSE) em vez de interromper tudo e sair com um erro. Assim, podemos distinguir um retorno de função errôneo e normal apenas por verificar o tipo de resultado. Um pouco confuso provavelmente, mas funciona.


Alguns pacotes R, previsão e rughar, por exemplo, fornecem uma função similar auto. arima fora da caixa. Assim, pode-se construir sua infraestrutura em torno de um desses.


Previsão.


Uma vez que os parâmetros são selecionados, o tempo necessário para determinar a posição no fechamento. Uma maneira de fazer isso é por uma previsão um dia antes, se a predição é negativa (lembre-se da série em que estamos operando é o retorno diário), então a posição desejada é curta, senão é longo.


Agora, para construir um indicador para o teste de volta, pode-se caminhar a série de retorno diário e, em cada ponto, execute as etapas que cobrimos até agora. O loop principal parece ser (abreviado de propósito):


Onde a história é o período de look-back a considerar em cada ponto, geralmente uso 500, que é cerca de dois anos de dados. Em outras palavras, para determinar a posição em cada dia individual (o dia anterior próximo ao dia atual fechado determina o retorno) usamos o histórico de 500 dias, atrasado por dias atrasados. Você verá mais tarde como os atrasos entram em prática na prática.


Observe que essa previsão também deve ser cercada por um bloco tryCatch. O armaSearch também possui o bom recurso para determinar se um modelo tem uma previsão ou não (prever sucesso ou não, este teste é controlado através do parâmetro forForecast).


Melhorando a performance.


O número de cálculos que temos a fazer, acrescenta-se rapidamente. Por exemplo, por 10 anos de dados históricos, precisamos calcular cerca de 2.520 dias de negociação. Para cada dia, vamos encaixar e prever pelo menos 35 (35 = 6 * 6-1, 0 a 5 tanto para o componente AR e MA, mas excluindo os modelos (0,0)). Multiplicando o número de modelos pelo número de dias, e já estamos olhando mais de 88 mil ajustes de modelo & # 8211; Isso é um monte de cálculos.


Uma maneira de melhorar o desempenho desses cálculos necessários pode ser conseguida através da utilização de CPUs multi-core. Minha abordagem é paralelizar a seleção do modelo, a função armaSearch no código acima. Embora esta não seja a abordagem mais eficiente, certamente é mais prática, pois também aumentará o desempenho do armaSearch quando usado de forma independente.


Eu ganhei # 8217; t publicar a versão final do código aqui devido ao seu comprimento. Eu vou dar-lhe o link GIST em vez disso!


Modelagem de volatilidade com o GARCH.


As séries temporais financeiras são aleatórias em geral. Uma das poucas propriedades que exibem é o agrupamento de volatilidade. Isso geralmente é alcançado estendendo a previsão ARMA com um modelo GARCH. Soa complexo, e os detalhes teóricos são complexos de fato, mas resulta ser bastante direto em R:


Claro, também precisamos modificar todas as funções relevantes, como o armaSearch. As chamadas para garchFit e prever também precisam ser tratadas através do tryCatch. Observe também que prever retorna uma matriz para modelos GARCH.


O código fonte completo está disponível a partir de um GitHub Gist.


S & # 038; P 500 Performance.


Vamos começar com a curva de equidade de aplicar a estratégia ARMA + GARCH ao longo dos 60 anos completos (desde 1950) dos dados históricos P & S 038; P 500.


ARMA vs Buy-and-Hold.


Parece fantástico! Na verdade, isso me impressionou tanto que procurei erros no código por algum tempo. 🙂 Mesmo em um gráfico logarítmico, o desempenho deste método é deslumbrante e # 8211; CAGR de 18,87%, e a estratégia ARMA + GARCH atinge esse desempenho com uma redução máxima comparável de 56%.


Para calcular o crescimento da estratégia ARMA, primeiro precisamos do indicador diário (este indicador demora cerca de dois dias para calcular com todas as otimizações abordadas nesta publicação).


A primeira coluna é a data, a segunda a posição para este dia: 1 para longo, -1 para breve, 0 para nenhum. Observe que a posição já está alinhada com o dia do retorno (é calculada no final do dia anterior), ou seja, o indicador está alinhado corretamente com os retornos # 8211; Não há necessidade de deslocamento direto através de atraso. O indicador, a primeira coluna, precisa ser multiplicado com os retornos diários S & # 038; P 500. O resto das colunas são irrelevantes e espero que seja auto-explicativo.


Deixe terminar a postagem com o código que carrega o indicador e traça o gráfico:


Eu tenho enólogo seu blog muito informativo. Se possível, ficaria muito interessado na fonte completa. Gostaria de ver se eu poderia modificá-lo para ver como ele funcionaria em um backtest usando o pacote quantstrat.


Para testar, eu não uso quantstrat por vários motivos. Pelo que eu lembro quando pensei em usar isso, meu plano era gerar o indicador (esta etapa leva tempo) e depois use o indicador computado como um argumento de entrada e simplesmente copie a posição.


Quem eu envio para o código-fonte da pesquisa GARCH?


Esse é o lugar certo, o site ainda está sendo construído e o formulário de comentários está por vir. 🙂


Confirme o código # 8211; Não tenho a certeza de que eu ainda quero publicar completamente. Também requer alguns recursos computacionais para realizar uma simulação completa.


Recentemente começou a usar R para fazer algumas análises de estoque, e tropeçou em seus excelentes blogs e obteve algumas informações muito úteis. É possível enviar-me uma fonte completa e eu quero estudá-la e testá-la


Da mesma forma, se você estiver aberto a isso, eu adoro estressar-testar o código no meu fim. Abordagem muito interessante.


Olá! Apenas por curiosidade aqui, os resultados que você publicou foram produzidos ao examinar os retornos diários ao longo de um determinado período de lookback e depois tentar predizer o retorno no dia seguinte. Você experimentou sua estratégia ARMA em retornos semanais? Como os resultados se acumulam contra a estratégia, onde os retornos diários são alimentados em seu modelo? Além disso, seria interessante ver alguns outros números, como os vencedores%, por exemplo. Você está atualmente usando este modelo para trocar dinheiro real? Excelente postagem e continue com o bom trabalho!


Oi. Eu não tentei retornos semanais, provavelmente vale a pena olhar para ele, embora para retornos semanais eu prefiro usar um modelo levando em consideração outros recursos além de retornos. Mais adequado para um SVM ou uma Rede Neural.


Sim, usei a estratégia ARMA + GARCH para trocar um único instrumento financeiro (não o SPY) há mais de um ano. Esta é a principal razão pela qual estou relutante em compartilhar o código.


Por último, eu estou olhando para atualizar o post com mais resumos e estatísticas de negócios, mas haven # 8217; t feito até agora, porque não consegui um formato satisfatório (eu sou exigente). :)


Estou extremamente grato a você por colocar códigos e informações úteis para análise quantitativa. Não tenho visto tais procedimentos organizados e códigos para R para análise de quantos em qualquer outro lugar. Tenho visitado seu blog há muito tempo. Estou tentando seguir os códigos aqui, mas tenho medo de que eu definitivamente esqueça alguns passos aqui. A função de armação me dá arma (5,2) para o & # 8216; SPY & # 8217; mas você está usando arma (0,2) para garchfit. Posso saber porquê ?. Se estou faltando alguma coisa, me guie e pode me enviar o código completo para prabinseth @ gmail. Desde já, obrigado.


Oi Prabin, sempre feliz de ouvir pessoas que gostam do blog, me inspiram a não negligenciá-lo. :)


O código ao qual você está se referindo é apenas uma ilustração de como usar o garchFit. O (0,2) é completamente aleatório & # 8211; Eu apenas escolho alguns números. Para o uso da vida real, é necessário criar uma função garchSearch, semelhante à armaSearch mostrada. É semelhante, mas há diferença: os modelos possíveis consistem em quatro elementos, os dois primeiros são (AR, MA), mas também há dois componentes GARCH, garchFit substitui o armaFit e também os resultados do garchFit são um pouco mais detalhados (uma matriz vs um número).


O código não é totalmente funcional como está. A razão pela qual eu não quero postar o código completo é que eu uso diariamente. Os resultados da execução diária no SPY estão disponíveis na página S & # 038; P 500. Tem a posição diária baseada em ARMA + GARCH, bem como, a tabela de ação para o final do dia.


Esse é o estado sobre ARMA + GARCH, mas eu prometo que ganhei # 8217; t fazer o mesmo por coisas novas (SVMs estão chegando). Vou publicar a versão totalmente funcional do código, embora eu não tenha atualizado com melhorias.


Oi, postagem muito interessante. Tenho uma pergunta sobre a função armaComputeForecasts que produz previsões contínuas. Quando isso produz uma previsão, a data do previsão (ou seja, o índice na linha xts correspondente) corresponde à data em que foi criada ou à data em que está prevista, ou seja, eu precisaria atrasar a prorrogação como de costume com um indicador ou isso já é cuidado?


Isso corresponde à data em que está prevista. Não é necessário atrasar ainda mais, apenas alinhe com a série de retorno.


Eu estou usando a mistura de ARMA + GARCH, mas às vezes o garch não consegue prever e retornar NA (Bad Model). Nesse caso, o que você faz? Você repete o valor anterior ou tenta pesquisar novamente?


Apenas compartilhando: eu estou comparando as funções garch e garchFit para calcular GARCH (1,1) e a função garch é muito mais rápido do que o garchFit.


Minha abordagem é percorrer todos os modelos entre (0,0,1,1) e (5,5,1,1), ignorar a uma vez que não converge e escolha aquela com AIC mais baixa. Se nenhum dos modelos (36 no total) converge, a previsão é 0, fora do mercado.


Talvez eu esteja errado, mas adicionar garch a um modelo de arma só melhora os intervalos de confiança e não a previsão. Você usa essas informações para dimensionar sua posição? Você tentou aparch em vez de garch para enfrentar a assimetria de volatilidade versus retornos?


Não consigo argumentar sobre as implicações teóricas de adicionar garch a um modo arma, mas definitivamente melhora as previsões de minhas experiências. Observe que não mesto as previsões como um erro absoluto, mas mais como um valor verdadeiro / falso (estimativa correta para a direção).


O pacote fGarch suporta o uso de distribuições distorcidas (sged, sstd) e eles também parecem melhorar as previsões. No momento, estou ficando sem recursos para testar qualquer coisa nova, mas posso tentar em algum momento no futuro. Obrigado por sugerir isso.


Isso é interessante. Pode ser que a adição de garch aumenta os parâmetros e isso afeta o modelo final selecionado pelo AIC de forma a melhorar a previsão.


Obrigado por compartilhar sua pesquisa.


Obrigado. Muito educacional.


Uma vez que o desempenho superior da ARMA parece bastante específico do período (a grande maioria dos retornos em excesso parece ser gerada entre 1965-75), seria muito mais útil ver um gráfico de retornos cumulativos rolantes para cada estratégia (ou seja, mais de 3 ou 5 anos). Além disso, os retornos de ARMA são presumivelmente brutos de t-cost aqui, então o roteamento da estratégia é outra consideração muito importante (você consegue compartilhar o que era?).


Oi, no meu antigo blog (theaverageinvestor. wordpress / 2018/07 /), mencionei que houve um comércio em média a cada 2,35 dias. Lembro-me de contar os negócios e dividir os dias.


O indicador para a série está disponível aqui: quintuitive / wp-content / uploads / 2018/08 / gspcInd3.csv. Ele precisa ser comparado com o índice de caixa S & # 038; P 500, sem atraso, mas pode-se obter todos os tipos de estatísticas. Certamente vou fazer isso um dia, não tenho certeza quando.


Com esta estratégia, não estou muito preocupado com os custos de transação. Usando uma conta regular e de varejo em Interactive Brokers, pode-se trocar uma participação da SPY por US $ 0,005. Ao preço atual de US $ 140, esse é insignificante, a menos que seja feito algumas vezes ao dia.


Seu post não é apenas interessante para ler, mas também atua como um guia para as pessoas novas no campo das finanças quantitativas. Com um iniciante neste campo, seu blog parece ser uma mina de ouro. Eu tenho algumas perguntas, no entanto, eu Utilizou seu código do Armasearch em um instrumento específico e descobriu que, com os indicadores, não deu um desempenho melhor do que comprar e manter, então, eu tentei encaixar no código garchFit usando garch (1,1) como o garch erros, você poderia me orientar gentilmente para que eu pudesse fazer isso? Os exemplos ou links relevantes seriam muito úteis.


Além disso, não entendi do seu código, como exatamente para executar o comércio, ou seja, pontos de entrada e saída, você poderia me orientar gentilmente no mesmo?


O seu blog não é apenas interessante, mas também informativo para as pessoas novas no mundo das finanças quantitativas. Tenho algumas perguntas, usei a função de armadura para um determinado instrumento e, após testar, achou que os resultados eram inferiores para comprar e segurar, então Estou tentando encaixar o garch (1,1), você poderia me guia gentilmente sobre como fazer o mesmo?


Além disso, você poderia me ajudar em relação aos pontos de entrada e saída do indicador gerado por você acima?


Oi, este é o meu melhor esforço (sem fornecer o código-fonte em si) para explicar como usar o garchFit. Você pode tentar primeiro as outras abordagens de arma, eu recomendaria o pacote de previsão e o livro de seu autor (otexts / fpp /), ou o pacote de rugigrama. Ambos os pacotes fornecem uma abordagem mais científica e avançada para a seleção do modelo de arma.


Aplicar as idéias neste blog na prática requer uma quantidade significativa de trabalho adicional. O meu único aconselhamento, que descrevi em outras postagens, é pensar em se aplicar em prática real em cada etapa.


Muito obrigado pelas excelentes apresentações que você fornece para iniciantes (como eu) em finanças quantitativas.


No seu trabalho, você está passando as séries temporais dia a dia, encontrando o melhor modelo ARMA e # 8211; ARMA (p, q)


e então use o modelo para prever a direção do dia seguinte.


Em seguida, para melhorar o desempenho, você usa os melhores paremeters de arma (p, q) para esse tempo.


com GARCH (1,1) para criar um novo modelo e usá-lo para prever a direção do dia seguinte.


Então você tem um modelo com 4 parâmetros usados ​​no garchFit.


Estou usando uma biblioteca GARCH diferente (não em R, está em C #) e nele.


Os parâmetros para o modelo são apenas 2 (em vez de 4):


o número de parâmetros de regressão automática (AR) eo número de parâmetros de média móvel (MA).


Você pode avisar sobre como usar seu método no meu cenário.


(como sempre criando um GRACH (1,1) sem considerar o ARMA (P, Q) é diferente).


Parece que a razão pela qual você tem apenas 2 parâmetros para o seu modelo é porque você está tentando ajustar sua data a um modelo ARMA sem o componente de heterocedasticidade.


O método GarchFit dentro da biblioteca fGarch em R permite caber em um modelo autoregressivo generalizado (daí os 4 parâmetros)


Pergunta rápida (relacionada) para você: você poderia me apontar para a biblioteca C # a que você está se referindo? Eu, eu mesmo, gosto bastante de C # (como eu tenho uma arquitetura inteira construída ao redor) e eu gostaria de incorporar uma biblioteca de montagem de dados que permite chamar um modelo ARMA.


Suas postagens são realmente ótimas e têm uma grande quantidade de informações valiosas. Eu tentei olhar para o indicador diário csv, mas não está mais em cima. Poderia ter uma cópia para inspecionar? Atualmente, estou testando o código completo da arma e quero saber como avaliar os resultados corretamente antes de tentar implementar o componente GARCH.


Atualizou o link & # 8211; Obrigado por me informar.


Em sua outra publicação sobre as regras de backtesting, você fez uma boa observação sobre a sinalização contra os preços, incluindo as divisões, mas não os dividendos, enquanto o backtesting em relação aos preços totalmente ajustados (incluindo divisões e dividendos). Como você pode fazer o primeiro usando getSymbols e Yahoo como fonte de dados? É minha impressão de que você só pode ajustar-se diretamente para ambos, em vez de apenas um.


adjustOHLC do quantmod faz isso: adjustOHLC (x, adjust = & # 8221; split & # 8221 ;, use. Adjusted = FALSE). Use o argumento symbol. name se a variável tiver um nome diferente do símbolo real.


Eu tenho perguntas específicas sobre a implementação do GARCH que você provavelmente não quer discutir na seção de comentários. Se você pode ver meu e-mail na área de administração do WP, você estaria aberto para discuti-los em particular?


Publicação muito interessante, mas o código fonte parece não estar mais disponível e # 8230; Alguém pode me enviar isso? meu e-mail um vestido: dentelle55@yahoo. fr.


Oi, que fonte não está mais disponível? Envie-me o link que expirou e vou atualizá-lo.


Este é um excelente trabalho! Mas eu tenho algumas perguntas sobre o seu modelo.


Esta abordagem é comumente usada para modelos de volatilidade (arma (p, q) + garch (1,1)). Qual a diferença entre o seu modelo e os modelos de volatilidade? A maioria deles está prevendo a volatilidade e não como você os retornos no dia seguinte, e não são eles? # 8230; Não tenho a diferença até agora # 8230; Você já considerou usar um modelo EGARCH ou TGARCH?


Oi. Também me perguntei o mesmo, mas não vejo uma razão pela qual também não podemos usar as previsões médias. Dos meus experimentos, as previsões ARMA + GARCH são superiores em termos de poder preditivo em comparação com apenas a previsão ARMA.


Um artigo que conheço, que usa um método semelhante (entre outras coisas) é "Comércio técnico, previsibilidade e aprendizado em mercados cambiais" # 8221; & # 8230; Não usei modelos EGARCH / TGARCH.


Tenho uma pergunta sobre a escolha do modelo. Você corre todas as combinações em (0,0) a (5,5) e escolha o melhor com base em AIC.


Mas e se esse & # 8220; melhor & # 8221; resulta em coeficientes insignificantes de arma ou garch? E isso acontece com bastante frequência. Isso é por causa dos dados na amostra então?


Obrigado pelo blog e pela resposta, informações realmente interessantes no blog sobre como usar a academia na prática, como antes, eu só estava desenvolvendo modelos para a universidade.


Os coeficientes insignificantes zero são uma maneira de abordar isso. Eu sou cético quanto melhora, mas não o testei seriamente. Uma outra questão seria o que fazer quando todos os coeficientes forem insignificantes? Jogue o modelo e use o próximo melhor com base em AIC, ou saia do mercado?


Obrigado pela resposta!


Na verdade, muitas vezes é possível avançar para outro modelo com quase o mesmo AIC. Na verdade, a estimativa do modelo depende muito do tamanho dos dados na amostra (dependendo do estágio de volatilidade). Pode-se repetir o seu procedimento de estimativa e previsão para diferentes tamanhos de dados na amostra esperando resultados robustos.


Em todos os lugares acima, você menciona apenas a previsão em n passos à frente. Você tentou simulações para avaliar derivativos, por exemplo? Você acha que também é possível modelar uma taxa de juros baixa com o arma-garch estimado em dados overnight ou semanais, de modo que corresponda à estrutura do termo atual?


A execução de várias janelas simultaneamente é uma ideia muito interessante. Definitivamente vou considerar executar um teste. Na verdade, em vez de escolher pela AIC, provavelmente é provável que use a votação entre todos os modelos que fornecem uma predição & # 8230;


Eu nunca usei ARMA / GARCH para preços de derivados, mas entendi que os derivados de preços são a principal aplicação. Os dados semanais / mensais são úteis, a menos que sejam muito voláteis, mesmo que diariamente, eu vi os modelos ter problemas com alguns futuros mais voláteis.


Oi Ivan, como você está?


Tenho tentado replicar a planilha com sinais (que você postou acima), mas não consegui. Você está executando apenas esse modelo Arma-garch (período de informação de 500 dias de negociação) e usando a previsão do modelo ajustado para definir sua posição comercial no dia seguinte? Sobre a especificação de seu modelo & # 8230 ;. relacionado aos termos de inovação & # 8230; qual distribuição você está usando? & # 8220; Erro generalizado & # 8221; ??


Obrigado pela sua atenção e gostaria de congratular o trabalho que você fez no seu blog & # 8230 ;. Eu tenho acompanhado por algum tempo seu trabalho e as discussões aqui são muito educativas / construtivas!


Gostoso de ouvir o blog é interessante e as pessoas acham útil. Você está usando o código da mina, do site? Eu raramente uso qualquer coisa, exceto a distribuição de erro generalizada distorcida (& # 8220; sged & # 8221; é o parâmetro garchFit para ele). Se você vê as diferenças, envie-me uma repro e vou dar uma olhada.


Ivan & # 8230; Existe algum e-mail que eu possa enviar-lhe uma planilha que contenha o backtest que fiz? Envie para yuriverges @ globo.


Eu sou novo em R, e este é um blog muito útil e muito informativo. Obrigado.


Você pode dar o conjunto de dados que você usou para determinar a ordem do processo ARMA (conjunto de dados xx). Executei a função armaSearch no console R usando meu conjunto de dados, mas não devolveu nenhum resultado.


Não há necessidade do acima, posso resolver. Você está executando essas simulações em uma máquina linux? Como o Windows não parece permitir que um use multi-core. Você está ciente de quaisquer pacotes que ajudem a fazer isso? Eu encontrei alguns, mas não tenho certeza qual é o melhor para o fGarch.


Abri a fonte um pouco depois e # 8211; gist. github / ivannp / 5198580. Está no post, provavelmente um pouco difícil de encontrar.


Sim, estou usando o linux, e sim, o pacote paralelo costumava ter alguns problemas no Windows, mas acho que estes foram esclarecidos. Não?


Espero que isto ajude!


Obrigado pela adorável publicação. É bem escrito e bastante útil para quem procura se destacar nessa área.


BTW, este link não funciona mais.


Você poderia olhar para ele e corrigir o link quebrado? Talvez, você pode querer publicá-lo como um arquivo / link autônomo para download.


Muitos agradecimentos e cumprimentos,


Estou usando o modelo ARMA (P, Q) / GARCH (p, q) na minha dissertação, mas eu não sei como escolher meus valores P, Q, p, q. Sob simples ARMA, eu sei que só tenho que olhar para o ACF / PACF da Time Series, mas eu estou perdido para o modelo ARMA / GARCH.


Você pode me ajudar por favor?


Oi, o método que uso é fazer um ciclo de um conjunto de modelos e escolher o & # 8220; melhor & # 8221; com base em uma das estatísticas bem conhecidas & # 8211; AIC / BIC / HIC / etc. Eu aprendi essa abordagem para os modelos ARMA da Série de tempos introdutórios # 8220 com R & # 8221; (amazon / Introduction-Time-Series-Paul-Cowpertwait / dp / 0387886974). O código-fonte da minha abordagem é desta publicação: quintuitive / 2018/03/24 / automatic-arma ... on-in-parallel /.


Eu vi em documentos que o modelo garch usa termos de erro para se calibrar, mas como faço para obter o termo de erro quando eu não tenho mesmo um modelo para a equação média?


O modelo Garch deve ser aplicado nos resíduos (Et) de uma série ou na própria série (Xt)?


Eu vi no livro que você sugeriu que ele aplica a função garch aos erros simulados, então ele aplica-lo aos dados SP500, fiquei confuso com isso.


Tenho certeza de que não estão com erro sobre como usar o GARCH, mas você pode querer verificar com a literatura. No capítulo de seleção do modelo ARMA (sem GARCH), no entanto, eles alternam vários modelos e selecionam o baseado em AIC. O pacote de previsão de Rob Hyndman tem uma abordagem semelhante para o ARMA. Eu simplesmente estou usando a mesma abordagem para ARMA + GARCH. Ciclismo através de um conjunto de modelos predefinido dá-lhe a oportunidade de procurar e comparar outras métricas também. intervalos de confiança, por exemplo.


Eu tentei usar o pacote fGarch, mas eu preciso especificar os parâmetros, isn & # 8217; t existe uma função é o pacote que procura o melhor modelo ARMA-GARCH? Como o auto. arima do.


E quanto a você, quais dados você alimenta no modelo GARCH? Residuais? Ou os retornos?


Será que ele ajusta o ARMA primeiro, em seguida, use os resíduos para calcular o GARCH? Ou ele faz isso em paralelo?


Eu sou novo em R, então eu não entendo muito o que está escrito nos códigos.


Muito interessante, obrigado.


Eu não sei se é só eu ou se talvez todos os outros tenham problemas com o seu site.


Parece que algum texto do seu conteúdo está sendo executado.


fora da tela. Alguém pode fornecer comentários e me informar se isso também está acontecendo com eles?


Isso pode ser um problema com o meu navegador de internet.


porque eu já tinha acontecido anteriormente. Obrigado.


Esta é a primeira vez que ouço essa queixa. Vou manter um olho em relatórios semelhantes.


Adorei ler seu blog sobre isso. Utilizei a função alternativa auto. arima () em vez da sua função de ARMA procuração (muito mais lenta e mais cara), mas essa deu backtests drasticamente diferentes e apresentou desempenho pior do que Buy-and-Hold. Ele não replicou seus resultados com base em seu ARMAsearch, mas, no entanto, conseguiu muitos lucros em torno da crise do & # 8217; 08, bem como o seu ARMAsearch fez, mas ainda não se compara realmente. Isso foi interessante para mim. Por enquanto estou lendo o código-fonte auto. arima () e comparando-o com o seu ARMAsearch. Parece que você fez uma pesquisa em grade; auto. arima () faz uma pesquisa local (o que explica a velocidade).


Posso perguntar quais tipos de hardware você está usando hoje em dia? Você faz algum cálculo de GPU?


Olá, feliz que goste do meu blog. Para o meu uso, acho que as CPUs da Intel oferecem desempenho e paralelização suficientes. O hardware que uso é quad-core i7 com hyperthreading, o que o torna & # 8220; quase & # 8221; 8 vias. Em tal máquina, um backtest ARMA + GARCH leva menos de um dia (se a minha memória estiver correta) por cerca de 50 anos de dados. Ele faz todo o trabalho para prever decisões on-close para um dia específico (ou seja, o trabalho necessário para se preparar para um dia de negociação) em aproximadamente algumas horas.


Na verdade, você está certo, a função auto. arima usa um algoritmo diferente, que não analisa todos os resultados. Da minha experiência, não é direto replicar resultados de 100% entre pacotes. Especialmente quando se trata da distribuição dos resíduos. Notei o mesmo quando, em algum momento, tentei brevemente o pacote de rugiscas.


Eu sou um novato para as finanças matemáticas. Eu estava apenas discutindo com meu professor sobre o uso do modelo ARMA na negociação real na semana passada. Eu achei seu modelo de detalhe muito interessante. Então eu tento estudá-lo linha a linha. Tentei imprimir o erro padrão junto com a predição e descobriu que a magnitude do erro padrão é muito maior do que a predição. Eu estava pensando se isso colocaria muito risco na decisão individual, limitando o modelo a funcionar em grande número de decisões apenas, e talvez não seja assim ao usar a estratégia por um curto período de tempo.


A esperança pode ter sua idéia. Obrigado.


Esse é um problema e já foi discutido em outros comentários. Se alguém não quer usar esse método por falta de méritos estatísticos e # 8211; que assim seja. An alternative approach would be to develop a system that uses a method while “it works”.


Great blog, thanks. I have been using your code for some research… would you be willing to post the source code for creating the indicator matrix? Obrigado.


Hi, is this link gist. github/ivannp/5198580 what you are looking for? It’s a stripped down and older version of what I actually use.


Thanks… Only thing that isn’t clear to me…in the garchautotryfit, what is “ll” represent? Obrigado!


mclapply takes models, a list of all the models (and each model is also a list, thus, we have a list of lists) we want to compute as its first argument, then it calls garchAutoTryFit for each individual model from this list, passing the model as it’s first argument.


The following line adds a new model to the list in garchAuto:


models[[length( models ) + 1]] = list( order=c( p, q, r, s ), dist=dist )


Each model is also a list, containing the order (accessed via $order) and the distribution (accessed via $dist).


Now I feel it’s a bit of an ugly way to do things, but it gets the work done.:)


Ok… that makes sense to me, but what is actually building the ll? garchAutoTryFit and garchAuto are allowing you to optimize the parameters for the prediction you make with garchfit… I know that the “data” or “xx” in the code is the return series, but I don’t see how to execute the functions without an initial ll. Obrigado!


ll is constructed inside garchAuto, using min. order, max. order and a few other parameters passed to the routine by the user. If min. order is (0,0,1,1) and max. order is (5,5,1,1), garchAuto constructs an ll which contains all possible variations within these limits, for instance, it will contain (0,0,1,1), (0,1,1,1), etc. By default, the routine chooses the best model within (0,0,1,1) and (5,5,1,1).


Ok… obrigado. I have been trying to run garchAuto using a return series as the xx input but only receive NULL.


Very informative blog! I am planning to use a similar strategy using auto. arima(), without success so far – just starting though.


& # 8211; What was your approximative CAGR using only ARIMA models without Garch?


& # 8211; How do you decide which position to take: do you buy as soon as the forecast on the return is positive and sell if – negative, or do you implement minimal thresholds (to avoid selling or buying if the difference is too small)? If so, how do you define these thresholds?


& # 8211; Could you please cite some of the reasons why you don’t forecast on the original series? Is it a critical condition IYO?


& # 8211; Can you advise on how I could proceed with my (currently) unsuccessful auto. arima() strategy?


ARIMA without GARCH is not very good on the SPY. Neither on other ETFs. Even with GARCH, it needs additional work to come up with something trade-able.


I assume I am able to execute the trades at the close, which is achievable in real life. Easiest is to trade the futures (open 24/7) however one needs to backtest it properly.


ARMA/GARCH are used on stationary time series. The returns are stationary, the closing prices are not.


I am a novice trader looking to apply a degree in stats to the world of financial markets. I saw that you didn’t want to share the code a few years back, but if there is any form/script I could look through and use to better learn R, then I would be more than grateful if you could send it my way. Thanks again for the post, it was excellent.


QuantStart.


Join the Quantcademy private membership portal that caters to the rapidly-growing retail quant trader community . You'll find a knowledgeable, like-minded group of quant traders ready to answer your most pressing quant trading questions.


Check out my ebook on quant trading where I teach you how to build profitable systematic trading strategies with Python tools, from scratch.


Take a look at my new ebook on advanced trading strategies using time series analysis, machine learning and Bayesian statistics, with Python and R .


By Michael Halls-Moore on October 7th, 2018.


In this article I want to show you how to apply all of the knowledge gained in the previous time series analysis posts to a trading strategy on the S&P500 US stock market index.


We will see that by combining the ARIMA and GARCH models we can significantly outperform a "Buy-and-Hold" approach over the long term.


Visão geral da estratégia.


The idea of the strategy is relatively simple but if you want to experiment with it I highly suggest reading the previous posts on time series analysis in order to understand what you would be modifying!


The strategy is carried out on a "rolling" basis:


For each day, $n$, the previous $k$ days of the differenced logarithmic returns of a stock market index are used as a window for fitting an optimal ARIMA and GARCH model. The combined model is used to make a prediction for the next day returns. If the prediction is negative the stock is shorted at the previous close, while if it is positive it is longed. If the prediction is the same direction as the previous day then nothing is changed.


For this strategy I have used the maximum available data from Yahoo Finance for the S&P500. I have taken $k=500$ but this is a parameter that can be optimised in order to improve performance or reduce drawdown.


The backtest is carried out in a straightforward vectorised fashion using R. It has not been implemented in the Python event-driven backtester as of yet. Hence the performance achieved in a real trading system would likely be slightly less than you might achieve here, due to commission and slippage.


Strategy Implementation.


To implement the strategy we are going to use some of the code we have previously created in the time series analysis article series as well as some new libraries including rugarch, which has been suggested to me by Ilya Kipnis over at QuantStrat Trader.


I will go through the syntax in a step-by-step fashion and then present the full implementation at the end, as well as a link to my dataset for the ARIMA+GARCH indicator. I've included the latter because it has taken me a couple of days on my dekstop PC to generate the signals!


You should be able to replicate my results in entirety as the code itself is not too complex, although it does take some time to simulate if you carry it out in full.


The first task is to install and import the necessary libraries in R:


If you already have the libraries installed you can simply import them:


With that done are going to apply the strategy to the S&P500. We can use quantmod to obtain data going back to 1950 for the index. Yahoo Finance uses the symbol "^GPSC".


We can then create the differenced logarithmic returns of the "Closing Price" of the S&P500 and strip out the initial NA value:


We need to create a vector, forecasts to store our forecast values on particular dates. We set the length foreLength to be equal to the length of trading data we have minus $k$, the window length:


At this stage we need to loop through every day in the trading data and fit an appropriate ARIMA and GARCH model to the rolling window of length $k$. Given that we try 24 separate ARIMA fits and fit a GARCH model, for each day, the indicator can take a long time to generate.


We use the index d as a looping variable and loop from $k$ to the length of the trading data:


We then create the rolling window by taking the S&P500 returns and selecting the values between $1+d$ and $k+d$, where $k=500$ for this strategy:


We use the same procedure as in the ARIMA article to search through all ARMA models with $p \in \ $ and $q \in \ $, with the exception of $p, q=0$.


We wrap the arimaFit call in an R tryCatch exception handling block to ensure that if we don't get a fit for a particular value of $p$ and $q$, we ignore it and move on to the next combination of $p$ and $q$.


Note that we set the "integrated" value of $d=0$ (this is a different $d$ to our indexing parameter!) and as such we are really fitting an ARMA model, rather than an ARIMA.


The looping procedure will provide us with the "best" fitting ARMA model, in terms of the Akaike Information Criterion, which we can then use to feed in to our GARCH model:


In the next code block we are going to use the rugarch library, with the GARCH(1,1) model. The syntax for this requires us to set up a ugarchspec specification object that takes a model for the variance and the mean. The variance receives the GARCH(1,1) model while the mean takes an ARMA(p, q) model, where $p$ and $q$ are chosen above. We also choose the sged distribution for the errors.


Once we have chosen the specification we carry out the actual fitting of ARMA+GARCH using the ugarchfit command, which takes the specification object, the $k$ returns of the S&P500 and a numerical optimisation solver. We have chosen to use hybrid , which tries different solvers in order to increase the likelihood of convergence:


If the GARCH model does not converge then we simply set the day to produce a "long" prediction, which is clearly a guess. However, if the model does converge then we output the date and tomorrow's prediction direction (+1 or -1) as a string at which point the loop is closed off.


In order to prepare the output for the CSV file I have created a string that contains the data separated by a comma with the forecast direction for the subsequent day:


The penultimate step is to output the CSV file to disk. This allows us to take the indicator and use it in alternative backtesting software for further analysis, if so desired:


However, there is a small problem with the CSV file as it stands right now. The file contains a list of dates and a prediction for tomorrow's direction. If we were to load this into the backtest code below as it stands, we would actually be introducing a look-ahead bias because the prediction value would represent data not known at the time of the prediction.


In order to account for this we simply need to move the predicted value one day ahead. I have found this to be more straightforward using Python. Since I don't want to assume that you've installed any special libraries (such as pandas), I've kept it to pure Python.


Here is the short script that carries this procedure out. Make sure to run it in the same directory as the forecasts. csv file:


At this point we now have the corrected indicator file stored in forecasts_new. csv . Since this takes a substantial amount of time to calculate, I've provided the full file here for you to download yourself:


Strategy Results.


Now that we have generated our indicator CSV file we need to compare its performance to "Buy & Hold".


We firstly read in the indicator from the CSV file and store it as spArimaGarch :


We then create an intersection of the dates for the ARIMA+GARCH forecasts and the original set of returns from the S&P500. We can then calculate the returns for the ARIMA+GARCH strategy by multiplying the forecast sign (+ or -) with the return itself:


Once we have the returns from the ARIMA+GARCH strategy we can create equity curves for both the ARIMA+GARCH model and "Buy & Hold". Finally, we combine them into a single data structure:


Finally, we can use the xyplot command to plot both equity curves on the same plot:


The equity curve up to 6th October 2018 is as follows:


Equity curve of ARIMA+GARCH strategy vs "Buy & Hold" for the S&P500 from 1952.


As you can see, over a 65 year period, the ARIMA+GARCH strategy has significantly outperformed "Buy & Hold". However, you can also see that the majority of the gain occured between 1970 and 1980. Notice that the volatility of the curve is quite minimal until the early 80s, at which point the volatility increases significantly and the average returns are less impressive.


Clearly the equity curve promises great performance over the whole period . However, would this strategy really have been tradeable?


First of all, let's consider the fact that the ARMA model was only published in 1951. It wasn't really widely utilised until the 1970's when Box & Jenkins discussed it in their book.


Secondly, the ARCH model wasn't discovered (publicly!) until the early 80s, by Engle, and GARCH itself was published by Bollerslev in 1986.


Thirdly, this "backtest" has actually been carried out on a stock market index and not a physically tradeable instrument. In order to gain access to an index such as this it would have been necessary to trade S&P500 futures or a replica Exchange Traded Fund (ETF) such as SPDR.


Hence is it really that appropriate to apply such models to a historical series prior to their invention? An alternative is to begin applying the models to more recent data. In fact, we can consider the performance in the last ten years, from Jan 1st 2005 to today:


Equity curve of ARIMA+GARCH strategy vs "Buy & Hold" for the S&P500 from 2005 until today.


As you can see the equity curve remains below a Buy & Hold strategy for almost 3 years, but during the stock market crash of 2008/2009 it does exceedingly well. This makes sense because there is likely to be a significant serial correlation in this period and it will be well-captured by the ARIMA and GARCH models. Once the market recovered post-2009 and enters what looks to be more a stochastic trend, the model performance begins to suffer once again.


Note that this strategy can be easily applied to different stock market indices, equities or other asset classes. I strongly encourage you to try researching other instruments, as you may obtain substantial improvements on the results presented here.


Próximos passos.


Now that we've finished discussing the ARIMA and GARCH family of models, I want to continue the time series analysis discussion by considering long-memory processes, state-space models and cointegrated time series.


These subsequent areas of time series will introduce us to models that can improve our forecasts beyond those I've presented here, which will significantly increase our trading profitability and/or reduce risk.


Here is the full listing for the indicator generation, backtesting and plotting:


And the Python code to apply to forecasts. csv before reimporting:


Just Getting Started with Quantitative Trading?


3 Reasons to Subscribe to the QuantStart Email List:


1. Quant Trading Lessons.


You'll get instant access to a free 10-part email course packed with hints and tips to help you get started in quantitative trading!


2. All The Latest Content.


Every week I'll send you a wrap of all activity on QuantStart so you'll never miss a post again.


Real, actionable quant trading tips with no nonsense.


Systematic Investor.


Systematic Investor Blog.


Trading using Garch Volatility Forecast.


Quantum Financier wrote an interesting article Regime Switching System Using Volatility Forecast. The article presents an elegant algorithm to switch between mean-reversion and trend-following strategies based on the market volatility. Two model are examined: one using the historical volatility and another using the Garch(1,1) Volatility Forecast. The mean-reversion strategy is modeled with RSI(2): Long when RSI(2), and Short otherwise. The trend-following strategy is modeled with SMA 50/200 crossover: Long when SMA(50) > SMA(200), and Short otherwise.


I want show how to implement these ideas using the backtesting library in the Systematic Investor Toolbox.


Following code loads historical prices from Yahoo Fiance and compares performance of the Buy and Hold, Mean-Reversion, and Trend-Following strategies using the backtesting library in the Systematic Investor Toolbox:


Next, let’s create a strategy that switches between mean-reversion and trend-following strategies based on historical market volatility.


Next, let’s create a GARCH(1,1) Volatility Forecast. I would recommend reading following articles for anyone who wants to find what GARCH is all about or to refresh their knowledge:


There are a few R packages to fit GARCH models. I will consider garch function from tseries package and garchFit function from fGarch package. The garch function from tseries package is fast but does not always find solution. The garchFit function from fGarch package is slower but does converge more consistently. To demonstrate the speed difference between garch function and garchFit function I created a simple benchmark:


The garchFit function is on average 6 times slower than garch function. So to forecast volatility I will try to use garch function whenever it can find a solution and garchFit function otherwise.


Now, let’s create a strategy that switches between mean-reversion and trend-following strategies based on GARCH(1,1) volatility forecast.


The switching strategy that uses GARCH(1,1) volatility forecast performed slightly better than the one that uses historical volatility.


There many different approaches you can take to incorporate forecasting into your models and trading strategies. R has a very rich set of packages to model and forecast time series. Here are some examples that I found interesting:


To view the complete source code for this example, please have a look at the bt. volatility. garch() function in bt. test. r at github.


Compartilhar isso:


Relacionados.


Pós-navegação.


Deixe uma resposta Cancelar resposta.


Just a slight clarification: I used garch to try to calibrate the significance of other people’s predictions — I’m not making any predictions myself.


Pat, thank you for clarification. I have updated the post.


Obrigado pela postagem.


The strategy looks good at first sight. Though when I look more closely it seems to pretty much follow the index (or the buy and hold..) when times are good and edges higher “just” from avoiding the drawdowns, with a distinct rise that comes from the 2008 crise period which can be regarded as non-standard.


Thank you for your excellent blog.


How do I change the code so I can use a csv file(Date, O,H, L,C, V) to read in the data instead of yahoo?


getSymbols(tickers, src = 'yahoo', from = '1970-01-01', env = data, auto. assign = T)


for(i in ls(data)) data[[i]] = adjustOHLC(data[[i]], use. Adjusted=T)


Thank you for your help.


Thank you for reading my blog. There is getSymbols. csv function in the quantmod package that reads data from the local csv file.


Once again a very interesting post!


I have however a question about the time frame that is used to calculate volatility rank.


If I understand this example correctly we look at the past 21 days and rank them as compared to the last 252 days?


If I am correct I believe this has some unwanted side effects. This would mean that in the years 2003 through 2006 (when volatility was very low) this system would half of the time be trading a system that was intended for high volatility periods. It would also mean that during the high volatile periods of 2007 through 2009 we would half the time be trading a system that was intended for low volatility.


Robot Wealth.


Fitting time series models to the forex market: are ARIMA/GARCH predictions profitable?


Recently, I wrote about fitting mean-reversion time series models to financial data and using the models’ predictions as the basis of a trading strategy. Continuing my exploration of time series modelling, I decided to research the autoregressive and conditionally heteroskedastic family of time series models. In particular, I wanted to understand the autogressive integrated moving average (ARIMA) and generalized autoregressive conditional heteroskedasticity (GARCH) models, since they are referenced frequently in the quantitative finance literature, and its about time I got up to speed. What follows is a summary of what I learned about these models, a general fitting procedure and a simple trading strategy based on the forecasts of a fitted model.


Several definitions are necessary to set the scene. I don’t want to reproduce the theory I’ve been wading through; rather here is my very high level summary of what I’ve learned about time series modelling, in particular the ARIMA and GARCH models and how they are related to their component models:


At its most basic level, fitting ARIMA and GARCH models is an exercise in uncovering the way in which observations, noise and variance in a time series affect subsequent values of the time series. Such a model, properly fitted, would have some predictive utility, assuming of course that the model remained a good fit for the underlying process for some time in the future.


An ARMA model (note: no “I”) is a linear combination of an autoregressive (AR) model and moving average (MA) model. An AR model is one whose predictors are the previous values of the series. An MA model is structurally similar to an AR model, except the predictors are the noise terms. An autoregressive moving average model of order p, q – ARMA(p, q) – is a linear combination of the two and can be defined as:


where $w_ $ is white noise and $a_ $ and $ b_ $ are coefficients of the model.


An ARIMA(p, d,q) model is simply an ARMA(p, q) model differenced ‘d’ times – or integrated (I)- to produce a stationary series.


Finally, a GARCH model attempts to also explain the heteroskedastic behavior of a time series (that is, the characteristic of volatility clustering) as well as the serial influences of the previous values of the series (explained by the AR component) and the noise terms (explained by the MA component). A GARCH model uses an autoregressive process for the variance itself, that is, it uses past values of the variance to account for changes to the variance over time.


With that context setting out of the way, I next fit an ARIMA/GARCH model to the EUR/USD exchange rate and use it as the basis of a trading system. The model’s parameters for each day are estimated using a fitting procedure, that model is then used to predict the next day’s return and a position is entered accordingly and held for one trading day. If the prediction is the same as for the previous day, the existing position is maintained.


A rolling window of log returns is used to fit an optimal ARIMA/GARCH model at the close of each trading day. The fitting procedure is based on a brute force search of the parameters that minimize the Aikake Information Criterion, but other methods can be used. For example, we could choose parameters that minimize the Bayesian Information Criterion, which may help to reduce overfitting by penalizing complex models (that is, models with a large number of parameters). This fitting procedure was inspired by Michael Halls-Moore’s post about an ARIMA+GARCH trading strategy for the S&P500, and I borrowed some of his code.


I chose to use a rolling window of 1000 days to fit the model, but this is a parameter for optimization. There is a case for using as much data as possible in the rolling window, but this may fail to capture the evolving model parameters quickly enough to adapt to a changing market. I won’t explore this too much here, but it would be interesting to investigate the strategy’s performance as a function of the lookback window. Here’s the code:


First, the directional predictions only: buy when a positive return is forecast and sell when a negative return is forecast. The results of this approach are shown below (no allowance for transaction costs):


You might have noticed that in the model fitting procedure above, I retained the actual forecast return values as well as the direction of the forecast return. I want to investigate the predictive power of the magnitude of the forecast return value. Specifically, does filtering trades when the magnitude of the forecast return is below a certain threshold improve the performance of the strategy? The code below performs this analysis for a small return threshold. For simplicity, I converted the forecast log returns to simple returns to enable manipulation of the sign of the forecast and easy implementation.


And the results overlaid with the raw strategy:


It occurred to me that the ARIMA/GARCH model we fit on certain days may be a better or worse representation of the underlying process than other days. Perhaps filtering trades when we have less confidence in our model would improve performance. This approach requires that the statistical significance of each day’s model fit be evaluated, and a trade only entered when this significance exceeds a certain threshold. There are a number of ways this could be accomplished. Firstly, we could visually examine the correlogram of the model residuals and make a judgement on the goodness of fit on that basis. Ideally, the correlogram of the residuals would resemble a white noise process, showing no serial correlation. The correlogram of the residuals can be constructed in R as follows:


acf ( fit @ fit $ residuals , main = 'ACF of Model Residuals' )


While this correlogram suggests a good model fit, it is obviously not a great approach as it relies on subjective judgement, not to mention the availability of a human to review each day’s model. A better approach would be to examine the Ljung-Box statistics for the model fit. The Ljung-Box is a hypothesis test for evaluating whether the autocorrelations of the residuals of a fitted model differ significantly from zero. In this test, the null hypothesis is that the autocorrelation of the residuals is zero; the alternate is that the series possesses serial correlation. Rejection of the null and confirmation of the alternate would imply that the model is not a good fit, as there is unexplained structure in the residuals. The Ljung-Box statistic is calculated in R as follows:


The p-value in this case provides evidence that the residuals are independent and that this particular model is a good fit. By way of explanation, the Ljung-Box test statistic (X-squared in the code output above) grows larger for increasing autocorrelation of the residuals. The p-value is the probability of obtaining a value as large or larger than the test statistic under the null hypothesis. Therefore, a high p-value in this case is evidence for independence of the residuals. Note that it applies to all lags up to the one specified in the Box . test ( ) function.


Applying the Ljung-Box test to each day’s model fit reveals very few days where the null hypothesis of independent residuals is rejected, so extending the strategy to also filter any trades triggered by a poor model fit is unlikely to add much value:


Conclusions and future work.


The performance of the ARIMA/GARCH strategy outperforms a buy and hold strategy on the EUR/USD for the backtest period, however the performance is nothing spectacular. It seems that it is possible to improve the performance of the strategy by filtering on characteristics such as the magnitude of the prediction and the goodness of fit of the model, although the latter does not add much value in this particular example. Another filtering option could be to calculate the 95% confidence interval for each day’s forecast and only enter a trade when the sign of each limit is the same, although this would greatly reduce the number of trades actually taken.


There are many other varieties of the GARCH model, for example exponential, integrated, quadratic, threshold, structural and switching to name a few. These may or may not provide a better representation of the underlying process than the simple GARCH (1,1) model used in this example. For an exposition of these and other flavors of GARCH, see Bollerslev et. al. (1994).


An area of research that I have found highly interesting recently is time series forecasting through the intelligent combination of disparate models, for example by taking the average of the individual predictions of several models or seeking consensus or a majority vote on the sign of the prediction. To borrow some machine learning nomenclature, this ‘ensembling’ of models can often produce more accurate forecasts than any of the constituent models. Perhaps a useful approach would be to ensemble the predictions of the ARIMA/GARCH model presented here with a suitably trained artificial neural network or other statistical learning method. We could perhaps expect the ARIMA/GARCH model to capture any linear characteristics of the time series, while the neural network may be a good fit for the non-linear characteristics. This is all pure speculation, potentially with some backing from this paper, but an interesting research avenue nevertheless.


If you have any ideas for improving the forecast accuracy of time series models, I’d love to hear about them in the comments.


Finally, credit where credit is due: although I worked my way through numerous sources of information on financial time series modelling, I found Michael Halls-Moore’s detailed posts on the subject extremely helpful. He starts from the beginning and works through various models of increasing complexity. As stated in the main post, I also borrowed from his ARIMA + GARCH trading strategy for the S&P500 in designing the EUR/USD strategy presented here, particularly the approach to determining model parameters through iterative minimization of the Aikake Information Criterion. The ideas around filtering trades on the basis of the results of the Ljung-Box test and the absolute magnitude of the forecast value were my own (although I’m sure I’m not the first to come up with them).


Other references I found particularly useful:


Bollerslev, T. (2001). Financial Econometrics: Past Developments and Future Challenges , in Journal of Econometrics, Vol. 100, 41-51.


Bollerslev, T., Engle, R. F. and Nelson, D. B. (1994). GARCH Models , in: Engle, R. F., and McFadden, D. L. (eds.) Handbook of Econometrics, Vol. 4, Elsevier, Amsterdam, 2961-3038.


Engle, R. (2002). New Frontiers for ARCH Models , in Journal of Applied Econometrics, Vol. 17, 425-466.


Qi, M. and Zhang, G. P. (2008). Trend Time Series Modelling and Forecasting with Neural Networks , in IEEE Transactions on Nerual Networks, Vol. 19, No. 5, 8-8-816.


Tsay, R. (2018). Conditional Heteroscedastic Models , in Tsay, R. Analysis of Financial Time Series, Third Edition, Wiley, 109-174.


Here you can download the code and data used in this analysis: arima_garch.

No comments:

Post a Comment