Thursday 17 August 2017

Mover Média Covariância Estacionária


Média de Mudança Autoregressiva Modelos de ARMA (p, q) para Análise da Série de Tempo - Parte 1 No último artigo, analisamos as caminhadas aleatórias e o ruído branco como modelos de séries temporais básicas para certos instrumentos financeiros, como preços diários de patrimônio e índice de ações. Descobrimos que, em alguns casos, um modelo de caminhada aleatória era insuficiente para capturar o comportamento de autocorrelação total do instrumento, o que motiva modelos mais sofisticados. Nos próximos dois artigos, vamos discutir três tipos de modelo, ou seja, o modelo Autoregressivo (AR) da ordem p, o modelo de ordem média móvel (MA) da ordem e o modelo de ordem média auto - gressiva mista (ARMA) da ordem p , Q. Esses modelos nos ajudarão a tentar capturar ou explicar mais a correlação serial presente dentro de um instrumento. Em última análise, eles nos fornecerão um meio de prever os preços futuros. No entanto, é bem sabido que as séries temporais financeiras possuem uma propriedade conhecida como aglomeração de volatilidade. Ou seja, a volatilidade do instrumento não é constante no tempo. O termo técnico para este comportamento é conhecido como heterocedasticidade condicional. Uma vez que os modelos AR, MA e ARMA não são condicionalmente heterossejidos, isto é, eles não levam em consideração a acumulação de volatilidade, finalmente precisaremos de um modelo mais sofisticado para nossas previsões. Tais modelos incluem o modelo Heteroskedastic condicional autogressivo (ARCH) e o modelo Heteroskedastic condicional autogressivo generalizado (GARCH), e suas muitas variantes. O GARCH é particularmente conhecido em financiamento quantitativo e é usado principalmente para simulações de séries temporais financeiras como meio de estimar o risco. No entanto, como acontece com todos os artigos QuantStart, quero construir esses modelos a partir de versões mais simples para que possamos ver como cada nova variante altera nossa capacidade preditiva. Apesar de AR, MA e ARMA serem modelos de séries temporais relativamente simples, eles são a base de modelos mais complicados, como a Média Mover Integrada Autoregressiva (ARIMA) e a família GARCH. Por isso, é importante estudá-los. Uma das nossas primeiras estratégias de negociação na série de artigos da série temporal será combinar ARIMA e GARCH para prever antecipadamente os preços n. No entanto, teremos que esperar até discutirmos ARIMA e GARCH separadamente antes de aplicá-los a uma estratégia real. Como vamos prosseguir Neste artigo, vamos descrever alguns novos conceitos de séries temporais que bem precisam dos métodos restantes, a saber, rigorosos Estacionária e o critério de informação Akaike (AIC). Subsequentemente a esses novos conceitos, seguiremos o padrão tradicional para o estudo de novos modelos de séries temporais: Justificação - A primeira tarefa é fornecer uma razão pela qual estavam interessados ​​em um modelo particular, como quants. Por que estamos apresentando o modelo da série temporal? Que efeitos ele pode capturar? O que ganhamos (ou perdemos) adicionando em complexidade extra Definição - Precisamos fornecer a definição matemática completa (e notação associada) do modelo da série temporal para minimizar Qualquer ambiguidade. Propriedades de segunda ordem - Vamos discutir (e, em alguns casos, derivar) as propriedades de segunda ordem do modelo da série temporal, que inclui sua média, sua variação e sua função de autocorrelação. Correlograma - Usaremos as propriedades de segunda ordem para plotar um correlograma de uma realização do modelo de séries temporais para visualizar seu comportamento. Simulação - Vamos simular as realizações do modelo da série temporal e, em seguida, ajustar o modelo a essas simulações para garantir que possamos implementações precisas e entender o processo de montagem. Dados financeiros reais - Ajudaremos o modelo da série temporal a dados financeiros reais e consideraremos o correlograma dos resíduos para ver como o modelo explica a correlação serial na série original. Previsão - Vamos criar previsões n-passo a frente do modelo da série temporal para realizações específicas, a fim de produzir sinais de negociação. Quase todos os artigos que escrevo em modelos de séries temporais cairão nesse padrão e nos permitirá comparar facilmente as diferenças entre cada modelo à medida que adicionamos mais complexidade. Começamos por analisar a estacionária rigorosa e a AIC. Estritamente estacionário Nós fornecemos a definição de estacionaria no artigo sobre a correlação em série. No entanto, como vamos entrar no reino de muitas séries financeiras, com várias freqüências, precisamos garantir que nossos (eventuais) modelos levem em consideração a volatilidade variável no tempo dessas séries. Em particular, precisamos considerar sua heterossextibilidade. Encontraremos esse problema quando tentarmos ajustar certos modelos a séries históricas. Geralmente, nem toda a correlação em série nos resíduos de modelos ajustados pode ser contabilizada sem levar em consideração a heterocedasticidade. Isso nos leva de volta à estacionança. Uma série não é estacionária na variância se tiver volatilidade variável no tempo, por definição. Isso motiva uma definição mais rigorosa de estacionaria, a saber, a estacionalização rigorosa: Estritamente estacionário Série A modelo de série temporal, é estritamente estacionário se a distribuição estatística conjunta dos elementos x, ldots, x é a mesma que a de xm, ldots, xm, Forall ti, m. Pode-se pensar nessa definição como simplesmente que a distribuição da série temporal é inalterada para qualquer mudança abrupta no tempo. Em particular, a média ea variância são constantes no tempo para uma série estritamente estacionária e a autocovariância entre xt e xs (digamos) depende apenas da diferença absoluta de t e s, t-s. Nós estaremos revendo estritamente séries estacionárias em postagens futuras. O Critério de Informação Akaike mencionado em artigos anteriores que eventualmente precisamos considerar como escolher entre os melhores modelos separados. Isto é verdade não só da análise das séries temporais, mas também da aprendizagem por máquinas e, mais amplamente, das estatísticas em geral. Os dois principais métodos que usaremos (por enquanto) são o Critério de Informação Akaike (AIC) e o Critério de Informação Bayesiano (à medida que avançamos com nossos artigos sobre Estatísticas Bayesianas). Bem, considere brevemente o AIC, pois será usado na Parte 2 do artigo ARMA. AIC é essencialmente uma ferramenta para auxiliar na seleção do modelo. Ou seja, se temos uma seleção de modelos estatísticos (incluindo séries temporais), a AIC estima a qualidade de cada modelo em relação aos outros que temos disponível. Baseia-se na teoria da informação. Que é um tópico muito interessante e profundo que, infelizmente, não podemos entrar em detalhes demais. Ele tenta equilibrar a complexidade do modelo, o que significa, neste caso, o número de parâmetros, com o quão bem se ajusta aos dados. Permite fornecer uma definição: Critério de informação de Akaike Se tomarmos a função de verossimilhança para um modelo estatístico, que possui parâmetros k e L maximiza a probabilidade. Então o Critério de Informação de Akaike é dado por: O modelo preferido, a partir de uma seleção de modelos, tem o mínimo AIC do grupo. Você pode ver que o AIC cresce à medida que o número de parâmetros, k, aumenta, mas é reduzido se a probabilidade de log negativa aumentar. Essencialmente, penaliza modelos que são superados. Vamos criar modelos AR, MA e ARMA de diferentes ordens e uma maneira de escolher o melhor modelo que se encaixa em um determinado conjunto de dados é usar o AIC. Isto é o que bem estar fazendo no próximo artigo, principalmente para modelos ARMA. Autoregressivo (AR) Modelos de ordem p O primeiro modelo que consideramos, que constitui a base da Parte 1, é o modelo Autoregressivo de ordem p, muitas vezes reduzido a AR (p). No artigo anterior consideramos a caminhada aleatória. Onde cada termo, xt é dependente unicamente do termo anterior, x e um termo estocástico de ruído branco, wt: o modelo autorregressivo é simplesmente uma extensão da caminhada aleatória que inclui termos mais atrasados ​​no tempo. A estrutura do modelo é linear. Esse é o modelo depende linearmente dos termos anteriores, com coeficientes para cada termo. É aí que o regressivo vem de autoregressivo. É essencialmente um modelo de regressão onde os termos anteriores são os preditores. Modelo Autoregressivo de ordem p Um modelo de série temporal,, é um modelo de ordem autoregressivo p. AR (p), se: begin xt alpha1 x ldots alphap x wt sum p alphai x wt end Onde está o ruído branco e alphai em mathbb, com alphap neq 0 para um processo autorregressivo de ordem p. Se considerarmos o operador de deslocamento para trás. (Veja o artigo anterior), então podemos reescrever o acima como uma função theta de: begin thetap () xt (1 - alpha1 - alpha2 2 - ldots - alphap) xt wt end Talvez a primeira coisa a notar sobre o modelo AR (p) É que uma caminhada aleatória é simplesmente AR (1) com alfa 1 igual à unidade. Como afirmamos acima, o modelo autogressivo é uma extensão da caminhada aleatória, então isso faz sentido. É direto fazer previsões com o modelo AR (p), para qualquer momento t, uma vez que temos os coeficientes de alphai determinados, nossa estimativa Simplesmente se torna: começo chapéu t alpha1 x ldots alphap x end Assim, podemos fazer previsões n-passo a frente produzindo chapéu, chapéu, chapéu, etc. até o chapéu. Na verdade, uma vez que consideremos os modelos ARMA na Parte 2, usaremos a função de predição R para criar previsões (juntamente com bandas de intervalo de confiança de erro padrão) que nos ajudarão a produzir sinais comerciais. Stationarity para Processos Autoregressivos Um dos aspectos mais importantes do modelo AR (p) é que nem sempre é estacionário. Na verdade, a estacionariedade de um modelo específico depende dos parâmetros. Eu já toquei isso antes em um artigo anterior. Para determinar se um processo AR (p) está parado ou não, precisamos resolver a equação característica. A equação característica é simplesmente o modelo autorregressivo, escrito em forma de deslocamento para trás, definido como zero: resolvemos esta equação. Para que o processo autoregressivo particular seja estacionário, precisamos de todos os valores absolutos das raízes dessa equação para exceder a unidade. Esta é uma propriedade extremamente útil e nos permite calcular rapidamente se um processo AR (p) está parado ou não. Vamos considerar alguns exemplos para tornar esta idéia concreta: Random Walk - O processo AR (1) com alpha1 1 tem a equação característica theta 1 -. Claramente, isso tem a raiz 1 e, como tal, não é estacionário. AR (1) - Se escolhermos alpha1 frac, obtemos xt frac x wt. Isso nos dá uma equação característica de 1 - frac 0, que tem uma raiz de 4 gt 1 e, portanto, esse processo particular de AR (1) é estacionário. AR (2) - Se formamos alpha1 alpha2 frac, obtemos xt frac x frac x wt. Sua equação característica torna-se - frac () () 0, que dá duas raízes de 1, -2. Uma vez que esta tem uma unidade de raiz é uma série não estacionária. No entanto, outras séries AR (2) podem ser estacionárias. Propriedades de segunda ordem A média de um processo AR (p) é zero. No entanto, as autocovariâncias e autocorrelações são dadas por funções recursivas, conhecidas como equações de Yule-Walker. As propriedades completas são dadas abaixo: begin mux E (xt) 0 end begin gammak soma p alphai gamma, enspace k 0 end begin rhok soma p alphai rho, enspace k 0 end Observe que é necessário conhecer os valores dos parâmetros alphai antes de Calculando as autocorrelações. Agora que declaramos as propriedades de segunda ordem, podemos simular várias ordens de AR (p) e traçar os correlogramas correspondentes. Simulações e Correlogramas Comece com um processo AR (1). Isso é semelhante a uma caminhada aleatória, exceto que o alfa1 não tem igual a unidade. Nosso modelo terá alfa1 0,6. O código R para criar esta simulação é o seguinte: Observe que nosso loop for é realizado de 2 a 100, não de 1 a 100, como xt-1 quando t0 não é indexável. Da mesma forma, para processos AR (p) de ordem superior, t deve variar de p para 100 neste loop. Podemos traçar a realização deste modelo e seu correlograma associado usando a função de layout: agora tentamos ajustar um processo AR (p) aos dados simulados que acabamos de gerar, para ver se podemos recuperar os parâmetros subjacentes. Você pode lembrar que realizamos um procedimento semelhante no artigo sobre ruídos brancos e passeios aleatórios. Na medida em que R fornece um comando útil ar para caber modelos autorregressivos. Podemos usar esse método para primeiro nos dizer a melhor ordem p do modelo (conforme determinado pela AIC acima) e nos fornecer estimativas de parâmetros para o alfai, que podemos usar para formar intervalos de confiança. Para completar, vamos recriar a série x: agora usamos o comando ar para ajustar um modelo autoregressivo ao nosso processo de AR (1) simulado, usando a estimativa de máxima verossimilhança (MLE) como procedimento de montagem. Em primeiro lugar, extrairemos a melhor ordem obtida: o comando ar determinou com sucesso que nosso modelo de série temporal subjacente é um processo AR (1). Podemos então obter as estimativas dos parâmetros alfai: o procedimento MLE produziu uma estimativa, o chapéu 0.523, que é ligeiramente inferior ao valor verdadeiro de alpha1 0.6. Finalmente, podemos usar o erro padrão (com a variância assintótica) para construir 95 intervalos de confiança em torno do (s) parâmetro (s) subjacente (s). Para conseguir isso, simplesmente criamos um vetor c (-1,96, 1,96) e, em seguida, multiplicamos pelo erro padrão: o parâmetro verdadeiro se enquadra no intervalo de confiança 95, como esperamos do fato de que geramos a realização do modelo especificamente . Que tal se mudarmos o alpha1 -0.6. Como antes, podemos ajustar um modelo de AR (p) usando ar: Mais uma vez, recuperamos a ordem correta do modelo, com uma boa estimativa de chapéu -0.597 de alfa1-0.6. Também vemos que o parâmetro verdadeiro cai novamente no intervalo de confiança 95. Permite adicionar mais complexidade aos nossos processos autorregressivos, simulando um modelo de ordem 2. Em particular, estabelecemos alfa10.666, mas também definimos alpha2 -0.333. Heres o código completo para simular e traçar a realização, bem como o correlograma para tal série: como antes, podemos ver que o correlograma difere significativamente do ruído branco, como esperam. Existem picos estatisticamente significativos em k1, k3 e k4. Mais uma vez, iriam usar o comando ar para ajustar um modelo AR (p) à nossa realização AR (2) subjacente. O procedimento é semelhante ao ajuste AR (1): a ordem correta foi recuperada e as estimativas do parâmetro hat 0.696 e hat -0.395 não estão muito longe dos valores dos parâmetros verdadeiros de alpha10.666 e alpha2-0.333. Observe que recebemos uma mensagem de aviso de convergência. Observe também que R realmente usa a função arima0 para calcular o modelo AR. Além disso, aprender em artigos subseqüentes, os modelos AR (p) são simplesmente modelos ARIMA (p, 0, 0) e, portanto, um modelo AR é um caso especial de ARIMA sem componente de média móvel (MA). Bem, também estar usando o comando arima para criar intervalos de confiança em torno de múltiplos parâmetros, e é por isso que negligenciamos fazê-lo aqui. Agora que nós criamos alguns dados simulados, é hora de aplicar os modelos AR (p) às séries temporais de ativos financeiros. Dados Financeiros Amazon Inc. Comece pela obtenção do preço das ações da Amazon (AMZN) usando o quantmod como no último artigo: A primeira tarefa é sempre traçar o preço para uma breve inspeção visual. Neste caso, bem, use os preços de fechamento diários: você notará que o quantmod adiciona alguma formatação para nós, ou seja, a data e um gráfico um pouco mais bonito do que os gráficos R habituais: agora vamos tomar os retornos logarítmicos da AMZN e depois o primeiro Diferença de ordem da série para converter a série de preços original de uma série não estacionária para uma (potencialmente) estacionária. Isso nos permite comparar maçãs com maçãs entre ações, índices ou qualquer outro recurso, para uso em estatísticas multivariadas posteriores, como no cálculo de uma matriz de covariância. Se você gostaria de uma explicação detalhada sobre o motivo pelo qual os retornos de registro são preferíveis, dê uma olhada neste artigo na Quantividade. Vamos criar uma nova série, amznrt. Para manter nossos retornos de log diferentes: Mais uma vez, podemos traçar a série: nesta etapa, queremos traçar o correlograma. Olhamos para ver se a série diferenciada se parece com ruído branco. Se não existir, então, há uma correlação serial inexplicada, que pode ser explicada por um modelo autorregressivo. Observamos um pico estatisticamente significativo em k2. Portanto, existe uma possibilidade razoável de correlação serial inexplicada. Esteja ciente de que isso pode ser devido ao viés de amostragem. Como tal, podemos tentar ajustar um modelo AR (p) à série e produzir intervalos de confiança para os parâmetros: Ajustar o modelo ar autoregressivo à série de preços de registro diferenciada de primeira ordem produz um modelo AR (2), com chapéu -0.0278 E chapéu -0.0687. Eu também emitido a variância aestotica para que possamos calcular erros padrão para os parâmetros e produzir intervalos de confiança. Queremos ver se zero faz parte do intervalo de confiança 95, como se fosse, reduz a nossa confiança de que temos um verdadeiro processo subjacente AR (2) para a série AMZN. Para calcular os intervalos de confiança no nível 95 para cada parâmetro, usamos os seguintes comandos. Tomamos a raiz quadrada do primeiro elemento da matriz de variância assintótica para produzir um erro padrão, então crie intervalos de confiança, multiplicando-o por -1,96 e 1,96, respectivamente, pelo nível 95: Observe que isso se torna mais direto ao usar a função arima , Mas espere até a Parte 2 antes de apresentá-lo corretamente. Assim, podemos ver que por alfa1 zero está contido dentro do intervalo de confiança, enquanto que para alfa2 zero não está contido no intervalo de confiança. Por isso, devemos ter muito cuidado ao pensar que realmente temos um modelo AR (2) generativo subjacente para AMZN. Em particular, observamos que o modelo autorregressivo não leva em consideração o agrupamento de volatilidade, o que leva ao agrupamento de correlação serial em séries temporais financeiras. Quando consideramos os modelos ARCH e GARCH em artigos posteriores, iremos explicar isso. Quando chegarmos a usar a função arima completa no próximo artigo, faremos previsões da série diária de preços de registro para nos permitir criar sinais de negociação. SampP500 US Equity Index Junto com ações individuais, também podemos considerar o índice US Equity, o SampP500. Permite a aplicação de todos os comandos anteriores a esta série e produzimos as parcelas como antes: podemos traçar os preços: como antes, bem, crie a diferença de primeira ordem dos preços de fechamento de registro: mais uma vez, podemos traçar a série: é claro A partir deste gráfico que a volatilidade não é estacionária no tempo. Isso também se reflete na trama do correlograma. Existem muitos picos, incluindo k1 e k2, que são estatisticamente significativos além de um modelo de ruído branco. Além disso, vemos evidências de processos de memória longa, pois existem alguns picos estatisticamente significativos em k16, k18 e k21: Em última análise, precisaremos de um modelo mais sofisticado do que um modelo de ordem autoregressivo p. No entanto, nesta fase, ainda podemos tentar ajustar esse modelo. Vamos ver o que obtemos se o fizermos: Usando ar produz um modelo AR (22), ou seja, um modelo com 22 parâmetros não-zero O que isso nos diz É indicativo de que há uma complexidade muito maior na correlação serial do que Um modelo linear simples de preços passados ​​pode realmente explicar. No entanto, já sabíamos disso porque podemos ver que existe uma correlação séria em série na volatilidade. Por exemplo, considere o período altamente volátil em torno de 2008. Isso motiva o próximo conjunto de modelos, ou seja, o MA em movimento (q) e a média móvel auto-agressiva ARMA (p, q). Bem, saiba mais sobre estes na Parte 2 deste artigo. Como mencionamos repetidamente, estes nos levarão finalmente à família de modelos ARIMA e GARCH, que proporcionará um ajuste muito melhor à complexidade de correlação em série do Samp500. Isso nos permitirá melhorar significativamente nossas previsões e, em última análise, produzir estratégias mais lucrativas. Clique abaixo para aprender mais sobre. A informação contida neste site é a opinião dos autores individuais com base em sua observação pessoal, pesquisa e anos de experiência. A editora e seus autores não são conselheiros de investimento registrados, advogados, CPAs ou outros profissionais de serviços financeiros e não prestam assessoria jurídica, fiscal, contábil, de investimento ou outros serviços profissionais. A informação oferecida por este site é apenas de educação geral. Como cada situação factual de indivíduos é diferente, o leitor deve procurar seu próprio conselheiro pessoal. Nem o autor nem o editor assumem qualquer responsabilidade ou responsabilidade por quaisquer erros ou omissões e não devem ter responsabilidade nem responsabilidade para qualquer pessoa ou entidade em relação a danos causados ​​ou alegadamente causados ​​direta ou indiretamente pelas informações contidas neste site. Use por sua conta e risco. Além disso, este site pode receber compensações financeiras das empresas mencionadas através de publicidade, programas afiliados ou de outra forma. Taxas e ofertas de anunciantes exibidos neste site mudam com freqüência, às vezes sem aviso prévio. Enquanto nos esforçamos para manter informações precisas e oportunas, os detalhes da oferta podem estar desactualizados. Os visitantes devem assim verificar os termos de tais ofertas antes de participar delas. O autor e a editora renunciam à responsabilidade pela atualização de informações e negam a responsabilidade pelo conteúdo, produtos e serviços de terceiros, inclusive quando acessados ​​através de hiperlinks ou propagandas neste site. Nos seguintes tópicos, analisaremos técnicas que são úteis para analisar séries temporais Dados, ou seja, seqüências de medidas que seguem ordens não aleatórias. Ao contrário das análises de amostras aleatórias de observações que são discutidas no contexto da maioria das outras estatísticas, a análise de séries temporais baseia-se no pressuposto de que valores sucessivos no arquivo de dados representam medidas consecutivas tomadas em intervalos de tempo igualmente espaçados. As discussões detalhadas dos métodos descritos nesta seção podem ser encontradas em Anderson (1976), Box e Jenkins (1976), Kendall (1984), Kendall e Ord (1990), Montgomery, Johnson e Gardiner (1990), Pankratz (1983). ), Shumway (1988), Vandaele (1983), Walker (1991) e Wei (1989). Existem dois objetivos principais da análise de séries temporais: (a) identificar a natureza do fenômeno representado pela seqüência de observações e (b) prever (prever valores futuros da variável série temporal). Ambos os objetivos requerem que o padrão de dados da série temporal observada seja identificado e mais ou menos formalmente descrito. Uma vez que o padrão é estabelecido, podemos interpretá-lo e integrá-lo com outros dados (ou seja, usá-lo em nossa teoria do fenômeno investigado, por exemplo, os preços das mercadorias sesonais). Independentemente da profundidade do nosso entendimento e da validade de nossa interpretação (teoria) do fenômeno, podemos extrapolar o padrão identificado para prever eventos futuros. Padrão sistemático e ruído aleatório Como na maioria das outras análises, na análise de séries temporais presume-se que os dados consistem em um padrão sistemático (geralmente um conjunto de componentes identificáveis) e ruído aleatório (erro) que normalmente torna o padrão difícil de identificar. A maioria das técnicas de análise de séries temporais envolvem alguma forma de filtrar o ruído para tornar o padrão mais saliente. Dois Aspectos Gerais dos Padrões da Série de Tempo A maioria dos padrões de séries temporais podem ser descritos em termos de duas classes básicas de componentes: tendência e sazonalidade. O primeiro representa um componente geral linear sistemático ou (mais frequentemente) não-linear que muda ao longo do tempo e não repete ou, pelo menos, não se repete no intervalo de tempo capturado pelos nossos dados (por exemplo, um platô seguido de um período de crescimento exponencial). O último pode ter uma natureza formalmente semelhante (por exemplo, um platô seguido por um período de crescimento exponencial), no entanto, ele se repete em intervalos sistemáticos ao longo do tempo. Essas duas classes gerais de componentes da série temporal podem coexistir em dados da vida real. Por exemplo, as vendas de uma empresa podem crescer rapidamente ao longo dos anos, mas ainda seguem padrões sazonais consistentes (por exemplo, até 25 de vendas anuais cada ano são feitas em dezembro, enquanto que apenas 4 em agosto). Este padrão geral está bem ilustrado em um conjunto clássico de dados da série G (Box e Jenkins, 1976, p. 531), que representa o total mensal de passageiros de companhias aéreas internacionais (medidas em milhares) em doze anos consecutivos de 1949 a 1960 (ver exemplo de arquivo de dados G. Sta e gráfico acima). Se você traçar as observações sucessivas (meses) dos totais dos passageiros das companhias aéreas, surge uma tendência clara e quase linear, indicando que a indústria aérea teve um crescimento constante ao longo dos anos (aproximadamente 4 vezes mais passageiros viajaram em 1960 do que em 1949). Ao mesmo tempo, os números mensais seguirão um padrão quase idêntico a cada ano (por exemplo, mais pessoas viajam durante os feriados, em qualquer outro período do ano). Este exemplo de arquivo de dados também ilustra um padrão geral muito comum em dados de séries temporais, onde a amplitude das mudanças sazonais aumenta com a tendência geral (ou seja, a variância está correlacionada com a média sobre os segmentos da série). Esse padrão, denominado estacionalidade multiplicativa, indica que a amplitude relativa das mudanças sazonais é constante ao longo do tempo, portanto está relacionada à tendência. Não há técnicas de quotizações comprovadas para identificar componentes de tendência nos dados da série temporal, desde que a tendência seja monótona (consistentemente aumentando ou diminuindo), essa parte da análise de dados geralmente não é muito difícil. Se os dados da série temporal contêm um erro considerável, o primeiro passo no processo de identificação da tendência é o alisamento. Suavização. O suavização sempre envolve alguma forma de média local de dados, de modo que os componentes não-sistemáticos das observações individuais se cancelem mutuamente. A técnica mais comum é o alisamento médio móvel que substitui cada elemento da série pela média simples ou ponderada de n elementos circundantes, onde n é a largura do quotwindowquot de suavização (ver Caixa amp Jenkins, 1976 Velleman amp Hoaglin, 1981). Medianas podem ser usadas em vez de meios. A principal vantagem da mediana em comparação com o alisamento médio móvel é que seus resultados são menos tendenciosos por outliers (dentro da janela de suavização). Assim, se houver valores abertos nos dados (por exemplo, devido a erros de medição), o suavização mediana normalmente produz curvas mais suaves ou pelo menos mais confiáveis ​​do que a média móvel com base na mesma largura da janela. A principal desvantagem do alisamento mediano é que, na ausência de valores abertos claros, ele pode produzir curvas mais quotjaggedquot do que a média móvel e não permite a ponderação. Nos casos relativamente menos comuns (em dados de séries temporais), quando o erro de medição é muito grande, podem ser utilizadas as técnicas de alisamento de mínimos quadrados ponderados pela distância ou técnicas de suavização ponderadas exponencialmente. Todos esses métodos vão filtrar o ruído e converter os dados em uma curva suave que é relativamente imparcial por outliers (veja as seções respectivas em cada um desses métodos para mais detalhes). As séries com relativamente poucos pontos sistematicamente distribuídos podem ser suavizadas com splines bicubic. Ajustando uma função. Muitos dados monótonos de séries temporais podem ser adequadamente aproximados por uma função linear se houver um componente não linear linear monotonômico claro, os dados primeiro precisam ser transformados para remover a não-linearidade. Geralmente, uma função polinomial logarítmica, exponencial ou (menos freqüentemente) pode ser usada. Análise da sazonalidade A dependência sazonal (sazonalidade) é outro componente geral do padrão das séries temporais. O conceito foi ilustrado no exemplo dos dados dos passageiros das companhias aéreas acima. É formalmente definido como dependência correlacional da ordem k entre cada i ímero da série e o elemento (i-k) th (Kendall, 1976) e medido por autocorrelação (ou seja, uma correlação entre os dois termos) k é geralmente chamado de atraso. Se o erro de medição não for muito grande, a sazonalidade pode ser identificada visualmente na série como um padrão que repete todos os elementos k. Correlato de auto-correlação. Os padrões sazonais das séries temporais podem ser examinados através de correlogramas. O correlograma (autocorrelograma) exibe graficamente e numericamente a função de autocorrelação (ACF), ou seja, coeficientes de correlação em série (e seus erros padrão) para atrasos consecutivos em um intervalo especificado de atrasos (por exemplo, de 1 a 30). As variações de dois erros padrão por cada atraso geralmente são marcadas em correlogramas, mas tipicamente o tamanho da auto-correlação é mais interessante do que a sua confiabilidade (ver Conceitos Elementares), porque geralmente estamos interessados ​​em autocorrelações muito fortes (e, portanto, altamente significativas). Examinando correlogramas. Ao examinar os correlogramas, deve-se ter em mente que as autocorrelações por atrasos consecutivos são formalmente dependentes. Considere o seguinte exemplo. Se o primeiro elemento estiver intimamente relacionado com o segundo e o segundo com o terceiro, o primeiro elemento também deve estar um pouco relacionado ao terceiro, etc. Isso implica que o padrão de dependências em série pode variar consideravelmente após a remoção da primeira ordem Auto-correlação (ou seja, depois de diferenciar a série com um atraso de 1). Autocorrelações parciais. Outro método útil para examinar as dependências em série é examinar a função de autocorrelação parcial (PACF) - uma extensão da autocorrelação, onde a dependência dos elementos intermediários (aqueles dentro do atraso) é removida. Em outras palavras, a autocorrelação parcial é semelhante à autocorrelação, exceto que, ao calcular, as correlações (auto) com todos os elementos dentro do atraso são retiradas (Box amp Jenkins, 1976, veja também McDowall, McCleary, Meidinger, amp, Hay, 1980). ). Se for especificado um atraso de 1 (ou seja, não há elementos intermédios dentro do intervalo), a autocorrelação parcial é equivalente a auto-correlação. Em certo sentido, a autocorrelação parcial fornece uma imagem quotcleanerquot de dependências em série para atrasos individuais (não confundidas por outras dependências em série). Removendo a dependência serial. A dependência serial para um atraso particular de k pode ser removida diferenciando a série, que está convertendo cada i elemento da série em sua diferença do elemento (i-k) th. Existem duas razões principais para tais transformações. Primeiro, pode-se identificar a natureza oculta das dependências sazonais na série. Lembre-se que, como mencionado no parágrafo anterior, as autocorrelações por atrasos consecutivos são interdependentes. Portanto, remover algumas das autocorrelações mudará outras correlações automáticas, ou seja, pode eliminá-las ou pode tornar mais aparentes outros efeitos sazonais. O outro motivo para remover as dependências sazonais é tornar a série estacionária necessária para o ARIMA e outras técnicas. Os procedimentos de modelagem e previsão discutidos nos Padrões de Identificação em Dados da Série de Tempo. Envolveu conhecimento sobre o modelo matemático do processo. No entanto, na pesquisa e na prática da vida real, os padrões dos dados não são claros, as observações individuais envolvem um erro considerável e ainda não precisamos apenas descobrir os padrões ocultos nos dados, mas também gerar previsões. A metodologia ARIMA desenvolvida por Box e Jenkins (1976) nos permite fazer exatamente que ganhou enorme popularidade em muitas áreas e as práticas de pesquisa confirmam seu poder e flexibilidade (Hoff, 1983 Pankratz, 1983 Vandaele, 1983). No entanto, devido à sua força e flexibilidade, a ARIMA é uma técnica complexa, não é fácil de usar, requer muita experiência e, embora produza resultados satisfatórios, esses resultados dependem do nível de especialização dos pesquisadores (Bails amp Peppers , 1982). As seções a seguir apresentarão as idéias básicas desta metodologia. Para aqueles interessados ​​em um breve, orientado a aplicações (não matemática), introdução aos métodos ARIMA, recomendamos McDowall, McCleary, Meidinger e Hay (1980). Processo Autoregressivo de dois Processos Comuns. A maioria das séries temporais consistem em elementos que são dependentes em série no sentido de que se pode estimar um coeficiente ou um conjunto de coeficientes que descrevem elementos consecutivos da série a partir de elementos específicos, atrasados ​​no tempo (anteriores). Isso pode ser resumido na equação: Onde: é uma constante (interceptação) e 1. 2. 3 são os parâmetros do modelo autorregressivo. Coloque em palavras, cada observação é composta por um componente de erro aleatório (choque aleatório) e uma combinação linear de observações anteriores. Requisito de aposentadoria. Observe que um processo autorregressivo só será estável se os parâmetros estiverem dentro de um determinado intervalo, por exemplo, se houver apenas um parâmetro autorregressivo, então deve estar dentro do intervalo de -1 lt lt 1. Caso contrário, os efeitos passados ​​se acumulariam e os valores De xts sucessivos se moveriam para o infinito, ou seja, a série não seria estacionária. Se houver mais de um parâmetro autorregressivo, podem ser definidas restrições (gerais) semelhantes nos valores dos parâmetros (por exemplo, ver Box Jenkins, 1976 Montgomery, 1990). Processo médio móvel. Independente do processo autorregressivo, cada elemento da série também pode ser afetado pelo erro passado (ou choque aleatório) que não pode ser explicado pelo componente autoregressivo, ou seja: Onde: 181 é uma constante e 1. 2. 3 são os parâmetros do modelo médio móvel. Coloque em palavras, cada observação é composta por um componente de erro aleatório (choque aleatório) e uma combinação linear de choques aleatórios prévios. Requisito de Invertibilidade. Sem entrar em demasiados detalhes, existe uma quotualidade entre o processo da média móvel e o processo autorregressivo (por exemplo, ver Box amp Jenkins, 1976 Montgomery, Johnson, amp Gardiner, 1990), ou seja, a equação média móvel acima pode ser reescrita ( Invertida) em uma forma autorregressiva (de ordem infinita). No entanto, análogo à condição de estacionaria descrita acima, isso só pode ser feito se os parâmetros da média móvel seguirem certas condições, ou seja, se o modelo for reversível. Caso contrário, a série não será estacionária. Modelo de média móvel autorregressiva. O modelo geral introduzido por Box e Jenkins (1976) inclui parâmetros de média autorregressivos e móveis, e inclui explicitamente a diferenciação na formulação do modelo. Especificamente, os três tipos de parâmetros no modelo são: os parâmetros autorregressivos (p), o número de passagens de diferenciação (d) e os parâmetros de média móvel (q). Na notação introduzida por Box e Jenkins, os modelos são resumidos como ARIMA (p, d, q), portanto, por exemplo, um modelo descrito como (0, 1, 2) significa que ele contém 0 (zero) parâmetros autorregressivos (p) E 2 parâmetros de média móvel (q) que foram computados para a série depois de terem sido diferenciados uma vez. Identificação. Como mencionado anteriormente, a série de entrada para ARIMA precisa ser estacionária. Isto é, deve ter um meio, variância e autocorrelação constantes ao longo do tempo. Portanto, geralmente a série primeiro precisa ser diferenciada até estar estacionada (isso também requer muitas vezes o log que transforma os dados para estabilizar a variância). O número de vezes que a série precisa ser diferenciado para alcançar a estacionaridade é refletido no parâmetro d (veja o parágrafo anterior). Para determinar o nível necessário de diferenciação, deve-se examinar a parcela dos dados e o autocorrelograma. Mudanças significativas no nível (fortes mudanças para cima ou para baixo) geralmente requerem uma primeira ordem não sazonal (lag1) que diferenciam fortes mudanças de inclinação, geralmente requerem diferenciação não sazonal de segunda ordem. Os padrões sazonais requerem diferentes diferenças sazonais (ver abaixo). Se os coeficientes de autocorrelação estimados diminuírem lentamente em atrasos mais longos, a diferenciação de primeira ordem geralmente é necessária. No entanto, deve-se ter em mente que algumas séries temporais podem exigir pouca ou nenhuma diferenciação, e que, em séries diferenciadas, produzem estimativas de coeficientes menos estáveis. Nesta fase (que geralmente é chamada de fase de identificação, veja abaixo), também precisamos decidir quantos parâmetros autorregressivos (p) e média móvel (q) são necessários para produzir um modelo efetivo, mas ainda parcimonioso, do processo (parcimonioso significa que ele Tem o menor número de parâmetros e maior número de graus de liberdade entre todos os modelos que se encaixam nos dados). Na prática, os números dos parâmetros p ou q raramente precisam ser maiores do que 2 (veja abaixo recomendações mais específicas). Estimativa e Previsão. No próximo passo (Estimativa), os parâmetros são estimados (usando procedimentos de minimização de função, veja abaixo para obter mais informações sobre procedimentos de minimização, veja também Estimação não linear), de modo que a soma dos resíduos quadrados seja minimizada. As estimativas dos parâmetros são usadas na última etapa (Previsão) para calcular novos valores da série (além dos incluídos no conjunto de dados de entrada) e intervalos de confiança para os valores previstos. O processo de estimativa é realizado em dados transformados (diferenciados) antes que as previsões sejam geradas, a série precisa ser integrada (a integração é o inverso da diferenciação) para que as previsões sejam expressas em valores compatíveis com os dados de entrada. Este recurso de integração automática é representado pela letra I em nome da metodologia (ARIMA Auto-Regressive Integrated Moving Average). A constante nos modelos ARIMA. Além dos parâmetros padrão padrão autorregressivo e móvel, os modelos ARIMA também podem incluir uma constante, conforme descrito acima. A interpretação de uma constante (estatisticamente significante) depende do modelo que esteja em forma. Especificamente, (1) se não houver parâmetros autorregressivos no modelo, então o valor esperado da constante é, a média da série (2), se houver parâmetros autorregressivos na série, então a constante representa a intercepção. Se a série for diferente, então a constante representa a média ou a intercepção da série diferenciada. Por exemplo, se a série for diferenciada uma vez, e não há parâmetros autorregressivos no modelo, então a constante representa a média da série diferenciada e Portanto, a inclinação da tendência linear das séries não diferenciadas. Número de parâmetros a serem estimados. Antes que a estimativa possa começar, precisamos decidir (identificar) o número específico e o tipo de parâmetros ARIMA a serem estimados. As principais ferramentas utilizadas na fase de identificação são tramas da série, correlogramas de auto correlação (ACF) e autocorrelação parcial (PACF). A decisão não é direta e em casos menos típicos requer não só experiência, mas também uma boa experiência de modelos alternativos (bem como os parâmetros técnicos de ARIMA). No entanto, a maioria dos padrões de séries temporais empíricas podem ser suficientemente aproximados usando um dos 5 modelos básicos que podem ser identificados com base na forma do autocorrelograma (ACF) e auto-correlograma parcial (PACF). O breve resumo a seguir é baseado em recomendações práticas de Pankratz (1983) para conselhos práticos adicionais, ver também Hoff (1983), McCleary e Hay (1980), McDowall, McCleary, Meidinger e Hay (1980) e Vandaele (1983) . Além disso, note que, uma vez que o número de parâmetros (a serem estimados) de cada tipo é quase nunca maior do que 2, muitas vezes é prático tentar modelos alternativos nos mesmos dados. Um parâmetro autorregressivo (p). ACF - Decaptação exponencial PACF - pico no intervalo 1, sem correlação para outros atrasos. Dois parâmetros autorregressivos (p). ACF - um padrão de forma de onda senoidal ou um conjunto de decadências exponenciais PACF - picos nos intervalos 1 e 2, sem correlação para outros atrasos. Um parâmetro de média móvel (q). ACF - pico no intervalo 1, sem correlação para outros atrasos PACF - diminui exponencialmente. Dois parâmetros de média móvel (q). ACF - picos nos laços 1 e 2, sem correlação para outros lags PACF - um padrão de forma de onda senoidal ou um conjunto de decações exponenciais. Um parâmetro autorregressivo (p) e uma média móvel (q). ACF - Decadência exponencial a partir do lag 1 PACF - Decadência exponencial a partir do intervalo 1. Modelos sazonais. O ARIMA sazonal multiplicativo é uma generalização e extensão do método introduzido nos parágrafos anteriores para séries em que um padrão repete sazonalmente ao longo do tempo. Além dos parâmetros não sazonais, os parâmetros sazonais para um atraso específico (estabelecido na fase de identificação) precisam ser estimados. Analogamente aos parâmetros ARIMA simples, estes são: parâmetros autorregressivos sazonais (ps), diferenciais sazonais (ds) e estacionais (qs). Por exemplo, o modelo (0,1,2) (0,1,1) descreve um modelo que não inclui parâmetros autoregressivos, 2 parâmetros de média móvel contínua e 1 parâmetro de média móvel sazonal, e esses parâmetros foram calculados para a série depois Foi diferenciado uma vez com o atraso 1, e uma vez diferenciado sazonalmente. O desvio sazonal utilizado para os parâmetros sazonais é geralmente determinado durante a fase de identificação e deve ser explicitamente especificado. As recomendações gerais sobre a seleção de parâmetros a serem estimados (com base em ACF e PACF) também se aplicam aos modelos sazonais. A principal diferença é que em séries sazonais, ACF e PACF mostrarão coeficientes consideráveis ​​em múltiplos do intervalo sazonal (além de seus padrões globais que refletem os componentes não sazonais da série). Existem vários métodos diferentes para estimar os parâmetros. Todos eles devem produzir estimativas muito semelhantes, mas podem ser mais ou menos eficientes para qualquer modelo. Em geral, durante a fase de estimativa de parâmetros é utilizado um algoritmo de minimização de função (o chamado método quase-Newton refere-se à descrição do método de estimativa não linear) para maximizar a probabilidade (probabilidade) das séries observadas, dados os valores dos parâmetros. Na prática, isso requer o cálculo das somas (condicionais) de quadrados (SS) dos resíduos, dados os respectivos parâmetros. Foram propostos diferentes métodos para calcular o SS para os resíduos: (1) o método aproximado de máxima verossimilhança de acordo com McLeod e Sales (1983), (2) o método aproximado de máxima verossimilhança com backcasting e (3) o método exato de máxima verossimilhança De acordo com Melard (1984). Comparação de métodos. Em geral, todos os métodos devem produzir estimativas de parâmetros muito semelhantes. Além disso, todos os métodos são quase igualmente eficientes na maioria dos aplicativos da série temporal do mundo real. No entanto, o método 1 acima, (probabilidade máxima aproximada, sem retrocessos) é o mais rápido e deve ser usado em particular para séries temporais muito longas (por exemplo, com mais de 30.000 observações). O método de máxima verossimilhança exacta (número 3 acima) também pode tornar-se ineficiente quando usado para estimar parâmetros para modelos sazonais com atrasos sazonais longos (por exemplo, com atrasos anuais de 365 dias). Por outro lado, você deve sempre usar primeiro o método de máxima verossimilhança para estabelecer estimativas de parâmetros iniciais que são muito próximas dos valores finais reais, geralmente, apenas algumas iterações com o método exato de máxima verossimilhança (3. Acima) são Necessário finalizar as estimativas dos parâmetros. Parámetros de erros padrão. Para todas as estimativas de parâmetros, você calculará os chamados erros padrão assintóticos. Estes são calculados a partir da matriz de derivadas parciais de segunda ordem que é aproximada por diferenciação finita (veja também a respectiva discussão na Estimação Não-Linear). Valor de pênalti. Conforme mencionado acima, o procedimento de estimação requer que as somas (condicionais) dos quadrados dos resíduos ARIMA sejam minimizadas. Se o modelo for inadequado, pode ocorrer durante o processo de estimação iterativo que as estimativas dos parâmetros se tornem muito grandes e, de fato, inválidas. Nesse caso, ele atribuirá um valor muito grande (um chamado valor de penalidade) ao SS. Isso geralmente atrai o processo de iteração para mover os parâmetros longe de intervalos inválidos. No entanto, em alguns casos, mesmo esta estratégia falha, e você pode ver na tela (durante o procedimento de Estimativa) valores muito grandes para SS em iterações consecutivas. Nesse caso, avalie cuidadosamente a adequação do seu modelo. Se o seu modelo contém muitos parâmetros, e talvez um componente de intervenção (veja abaixo), você pode tentar novamente com diferentes valores de inicialização de parâmetros. Avaliação das estimativas dos parâmetros do modelo. Você relatará valores t aproximados, calculados a partir dos erros padrão do parâmetro (veja acima). Se não for significativo, o respectivo parâmetro pode, na maioria dos casos, ser descartado do modelo sem afetar substancialmente o ajuste geral do modelo. Outros critérios de qualidade. Outra medida direta e comum da confiabilidade do modelo é a precisão de suas previsões geradas com base em dados parciais para que as previsões possam ser comparadas com observações (originais) conhecidas. No entanto, um bom modelo não deve apenas fornecer previsões suficientemente precisas, também deve ser parcimonioso e produzir resíduos estatisticamente independentes que contenham apenas ruído e nenhum componente sistemático (por exemplo, o correlograma de resíduos não deve revelar dependências em série). Um bom teste do modelo é (a) traçar os resíduos e inspecioná-los para quaisquer tendências sistemáticas, e (b) examinar o autocorrelograma dos resíduos (não deve haver dependência serial entre os resíduos). Análise de resíduos. A principal preocupação aqui é que os resíduos são sistematicamente distribuídos em toda a série (por exemplo, eles podem ser negativos na primeira parte da série e aproximar zero na segunda parte) ou que eles contêm alguma dependência serial que pode sugerir que o modelo ARIMA é Insuficiente. A análise dos resíduos ARIMA constitui um teste importante do modelo. O procedimento de estimativa pressupõe que os resíduos não são correlacionados (auto-) e que são normalmente distribuídos. Limitações. O método ARIMA é apropriado somente para uma série de tempo que é estacionária (isto é, sua média, variância e autocorrelação devem ser aproximadamente constantes ao longo do tempo) e recomenda-se que haja pelo menos 50 observações nos dados de entrada. Também é assumido que os valores dos parâmetros estimados são constantes em toda a série. Série de tempo interrompido ARIMA Uma questão de pesquisa comum na análise de séries temporais é se um evento externo afetou observações subsequentes. Por exemplo, a implementação de uma nova política econômica melhorou o desempenho econômico, uma nova lei anti-crime afetou as taxas de criminalidade subsequentes e assim por diante. Em geral, gostaríamos de avaliar o impacto de um ou mais eventos discretos nos valores das séries temporais. Este tipo de análise de séries temporais interrompidas é descrito em detalhes em McDowall, McCleary, Meidinger, Hay (1980). McDowall, et. Al. Distinguir entre três tipos principais de impactos que são possíveis: (1) abrupto permanente, (2) permanente gradual e (3) temporário abrupto. Veja também: Identificando Padrões em Dados da Série de Tempo ARIMA Suposição Exponencial Decomposição Sazonal (Censo I) X-11 Método do Censo II ajuste sazonal X-11 Método do Censo II tabelas de resultados Análise de Lags Distribuído Análise de Espectro Único (Fourier) Análise de Cross-spectrum Noções básicas e Princípios Transformações rápidas de Fourier O alisamento exponencial tornou-se muito popular como um método de previsão para uma grande variedade de dados de séries temporais. Historicamente, o método foi desenvolvido independentemente por Brown e Holt. Brown trabalhou para a Marinha dos EUA durante a Segunda Guerra Mundial, onde sua tarefa era projetar um sistema de rastreamento para informações de controle de fogo para calcular a localização dos submarinos. Mais tarde, ele aplicou essa técnica para a previsão de demanda de peças sobressalentes (um problema de controle de estoque). Ele descreveu essas idéias em seu livro de 1959 sobre controle de estoque. A pesquisa Holts foi patrocinada independentemente pelo Office of Naval Research, desenvolveu modelos exponenciais de suavização para processos constantes, processos com tendências lineares e dados sazonais. Gardner (1985) propôs uma classificação quotunifiedquot de métodos de suavização exponencial. Excelentes apresentações também podem ser encontradas em Makridakis, Wheelwright e McGee (1983), Makridakis e Wheelwright (1989), Montgomery, Johnson, amp Gardiner (1990). Suavização exponencial simples Um modelo simples e pragmático para uma série de tempo seria considerar cada observação como constituída por um componente constante (b) e um componente de erro (epsilon), isto é: X t b t. A constante b é relativamente estável em cada segmento da série, mas pode mudar lentamente ao longo do tempo. Se apropriado, então uma maneira de isolar o valor verdadeiro de b. E, portanto, a parte sistemática ou previsível da série, é calcular um tipo de média móvel, onde as observações atuais e imediatamente anteriores (quotyounger) são atribuídas maior peso do que as respectivas observações mais antigas. O alisamento exponencial simples cumpre exatamente essa ponderação, onde pesos exponencialmente menores são atribuídos a observações mais antigas. A fórmula específica para suavização exponencial simples é: quando aplicado de forma recursiva a cada observação sucessiva da série, cada novo valor suavizado (previsão) é calculado como a média ponderada da observação atual e a observação suavizada anterior, a observação suavizada anterior foi calculada por sua vez Do valor observado anterior e do valor suavizado antes da observação anterior, e assim por diante. Assim, de fato, cada valor suavizado é a média ponderada das observações anteriores, em que os pesos diminuem exponencialmente dependendo do valor do parâmetro (alfa). Se é igual a 1 (uma), as observações anteriores são ignoradas inteiramente se for igual a 0 (zero), então a observação atual é ignorada inteiramente, e o valor suavizado consiste inteiramente no valor suavizado anterior (que por sua vez é calculado a partir de A observação suavizada antes dele, e assim por diante, todos os valores suavizados serão iguais ao valor suavizado inicial S 0). Valores do intermediário produzirão resultados intermédios. Mesmo que tenha sido feito um trabalho significativo para estudar as propriedades teóricas do alisamento exponencial (simples e complexo) (por exemplo, ver Gardner, 1985 Muth, 1960, veja também McKenzie, 1984, 1985), o método ganhou popularidade principalmente por sua utilidade como um Ferramenta de previsão. Por exemplo, pesquisa empírica de Makridakis et al. (1982, Makridakis, 1983), mostrou que o alisamento exponencial simples é a melhor opção para a previsão de um período de antecedência, dentre os outros 24 métodos de séries temporais e usando uma variedade de medidas de precisão (ver também Gross e Craig, 1974, para Evidência empírica adicional). Assim, independentemente do modelo teórico para o processo subjacente às séries temporais observadas, o alisamento exponencial simples geralmente produzirá previsões bastante precisas. Escolhendo o melhor valor para o parâmetro (alfa) Gardner (1985) discute vários argumentos teóricos e empíricos para selecionar um parâmetro de suavização apropriado. Obviamente, olhando para a fórmula apresentada acima, deve cair no intervalo entre 0 (zero) e 1 (embora, veja Brenner et al., 1968, para uma perspectiva ARIMA, implicando 0lt lt2). Gardner (1985) relata que, entre os praticantes, geralmente é recomendável um menor que 0,30. No entanto, no estudo de Makridakis et al. (1982), valores acima de 0,30 freqüentemente renderam as melhores previsões. Depois de revisar a literatura sobre este tema, Gardner (1985) conclui que é melhor estimar um ótimo dos dados (veja abaixo), em vez de adivinhar e definir um valor artificialmente baixo. Estimando o melhor valor a partir dos dados. Na prática, o parâmetro de suavização é muitas vezes escolhido por uma pesquisa em grade do espaço de parâmetros que é, soluções diferentes para tentativas iniciadas, por exemplo, com 0,1 a 0,9, com incrementos de 0,1. Em seguida, é escolhido para produzir as menores somas de quadrados (ou quadrados médios) para os resíduos (ou seja, valores observados menos previsões de um passo a frente, este erro quadrado médio também é referido como erro quadrático médio ex post, MSE ex post para curto). Índices de falta de ajuste (Erro) A maneira mais direta de avaliar a precisão das previsões com base em um valor específico é simplesmente traçar os valores observados e as previsões passo a passo. Esta trama também pode incluir os resíduos (escalados contra o eixo direito de Y), de modo que as regiões de melhor ou pior ajuste também podem ser facilmente identificadas. This visual check of the accuracy of forecasts is often the most powerful method for determining whether or not the current exponential smoothing model fits the data. In addition, besides the ex post MSE criterion (see previous paragraph), there are other statistical measures of error that can be used to determine the optimum parameter (see Makridakis, Wheelwright, and McGee, 1983): Mean error: The mean error (ME) value is simply computed as the average error value (average of observed minus one-step-ahead forecast). Obviously, a drawback of this measure is that positive and negative error values can cancel each other out, so this measure is not a very good indicator of overall fit. Mean absolute error: The mean absolute error (MAE) value is computed as the average absolute error value. If this value is 0 (zero), the fit (forecast) is perfect. As compared to the mean squared error value, this measure of fit will de-emphasize outliers, that is, unique or rare large error values will affect the MAE less than the MSE value. Sum of squared error (SSE), Mean squared error. These values are computed as the sum (or average) of the squared error values. This is the most commonly used lack-of-fit indicator in statistical fitting procedures. Percentage error (PE). All the above measures rely on the actual error value. It may seem reasonable to rather express the lack of fit in terms of the relative deviation of the one-step-ahead forecasts from the observed values, that is, relative to the magnitude of the observed values. For example, when trying to predict monthly sales that may fluctuate widely (e. g. seasonally) from month to month, we may be satisfied if our prediction quothits the targetquot with about 10 accuracy. In other words, the absolute errors may be not so much of interest as are the relative errors in the forecasts. To assess the relative error, various indices have been proposed (see Makridakis, Wheelwright, and McGee, 1983). The first one, the percentage error value, is computed as: where X t is the observed value at time t . and F t is the forecasts (smoothed values). Mean percentage error (MPE). This value is computed as the average of the PE values. Mean absolute percentage error (MAPE). As is the case with the mean error value (ME, see above), a mean percentage error near 0 (zero) can be produced by large positive and negative percentage errors that cancel each other out. Thus, a better measure of relative overall fit is the mean absolute percentage error. Also, this measure is usually more meaningful than the mean squared error. For example, knowing that the average forecast is off by 5 is a useful result in and of itself, whereas a mean squared error of 30.8 is not immediately interpretable. Automatic search for best parameter. A quasi-Newton function minimization procedure (the same as in ARIMA is used to minimize either the mean squared error, mean absolute error, or mean absolute percentage error. In most cases, this procedure is more efficient than the grid search (particularly when more than one parameter must be determined), and the optimum parameter can quickly be identified. The first smoothed value S 0 . A final issue that we have neglected up to this point is the problem of the initial value, or how to start the smoothing process. If you look back at the formula above, it is evident that one needs an S 0 value in order to compute the smoothed value (forecast) for the first observation in the series. Depending on the choice of the parameter (i. e. when is close to zero), the initial value for the smoothing process can affect the quality of the forecasts for many observations. As with most other aspects of exponential smoothing it is recommended to choose the initial value that produces the best foreca sts. On the other hand, in practice, when there are many leading observations prior to a crucial actual forecast, the initial value will not affect that forecast by much, since its effect will have long faded from the smoothed series (due to the exponentially decreasing weights, the older an observation the less it will influence the forecast). Seasonal and Non-seasonal Models With or Without Trend The discussion above in the context of simple exponential smoothing introduced the basic procedure for identifying a smoothing parameter, and for evaluating the goodness-of-fit of a model. In addition to simple exponential smoothing, more complex models have been developed to accommodate time series with seasonal and trend components. The general idea here is that forecasts are not only computed from consecutive previous observations (as in simple exponential smoothing), but an independent (smoothed) trend and seasonal component can be added. Gardner (1985) discusses the different models in terms of seasonality (none, additive, or multiplicative) and trend (none, linear, exponential, or damped). Additive and multiplicative seasonality. Many time series data follow recurring seasonal patterns. For example, annual sales of toys will probably peak in the months of November and December, and perhaps during the summer (with a much smaller peak) when children are on their summer break. This pattern will likely repeat every year, however, the relative amount of increase in sales during December may slowly change from year to year. Thus, it may be useful to smooth the seasonal component independently with an extra parameter, usually denoted as ( delta ). Seasonal components can be additive in nature or multiplicative. For example, during the month of December the sales for a particular toy may increase by 1 million dollars every year. Thus, we could add to our forecasts for every December the amount of 1 million dollars (over the respective annual average) to account for this seasonal fluctuation. In this case, the seasonality is additive . Alternatively, during the month of December the sales for a particular toy may increase by 40, that is, increase by a factor of 1.4. Thus, when the sales for the toy are generally weak, than the absolute (dollar) increase in sales during December will be relatively weak (but the percentage will be constant) if the sales of the toy are strong, than the absolute (dollar) increase in sales will be proportionately greater. Again, in this case the sales increase by a certain factor . and the seasonal component is thus multiplicative in nature (i. e. the multiplicative seasonal component in this case would be 1.4). In plots of the series, the distinguishing characteristic between these two types of seasonal components is that in the additive case, the series shows steady seasonal fluctuations, regardless of the overall level of the series in the multiplicative case, the size of the seasonal fluctuations vary, depending on the overall level of the series. The seasonal smoothing parameter . In general the one-step-ahead forecasts are computed as (for no trend models, for linear and exponential trend models a trend component is added to the model see below): In this formula, S t stands for the (simple) exponentially smoothed value of the series at time t . and I t-p stands for the smoothed seasonal factor at time t minus p (the length of the season). Thus, compared to simple exponential smoothing, the forecast is quotenhancedquot by adding or multiplying the simple smoothed value by the predicted seasonal component. This seasonal component is derived analogous to the S t value from simple exponential smoothing as: Put in words, the predicted seasonal component at time t is computed as the respective seasonal component in the last seasonal cycle plus a portion of the error ( e t the observed minus the forecast value at time t ). Considering the formulas above, it is clear that parameter can assume values between 0 and 1. If it is zero, then the seasonal component for a particular point in time is predicted to be identical to the predicted seasonal component for the respective time during the previous seasonal cycle, which in turn is predicted to be identical to that from the previous cycle, and so on. Thus, if is zero, a constant unchanging seasonal component is used to generate the one-step-ahead forecasts. If the parameter is equal to 1, then the seasonal component is modified quotmaximallyquot at every step by the respective forecast error (times (1- ). which we will ignore for the purpose of this brief introduction). In most cases, when seasonality is present in the time series, the optimum parameter will fall somewhere between 0 (zero) and 1(one). Linear, exponential, and damped trend. To remain with the toy example above, the sales for a toy can show a linear upward trend (e. g. each year, sales increase by 1 million dollars), exponential growth (e. g. each year, sales increase by a factor of 1.3), or a damped trend (during the first year sales increase by 1 million dollars during the second year the increase is only 80 over the previous year, i. e. 800,000 during the next year it is again 80 less than the previous year, i. e. 800,000 .8 640,000 etc.). Each type of trend leaves a clear quotsignaturequot that can usually be identified in the series shown below in the brief discussion of the different models are icons that illustrate the general patterns. In general, the trend factor may change slowly over time, and, again, it may make sense to smooth the trend component with a separate parameter (denoted gamma for linear and exponential trend models, and phi for damped trend models). The trend smoothing parameters (linear and exponential trend) and (damped trend). Analogous to the seasonal component, when a trend component is included in the exponential smoothing process, an independent trend component is computed for each time, and modified as a function of the forecast error and the respective parameter. If the parameter is 0 (zero), than the trend component is constant across all values of the time series (and for all forecasts). If the parameter is 1, then the trend component is modified maximally from observation to observation by the respective forecast error. Parameter values that fall in-between represent mixtures of those two extremes. Parameter is a trend modification parameter, and affects how strongly changes in the trend will affect estimates of the trend for subsequent forecasts, that is, how quickly the trend will be damped or increased. Suppose you recorded the monthly passenger load on international flights for a period of 12 years ( see Box amp Jenkins, 1976). If you plot those data, it is apparent that (1) there appears to be a linear upwards trend in the passenger loads over the years, and (2) there is a recurring pattern or seasonality within each year (i. e. most travel occurs during the summer months, and a minor peak occurs during the December holidays). The purpose of the seasonal decomposition method is to isolate those components, that is, to de-compose the series into the trend effect, seasonal effects, and remaining variability. The quotclassicquot technique designed to accomplish this decomposition is known as the Census I method. This technique is described and discussed in detail in Makridakis, Wheelwright, and McGee (1983), and Makridakis and Wheelwright (1989). General model. The general idea of seasonal decomposition is straightforward. In general, a time series like the one described above can be thought of as consisting of four different components: (1) A seasonal component (denoted as S t . where t stands for the particular point in time) (2) a trend component ( T t ), (3) a cyclical component ( C t ), and (4) a random, error, or irregular component ( I t ). The difference between a cyclical and a seasonal component is that the latter occurs at regular (seasonal) intervals, while cyclical factors have usually a longer duration that varies from cycle to cycle. In the Census I method, the trend and cyclical components are customarily combined into a trend-cycle component ( TC t ). The specific functional relationship between these components can assume different forms. However, two straightforward possibilities are that they combine in an additive or a multiplicative fashion: Here X t stands for the observed value of the time series at time t . Given some a priori knowledge about the cyclical factors affecting the series (e. g. business cycles), the estimates for the different components can be used to compute forecasts for future observations. (However, the Exponential smoothing method, which can also incorporate seasonality and trend components, is the preferred technique for forecasting purposes.) Additive and multiplicative seasonality . Let us consider the difference between an additive and multiplicative seasonal component in an example: The annual sales of toys will probably peak in the months of November and December, and perhaps during the summer (with a much smaller peak) when children are on their summer break. This seasonal pattern will likely repeat every year. Seasonal components can be additive or multiplicative in nature. For example, during the month of December the sales for a particular toy may increase by 3 million dollars every year. Thus, we could add to our forecasts for every December the amount of 3 million to account for this seasonal fluctuation. In this case, the seasonality is additive . Alternatively, during the month of December the sales for a particular toy may increase by 40, that is, increase by a factor of 1.4. Thus, when the sales for the toy are generally weak, then the absolute (dollar) increase in sales during December will be relatively weak (but the percentage will be constant) if the sales of the toy are strong, then the absolute (dollar) increase in sales will be proportionately greater. Again, in this case the sales increase by a certain factor . and the seasonal component is thus multiplicative in nature (i. e. the multiplicative seasonal component in this case would be 1.4). In plots of series, the distinguishing characteristic between these two types of seasonal components is that in the additive case, the series shows steady seasonal fluctuations, regardless of the overall level of the series in the multiplicative case, the size of the seasonal fluctuations vary, depending on the overall level of the series. Additive and multiplicative trend-cycle. We can extend the previous example to illustrate the additive and multiplicative trend-cycle components. In terms of our toy example, a fashion trend may produce a steady increase in sales (e. g. a trend towards more educational toys in general) as with the seasonal component, this trend may be additive (sales increase by 3 million dollars per year) or multiplicative (sales increase by 30, or by a factor of 1.3, annually) in nature. In addition, cyclical components may impact sales to reiterate, a cyclical component is different from a seasonal component in that it usually is of longer duration, and that it occurs at irregular intervals. For example, a particular toy may be particularly hot during a summer season (e. g. a particular doll which is tied to the release of a major childrens movie, and is promoted with extensive advertising). Again such a cyclical component can effect sales in an additive manner or multiplicative manner. The Seasonal Decomposition (Census I) standard formulas are shown in Makridakis, Wheelwright, and McGee (1983), and Makridakis and Wheelwright (1989). Média móvel. First a moving average is computed for the series, with the moving average window width equal to the length of one season. If the length of the season is even, then the user can choose to use either equal weights for the moving average or unequal weights can be used, where the first and last observation in the moving average window are averaged. Ratios or differences. In the moving average series, all seasonal (within-season) variability will be eliminated thus, the differences (in additive models) or ratios (in multiplicative models) of the observed and smoothed series will isolate the seasonal component (plus irregular component). Specifically, the moving average is subtracted from the observed series (for additive models) or the observed series is divided by the moving average values (for multiplicative models). Seasonal components. The seasonal component is then computed as the average (for additive models) or medial average (for multiplicative models) for each point in the season. (The medial average of a set of values is the mean after the smallest and largest values are excluded). The resulting values represent the (average) seasonal component of the series. Seasonally adjusted series. The original series can be adjusted by subtracting from it (additive models) or dividing it by (multiplicative models) the seasonal component. The resulting series is the seasonally adjusted series (i. e. the seasonal component will be removed). Trend-cycle component. Remember that the cyclical component is different from the seasonal component in that it is usually longer than one season, and different cycles can be of different lengths. The combined trend and cyclical component can be approximated by applying to the seasonally adjusted series a 5 point (centered) weighed moving average smoothing transformation with the weights of 1, 2, 3, 2, 1. Random or irregular component. Finally, the random or irregular (error) component can be isolated by subtracting from the seasonally adjusted series (additive models) or dividing the adjusted series by (multiplicative models) the trend-cycle component. X-11 Census Method II Seasonal Adjustment The general ideas of seasonal decomposition and adjustment are discussed in the context of the Census I seasonal adjustment method ( Seasonal Decomposition (Census I) ). The Census method II (2) is an extension and refinement of the simple adjustment method. Over the years, different versions of the Census method II evolved at the Census Bureau the method that has become most popular and is used most widely in government and business is the so-called X-11 variant of the Census method II (see Hiskin, Young, Musgrave, 1967). Subsequently, the term X-11 has become synonymous with this refined version of the Census method II. In addition to the documentation that can be obtained from the Census Bureau, a detailed summary of this method is also provided in Makridakis, Wheelwright, and McGee (1983) and Makridakis and Wheelwright (1989). Suppose you recorded the monthly passenger load on international flights for a period of 12 years ( see Box Jenkins, 1976). If you plot those data, it is apparent that (1) there appears to be an upwards linear trend in the passenger loads over the years, and (2) there is a recurring pattern or seasonality within each year (i. e. most travel occurs during the summer months, and a minor peak occurs during the December holidays). The purpose of seasonal decomposition and adjustment is to isolate those components, that is, to de-compose the series into the trend effect, seasonal effects, and remaining variability. The classic technique designed to accomplish this decomposition was developed in the 1920s and is also known as the Census I method (see the Census I overview section). This technique is also described and discussed in detail in Makridakis, Wheelwright, and McGee (1983), and Makridakis and Wheelwright (1989). General model. The general idea of seasonal decomposition is straightforward. In general, a time series like the one described above can be thought of as consisting of four different components: (1) A seasonal component (denoted as S t . where t stands for the particular point in time) (2) a trend component ( T t ), (3) a cyclical component ( C t ), and (4) a random, error, or irregular component ( I t ). The difference between a cyclical and a seasonal component is that the latter occurs at regular (seasonal) intervals, while cyclical factors usually have a longer duration that varies from cycle to cycle. The trend and cyclical components are customarily combined into a trend-cycle component ( TC t ). The specific functional relationship between these components can assume different forms. However, two straightforward possibilities are that they combine in an additive or a multiplicative fashion: X t represents the observed value of the time series at time t . Given some a priori knowledge about the cyclical factors affecting the series (e. g. business cycles), the estimates for the different components can be used to compute forecasts for future observations. (However, the Exponential smoothing method, which can also incorporate seasonality and trend components, is the preferred technique for forecasting purposes.) Additive and multiplicative seasonality. Consider the difference between an additive and multiplicative seasonal component in an example: The annual sales of toys will probably peak in the months of November and December, and perhaps during the summer (with a much smaller peak) when children are on their summer break. This seasonal pattern will likely repeat every year. Seasonal components can be additive or multiplicative in nature. For example, during the month of December the sales for a particular toy may increase by 3 million dollars every year. Thus, you could add to your forecasts for every December the amount of 3 million to account for this seasonal fluctuation. In this case, the seasonality is additive . Alternatively, during the month of December the sales for a particular toy may increase by 40, that is, increase by a factor of 1.4. Thus, when the sales for the toy are generally weak, then the absolute (dollar) increase in sales during December will be relatively weak (but the percentage will be constant) if the sales of the toy are strong, then the absolute (dollar) increase in sales will be proportionately greater. Again, in this case the sales increase by a certain factor . and the seasonal component is thus multiplicative in nature (i. e. the multiplicative seasonal component in this case would be 1.4). In plots of series, the distinguishing characteristic between these two types of seasonal components is that in the additive case, the series shows steady seasonal fluctuations, regardless of the overall level of the series in the multiplicative case, the size of the seasonal fluctuations vary, depending on the overall level of the series. Additive and multiplicative trend-cycle. The previous example can be extended to illustrate the additive and multiplicative trend-cycle components. In terms of the toy example, a fashion trend may produce a steady increase in sales (e. g. a trend towards more educational toys in general) as with the seasonal component, this trend may be additive (sales increase by 3 million dollars per year) or multiplicative (sales increase by 30, or by a factor of 1.3, annually) in nature. In addition, cyclical components may impact sales. To reiterate, a cyclical component is different from a seasonal component in that it usually is of longer duration, and that it occurs at irregular intervals. For example, a particular toy may be particularly hot during a summer season (e. g. a particular doll which is tied to the release of a major childrens movie, and is promoted with extensive advertising). Again such a cyclical component can effect sales in an additive manner or multiplicative manner. The Census II Method The basic method for seasonal decomposition and adjustment outlined in the Basic Ideas and Terms topic can be refined in several ways. In fact, unlike many other time-series modeling techniques (e. g. ARIMA ) which are grounded in some theoretical model of an underlying process, the X-11 variant of the Census II method simply contains many ad hoc features and refinements, that over the years have proven to provide excellent estimates for many real-world applications (see Burman, 1979, Kendal Ord, 1990, Makridakis Wheelwright, 1989 Wallis, 1974). Some of the major refinements are listed below. Trading-day adjustment. Different months have different numbers of days, and different numbers of trading-days (i. e. Mondays, Tuesdays, etc.). When analyzing, for example, monthly revenue figures for an amusement park, the fluctuation in the different numbers of Saturdays and Sundays (peak days) in the different months will surely contribute significantly to the variability in monthly revenues. The X-11 variant of the Census II method allows the user to test whether such trading-day variability exists in the series, and, if so, to adjust the series accordingly. Extreme values. Most real-world time series contain outliers, that is, extreme fluctuations due to rare events. For example, a strike may affect production in a particular month of one year. Such extreme outliers may bias the estimates of the seasonal and trend components. The X-11 procedure includes provisions to deal with extreme values through the use of quotstatistical control principles, quot that is, values that are above or below a certain range (expressed in terms of multiples of sigma . the standard deviation) can be modified or dropped before final estimates for the seasonality are computed. Multiple refinements. The refinement for outliers, extreme values, and different numbers of trading-days can be applied more than once, in order to obtain successively improved estimates of the components. The X-11 method applies a series of successive refinements of the estimates to arrive at the final trend-cycle, seasonal, and irregular components, and the seasonally adjusted series. Tests and summary statistics. In addition to estimating the major components of the series, various summary statistics can be computed. For example, analysis of variance tables can be prepared to test the significance of seasonal variability and trading-day variability (see above) in the series the X-11 procedure will also compute the percentage change from month to month in the random and trend-cycle components. As the duration or span in terms of months (or quarters for quarterly X-11 ) increases, the change in the trend-cycle component will likely also increase, while the change in the random component should remain about the same. The width of the average span at which the changes in the random component are about equal to the changes in the trend-cycle component is called the month (quarter) for cyclical dominance . or MCD (QCD) for short. For example, if the MCD is equal to 2 then one can infer that over a 2 month span the trend-cycle will dominate the fluctuations of the irregular (random) component. These and various other results are discussed in greater detail below. Result Tables Computed by the X-11 Method The computations performed by the X-11 procedure are best discussed in the context of the results tables that are reported. The adjustment process is divided into seven major steps, which are customarily labeled with consecutive letters A through G. Prior adjustment (monthly seasonal adjustment only). Before any seasonal adjustment is performed on the monthly time series, various prior user - defined adjustments can be incorporated. The user can specify a second series that contains prior adjustment factors the values in that series will either be subtracted (additive model) from the original series, or the original series will be divided by these values (multiplicative model). For multiplicative models, user-specified trading-day adjustment weights can also be specified. These weights will be used to adjust the monthly observations depending on the number of respective trading-days represented by the observation. Preliminary estimation of trading-day variation (monthly X-11) and weights. Next, preliminary trading-day adjustment factors (monthly X-11 only) and weights for reducing the effect of extreme observations are computed. Final estimation of trading-day variation and irregular weights (monthly X - 11 ). The adjustments and weights computed in B above are then used to derive improved trend-cycle and seasonal estimates. These improved estimates are used to compute the final trading-day factors (monthly X-11 only) and weights. Final estimation of seasonal factors, trend-cycle, irregular, and seasonally adjusted series. The final trading-day factors and weights computed in C above are used to compute the final estimates of the components. Modified original, seasonally adjusted, and irregular series. The original and final seasonally adjusted series, and the irregular component are modified for extremes. The resulting modified series allow the user to examine the stability of the seasonal adjustment. Month (quarter) for cyclical dominance (MCD, QCD), moving average, and summary measures. In this part of the computations, various summary measures (see below) are computed to allow the user to examine the relative importance of the different components, the average fluctuation from month-to-month (quarter-to-quarter), the average number of consecutive changes in the same direction (average number of runs), etc. Charts. Finally, you will compute various charts (graphs) to summarize the results. For example, the final seasonally adjusted series will be plotted, in chronological order, or by month (see below). Specific Description of all Result Tables Computed by the X-11 Method In each part A through G of the analysis (see Results Tables Computed by the X-11 Method ), different result tables are computed. Customarily, these tables are numbered, and also identified by a letter to indicate the respective part of the analysis. For example, table B 11 shows the initial seasonally adjusted series C 11 is the refined seasonally adjusted series, and D 11 is the final seasonally adjusted series. Shown below is a list of all available tables. Those tables identified by an asterisk () are not available (applicable) when analyzing quarterly series. (Also, for quarterly adjustment, some of the computations outlined below are slightly different for example instead of a 12-term monthly moving average, a 4-term quarterly moving average is applied to compute the seasonal factors the initial trend-cycle estimate is computed via a centered 4-term moving average, the final trend-cycle estimate in each part is computed by a 5-term Henderson average.) Following the convention of the Bureau of the Census version of the X-11 method, three levels of printout detail are offered: Standard (17 to 27 tables), Long (27 to 39 tables), and Full (44 to 59 tables). In the description of each table below, the letters S, L, and F are used next to each title to indicate, which tables will be displayed andor printed at the respective setting of the output option. (For the charts, two levels of detail are available: Standard and All .) See the table name below, to obtain more information about that table. A 2. Prior Monthly Adjustment (S) Factors Tables B 14 through B 16, B18, and B19: Adjustment for trading-day variation. These tables are only available when analyzing monthly series. Different months contain different numbers of days of the week (i. e. Mondays, Tuesdays, etc.). In some series, the variation in the different numbers of trading-days may contribute significantly to monthly fluctuations (e. g. the monthly revenues of an amusement park will be greatly influenced by the number of SaturdaysSundays in each month). The user can specify initial weights for each trading-day (see A 4 ), andor these weights can be estimated from the data (the user can also choose to apply those weights conditionally, i. e. only if they explain a significant proportion of variance). B 14. Extreme Irregular Values Excluded from Trading-day Regression (L) B 15. Preliminary Trading-day Regression (L) B 16. Trading-day Adjustment Factors Derived from Regression Coefficients (F) B 17. Preliminary Weights for Irregular Component (L) B 18. Trading-day Factors Derived from Combined Daily Weights (F) B 19. Original Series Adjusted for Trading-day and Prior Variation (F) C 1. Original Series Modified by Preliminary Weights and Adjusted for Trading-day and Prior Variation (L) Tables C 14 through C 16, C 18, and C 19: Adjustment for trading-day variation. These tables are only available when analyzing monthly series, and when adjustment for trading-day variation is requested. In that case, the trading-day adjustment factors are computed from the refined adjusted series, analogous to the adjustment performed in part B ( B 14 through B 16, B 18 and B 19 ). C 14. Extreme Irregular Values Excluded from Trading-day Regression (S) C 15. Final Trading-day Regression (S) C 16. Final Trading-day Adjustment Factors Derived from Regression X11 output: Coefficients (S) C 17. Final Weights for Irregular Component (S) C 18. Final Trading-day Factors Derived From Combined Daily Weights (S) C 19. Original Series Adjusted for Trading-day and Prior Variation (S) D 1. Original Series Modified by Final Weights and Adjusted for Trading-day and Prior Variation (L) Distributed lags analysis is a specialized technique for examining the relationships between variables that involve some delay. For example, suppose that you are a manufacturer of computer software, and you want to determine the relationship between the number of inquiries that are received, and the number of orders that are placed by your customers. You could record those numbers monthly for a one year period, and then correlate the two variables. However, obviously inquiries will precede actual orders, and one can expect that the number of orders will follow the number of inquiries with some delay. Put another way, there will be a (time) lagged correlation between the number of inquiries and the number of orders that are received. Time-lagged correlations are particularly common in econometrics. For example, the benefits of investments in new machinery usually only become evident after some time. Higher income will change peoples choice of rental apartments, however, this relationship will be lagged because it will take some time for people to terminate their current leases, find new apartments, and move. In general, the relationship between capital appropriations and capital expenditures will be lagged, because it will require some time before investment decisions are actually acted upon. In all of these cases, we have an independent or explanatory variable that affects the dependent variables with some lag. The distributed lags method allows you to investigate those lags. Detailed discussions of distributed lags correlation can be found in most econometrics textbooks, for example, in Judge, Griffith, Hill, Luetkepohl, and Lee (1985), Maddala (1977), and Fomby, Hill, and Johnson (1984). In the following paragraphs we will present a brief description of these methods. We will assume that you are familiar with the concept of correlation (see Basic Statistics ), and the basic ideas of multiple regression (see Multiple Regression ). Suppose we have a dependent variable y and an independent or explanatory variable x which are both measured repeatedly over time. In some textbooks, the dependent variable is also referred to as the endogenous variable, and the independent or explanatory variable the exogenous variable. The simplest way to describe the relationship between the two would be in a simple linear relationship: In this equation, the value of the dependent variable at time t is expressed as a linear function of x measured at times t. t-1. t-2 . etc. Thus, the dependent variable is a linear function of x . and x is lagged by 1, 2 . etc. time periods. The beta weights ( i ) can be considered slope parameters in this equation. You may recognize this equation as a special case of the general linear regression equation (see the Multiple Regression overview). If the weights for the lagged time periods are statistically significant, we can conclude that the y variable is predicted (or explained) with the respective lag. Almon Distributed Lag A common problem that often arises when computing the weights for the multiple linear regression model shown above is that the values of adjacent (in time) values in the x variable are highly correlated. In extreme cases, their independent contributions to the prediction of y may become so redundant that the correlation matrix of measures can no longer be inverted, and thus, the beta weights cannot be computed. In less extreme cases, the computation of the beta weights and their standard errors can become very imprecise, due to round-off error. In the context of Multiple Regression this general computational problem is discussed as the multicollinearity or matrix ill-conditioning issue. Almon (1965) proposed a procedure that will reduce the multicollinearity in this case. Specifically, suppose we express each weight in the linear regression equation in the following manner: Almon could show that in many cases it is easier (i. e. it avoids the multicollinearity problem) to estimate the alpha values than the beta weights directly. Note that with this method, the precision of the beta weight estimates is dependent on the degree or order of the polynomial approximation . Misspecifications. A general problem with this technique is that, of course, the lag length and correct polynomial degree are not known a priori . The effects of misspecifications of these parameters are potentially serious (in terms of biased estimation). This issue is discussed in greater detail in Frost (1975), Schmidt and Waud (1973), Schmidt and Sickles (1975), and Trivedi and Pagan (1979). Single Spectrum (Fourier) Analysis Spectrum analysis is concerned with the exploration of cyclical patterns of data. The purpose of the analysis is to decompose a complex time series with cyclical components into a few underlying sinusoidal (sine and cosine) functions of particular wavelengths. The term quotspectrumquot provides an appropriate metaphor for the nature of this analysis: Suppose you study a beam of white sun light, which at first looks like a random (white noise) accumulation of light of different wavelengths. However, when put through a prism, we can separate the different wave lengths or cyclical components that make up white sun light. In fact, via this technique we can now identify and distinguish between different sources of light. Thus, by identifying the important underlying cyclical components, we have learned something about the phenomenon of interest. In essence, performing spectrum analysis on a time series is like putting the series through a prism in order to identify the wave lengths and importance of underlying cyclical components. As a result of a successful analysis one might uncover just a few recurring cycles of different lengths in the time series of interest, which at first looked more or less like random noise. A much cited example for spectrum analysis is the cyclical nature of sun spot activity (e. g. see Bloomfield, 1976, or Shumway, 1988). It turns out that sun spot activity varies over 11 year cycles. Other examples of celestial phenomena, weather patterns, fluctuations in commodity prices, economic activity, etc. are also often used in the literature to demonstrate this technique. To contrast this technique with ARIMA or Exponential Smoothing. the purpose of spectrum analysis is to identify the seasonal fluctuations of different lengths, while in the former types of analysis, the length of the seasonal component is usually known (or guessed) a priori and then included in some theoretical model of moving averages or autocorrelations. The classic text on spectrum analysis is Bloomfield (1976) however, other detailed discussions can be found in Jenkins and Watts (1968), Brillinger (1975), Brigham (1974), Elliott and Rao (1982), Priestley (1981), Shumway (1988), or Wei (1989). Cross-spectrum analysis is an extension of Single Spectrum (Fourier) Analysis to the simultaneous analysis of two series. In the following paragraphs, we will assume that you have already read the introduction to single spectrum analysis. Detailed discussions of this technique can be found in Bloomfield (1976), Jenkins and Watts (1968), Brillinger (1975), Brigham (1974), Elliott and Rao (1982), Priestley (1981), Shumway (1988), or Wei (1989). Strong periodicity in the series at the respective frequency. A much cited example for spectrum analysis is the cyclical nature of sun spot activity (e. g. see Bloomfield, 1976, or Shumway, 1988). It turns out that sun spot activity varies over 11 year cycles. Other examples of celestial phenomena, weather patterns, fluctuations in commodity prices, economic activity, etc. are also often used in the literature to demonstrate this technique. The purpose of cross-spectrum analysis is to uncover the correlations between two series at different frequencies. For example, sun spot activity may be related to weather phenomena here on earth. If so, then if we were to record those phenomena (e. g. yearly average temperature) and submit the resulting series to a cross-spectrum analysis together with the sun spot data, we may find that the weather indeed correlates with the sunspot activity at the 11 year cycle. That is, we may find a periodicity in the weather data that is in-sync with the sun spot cycles. One can easily think of other areas of research where such knowledge could be very useful for example, various economic indicators may show similar (correlated) cyclical behavior various physiological measures likely will also display quotcoordinatedquot (i. e. correlated) cyclical behavior, and so on. Basic Notation and Principles A simple example Consider the following two series with 16 cases: 000000 7.945114 .077020 3.729484 .304637 .078835 .043539 .032740 0.000000 Results for Each Variable The complete summary contains all spectrum statistics computed for each variable, as described in the Single Spectrum (Fourier) Analysis overview section. Looking at the results shown above, it is clear that both variables show strong periodicities at the frequencies .0625 and .1875. Cross-periodogram, Cross-Density, Quadrature-density, Cross-amplitude Analogous to the results for the single variables, the complete summary will also display periodogram values for the cross periodogram. However, the cross-spectrum consists of complex numbers that can be divided into a real and an imaginary part. These can be smoothed to obtain the cross-density and quadrature density (quad density for short) estimates, respectively. (The reasons for smoothing, and the different common weight functions for smoothing are discussed in the Single Spectrum (Fourier) Analysis .) The square root of the sum of the squared cross-density and quad-density values is called the cross - amplitude . The cross-amplitude can be interpreted as a measure of covariance between the respective frequency components in the two series. Thus we can conclude from the results shown in the table above that the .0625 and .1875 frequency components in the two series covary. Squared Coherency, Gain, and Phase Shift There are additional statistics that can be displayed in the complete summary. Squared coherency. One can standardize the cross-amplitude values by squaring them and dividing by the product of the spectrum density estimates for each series. The result is called the squared coherency . which can be interpreted similar to the squared correlation coefficient (see Correlations - Overview ), that is, the coherency value is the squared correlation between the cyclical components in the two series at the respective frequency. However, the coherency values should not be interpreted by themselves for example, when the spectral density estimates in both series are very small, large coherency values may result (the divisor in the computation of the coherency values will be very small), even though there are no strong cyclical components in either series at the respective frequencies. Gain. The gain value is computed by dividing the cross-amplitude value by the spectrum density estimates for one of the two series in the analysis. Consequently, two gain values are computed, which can be interpreted as the standard least squares regression coefficients for the respective frequencies. Phase shift. Finally, the phase shift estimates are computed as tan-1 of the ratio of the quad density estimates over the cross-density estimate. The phase shift estimates (usually denoted by the Greek letter ) are measures of the extent to which each frequency component of one series leads the other. How the Example Data were Created Now, let us return to the example data set presented above. The large spectral density estimates for both series, and the cross-amplitude values at frequencies 0.0625 and .1875 suggest two strong synchronized periodicities in both series at those frequencies. In fact, the two series were created as: v1 cos(2 .0625(v0-1)) .75sin(2 .2(v0-1)) v2 cos(2 .0625(v02)) .75sin(2 .2(v02)) Frequency and Period The wave length of a sine or cosine function is typically expressed in terms of the number of cycles per unit time ( Frequency ), often denoted by the Greek letter nu ( some text books also use f ). For example, the number of letters handled in a post office may show 12 cycles per year: On the first of every month a large amount of mail is sent (many bills come due on the first of the month), then the amount of mail decreases in the middle of the month, then it increases again towards the end of the month. Therefore, every month the fluctuation in the amount of mail handled by the post office will go through a full cycle. Thus, if the unit of analysis is one year, then n would be equal to 12, as there would be 12 cycles per year. Of course, there will likely be other cycles with different frequencies. For example, there might be annual cycles ( 1), and perhaps weekly cycles 2 cosine coefficient k 2 N2 where P k is the periodogram value at frequency k and N is the overall length of the series. The periodogram values can be interpreted in terms of variance (sums of squares) of the data at the respective frequency or period. Customarily, the periodogram values are plotted against the frequencies or periods. The Problem of Leakage In the example above, a sine function with a frequency of 0.2 was quotinsertedquot into the series. However, because of the length of the series (16), none of the frequencies reported exactly quothitsquot on that frequency. In practice, what often happens in those cases is that the respective frequency will quotleakquot into adjacent frequencies. For example, one may find large periodogram values for two adjacent frequencies, when, in fact, there is only one strong underlying sine or cosine function at a frequency that falls in-between those implied by the length of the series. There are three ways in which one can approach the problem of leakage: By padding the series one may apply a finer frequency quotrosterquot to the data, By tapering the series prior to the analysis one may reduce leakage, or By smoothing the periodogram one may identify the general frequency quotregionsquot or ( spectral densities ) that significantly contribute to the cyclical behavior of the series. See below for descriptions of each of these approaches. Padding the Time Series Because the frequency values are computed as Nt (the number of units of times) one may simply pad the series with a constant (e. g. zeros) and thereby introduce smaller increments in the frequency values. In a sense, padding allows one to apply a finer roster to the data. In fact, if we padded the example data file described in the example above with ten zeros, the results would not change, that is, the largest periodogram peaks would still occur at the frequency values closest to .0625 and .2. (Padding is also often desirable for computational efficiency reasons see below.) The so-called process of split-cosine-bell tapering is a recommended transformation of the series prior to the spectrum analysis. It usually leads to a reduction of leakage in the periodogram. The rationale for this transformation is explained in detail in Bloomfield (1976, p. 80-94). In essence, a proportion ( p ) of the data at the beginning and at the end of the series is transformed via multiplication by the weights: where m is chosen so that 2 mN is equal to the proportion of data to be tapered ( p ). Data Windows and Spectral Density Estimates In practice, when analyzing actual data, it is usually not of crucial importance to identify exactly the frequencies for particular underlying sine or cosine functions. Rather, because the periodogram values are subject to substantial random fluctuation, one is faced with the problem of very many quotchaoticquot periodogram spikes. In that case, one would like to find the frequencies with the greatest spectral densities . that is, the frequency regions, consisting of many adjacent frequencies, that contribute most to the overall periodic behavior of the series. This can be accomplished by smoothing the periodogram values via a weighted moving average transformation. Suppose the moving average window is of width m (which must be an odd number) the following are the most commonly used smoothers (note: p (m-1)2 ). Daniell (or equal weight) window. The Daniell window (Daniell 1946) amounts to a simple (equal weight) moving average transformation of the periodogram values, that is, each spectral density estimate is computed as the mean of the m2 preceding and subsequent periodogram values. Tukey window. In the Tukey (Blackman and Tukey, 1958) or Tukey-Hanning window (named after Julius Von Hann), for each frequency, the weights for the weighted moving average of the periodogram values are computed as: Hamming window. In the Hamming (named after R. W. Hamming) window or Tukey-Hamming window (Blackman and Tukey, 1958), for each frequency, the weights for the weighted moving average of the periodogram values are computed as: Parzen window. In the Parzen window (Parzen, 1961), for each frequency, the weights for the weighted moving average of the periodogram values are computed as: Bartlett window. In the Bartlett window (Bartlett, 1950) the weights are computed as: With the exception of the Daniell window, all weight functions will assign the greatest weight to the observation being smoothed in the center of the window, and increasingly smaller weights to values that are further away from the center. In many cases, all of these data windows will produce very similar results Preparing the Data for Analysis Let us now consider a few other practical points in spectrum analysis. Usually, one wants to subtract the mean from the series, and detrend the series (so that it is stationary ) prior to the analysis. Otherwise the periodogram and density spectrum will mostly be quotoverwhelmedquot by a very large value for the first cosine coefficient (for frequency 0.0). In a sense, the mean is a cycle of frequency 0 (zero) per unit time that is, it is a constant. Similarly, a trend is also of little interest when one wants to uncover the periodicities in the series. In fact, both of those potentially strong effects may mask the more interesting periodicities in the data, and thus both the mean and the trend (linear) should be removed from the series prior to the analysis. Sometimes, it is also useful to smooth the data prior to the analysis, in order to quottamequot the random noise that may obscure meaningful periodic cycles in the periodogram. Results when no Periodicity in the Series Exists Finally, what if there are no recurring cycles in the data, that is, if each observation is completely independent of all other observations If the distribution of the observations follows the normal distribution, such a time series is also referred to as a white noise series (like the white noise one hears on the radio when tuned in-between stations). A white noise input series will result in periodogram values that follow an exponential distribution. Thus, by testing the distribution of periodogram values against the exponential distribution, one may test whether the input series is different from a white noise series. In addition, the you can also request to compute the Kolmogorov-Smirnov one-sample d statistic (see also Nonparametrics and Distributions for more details). Testing for white noise in certain frequency bands. Note that you can also plot the periodogram values for a particular frequency range only. Again, if the input is a white noise series with respect to those frequencies (i. e. it there are no significant periodic cycles of those frequencies), then the distribution of the periodogram values should again follow an exponential distribution. The interpretation of the results of spectrum analysis is discussed in the Basic Notation and Principles topic, however, we have not described how it is done computationally. Up until the mid-1960s the standard way of performing the spectrum decomposition was to use explicit formulae to solve for the sine and cosine parameters. The computations involved required at least N2 (complex) multiplications. Thus, even with todays high-speed computers. it would be very time consuming to analyze even small time series (e. g. 8,000 observations would result in at least 64 million multiplications). The time requirements changed drastically with the development of the so-called fast Fourier transform algorithm. or FFT for short. In the mid-1960s, J. W. Cooley and J. W. Tukey (1965) popularized this algorithm which, in retrospect, had in fact been discovered independently by various individuals. Various refinements and improvements of this algorithm can be found in Monro (1975) and Monro and Branch (1976). Readers interested in the computational details of this algorithm may refer to any of the texts cited in the overview. Suffice it to say that via the FFT algorithm, the time to perform a spectral analysis is proportional to N log2( N ) -- a huge improvement. However, a draw-back of the standard FFT algorithm is that the number of cases in the series must be equal to a power of 2 (i. e. 16, 64, 128, 256. ). Usually, this necessitated padding of the series, which, as described above, will in most cases not change the characteristic peaks of the periodogram or the spectral density estimates. In cases, however, where the time units are meaningful, such padding may make the interpretation of results more cumbersome. Computation of FFT in Time Series The implementation of the FFT algorithm allows you to take full advantage of the savings afforded by this algorithm. On most standard computers, series with over 100,000 cases can easily be analyzed. However, there are a few things to remember when analyzing series of that size. As mentioned above, the standard (and most efficient) FFT algorithm requires that the length of the input series is equal to a power of 2. If this is not the case, additional computations have to be performed. It will use the simple explicit computational formulas as long as the input series is relatively small, and the number of computations can be performed in a relatively short amount of time. For long time series, in order to still utilize the FFT algorithm, an implementation of the general approach described by Monro and Branch (1976) is used. This method requires significantly more storage space, however, series of considerable length can still be analyzed very quickly, even if the number of observations is not equal to a power of 2. For time series of lengths not equal to a power of 2, we would like to make the following recommendations: If the input series is small to moderately sized (e. g. only a few thousand cases), then do not worry. The analysis will typically only take a few seconds anyway. In order to analyze moderately large and large series (e. g. over 100,000 cases), pad the series to a power of 2 and then taper the series during the exploratory part of your data analysis. copy Copyright StatSoft, Inc. 1984-2000 STATISTICA is a trademark of StatSoft, Inc.

No comments:

Post a Comment