Tuesday 4 July 2017

Mudança Média Cran R


Gt mav (c (4,5,4,6), 3) Série temporal: Início 1 Final 4 Frequência 1 1 NA 4.333333 5.000000 NA Aqui estava tentando fazer uma média móvel que levou em conta os últimos 3 números, então eu esperava Para obter apenas dois números de volta 8211 4.333333 e 5 8211 e se houvesse valores de NA, pensei que eles deveriam estar no início da seqüência. Na verdade, isso é o que o parâmetro 8216sides8217 controla: lados apenas para filtros de convolução. Se os lados 1 os coeficientes de filtro são para valores passados ​​apenas se os lados 2 estiverem centrados em torno de lag 0. Neste caso, o comprimento do filtro deve ser estranho, mas se for uniforme, mais do filtro está em frente do que para trás. Portanto, na nossa função 8216mav8217, a média de rolamento parece ter ambos os lados do valor atual em vez de apenas em valores passados. Nós podemos ajustar isso para obter o comportamento que queremos: gt library (zoo) gt rollmean (c (4,5,4,6), 3) 1 4.333333 5.000000 Eu também percebi que posso listar todas as funções em um pacote com o 8216ls8217 Função, então eu vou estar procurando digitalizar a lista de funções da zoo8217s na próxima vez que eu precisar fazer algumas séries temporais relacionadas 8211 there8217ll provavelmente já é uma função para ela gt ls (quotpackage: zooquot) 1 quotas. Datequot quotas. Date. numericquot quotas. Date. tsquot 4 Quotas. Date. yearmonquot quotas. date. yearqtrquot quotas. yearmonquot 7 quotas. yearmon. defaultquot quotas. yearqtrquot quotas. yearqtr. defaultquot 10 quotas. zooquot quotas. zoo. defaultquot quotas. zooregquot 13 quotas. zooreg. defaultquot quotautoplot. zooquot quotcbind. Zooquot 16 quotcoredataquot quatcoredata. defaultquot quotcoredatalt-quot 19 quotfacetfreequot quotformat. yearqtrquot quotfortify. zooot 22 quotfrequencylt-quet quotifelse. zooot quotindexquot 25 quotindexlt-quotindex2charquot quotis. regularquot 28 quotis. zooquot quotmake. par. listquot q UotMATCHquot 31 quatMATCH. defaultquot quatMATCH. timesquot quimedial. zoootot 34 quotmerge. zooquot quotna. aggregatequot quotna. aggregate. defaultquot 37 quotna. approxquot quotna. approx. defaultquot quotna. fillquot 40 quotna. fill. defaultquot quotna. locfquot quotna. locf. defaultquot 43 Quotna. splinequot quotna. spline. defaultquot quotna. StructTSquot 46 quotna. trimquot quotna. trim. defaultquot quotna. trim. tsquot 49 quotORDERquot quotORDER. defaultquot quotpanel. lines. itsquot 52 quotpanel. lines. tisquot quotpanel. lines. tsquot quotpanel. lines. Zooquot 55 quotpanel. plot. customquot quotpanel. plot. defaultquot quotpanel. points. itsquot 58 quotpanel. points. tisquot quotpanel. points. tsquot quotpanel. points. zooot 61 quotpanel. polygon. itsquot quotpanel. polygon. tisquot quotpanel. polygon. tsquot 64 Quotpanel. polygon. zooquot quotpanel. rect. itsquot quotpanel. rect. tisquot 67 quotpanel. rect. tsquot quotpanel. rect. zooot quotpanel. segments. itsquot 70 quotpanel. segments. tisquot quotpanel. segments. tsquot quotpanel. se Gments. zooot 73 quotpanel. text. itsquot quotpanel. text. tisquot quotpanel. text. tsquot 76 quotpanel. text. zooquot quotplot. zooquot quotquantile. zoootot 79 quotrbind. zooquot quotread. zooquot quotrev. zooot 82 quotrollapplyquot quotrollapplyrquot quotrollmaxquot 85 quotrollmax. defaultquot quotrollmaxrquot quotrollmeanquot 88 quotrollmean. defaultquot quotrollmeanrquot quotrollmedianquot 91 quotrollmedian. defaultquot quotrollmedianrquot quotrollsumquot 94 quotrollsum. defaultquot quotrollsumrquot quotscalexyearmonquot 97 quotscalexyearqtrquot quotscaleyyearmonquot quotscaleyyearqtrquot 100 quotSys. yearmonquot quotSys. yearqtrquot quottimelt-quot 103 quotwrite. zooquot quotxblocksquot quotxblocks. defaultquot 106 quotxtfrm. zooquot quotyearmonquot quotyearmontransquot 109 quotyearqtrquot quotyearqtrtransquot Quotzooot 112 quotzooregquot Be Sociable, ShareComo calcular a média móvel sem usar o filtro () Há um zilhão de respostas para isso, porque a sua pergunta é realmente: como eu aliso um Séries temporais Então você pode pesquisar palavras-chave apropriadas. Minha resposta é: não use médias móveis - isso é patéticamente antigo. Loess é uma das várias alternativas que você pode considerar. Publique no CV (stats. stackexchange) para outras alternativas estatísticas para o alisamento de séries temporais. Além disso, o quotunderstandingquot que você expressou acima é falho. As construções de tipo de aplicação são (R-level) loops. Então, você fez sua lição de casa ao ler A Intro to R (cran. r-project. orgdocmanualsR-intro. pdf) ou outros tutoriais na web. Caso contrário, faça isso antes de publicar aqui ainda. Bert Gunter Genentech Biostatistics Nonclinical (650) 467-7374 quotData não é informação. A informação não é conhecimento. E o conhecimento certamente não é sabedoria. H. Gilbert Welch No dia 17 de fevereiro de 2014, às 10:45, C O correio eletrônico enviado gt escreveu: gt Olá lista, gt Como calculo uma média móvel sem usar o filtro (). Filtro () gt não parece dar médias ponderadas. Gt gt Estou olhando para apply (), tapply. Mas nada é quotmovesquot. Gt gt Por exemplo, gt gt datlt-c (1:20) gt significa (dat1: 3) gt mean (dat 4: 6) gt mean (dat7: 9) gt mean (dat10: 12) gt gt etc. gt gt I Compreender o ponto de aplicação é evitar loops, como devo incorporar gt esta ideia no uso de uma aplicação () gt gt Obrigado, gt Mike gt gt versão HTML alternativa excluída gt gt gt email escondido lista de discussão gt stat. ethz. chmailmanlistinfor-help Gt POR FAVOR, leia o guia de publicação R-project. orgposting-guide. html gt e forneça um código comentado, mínimo, autônomo e reprodutível. Em resposta a esta postagem por tmrsg11 Em 17 de fevereiro de 2014, às 10:45 da manhã, C W escreveu: gt Hi list, gt Como calculo uma média móvel sem usar o filtro (). Filtro () gt não parece dar médias ponderadas. Gt gt Estou olhando para apply (), tapply. Mas nada é quotmovesquot. Gt gt Por exemplo, gt gt datlt-c (1:20) gt significa (dat1: 3) gt mean (dat 4: 6) gt mean (dat7: 9) gt mean (dat10: 12) gt gt etc. gt gt I Compreender o ponto de aplicação é evitar loops, como devo incorporar gt esta ideia no uso de uma aplicação () gt Construir um vetor para agrupar e usar tapply. A divisão do módulo é um método comum para alcançar isso. Às vezes, a função seq pode ser usada se você ajustar o comprimento corretamente. Gt tapply (dat, (0: ​​(length (dat) -1)) 3, mean) 0 1 2 3 4 5 6 2.0 5.0 8.0 11.0 14.0 17.0 19.5 tapply (dat, round (seq (1, (length (dat) 3), lenlength (dat))), significa) 1 2 3 4 5 6 7 1,5 4,5 8.0 11.0 14.5 18.0 20.0 O comentário sobre a ponderação dos não parece ser exemplificado no seu exemplo. Gt Obrigado, gt Mike gt gt versão HTML alternativa excluída gt gt gt email escondido lista de discussão gt stat. ethz. chmailmanlistinfor-help gt POR FAVOR, leia o guia de publicação R-project. orgposting-guide. html gt e forneça comentário, mínimo, auto - contido, código reprodutível. David Winsemius Alameda, CA, EUA Abrir esta postagem em exibição threaded Denunciar conteúdo como inapropriado Re: Como calcular a média móvel sem usar o filtro () Em resposta a esta postagem por Rui Barradas Para média móvel de 5 pontos, filtro (x, side2, filterrep (15, 5)), versus filtro (x, side2, filterrep (1, 5) Eles têm o mesmo efeito, uma vez que o total precisa ser 1. Gabor amp Rui: Estou ciente do pacote do zoológico, eu fiz Não quer instalar um pacote para uma função. Mesmo motivo para o pacote sos. David, obrigado, é isso que estou procurando. No dia 17 de fevereiro de 2014, às 14h07, Rui Barradas enviou um e-mail à gt, escreveu: gt Olá Gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt Ser calculado com algo como o seguinte. Gt gt s lt - (seqalong (dat) - 1) 3 gt sapply (split (dat, s), mean) gt gt gt Espero que isso ajude, gt gt Rui Barra As gt gt gt Em 17-02-2014 18:45, C W escreveu: gt gtgt Hi list, gtgt Como calculo uma média móvel sem usar o filtro (). Filtro () não parece dar médias ponderadas. Gtgt gtgt Estou olhando para apply (), tapply. Mas nada é quotmovesquot. Por exemplo, gtgt gtgt datlt-c (1:20) gtgt significa (dat1: 3) gtgt significa (dat4: 6) gtgt mean (dat7: 9) gtgt mean (dat10: 12) gtgt gtgt etc. gtgt gtgt I Entender o ponto de aplicação é evitar loops, como devo usar esta idéia no uso de uma aplicação () gtgt gtgt Obrigado, gtgt Mike gtgt gtgt alternativa versão HTML excluída gtgt gtgt gtgt email escondido lista de discussão gtgt stat. ethz. chmailmanlistinfor - Help gtgt POR FAVOR, leia o guia de publicação R-project. org gtgt posting-guide. html gtgt e forneça um código comentado, mínimo, autônomo e reprodutível. Gtgt gtgt alternativa versão HTML eliminadaUsando R para Time Series Analysis Time Series Analysis Este folheto informa-lhe 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 do produto M24902), disponível na Open University Shop. Neste livreto, vou usar conjuntos de dados da série temporal que foram gentilmente disponibilizados por Rob Hyndman em sua Time Series Data Library no robjhyndmanTSDL. Se você gosta deste livreto, 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álises multivariadas, 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á para 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: apenas 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 temporal 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üência 12, 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 nesse 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 em 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: Da mesma forma, 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 de tempo 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. Mais uma vez, 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 Aproximadamente constante em tamanho 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 de Queensland, Austrália, escrevemos: neste caso, parece que um modelo aditivo não é apropriado para descrever esta série de tempo, uma vez que o tamanho Das flutuações sazonais e das 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 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 temporal sazonal, um componente sazonal. Decomposição de dados não sazonais Uma série de tempo 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, a série temporal da idade da morte de 42 reis sucessivos da Inglaterra aparece não é sazonal, e provavelmente pode ser descrita 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 traçar os dados da série temporizada suavizadas, nós escrevemos: Ainda parece haver bastante flutuações aleatórias na série de tempo suavizada usando uma média móvel simples da ordem 3. Assim, para estimar o componente de tendência com mais precisão, 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 cada verão e todo 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 em variáveis ​​nascimentos de timescomponentes de temporada, tendências de freqüência de nascimento e pendentes de nascimento. 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 os componentes da tendência estimada de tendência, sazonal e irregular da série temporal usando a função 8220plot () 8221, por exemplo: o gráfico acima mostra as séries temporais originais (topo), o componente de tendência estimado (segundo da parte superior) O componente sazonal estimado (terceiro da parte superior) e o componente irregular estimado (parte inferior). Nós vemos 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 de 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 a série temporal 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 da série temporal original: 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 sazonalmente ajustada. 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ê tem uma série de tempo que pode ser descrita usando um modelo aditivo com nível constante e sem sazonalidade, você pode usar suavização 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 do alfa situa-se entre 0 e 1. Os valores de alfa que são próximos de 0 significam que pouco peso é colocado nas 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 na série temporal 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 suavização exponencial simples. Para fazer previsões usando suavização 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 o suavização exponencial de Holt8217s ou o 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 cerca de 0,024. Isto é 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, de modo que 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 de variáveis ​​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 para precipitação 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 outros 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 ter instalado 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 de sombra 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, 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 em Londres, nós escrevemos: Aqui, a estatística de teste de Ljung-Box é 17,4 e o valor de p é 0,6 , Portanto, há pouca evidência de autocorrelações não-zero nos erros de previsão na amostra nos 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ável 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 como 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 direta é 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 ser 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 de Londres, 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 sobre as 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 de 8282 da mulher na bainha, de 1866 a 1911. Os dados estão disponíveis no arquivo robjhyndmantsdldatarobertsskirts. Dat (dados originais de Hipel e McLeod, 1994). We can read in and plot the data in R by typing: We can see from the plot that there was an increase in hem diameter from about 600 in 1866 to about 1050 in 1880, and that afterwards the hem diameter decreased to about 520 in 1911. To make forecasts, we can fit a predictive model using the HoltWinters() function in R. To use HoltWinters() for Holt8217s exponential smoothing, we need to set the parameter gammaFALSE (the gamma parameter is used for Holt-Winters exponential smoothing, as described below). For example, to use Holt8217s exponential smoothing to fit a predictive model for skirt hem diameter, we type: The estimated value of alpha is 0.84, and of beta is 1.00. These are both high, telling us that both the estimate of the current value of the level, and of the slope b of the trend component, are based mostly upon very recent observations in the time series. This makes good intuitive sense, since the level and the slope of the time series both change quite a lot over time. The value of the sum-of-squared-errors for the in-sample forecast errors is 16954. We can plot the original time series as a black line, with the forecasted values as a red line on top of that, by typing: We can see from the picture that the in-sample forecasts agree pretty well with the observed values, although they tend to lag behind the observed values a little bit. If you wish, you can specify the initial values of the level and the slope b of the trend component by using the 8220l. start8221 and 8220b. start8221 arguments for the HoltWinters() function. It is common to set the initial value of the level to the first value in the time series (608 for the skirts data), and the initial value of the slope to the second value minus the first value (9 for the skirts data). For example, to fit a predictive model to the skirt hem data using Holt8217s exponential smoothing, with initial values of 608 for the level and 9 for the slope b of the trend component, we type: As for simple exponential smoothing, we can make forecasts for future times not covered by the original time series by using the forecast. HoltWinters() function in the 8220forecast8221 package. For example, our time series data for skirt hems was for 1866 to 1911, so we can make predictions for 1912 to 1930 (19 more data points), and plot them, by typing: The forecasts are shown as a blue line, with the 80 prediction intervals as an orange shaded area, and the 95 prediction intervals as a yellow shaded area. As for simple exponential smoothing, we can check whether the predictive model could be improved upon by checking whether the in-sample forecast errors show non-zero autocorrelations at lags 1-20. For example, for the skirt hem data, we can make a correlogram, and carry out the Ljung-Box test, by typing: Here the correlogram shows that the sample autocorrelation for the in-sample forecast errors at lag 5 exceeds the significance bounds. However, we would expect one in 20 of the autocorrelations for the first twenty lags to exceed the 95 significance bounds by chance alone. Indeed, when we carry out the Ljung-Box test, the p-value is 0.47, indicating that there is little evidence of non-zero autocorrelations in the in-sample forecast errors at lags 1-20. As for simple exponential smoothing, we should also check that the forecast errors have constant variance over time, and are normally distributed with mean zero. We can do this by making a time plot of forecast errors, and a histogram of the distribution of forecast errors with an overlaid normal curve: The time plot of forecast errors shows that the forecast errors have roughly constant variance over time. The histogram of forecast errors show that it is plausible that the forecast errors are normally distributed with mean zero and constant variance. Thus, the Ljung-Box test shows that there is little evidence of autocorrelations in the forecast errors, while the time plot and histogram of forecast errors show that it is plausible that the forecast errors are normally distributed with mean zero and constant variance. Therefore, we can conclude that Holt8217s exponential smoothing provides an adequate predictive model for skirt hem diameters, which probably cannot be improved upon. In addition, it means that the assumptions that the 80 and 95 predictions intervals were based upon are probably valid. Holt-Winters Exponential Smoothing If you have a time series that can be described using an additive model with increasing or decreasing trend and seasonality, you can use Holt-Winters exponential smoothing to make short-term forecasts. Holt-Winters exponential smoothing estimates the level, slope and seasonal component at the current time point. Smoothing is controlled by three parameters: alpha, beta, and gamma, for the estimates of the level, slope b of the trend component, and the seasonal component, respectively, at the current time point. The parameters alpha, beta and gamma all have values between 0 and 1, and values that are close to 0 mean that relatively little weight is placed on the most recent observations when making forecasts of future values. An example of a time series that can probably be described using an additive model with a trend and seasonality is the time series of the log of monthly sales for the souvenir shop at a beach resort town in Queensland, Australia (discussed above): To make forecasts, we can fit a predictive model using the HoltWinters() function. For example, to fit a predictive model for the log of the monthly sales in the souvenir shop, we type: The estimated values of alpha, beta and gamma are 0.41, 0.00, and 0.96, respectively. The value of alpha (0.41) is relatively low, indicating that the estimate of the level at the current time point is based upon both recent observations and some observations in the more distant past. The value of beta is 0.00, indicating that the estimate of the slope b of the trend component is not updated over the time series, and instead is set equal to its initial value. This makes good intuitive sense, as the level changes quite a bit over the time series, but the slope b of the trend component remains roughly the same. In contrast, the value of gamma (0.96) is high, indicating that the estimate of the seasonal component at the current time point is just based upon very recent observations. As for simple exponential smoothing and Holt8217s exponential smoothing, we can plot the original time series as a black line, with the forecasted values as a red line on top of that: We see from the plot that the Holt-Winters exponential method is very successful in predicting the seasonal peaks, which occur roughly in November every year. To make forecasts for future times not included in the original time series, we use the 8220forecast. HoltWinters()8221 function in the 8220forecast8221 package. For example, the original data for the souvenir sales is from January 1987 to December 1993. If we wanted to make forecasts for January 1994 to December 1998 (48 more months), and plot the forecasts, we would type: The forecasts are shown as a blue line, and the orange and yellow shaded areas show 80 and 95 prediction intervals, respectively. We can investigate whether the predictive model can be improved upon by checking whether the in-sample forecast errors show non-zero autocorrelations at lags 1-20, by making a correlogram and carrying out the Ljung-Box test: The correlogram shows that the autocorrelations for the in-sample forecast errors do not exceed the significance bounds for lags 1-20. Furthermore, the p-value for Ljung-Box test is 0.6, indicating that there is little evidence of non-zero autocorrelations at lags 1-20. We can check whether the forecast errors have constant variance over time, and are normally distributed with mean zero, by making a time plot of the forecast errors and a histogram (with overlaid normal curve): From the time plot, it appears plausible that the forecast errors have constant variance over time. From the histogram of forecast errors, it seems plausible that the forecast errors are normally distributed with mean zero. Thus, there is little evidence of autocorrelation at lags 1-20 for the forecast errors, and the forecast errors appear to be normally distributed with mean zero and constant variance over time. This suggests that Holt-Winters exponential smoothing provides an adequate predictive model of the log of sales at the souvenir shop, which probably cannot be improved upon. 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 uk

No comments:

Post a Comment