Friday 4 August 2017

Moving Average Acf


Usando R para Time Series Analysis Time Series Analysis Este folheto informa você como usar o software estatístico R para realizar algumas análises simples que são comuns na análise de dados de séries temporais. Este folheto pressupõe que o leitor possui algum conhecimento básico da análise de séries temporais e o foco principal do folheto não é explicar a análise de séries temporais, mas sim explicar como realizar essas análises usando R. Se você é novo em séries temporais Análise e quer aprender mais sobre qualquer um dos conceitos apresentados aqui, eu recomendo o livro Open University 8220Time series8221 (código de produto M24902), disponível na Open University Shop. Neste livreto, vou usar conjuntos de dados da série de tempo que foram gentilmente disponibilizados por Rob Hyndman em sua Time Series Data Library no robjhyndmanTSDL. Se você gosta deste folheto, você também pode verificar meu livreto no uso de R para estatísticas biomédicas, a-little-book-of-r-for-biomedical-statistics. readthedocs. org. E meu livreto sobre o uso de R para análise multivariada, pequeno-livro-de-r-for-multivariado-analysis. readthedocs. org. Dados da série de tempo de leitura A primeira coisa que você deseja fazer para analisar seus dados da série temporal será lê-lo em R e traçar as séries temporais. Você pode ler dados em R usando a função scan (), que assume que seus dados para pontos de tempo sucessivos estão em um arquivo de texto simples com uma coluna. Por exemplo, o arquivo robjhyndmantsdldatamisckings. dat contém dados sobre a idade da morte de reis sucessivos da Inglaterra, começando com William the Conqueror (fonte original: Hipel e Mcleod, 1994). O conjunto de dados parece assim: somente as primeiras linhas do arquivo foram exibidas. As primeiras três linhas contêm alguns comentários sobre os dados e queremos ignorar isso quando lemos os dados em R. Podemos usar isso usando o parâmetro 8220skip8221 da função scan (), que especifica quantas linhas no topo de O arquivo a ignorar. Para ler o arquivo em R, ignorando as três primeiras linhas, escrevemos: neste caso, a idade da morte de 42 reis sucessivos da Inglaterra foi lida na variável 8216kings8217. Depois de ler os dados da série temporal em R, o próximo passo é armazenar os dados em um objeto de séries temporais em R, para que você possa usar as diversas funções do R8217 para analisar dados da série temporal. Para armazenar os dados em um objeto de séries temporais, usamos a função ts () em R. Por exemplo, para armazenar os dados na variável 8216kings8217 como um objeto de séries temporais em R, nós escrevemos: às vezes o conjunto de dados da série de tempo que você Podem ter sido coletados em intervalos regulares que foram inferiores a um ano, por exemplo, mensais ou trimestrais. Neste caso, você pode especificar o número de vezes que os dados foram coletados por ano usando o parâmetro 8216frequency8217 na função ts (). Para dados de séries temporais mensais, você define a freqüência12, enquanto que para dados de séries temporais trimestrais, você define a freqüência4. Você também pode especificar o primeiro ano em que os dados foram coletados e o primeiro intervalo desse ano usando o parâmetro 8216start8217 na função ts (). Por exemplo, se o primeiro ponto de dados corresponder ao segundo trimestre de 1986, você estabeleceria startc (1986,2). Um exemplo é um conjunto de dados do número de nascimentos por mês na cidade de Nova York, de janeiro de 1946 a dezembro de 1959 (originalmente coletado por Newton). Estes dados estão disponíveis no arquivo robjhyndmantsdldatadatanybirths. dat Podemos ler os dados em R e armazená-lo como um objeto de séries temporais, digitando: De forma semelhante, o arquivo robjhyndmantsdldatadatafancy. dat contém vendas mensais para uma loja de souvenirs em uma cidade balnear em Queensland, Austrália, em janeiro de 1987 a dezembro de 1993 (dados originais de Wheelwright e Hyndman, 1998). Podemos ler os dados em R digitando: Traçando séries de tempo Depois de ler uma série de tempo em R, o próximo passo geralmente é fazer um gráfico dos dados da série temporal, o que você pode fazer com a função plot. ts () Em R. Por exemplo, para traçar as séries temporais da idade da morte de 42 reis sucessivos da Inglaterra, escrevemos: podemos ver a partir do gráfico do tempo que esta série temporal provavelmente poderia ser descrita usando um modelo aditivo, uma vez que as flutuações aleatórias Nos dados são aproximadamente constantes em tamanho ao longo do tempo. Do mesmo modo, para traçar as séries temporais do número de nascimentos por mês na cidade de Nova York, escrevemos: podemos ver a partir desta série de tempos que parece haver variação sazonal no número de nascimentos por mês: há um pico a cada verão , E a cada inverno. Novamente, parece que esta série de tempo provavelmente poderia ser descrita usando um modelo aditivo, pois as flutuações sazonais são aproximadamente constantes em tamanho ao longo do tempo e não parecem depender do nível da série temporal, e as flutuações aleatórias também parecem ser Tamanho quase igual ao longo do tempo. Da mesma forma, para traçar as séries temporais das vendas mensais para a loja de lembranças em uma cidade balnear em Queensland, Austrália, nós escrevemos: neste caso, parece que um modelo aditivo não é apropriado para descrever esta série de tempo, já que o tamanho Das flutuações sazonais e flutuações aleatórias parecem aumentar com o nível das séries temporais. Assim, talvez precisemos transformar a série temporal para obter uma série de tempo transformada que pode ser descrita usando um modelo aditivo. Por exemplo, podemos transformar as séries temporais calculando o log natural dos dados originais: Aqui podemos ver que o tamanho das flutuações sazonais e as flutuações aleatórias nas séries temporais log-transformadas parecem ser aproximadamente constantes ao longo do tempo e fazem Não depende do nível das séries temporais. Assim, as séries temporais log-transformadas provavelmente podem ser descritas usando um modelo aditivo. Decomposição de séries temporais A decomposição de uma série de tempos significa separá-la em seus componentes constituintes, que geralmente são um componente de tendência e um componente irregular, e se é uma série temporária sazonal, um componente sazonal. Decomposição de dados não sazonais Uma série temporal não sazonal consiste em um componente de tendência e um componente irregular. A descomposição da série temporal envolve a tentativa de separar a série temporal desses componentes, ou seja, estimar o componente de tendência e o componente irregular. Para estimar o componente de tendência de uma série temporal não-sazonal que pode ser descrita usando um modelo aditivo, é comum usar um método de suavização, como o cálculo da média móvel simples das séries temporais. A função SMA () no pacote 8220TTR8221 R pode ser usada para suavizar os dados da série temporal usando uma média móvel simples. Para usar esta função, primeiro precisamos instalar o pacote 8220TTR8221 R (para obter instruções sobre como instalar um pacote R, consulte Como instalar um pacote R). Depois de instalar o pacote 8220TTR8221 R, você pode carregar o pacote 8220TTR8221 R digitando: Você pode usar a função 8220SMA () 8221 para suavizar os dados da série temporal. Para usar a função SMA (), você precisa especificar a ordem (span) da média móvel simples, usando o parâmetro 8220n8221. Por exemplo, para calcular uma média móvel simples da ordem 5, definimos n5 na função SMA (). Por exemplo, como discutido acima, as séries temporais da idade da morte de 42 reis sucessivos de Inglaterra são não-sazonais, e provavelmente podem ser descritas usando um modelo aditivo, uma vez que as flutuações aleatórias nos dados são aproximadamente constantes em tamanho Tempo: Assim, podemos tentar estimar o componente de tendência desta série de tempo ao suavizar usando uma média móvel simples. Para suavizar as séries temporais usando uma média móvel simples da ordem 3 e plotar os dados da série temporizada suavizadas, nós escrevemos: Ainda parece haver bastante flutuações aleatórias nas séries temporais suavizadas usando uma simples média móvel da ordem 3. Assim, para estimar o componente de tendência de forma mais precisa, podemos querer tentar suavizar os dados com uma média móvel simples de uma ordem superior. Isso leva um pouco de teste e erro, para encontrar a quantidade certa de suavização. Por exemplo, podemos tentar usar uma média móvel simples da ordem 8: os dados alisados ​​com uma média móvel simples da ordem 8 dão uma imagem mais clara do componente de tendência, e podemos ver que a idade da morte dos reis ingleses parece Diminuiu de cerca de 55 anos para cerca de 38 anos durante o reinado dos primeiros 20 reis, e depois aumentou depois disso para cerca de 73 anos no final do reinado do 40º rei na série temporal. Decomposição de dados sazonais Uma série temporária sazonal consiste em um componente de tendência, um componente sazonal e um componente irregular. Descompactar a série temporal significa separar as séries temporais nestes três componentes: isto é, estimando esses três componentes. Para estimar o componente de tendência e componente sazonal de uma série de tempo sazonal que pode ser descrita usando um modelo aditivo, podemos usar a função 8220decompose () 8221 em R. Esta função estima os componentes de tendência, sazonal e irregular de uma série de tempo que Pode ser descrito usando um modelo aditivo. A função 8220decompose () 8221 retorna um objeto de lista como resultado, onde as estimativas do componente sazonal, componente de tendência e componente irregular são armazenadas em elementos nomeados desses objetos de lista, chamados 8220seasonal8221, 8220trend8221 e 8220random8221, respectivamente. Por exemplo, como discutido acima, a série temporal do número de nascimentos por mês na cidade de Nova York é sazonal com um pico a cada verão e a cada inverno, e provavelmente pode ser descrita usando um modelo aditivo, pois as flutuações sazonais e aleatórias parecem Seja aproximadamente constante em tamanho ao longo do tempo: para estimar a tendência, os componentes sazonais e irregulares desta série temporal, nós escrevemos: Os valores estimados dos componentes sazonais, tendenciais e irregulares agora são armazenados nas variáveis ​​nascimentos timeseriescomponentessazonais, tendências de nascimentos de nascimento e condições de nascimentocomponentesrandom. Por exemplo, podemos imprimir os valores estimados do componente sazonal digitando: Os fatores sazonais estimados são dados para os meses de janeiro a dezembro e são os mesmos para cada ano. O maior fator sazonal é para julho (cerca de 1,46), e o menor é para fevereiro (cerca de -2,08), indicando que parece haver um pico nos nascimentos em julho e uma vaca nos nascimentos em fevereiro de cada ano. Podemos traçar a tendência estimada, os componentes sazonais e irregulares das séries temporais usando a função 8220plot () 8221, por exemplo: o gráfico acima mostra a série temporal original (parte superior), o componente de tendência estimado (segundo da parte superior), O componente sazonal estimado (terceiro do topo) e o componente irregular estimado (parte inferior). Observamos que o componente de tendência estimado mostra uma pequena diminuição de cerca de 24 em 1947 para cerca de 22 em 1948, seguido por um aumento constante de então para cerca de 27 em 1959. Ajuste sazonal Se você tiver uma série de tempo sazonal que pode ser descrita usando Um modelo aditivo, você pode ajustar sazonalmente as séries temporais estimando o componente sazonal e subtraindo o componente sazonal estimado das séries temporais originais. Podemos fazer isso usando a estimativa do componente sazonal calculado pela função 8220decompose () 8221. Por exemplo, para ajustar sazonalmente as séries temporais do número de nascimentos por mês na cidade de Nova York, podemos estimar o componente sazonal usando 8220decompose () 8221 e, em seguida, subtrair o componente sazonal das séries temporais originais: podemos traçar o Série de tempo ajustada sazonalmente usando a função 8220plot () 8221, digitando: você pode ver que a variação sazonal foi removida da série de tempo ajustada sazonalmente. A série de tempo ajustada sazonalmente agora contém apenas o componente de tendência e um componente irregular. Previsões usando Suavização Exponencial O alisamento exponencial pode ser usado para fazer previsões de curto prazo para dados de séries temporais. Suavização exponencial simples Se você tiver uma série de tempo que pode ser descrita usando um modelo aditivo com nível constante e sem sazonalidade, você pode usar um alisamento exponencial simples para fazer previsões de curto prazo. O método de suavização exponencial simples fornece uma maneira de estimar o nível no ponto de tempo atual. O alisamento é controlado pelo parâmetro alfa para a estimativa do nível no ponto de tempo atual. O valor de alfa situa-se entre 0 e 1. Os valores de alfa que são próximos de 0 significam que pouco peso é colocado sobre as observações mais recentes ao fazer previsões de valores futuros. Por exemplo, o arquivo robjhyndmantsdldatahurstprecip1.dat contém precipitação anual total em polegadas para Londres, de 1813 a 1912 (dados originais de Hipel e McLeod, 1994). Podemos ler os dados em R e plotá-lo digitando: Você pode ver do gráfico que há um nível aproximadamente constante (a média permanece constante em aproximadamente 25 polegadas). As flutuações aleatórias nas séries temporais parecem ser aproximadamente constantes em tamanho ao longo do tempo, portanto, provavelmente é apropriado descrever os dados usando um modelo aditivo. Assim, podemos fazer previsões usando um alisamento exponencial simples. Para fazer previsões usando alisamento exponencial simples em R, podemos ajustar um modelo preditivo de alisamento exponencial simples usando a função 8220HoltWinters () 8221 em R. Para usar HoltWinters () para suavização exponencial simples, precisamos definir os parâmetros betaFALSE e gammaFALSE no Função HoltWinters () (os parâmetros beta e gamma são usados ​​para suavização exponencial de Holt8217s, ou suavização exponencial de Holt-Winters, conforme descrito abaixo). A função HoltWinters () retorna uma variável de lista, que contém vários elementos nomeados. Por exemplo, para usar o alisamento exponencial simples para fazer previsões para as séries temporais de precipitação anual em Londres, nós escrevemos: O resultado de HoltWinters () nos diz que o valor estimado do parâmetro alfa é de aproximadamente 0,024. Isso é muito próximo de zero, dizendo-nos que as previsões são baseadas em observações recentes e menos recentes (embora um pouco mais de peso seja colocado em observações recentes). Por padrão, HoltWinters () apenas faz previsões para o mesmo período de tempo coberto por nossa série temporal original. Nesse caso, nossa série temporal original incluiu chuvas para Londres de 1813 a 1912, então as previsões também são para 1813-1912. No exemplo acima, armazenamos a saída da função HoltWinters () na lista variável 8220rainseriesforecasts8221. As previsões feitas por HoltWinters () são armazenadas em um elemento nomeado dessa lista, variável chamada 8220fitted8221, para que possamos obter seus valores digitando: Podemos traçar as séries temporais originais contra as previsões digitando: A trama mostra a série temporal original em Preto, e as previsões como uma linha vermelha. A série temporal de previsões é muito mais lisa do que a série temporal dos dados originais aqui. Como medida da precisão das previsões, podemos calcular a soma de erros quadrados para os erros de previsão na amostra, ou seja, os erros de previsão para o período de tempo coberto por nossa série temporal original. O sum-of-squared-errors é armazenado em um elemento nomeado da lista variável 8220rainseriesforecasts8221 chamado 8220SSE8221, para que possamos obter seu valor digitando: isto é, aqui o sum-of-squared-errors é 1828.855. É comum em suavização exponencial simples usar o primeiro valor na série temporal como o valor inicial para o nível. Por exemplo, na série temporal de chuva em Londres, o primeiro valor é 23,56 (polegadas) para precipitação em 1813. Você pode especificar o valor inicial para o nível na função HoltWinters () usando o parâmetro 8220l. start8221. Por exemplo, para fazer previsões com o valor inicial do nível definido para 23.56, escrevemos: conforme explicado acima, por padrão HoltWinters () apenas faz previsões para o período de tempo coberto pelos dados originais, que é 1813-1912 para a precipitação Séries temporais. Podemos fazer previsões para mais pontos de tempo usando a função 8220forecast. HoltWinters () 8221 no pacote R 8220forecast8221. Para usar a função forecast. HoltWinters (), primeiro precisamos instalar o pacote 8220forecast8221 R (para obter instruções sobre como instalar um pacote R, consulte Como instalar um pacote R). Depois de instalar o pacote 8220forecast8221 R, você pode carregar o pacote 8220forecast8221 R digitando: Ao usar a função forecast. HoltWinters (), como seu primeiro argumento (entrada), você passa o modelo preditivo que você já instalou usando o Função HoltWinters (). Por exemplo, no caso da série temporal de precipitação, armazenamos o modelo preditivo feito usando HoltWinters () na variável 8220rainseriesforecasts8221. Você especifica quantos pontos de tempo você deseja fazer previsões ao usar o parâmetro 8220h8221 em forecast. HoltWinters (). Por exemplo, para fazer uma previsão de precipitação para os anos 1814-1820 (mais 8 anos) usando forecast. HoltWinters (), escrevemos: A função forecast. HoltWinters () fornece a previsão de um ano, um intervalo de 80 predições para A previsão e um intervalo de previsão de 95 para a previsão. Por exemplo, a precipitação prevista para 1920 é de cerca de 24,68 polegadas, com um intervalo de 95 predições de (16,24, 33,11). Para traçar as previsões feitas por forecast. HoltWinters (), podemos usar a função 8220plot. forecast () 8221: Aqui as previsões para 1913-1920 são traçadas como uma linha azul, o intervalo de 80 predições como área sombreada de laranja e 95, intervalo de predição como área sombreada amarela. Os 8216forecast errors8217 são calculados como os valores observados menos os valores previstos, para cada ponto do tempo. Só podemos calcular os erros de previsão para o período de tempo coberto por nossa série temporal original, que é 1813-1912 para os dados de precipitação. Como mencionado acima, uma medida da precisão do modelo preditivo é a soma de erros quadrados (SSE) para os erros de previsão na amostra. Os erros de previsão na amostra são armazenados no elemento nomeado 8220residuals8221 da variável de lista retornada por forecast. HoltWinters (). Se o modelo preditivo não puder ser melhorado, não deve haver correlações entre erros de previsão para previsões sucessivas. Em outras palavras, se houver correlações entre erros de previsão para previsões sucessivas, é provável que as previsões simples de suavização exponencial possam ser melhoradas por outra técnica de previsão. Para descobrir se este é o caso, podemos obter um correlograma dos erros de previsão na amostra para os atrasos 1-20. Podemos calcular um correlograma dos erros de previsão usando a função 8220acf () 8221 em R. Para especificar o atraso máximo que queremos observar, usamos o parâmetro 8220lag. max8221 em acf (). Por exemplo, para calcular um correlograma dos erros de previsão na amostra para os dados de precipitação de Londres por atrasos 1-20, nós escrevemos: você pode ver a partir do correlograma de amostra que a autocorrelação no lag 3 está apenas tocando os limites de significância. Para testar se há evidências significativas para correlações não-zero nos intervalos 1-20, podemos realizar um teste de Ljung-Box. Isso pode ser feito em R usando a função 8220Box. test () 8221. O atraso máximo que queremos observar é especificado usando o parâmetro 8220lag8221 na função Box. test (). Por exemplo, para testar se há autocorrelações não-zero nos intervalos 1-20, para os erros de previsão na amostra para dados de precipitação de Londres, nós escrevemos: Aqui, a estatística de teste de Ljung-Box é 17,4 e o valor de p é 0,6 , Portanto, há poucas evidências de autocorrelações não-zero nos erros de previsão na amostra aos intervalos 1-20. Para ter certeza de que o modelo preditivo não pode ser melhorado, também é uma boa idéia verificar se os erros de previsão são normalmente distribuídos com variância média zero e constante. Para verificar se os erros de previsão têm variação constante, podemos fazer um gráfico de tempo dos erros de previsão na amostra: o gráfico mostra que os erros de previsão na amostra parecem ter variância aproximadamente constante ao longo do tempo, embora o tamanho das flutuações em O início das séries temporais (1820-1830) pode ser um pouco menor do que em datas posteriores (por exemplo, 1840-1850). Para verificar se os erros de previsão são normalmente distribuídos com zero médio, podemos plotar um histograma dos erros de previsão, com uma curva normal superpurada que tem zero médio e o mesmo desvio padrão que a distribuição dos erros de previsão. Para fazer isso, podemos definir uma função R 8220plotForecastErrors () 8221, abaixo: você terá que copiar a função acima em R para usá-la. Você pode usar plotForecastErrors () para traçar um histograma (com curva normal sobreposta) dos erros de previsão para as previsões de precipitação: o gráfico mostra que a distribuição dos erros de previsão é aproximadamente centrada em zero e é distribuída mais ou menos normalmente, embora Parece ser um pouco distorcido para a direita em comparação com uma curva normal. No entanto, a inclinação certa é relativamente pequena e, portanto, é plausível que os erros de previsão sejam normalmente distribuídos com zero médio. O teste de Ljung-Box mostrou que há poucas evidências de autocorrelações não-zero nos erros de previsão na amostra, e a distribuição dos erros de previsão parece estar normalmente distribuída com zero médio. Isso sugere que o método de suavização exponencial simples fornece um modelo preditivo adequado para a precipitação londrina, que provavelmente não pode ser melhorado. Além disso, os pressupostos sobre os quais os intervalos de previsão de 80 e 95 foram baseados (que não existem autocorrelações nos erros de previsão, e os erros de previsão normalmente são distribuídos com zero médio e variância constante) provavelmente são válidos. Holt8217s Suavização exponencial Se você tem uma série de tempo que pode ser descrita usando um modelo aditivo com tendência crescente ou decrescente e sem sazonalidade, você pode usar o suavização exponencial Holt8217s para fazer previsões a curto prazo. O suavização exponencial de Holt8217s estima o nível e a inclinação no ponto de tempo atual. O alisamento é controlado por dois parâmetros, alfa, para a estimativa do nível no ponto de tempo atual e beta para a estimativa da inclinação b do componente de tendência no ponto de tempo atual. Tal como acontece com o alisamento exponencial simples, os parâmetros alfa e beta têm valores entre 0 e 1 e valores que são próximos de 0 significam que pouco peso é colocado nas observações mais recentes ao fazer previsões de valores futuros. Um exemplo de uma série de tempo que provavelmente pode ser descrito usando um modelo aditivo com uma tendência e nenhuma sazonalidade é a série temporal do diâmetro anual das saias da mulher 8217 na bainha, de 1866 a 1911. Os dados estão disponíveis no arquivo robjhyndmantsdldatarobertsskirts. Dat (dados originais de Hipel e McLeod, 1994). Podemos ler e plotar os dados em R digitando: podemos ver do enredo que houve um aumento no diâmetro de bainha de cerca de 600 em 1866 para cerca de 1050 em 1880 e que depois o diâmetro da bainha diminuiu para cerca de 520 em 1911 Para fazer previsões, podemos ajustar um modelo preditivo usando a função HoltWinters () em R. Para usar HoltWinters () para suavização exponencial de Holt8217s, precisamos definir o parâmetro gammaFALSE (o parâmetro gamma é usado para suavização exponencial Holt-Winters, como descrito abaixo). Por exemplo, para usar o suavização exponencial de Holt8217s para caber um modelo preditivo para o diâmetro da bainha da saia, nós escrevemos: O valor estimado de alfa é 0.84 e de beta é 1.00. Estes são ambos altos, dizendo-nos que tanto a estimativa do valor atual do nível, quanto a inclinação b do componente de tendência, baseiam-se principalmente em observações muito recentes na série temporal. Isso faz um bom senso intuitivo, já que o nível e a inclinação das séries temporais mudam muito ao longo do tempo. O valor dos erros de soma de quadrado para os erros de previsão na amostra é 16954. Podemos traçar a série temporal original como uma linha preta, com os valores previstos como uma linha vermelha em cima disso, digitando: Nós Pode ver da imagem que as previsões na amostra concordam muito bem com os valores observados, embora eles tendam a atrasar um pouco os valores observados. Se desejar, você pode especificar os valores iniciais do nível e a inclinação b do componente de tendência usando os argumentos 8220l. start8221 e 8220b. start8221 para a função HoltWinters (). É comum definir o valor inicial do nível para o primeiro valor na série temporal (608 para os dados das saias) e o valor inicial da inclinação para o segundo valor menos o primeiro valor (9 para os dados das saias). Por exemplo, para caber um modelo preditivo aos dados da bainha da saia usando o suavização exponencial de Holt8217s, com valores iniciais de 608 para o nível e 9 para a inclinação b do componente de tendência, nós escrevemos: quanto ao alisamento exponencial simples, podemos fazer previsões Para tempos futuros não cobertos pela série temporal original usando a função forecast. HoltWinters () no pacote 8220forecast8221. Por exemplo, nossos dados da série de tempo para os calçados da saia foram de 1866 a 1911, para que possamos fazer previsões para 1912 a 1930 (19 pontos de dados mais) e plotá-los, digitando: as previsões são mostradas como uma linha azul, com a 80 intervalos de previsão como uma área sombreada laranja e os 95 intervalos de previsão como uma área sombreada amarela. Quanto ao alisamento exponencial simples, podemos verificar se o modelo preditivo pode ser melhorado verificando se os erros de previsão na amostra mostram autocorrelações não-zero nos intervalos 1-20. Por exemplo, para os dados de bainha da saia, podemos fazer um correlograma e realizar o teste Ljung-Box, digitando: Aqui, o correlograma mostra que a autocorrelação da amostra para os erros de previsão na amostra no intervalo 5 excede os limites de significância. No entanto, esperamos que uma em cada 20 das autocorrelações para os primeiros vinte atrasos exceda os 95 limites de significados por acaso sozinhos. De fato, quando realizamos o teste Ljung-Box, o valor p é 0,47, indicando que há poucas evidências de autocorrelações não-zero nos erros de previsão na amostra aos intervalos 1-20. Quanto ao alisamento exponencial simples, também devemos verificar se os erros de previsão têm variação constante ao longo do tempo e normalmente são distribuídos com zero médio. Podemos fazer isso fazendo um gráfico temporal de erros de previsão e um histograma da distribuição de erros de previsão com uma curva normal superpuesta: o gráfico de tempo de erros de previsão mostra que os erros de previsão têm variância aproximadamente constante ao longo do tempo. O histograma de erros de previsão mostra que é plausível que os erros de previsão sejam normalmente distribuídos com variável zero e variável constante. Assim, o teste de Ljung-Box mostra que há pouca evidência de autocorrelações nos erros de previsão, enquanto o gráfico de tempo e histograma de erros de previsão mostram que é plausível que os erros de previsão sejam normalmente distribuídos com zero médio e variância constante. Portanto, podemos concluir que o suavização exponencial de Holt8217 fornece um modelo preditivo adequado para os diâmetros da bainha da saia, o que provavelmente não pode ser melhorado. Além disso, isso significa que os pressupostos sobre os quais os intervalos de previsão de 80 e 95 foram baseados são provavelmente válidos. Suavização exponencial Holt-Winters Se você possui uma série de tempo que pode ser descrita usando um modelo aditivo com tendência crescente ou decrescente e sazonalidade, você pode usar o suavização exponencial de Holt-Winters para fazer previsões de curto prazo. O suavização exponencial de Holt-Winters estima o nível, inclinação e componente sazonal no ponto de tempo atual. O alisamento é controlado por três parâmetros: alfa, beta e gama, para as estimativas do nível, a inclinação b do componente de tendência eo componente sazonal, respectivamente, no ponto de tempo atual. Os parâmetros alfa, beta e gama têm valores entre 0 e 1, e valores que são próximos de 0 significam que um peso relativamente pequeno é colocado nas observações mais recentes ao fazer previsões de valores futuros. Um exemplo de uma série de tempo que provavelmente pode ser descrito usando um modelo aditivo com tendência e sazonalidade é a série temporal do registro de vendas mensais para a loja de lembranças em uma cidade balnear de Queensland, Austrália (discutida acima): fazer Previsões, podemos ajustar um modelo preditivo usando a função HoltWinters (). Por exemplo, para caber um modelo preditivo para o log das vendas mensais na loja de lembranças, nós escrevemos: Os valores estimados de alfa, beta e gama são 0,41, 0,00 e 0,96, respectivamente. O valor de alfa (0,41) é relativamente baixo, indicando que a estimativa do nível no ponto do tempo atual é baseada em observações recentes e algumas observações no passado mais distante. O valor de beta é 0,00, o que indica que a estimativa da inclinação b do componente de tendência não é atualizada ao longo da série temporal e, em vez disso, é definida como igual ao seu valor inicial. Isso faz um bom senso intuitivo, já que o nível muda um pouco sobre as séries temporais, mas a inclinação b do componente de tendência permanece aproximadamente igual. Em contraste, o valor da gama (0,96) é alto, indicando que a estimativa do componente sazonal no momento atual é apenas baseada em observações muito recentes. Quanto ao suavização exponencial simples e ao suavização exponencial de Holt8217, podemos traçar a série temporal original como uma linha preta, com os valores previstos como uma linha vermelha em cima disso: vemos do gráfico que o método exponencial de Holt-Winters é muito bem-sucedido Na previsão dos picos sazonais, que ocorrem aproximadamente em novembro de cada ano. Para fazer previsões para tempos futuros não incluídos na série temporal original, usamos a função 8220forecast. HoltWinters () 8221 no pacote 8220forecast8221. Por exemplo, os dados originais para as vendas de lembranças são de janeiro de 1987 a dezembro de 1993. Se quisermos fazer previsões para janeiro de 1994 a dezembro de 1998 (mais 48 meses) e plotar as previsões, digitaremos: as previsões são mostradas como Uma linha azul e as áreas sombreadas laranja e amarela mostram 80 e 95 intervalos de predição, respectivamente. Podemos investigar se o modelo preditivo pode ser melhorado verificando se os erros de previsão na amostra mostram autocorrelações não-zero nos intervalos 1-20, fazendo um correlograma e realizando o teste de Ljung-Box: o correlograma mostra que as autocorrelações Para os erros de previsão na amostra não exceder os limites de significância para os atrasos 1-20. Além disso, o valor p para teste Ljung-Box é 0.6, indicando que há pouca evidência de autocorrelações não-zero nos intervalos 1-20. Podemos verificar se os erros de previsão têm variação constante ao longo do tempo, e normalmente são distribuídos com zero médio, fazendo um gráfico de tempo dos erros de previsão e um histograma (com curva normal superpurada): do gráfico de tempo, parece plausível que o Os erros de previsão têm variação constante ao longo do tempo. A partir do histograma de erros de previsão, parece plausível que os erros de previsão sejam normalmente distribuídos com zero médio. Assim, há pouca evidência de autocorrelação nos atrasos 1-20 para os erros de previsão, e os erros de previsão aparecem normalmente distribuídos com zero médio e variação constante ao longo do tempo. Isso sugere que o suavização exponencial de Holt-Winters fornece um modelo preditivo adequado do registro de vendas na loja de lembranças, que provavelmente não pode ser melhorado. Furthermore, the assumptions upon which the prediction intervals were based are probably valid. ARIMA Models Exponential smoothing methods are useful for making forecasts, and make no assumptions about the correlations between successive values of the time series. However, if you want to make prediction intervals for forecasts made using exponential smoothing methods, the prediction intervals require that the forecast errors are uncorrelated and are normally distributed with mean zero and constant variance. While exponential smoothing methods do not make any assumptions about correlations between successive values of the time series, in some cases you can make a better predictive model by taking correlations in the data into account. Autoregressive Integrated Moving Average (ARIMA) models include an explicit statistical model for the irregular component of a time series, that allows for non-zero autocorrelations in the irregular component. Differencing a Time Series ARIMA models are defined for stationary time series. Therefore, if you start off with a non-stationary time series, you will first need to 8216difference8217 the time series until you obtain a stationary time series. If you have to difference the time series d times to obtain a stationary series, then you have an ARIMA(p, d,q) model, where d is the order of differencing used. You can difference a time series using the 8220diff()8221 function in R. For example, the time series of the annual diameter of women8217s skirts at the hem, from 1866 to 1911 is not stationary in mean, as the level changes a lot over time: We can difference the time series (which we stored in 8220skirtsseries8221, see above) once, and plot the differenced series, by typing: The resulting time series of first differences (above) does not appear to be stationary in mean. Therefore, we can difference the time series twice, to see if that gives us a stationary time series: Formal tests for stationarity Formal tests for stationarity called 8220unit root tests8221 are available in the fUnitRoots package, available on CRAN, but will not be discussed here. The time series of second differences (above) does appear to be stationary in mean and variance, as the level of the series stays roughly constant over time, and the variance of the series appears roughly constant over time. Thus, it appears that we need to difference the time series of the diameter of skirts twice in order to achieve a stationary series. If you need to difference your original time series data d times in order to obtain a stationary time series, this means that you can use an ARIMA(p, d,q) model for your time series, where d is the order of differencing used. For example, for the time series of the diameter of women8217s skirts, we had to difference the time series twice, and so the order of differencing (d) is 2. This means that you can use an ARIMA(p,2,q) model for your time series. The next step is to figure out the values of p and q for the ARIMA model. Another example is the time series of the age of death of the successive kings of England (see above): From the time plot (above), we can see that the time series is not stationary in mean. To calculate the time series of first differences, and plot it, we type: The time series of first differences appears to be stationary in mean and variance, and so an ARIMA(p,1,q) model is probably appropriate for the time series of the age of death of the kings of England. By taking the time series of first differences, we have removed the trend component of the time series of the ages at death of the kings, and are left with an irregular component. We can now examine whether there are correlations between successive terms of this irregular component if so, this could help us to make a predictive model for the ages at death of the kings. Selecting a Candidate ARIMA Model If your time series is stationary, or if you have transformed it to a stationary time series by differencing d times, the next step is to select the appropriate ARIMA model, which means finding the values of most appropriate values of p and q for an ARIMA(p, d,q) model. To do this, you usually need to examine the correlogram and partial correlogram of the stationary time series. To plot a correlogram and partial correlogram, we can use the 8220acf()8221 and 8220pacf()8221 functions in R, respectively. To get the actual values of the autocorrelations and partial autocorrelations, we set 8220plotFALSE8221 in the 8220acf()8221 and 8220pacf()8221 functions. Example of the Ages at Death of the Kings of England For example, to plot the correlogram for lags 1-20 of the once differenced time series of the ages at death of the kings of England, and to get the values of the autocorrelations, we type: We see from the correlogram that the autocorrelation at lag 1 (-0.360) exceeds the significance bounds, but all other autocorrelations between lags 1-20 do not exceed the significance bounds. To plot the partial correlogram for lags 1-20 for the once differenced time series of the ages at death of the English kings, and get the values of the partial autocorrelations, we use the 8220pacf()8221 function, by typing: The partial correlogram shows that the partial autocorrelations at lags 1, 2 and 3 exceed the significance bounds, are negative, and are slowly decreasing in magnitude with increasing lag (lag 1: -0.360, lag 2: -0.335, lag 3:-0.321). The partial autocorrelations tail off to zero after lag 3. Since the correlogram is zero after lag 1, and the partial correlogram tails off to zero after lag 3, this means that the following ARMA (autoregressive moving average) models are possible for the time series of first differences: an ARMA(3,0) model, that is, an autoregressive model of order p3, since the partial autocorrelogram is zero after lag 3, and the autocorrelogram tails off to zero (although perhaps too abruptly for this model to be appropriate) an ARMA(0,1) model, that is, a moving average model of order q1, since the autocorrelogram is zero after lag 1 and the partial autocorrelogram tails off to zero an ARMA(p, q) model, that is, a mixed model with p and q greater than 0, since the autocorrelogram and partial correlogram tail off to zero (although the correlogram probably tails off to zero too abruptly for this model to be appropriate) We use the principle of parsimony to decide which model is best: that is, we assum e that the model with the fewest parameters is best. The ARMA(3,0) model has 3 parameters, the ARMA(0,1) model has 1 parameter, and the ARMA(p, q) model has at least 2 parameters. Therefore, the ARMA(0,1) model is taken as the best model. An ARMA(0,1) model is a moving average model of order 1, or MA(1) model. This model can be written as: Xt - mu Zt - (theta Zt-1), where Xt is the stationary time series we are studying (the first differenced series of ages at death of English kings), mu is the mean of time series Xt, Zt is white noise with mean zero and constant variance, and theta is a parameter that can be estimated. A MA (moving average) model is usually used to model a time series that shows short-term dependencies between successive observations. Intuitively, it makes good sense that a MA model can be used to describe the irregular component in the time series of ages at death of English kings, as we might expect the age at death of a particular English king to have some effect on the ages at death of the next king or two, but not much effect on the ages at death of kings that reign much longer after that. Shortcut: the auto. arima() function The auto. arima() function can be used to find the appropriate ARIMA model, eg. type 8220library(forecast)8221, then 8220auto. arima(kings)8221. The output says an appropriate model is ARIMA(0,1,1). Since an ARMA(0,1) model (with p0, q1) is taken to be the best candidate model for the time series of first differences of the ages at death of English kings, then the original time series of the ages of death can be modelled using an ARIMA(0,1,1) model (with p0, d1, q1, where d is the order of differencing required). Example of the Volcanic Dust Veil in the Northern Hemisphere Let8217s take another example of selecting an appropriate ARIMA model. The file file robjhyndmantsdldataannualdvi. dat contains data on the volcanic dust veil index in the northern hemisphere, from 1500-1969 (original data from Hipel and Mcleod, 1994). This is a measure of the impact of volcanic eruptions8217 release of dust and aerosols into the environment. We can read it into R and make a time plot by typing: From the time plot, it appears that the random fluctuations in the time series are roughly constant in size over time, so an additive model is probably appropriate for describing this time series. Furthermore, the time series appears to be stationary in mean and variance, as its level and variance appear to be roughly constant over time. Therefore, we do not need to difference this series in order to fit an ARIMA model, but can fit an ARIMA model to the original series (the order of differencing required, d, is zero here). We can now plot a correlogram and partial correlogram for lags 1-20 to investigate what ARIMA model to use: We see from the correlogram that the autocorrelations for lags 1, 2 and 3 exceed the significance bounds, and that the autocorrelations tail off to zero after lag 3. The autocorrelations for lags 1, 2, 3 are positive, and decrease in magnitude with increasing lag (lag 1: 0.666, lag 2: 0.374, lag 3: 0.162). The autocorrelation for lags 19 and 20 exceed the significance bounds too, but it is likely that this is due to chance, since they just exceed the significance bounds (especially for lag 19), the autocorrelations for lags 4-18 do not exceed the signifiance bounds, and we would expect 1 in 20 lags to exceed the 95 significance bounds by chance alone. From the partial autocorrelogram, we see that the partial autocorrelation at lag 1 is positive and exceeds the significance bounds (0.666), while the partial autocorrelation at lag 2 is negative and also exceeds the significance bounds (-0.126). The partial autocorrelations tail off to zero after lag 2. Since the correlogram tails off to zero after lag 3, and the partial correlogram is zero after lag 2, the following ARMA models are possible for the time series: an ARMA(2,0) model, since the partial autocorrelogram is zero after lag 2, and the correlogram tails off to zero after lag 3, and the partial correlogram is zero after lag 2 an ARMA(0,3) model, since the autocorrelogram is zero after lag 3, and the partial correlogram tails off to zero (although perhaps too abruptly for this model to be appropriate) an ARMA(p, q) mixed model, since the correlogram and partial correlogram tail off to zero (although the partial correlogram perhaps tails off too abruptly for this model to be appropriate) Shortcut: the auto. arima() function Again, we can use auto. arima() to find an appropriate model, by typing 8220auto. arima(volcanodust)8221, which gives us ARIMA(1,0,2), which has 3 parameters. However, different criteria can be used to select a model (see auto. arima() help page). If we use the 8220bic8221 criterion, which penalises the number of parameters, we get ARIMA(2,0,0), which is ARMA(2,0): 8220auto. arima(volcanodust, ic8221bic8221)8221. The ARMA(2,0) model has 2 parameters, the ARMA(0,3) model has 3 parameters, and the ARMA(p, q) model has at least 2 parameters. Therefore, using the principle of parsimony, the ARMA(2,0) model and ARMA(p, q) model are equally good candidate models. An ARMA(2,0) model is an autoregressive model of order 2, or AR(2) model. This model can be written as: Xt - mu (Beta1 (Xt-1 - mu)) (Beta2 (Xt-2 - mu)) Zt, where Xt is the stationary time series we are studying (the time series of volcanic dust veil index), mu is the mean of time series Xt, Beta1 and Beta2 are parameters to be estimated, and Zt is white noise with mean zero and constant variance. An AR (autoregressive) model is usually used to model a time series which shows longer term dependencies between successive observations. Intuitively, it makes sense that an AR model could be used to describe the time series of volcanic dust veil index, as we would expect volcanic dust and aerosol levels in one year to affect those in much later years, since the dust and aerosols are unlikely to disappear quickly. If an ARMA(2,0) model (with p2, q0) is used to model the time series of volcanic dust veil index, it would mean that an ARIMA(2,0,0) model can be used (with p2, d0, q0, where d is the order of differencing required). Similarly, if an ARMA(p, q) mixed model is used, where p and q are both greater than zero, than an ARIMA(p,0,q) model can be used. Forecasting Using an ARIMA Model Once you have selected the best candidate ARIMA(p, d,q) model for your time series data, you can estimate the parameters of that ARIMA model, and use that as a predictive model for making forecasts for future values of your time series. You can estimate the parameters of an ARIMA(p, d,q) model using the 8220arima()8221 function in R. Example of the Ages at Death of the Kings of England For example, we discussed above that an ARIMA(0,1,1) model seems a plausible model for the ages at deaths of the kings of England. You can specify the values of p, d and q in the ARIMA model by using the 8220order8221 argument of the 8220arima()8221 function in R. To fit an ARIMA(p, d,q) model to this time series (which we stored in the variable 8220kingstimeseries8221, see above), we type: As mentioned above, if we are fitting an ARIMA(0,1,1) model to our time series, it means we are fitting an an ARMA(0,1) model to the time series of first differences. An ARMA(0,1) model can be written Xt - mu Zt - (theta Zt-1), where theta is a parameter to be estimated. From the output of the 8220arima()8221 R function (above), the estimated value of theta (given as 8216ma18217 in the R output) is -0.7218 in the case of the ARIMA(0,1,1) model fitted to the time series of ages at death of kings. Specifying the confidence level for prediction intervals You can specify the confidence level for prediction intervals in forecast. Arima() by using the 8220level8221 argument. For example, to get a 99.5 prediction interval, we would type 8220forecast. Arima(kingstimeseriesarima, h5, levelc(99.5))8221. We can then use the ARIMA model to make forecasts for future values of the time series, using the 8220forecast. Arima()8221 function in the 8220forecast8221 R package. For example, to forecast the ages at death of the next five English kings, we type: The original time series for the English kings includes the ages at death of 42 English kings. The forecast. Arima() function gives us a forecast of the age of death of the next five English kings (kings 43-47), as well as 80 and 95 prediction intervals for those predictions. The age of death of the 42nd English king was 56 years (the last observed value in our time series), and the ARIMA model gives the forecasted age at death of the next five kings as 67.8 years. We can plot the observed ages of death for the first 42 kings, as well as the ages that would be predicted for these 42 kings and for the next 5 kings using our ARIMA(0,1,1) model, by typing: As in the case of exponential smoothing models, it is a good idea to investigate whether the forecast errors of an ARIMA model are normally distributed with mean zero and constant variance, and whether the are correlations between successive forecast errors. For example, we can make a correlogram of the forecast errors for our ARIMA(0,1,1) model for the ages at death of kings, and perform the Ljung-Box test for lags 1-20, by typing: Since the correlogram shows that none of the sample autocorrelations for lags 1-20 exceed the significance bounds, and the p-value for the Ljung-Box test is 0.9, we can conclude that there is very little evidence for non-zero autocorrelations in the forecast errors at lags 1-20. To investigate whether the forecast errors are normally distributed with mean zero and constant variance, we can make a time plot and histogram (with overlaid normal curve) of the forecast errors: The time plot of the in-sample forecast errors shows that the variance of the forecast errors seems to be roughly constant over time (though perhaps there is slightly higher variance for the second half of the time series). The histogram of the time series shows that the forecast errors are roughly normally distributed and the mean seems to be close to zero. Therefore, it is plausible that the forecast errors are normally distributed with mean zero and constant variance. Since successive forecast errors do not seem to be correlated, and the forecast errors seem to be normally distributed with mean zero and constant variance, the ARIMA(0,1,1) does seem to provide an adequate predictive model for the ages at death of English kings. Example of the Volcanic Dust Veil in the Northern Hemisphere We discussed above that an appropriate ARIMA model for the time series of volcanic dust veil index may be an ARIMA(2,0,0) model. To fit an ARIMA(2,0,0) model to this time series, we can type: As mentioned above, an ARIMA(2,0,0) model can be written as: written as: Xt - mu (Beta1 (Xt-1 - mu)) (Beta2 (Xt-2 - mu)) Zt, where Beta1 and Beta2 are parameters to be estimated. The output of the arima() function tells us that Beta1 and Beta2 are estimated as 0.7533 and -0.1268 here (given as ar1 and ar2 in the output of arima()). Now we have fitted the ARIMA(2,0,0) model, we can use the 8220forecast. ARIMA()8221 model to predict future values of the volcanic dust veil index. The original data includes the years 1500-1969. To make predictions for the years 1970-2000 (31 more years), we type: We can plot the original time series, and the forecasted values, by typing: One worrying thing is that the model has predicted negative values for the volcanic dust veil index, but this variable can only have positive values The reason is that the arima() and forecast. Arima() functions don8217t know that the variable can only take positive values. Clearly, this is not a very desirable feature of our current predictive model. Again, we should investigate whether the forecast errors seem to be correlated, and whether they are normally distributed with mean zero and constant variance. To check for correlations between successive forecast errors, we can make a correlogram and use the Ljung-Box test: The correlogram shows that the sample autocorrelation at lag 20 exceeds the significance bounds. However, this is probably due to chance, since we would expect one out of 20 sample autocorrelations to exceed the 95 significance bounds. Furthermore, the p-value for the Ljung-Box test is 0.2, indicating that there is little evidence for non-zero autocorrelations in the forecast errors for lags 1-20. To check whether the forecast errors are normally distributed with mean zero and constant variance, we make a time plot of the forecast errors, and a histogram: The time plot of forecast errors shows that the forecast errors seem to have roughly constant variance over time. However, the time series of forecast errors seems to have a negative mean, rather than a zero mean. We can confirm this by calculating the mean forecast error, which turns out to be about -0.22: The histogram of forecast errors (above) shows that although the mean value of the forecast errors is negative, the distribution of forecast errors is skewed to the right compared to a normal curve. Therefore, it seems that we cannot comfortably conclude that the forecast errors are normally distributed with mean zero and constant variance Thus, it is likely that our ARIMA(2,0,0) model for the time series of volcanic dust veil index is not the best model that we could make, and could almost definitely be improved upon Links and Further Reading Here are some links for further reading. For a more in-depth introduction to R, a good online tutorial is available on the 8220Kickstarting R8221 website, cran. r-project. orgdoccontribLemon-kickstart . There is another nice (slightly more in-depth) tutorial to R available on the 8220Introduction to R8221 website, cran. r-project. orgdocmanualsR-intro. html . You can find a list of R packages for analysing time series data on the CRAN Time Series Task View webpage . To learn about time series analysis, I would highly recommend the book 8220Time series8221 (product code M24902) by the Open University, available from the Open University Shop . There are two books available in the 8220Use R8221 series on using R for time series analyses, the first is Introductory Time Series with R by Cowpertwait and Metcalfe, and the second is Analysis of Integrated and Cointegrated Time Series with R by Pfaff. Acknowledgements I am grateful to Professor Rob Hyndman. for kindly allowing me to use the time series data sets from his Time Series Data Library (TSDL) in the examples in this booklet. Many of the examples in this booklet are inspired by examples in the excellent Open University book, 8220Time series8221 (product code M24902), available from the Open University Shop . Thank you to Ravi Aranke for bringing auto. arima() to my attention, and Maurice Omane-Adjepong for bringing unit root tests to my attention, and Christian Seubert for noticing a small bug in plotForecastErrors(). Thank you for other comments to Antoine Binard and Bill Johnston. I will be grateful if you will send me (Avril Coghlan) corrections or suggestions for improvements to my email address alc 64 sanger 46 ac 46 ukAutoregressive Moving Average ARMA(p, q) Models for Time Series Analysis - Part 1 In the last article we looked at random walks and white noise as basic time series models for certain financial instruments, such as daily equity and equity index prices. We found that in some cases a random walk model was insufficient to capture the full autocorrelation behaviour of the instrument, which motivates more sophisticated models. In the next couple of articles we are going to discuss three types of model, namely the Autoregressive (AR) model of order p, the Moving Average (MA) model of order q and the mixed Autogressive Moving Average (ARMA) model of order p, q. These models will help us attempt to capture or explain more of the serial correlation present within an instrument. Ultimately they will provide us with a means of forecasting the future prices. However, it is well known that financial time series possess a property known as volatility clustering . That is, the volatility of the instrument is not constant in time. The technical term for this behaviour is known as conditional heteroskedasticity . Since the AR, MA and ARMA models are not conditionally heteroskedastic, that is, they dont take into account volatility clustering, we will ultimately need a more sophisticated model for our predictions. Such models include the Autogressive Conditional Heteroskedastic (ARCH) model and Generalised Autogressive Conditional Heteroskedastic (GARCH) model, and the many variants thereof. GARCH is particularly well known in quant finance and is primarily used for financial time series simulations as a means of estimating risk. However, as with all QuantStart articles, I want to build up to these models from simpler versions so that we can see how each new variant changes our predictive ability. Despite the fact that AR, MA and ARMA are relatively simple time series models, they are the basis of more complicated models such as the Autoregressive Integrated Moving Average (ARIMA) and the GARCH family. Hence it is important that we study them. One of our first trading strategies in the time series article series will be to combine ARIMA and GARCH in order to predict prices n periods in advance. However, we will have to wait until weve discussed both ARIMA and GARCH separately before we apply them to a real strategy How Will We Proceed In this article we are going to outline some new time series concepts that well need for the remaining methods, namely strict stationarity and the Akaike information criterion (AIC) . Subsequent to these new concepts we will follow the traditional pattern for studying new time series models: Rationale - The first task is to provide a reason why were interested in a particular model, as quants. Why are we introducing the time series model What effects can it capture What do we gain (or lose) by adding in extra complexity Definition - We need to provide the full mathematical definition (and associated notation) of the time series model in order to minimise any ambiguity. Second Order Properties - We will discuss (and in some cases derive) the second order properties of the time series model, which includes its mean, its variance and its autocorrelation function. Correlogram - We will use the second order properties to plot a correlogram of a realisation of the time series model in order to visualise its behaviour. Simulation - We will simulate realisations of the time series model and then fit the model to these simulations to ensure we have accurate implementations and understand the fitting process. Real Financial Data - We will fit the time series model to real financial data and consider the correlogram of the residuals in order to see how the model accounts for serial correlation in the original series. Prediction - We will create n-step ahead forecasts of the time series model for particular realisations in order to ultimately produce trading signals. Nearly all of the articles I write on time series models will fall into this pattern and it will allow us to easily compare the differences between each model as we add further complexity. Were going to start by looking at strict stationarity and the AIC. Strictly Stationary We provided the definition of stationarity in the article on serial correlation. However, because we are going to be entering the realm of many financial series, with various frequencies, we need to make sure that our (eventual) models take into account the time-varying volatility of these series. In particular, we need to consider their heteroskedasticity . We will come across this issue when we try to fit certain models to historical series. Generally, not all of the serial correlation in the residuals of fitted models can be accounted for without taking heteroskedasticity into account. This brings us back to stationarity. A series is not stationary in the variance if it has time-varying volatility, by definition. This motivates a more rigourous definition of stationarity, namely strict stationarity : Strictly Stationary Series A time series model, , is strictly stationary if the joint statistical distribution of the elements x, ldots, x is the same as that of x m, ldots, x m, forall ti, m. One can think of this definition as simply that the distribution of the time series is unchanged for any abritrary shift in time. In particular, the mean and the variance are constant in time for a strictly stationary series and the autocovariance between xt and xs (say) depends only on the absolute difference of t and s, t-s. We will be revisiting strictly stationary series in future posts. Akaike Information Criterion I mentioned in previous articles that we would eventually need to consider how to choose between separate best models. This is true not only of time series analysis, but also of machine learning and, more broadly, statistics in general. The two main methods we will use (for the time being) are the Akaike Information Criterion (AIC) and the Bayesian Information Criterion (as we progress further with our articles on Bayesian Statistics ). Well briefly consider the AIC, as it will be used in Part 2 of the ARMA article. AIC is essentially a tool to aid in model selection. That is, if we have a selection of statistical models (including time series), then the AIC estimates the quality of each model, relative to the others that we have available. It is based on information theory. which is a highly interesting, deep topic that unfortunately we cant go into too much detail about. It attempts to balance the complexity of the model, which in this case means the number of parameters, with how well it fits the data. Lets provide a definition: Akaike Information Criterion If we take the likelihood function for a statistical model, which has k parameters, and L maximises the likelihood. then the Akaike Information Criterion is given by: The preferred model, from a selection of models, has the minium AIC of the group. You can see that the AIC grows as the number of parameters, k, increases, but is reduced if the negative log-likelihood increases. Essentially it penalises models that are overfit . We are going to be creating AR, MA and ARMA models of varying orders and one way to choose the best model fit a particular dataset is to use the AIC. This is what well be doing in the next article, primarily for ARMA models. Autoregressive (AR) Models of order p The first model were going to consider, which forms the basis of Part 1, is the Autoregressive model of order p, often shortened to AR(p). In the previous article we considered the random walk . where each term, xt is dependent solely upon the previous term, x and a stochastic white noise term, wt: The autoregressive model is simply an extension of the random walk that includes terms further back in time. The structure of the model is linear . that is the model depends linearly on the previous terms, with coefficients for each term. This is where the regressive comes from in autoregressive. It is essentially a regression model where the previous terms are the predictors. Autoregressive Model of order p A time series model, , is an autoregressive model of order p . AR(p), if: begin xt alpha1 x ldots alphap x wt sum p alphai x wt end Where is white noise and alphai in mathbb , with alphap neq 0 for a p-order autoregressive process. If we consider the Backward Shift Operator . (see previous article ) then we can rewrite the above as a function theta of : begin thetap ( ) xt (1 - alpha1 - alpha2 2 - ldots - alphap ) xt wt end Perhaps the first thing to notice about the AR(p) model is that a random walk is simply AR(1) with alpha1 equal to unity. As we stated above, the autogressive model is an extension of the random walk, so this makes sense It is straightforward to make predictions with the AR(p) model, for any time t, as once we have the alphai coefficients determined, our estimate simply becomes: begin hat t alpha1 x ldots alphap x end Hence we can make n-step ahead forecasts by producing hat t, hat , hat , etc up to hat . In fact, once we consider the ARMA models in Part 2, we will use the R predict function to create forecasts (along with standard error confidence interval bands) that will help us produce trading signals. Stationarity for Autoregressive Processes One of the most important aspects of the AR(p) model is that it is not always stationary. Indeed the stationarity of a particular model depends upon the parameters. Ive touched on this before in a previous article . In order to determine whether an AR(p) process is stationary or not we need to solve the characteristic equation . The characteristic equation is simply the autoregressive model, written in backward shift form, set to zero: We solve this equation for . In order for the particular autoregressive process to be stationary we need all of the absolute values of the roots of this equation to exceed unity. This is an extremely useful property and allows us to quickly calculate whether an AR(p) process is stationary or not. Lets consider a few examples to make this idea concrete: Random Walk - The AR(1) process with alpha1 1 has the characteristic equation theta 1 - . Clearly this has root 1 and as such is not stationary. AR(1) - If we choose alpha1 frac we get xt frac x wt. This gives us a characteristic equation of 1 - frac 0, which has a root 4 gt 1 and so this particular AR(1) process is stationary. AR(2) - If we set alpha1 alpha2 frac then we get xt frac x frac x wt. Its characteristic equation becomes - frac ( )( ) 0, which gives two roots of 1, -2. Since this has a unit root it is a non-stationary series. However, other AR(2) series can be stationary. Second Order Properties The mean of an AR(p) process is zero. However, the autocovariances and autocorrelations are given by recursive functions, known as the Yule-Walker equations. The full properties are given below: begin mux E(xt) 0 end begin gammak sum p alphai gamma , enspace k 0 end begin rhok sum p alphai rho , enspace k 0 end Note that it is necessary to know the alphai parameter values prior to calculating the autocorrelations. Now that weve stated the second order properties we can simulate various orders of AR(p) and plot the corresponding correlograms. Simulations and Correlograms Lets begin with an AR(1) process. This is similar to a random walk, except that alpha1 does not have to equal unity. Our model is going to have alpha1 0.6. The R code for creating this simulation is given as follows: Notice that our for loop is carried out from 2 to 100, not 1 to 100, as xt-1 when t0 is not indexable. Similarly for higher order AR(p) processes, t must range from p to 100 in this loop. We can plot the realisation of this model and its associated correlogram using the layout function: Lets now try fitting an AR(p) process to the simulated data weve just generated, to see if we can recover the underlying parameters. You may recall that we carried out a similar procedure in the article on white noise and random walks . As it turns out R provides a useful command ar to fit autoregressive models. We can use this method to firstly tell us the best order p of the model (as determined by the AIC above) and provide us with parameter estimates for the alphai, which we can then use to form confidence intervals. For completeness, lets recreate the x series: Now we use the ar command to fit an autoregressive model to our simulated AR(1) process, using maximum likelihood estimation (MLE) as the fitting procedure. We will firstly extract the best obtained order: The ar command has successfully determined that our underlying time series model is an AR(1) process. We can then obtain the alphai parameter(s) estimates: The MLE procedure has produced an estimate, hat 0.523, which is slightly lower than the true value of alpha1 0.6. Finally, we can use the standard error (with the asymptotic variance) to construct 95 confidence intervals around the underlying parameter(s). To achieve this, we simply create a vector c(-1.96, 1.96) and then multiply it by the standard error: The true parameter does fall within the 95 confidence interval, as wed expect from the fact weve generated the realisation from the model specifically. How about if we change the alpha1 -0.6 As before we can fit an AR(p) model using ar : Once again we recover the correct order of the model, with a very good estimate hat -0.597 of alpha1-0.6. We also see that the true parameter falls within the 95 confidence interval once again. Lets add some more complexity to our autoregressive processes by simulating a model of order 2. In particular, we will set alpha10.666, but also set alpha2 -0.333. Heres the full code to simulate and plot the realisation, as well as the correlogram for such a series: As before we can see that the correlogram differs significantly from that of white noise, as wed expect. There are statistically significant peaks at k1, k3 and k4. Once again, were going to use the ar command to fit an AR(p) model to our underlying AR(2) realisation. The procedure is similar as for the AR(1) fit: The correct order has been recovered and the parameter estimates hat 0.696 and hat -0.395 are not too far off the true parameter values of alpha10.666 and alpha2-0.333. Notice that we receive a convergence warning message. Notice also that R actually uses the arima0 function to calculate the AR model. As well learn in subsequent articles, AR(p) models are simply ARIMA(p, 0, 0) models, and thus an AR model is a special case of ARIMA with no Moving Average (MA) component. Well also be using the arima command to create confidence intervals around multiple parameters, which is why weve neglected to do it here. Now that weve created some simulated data it is time to apply the AR(p) models to financial asset time series. Financial Data Amazon Inc. Lets begin by obtaining the stock price for Amazon (AMZN) using quantmod as in the last article : The first task is to always plot the price for a brief visual inspection. In this case well using the daily closing prices: Youll notice that quantmod adds some formatting for us, namely the date, and a slightly prettier chart than the usual R charts: We are now going to take the logarithmic returns of AMZN and then the first-order difference of the series in order to convert the original price series from a non-stationary series to a (potentially) stationary one. This allows us to compare apples to apples between equities, indices or any other asset, for use in later multivariate statistics, such as when calculating a covariance matrix. If you would like a detailed explanation as to why log returns are preferable, take a look at this article over at Quantivity . Lets create a new series, amznrt. to hold our differenced log returns: Once again, we can plot the series: At this stage we want to plot the correlogram. Were looking to see if the differenced series looks like white noise. If it does not then there is unexplained serial correlation, which might be explained by an autoregressive model. We notice a statististically significant peak at k2. Hence there is a reasonable possibility of unexplained serial correlation. Be aware though, that this may be due to sampling bias. As such, we can try fitting an AR(p) model to the series and produce confidence intervals for the parameters: Fitting the ar autoregressive model to the first order differenced series of log prices produces an AR(2) model, with hat -0.0278 and hat -0.0687. Ive also output the aysmptotic variance so that we can calculate standard errors for the parameters and produce confidence intervals. We want to see whether zero is part of the 95 confidence interval, as if it is, it reduces our confidence that we have a true underlying AR(2) process for the AMZN series. To calculate the confidence intervals at the 95 level for each parameter, we use the following commands. We take the square root of the first element of the asymptotic variance matrix to produce a standard error, then create confidence intervals by multiplying it by -1.96 and 1.96 respectively, for the 95 level: Note that this becomes more straightforward when using the arima function, but well wait until Part 2 before introducing it properly. Thus we can see that for alpha1 zero is contained within the confidence interval, while for alpha2 zero is not contained in the confidence interval. Hence we should be very careful in thinking that we really have an underlying generative AR(2) model for AMZN. In particular we note that the autoregressive model does not take into account volatility clustering, which leads to clustering of serial correlation in financial time series. When we consider the ARCH and GARCH models in later articles, we will account for this. When we come to use the full arima function in the next article, we will make predictions of the daily log price series in order to allow us to create trading signals. SampP500 US Equity Index Along with individual stocks we can also consider the US Equity index, the SampP500. Lets apply all of the previous commands to this series and produce the plots as before: We can plot the prices: As before, well create the first order difference of the log closing prices: Once again, we can plot the series: It is clear from this chart that the volatility is not stationary in time. This is also reflected in the plot of the correlogram. There are many peaks, including k1 and k2, which are statistically significant beyond a white noise model. In addition, we see evidence of long-memory processes as there are some statistically significant peaks at k16, k18 and k21: Ultimately we will need a more sophisticated model than an autoregressive model of order p. However, at this stage we can still try fitting such a model. Lets see what we get if we do so: Using ar produces an AR(22) model, i. e. a model with 22 non-zero parameters What does this tell us It is indicative that there is likely a lot more complexity in the serial correlation than a simple linear model of past prices can really account for. However, we already knew this because we can see that there is significant serial correlation in the volatility. For instance, consider the highly volatile period around 2008. This motivates the next set of models, namely the Moving Average MA(q) and the Autoregressive Moving Average ARMA(p, q). Well learn about both of these in Part 2 of this article. As we repeatedly mention, these will ultimately lead us to the ARIMA and GARCH family of models, both of which will provide a much better fit to the serial correlation complexity of the Samp500. This will allows us to improve our forecasts significantly and ultimately produce more profitable strategies. Click Below To Learn More About. The information contained on this web site is the opinion of the individual authors based on their personal observation, research, and years of experience. The publisher and its authors are not registered investment advisers, attorneys, CPAs or other financial service professionals and do not render legal, tax, accounting, investment advice or other professional services. The information offered by this web site is general education only. Because each individuals factual situation is different the reader should seek his or her own personal adviser. Neither the author nor the publisher assumes any liability or responsibility for any errors or omissions and shall have neither liability nor responsibility to any person or entity with respect to damage caused or alleged to be caused directly or indirectly by the information contained on this site. Use at your own risk. Additionally, this website may receive financial compensation from the companies mentioned through advertising, affiliate programs or otherwise. Rates and offers from advertisers shown on this website change frequently, sometimes without notice. While we strive to maintain timely and accurate information, offer details may be out of date. Visitors should thus verify the terms of any such offers prior to participating in them. The author and its publisher disclaim responsibility for updating information and disclaim responsibility for third-party content, products, and services including when accessed through hyperlinks andor advertisements on this site.

No comments:

Post a Comment