Friday, December 23, 2016

Serie De Tiempo Irregular Media Móvil Exponencial


Estoy intentando extraer algunas métricas que miran cómo confiablemente los clientes conectan con un servicio. Los datos sin procesar están en la forma del cliente A, vinieron en línea fuera del tiempo X. La conexión es altamente unreliable, y quiero algún tipo de media móvil para demostrar si la conexión está mejorando o no con el tiempo. Los clientes no siempre están conectados, por lo que simplemente desconectarse no significa que sea un fallo. Hasta ahora, he tomado datos y aplicado algunas suposiciones para ayudar a simplificar, supongo que si un cliente se vuelve a conectar dentro de un minuto de desconectar, entonces eso es una falla. Estos Ive modelado como un impluses simple, es decir. Cliente A tenía falla en el tiempo X. La parte que estoy luchando con es cómo convertir esta trama en una media móvil (estoy jugando con R para crujir los números). Creo que debería ser capaz de hacer esto con un filtro de paso bajo, o utilizar el paquete de zoo y rollmean. Sin embargo, no sé cómo manejar los casos en los que el cliente simplemente no quería estar en línea. Tengo un valor continuo para el que Id como calcular una media móvil exponencial. Normalmente Id simplemente usa la fórmula estándar para esto: donde S n es el nuevo promedio, alfa es el alfa, Y es la muestra, y S n-1 es el promedio anterior. Por desgracia, debido a varios problemas que no tienen un tiempo de muestra consistente. Puedo saber que puedo probar como máximo, digamos, una vez por milisegundo, pero debido a factores fuera de mi control, es posible que no pueda tomar una muestra durante varios milisegundos a la vez. Un caso más probable, sin embargo, es que la simple muestra un poco temprano o tarde: en lugar de muestreo a 0, 1 y 2 ms. Muestra a 0, 0,9 y 2,1 ms. Yo anticipo que, independientemente de los retrasos, mi frecuencia de muestreo estará muy, muy por encima del límite de Nyquist, y por lo tanto no necesito preocuparme por aliasing. Creo que puedo lidiar con esto de una manera más o menos razonable variando el alfa apropiadamente, basado en el tiempo transcurrido desde la última muestra. Parte de mi razonamiento de que esto funcionará es que la EMA interpola linealmente entre el punto de datos anterior y el actual. Si consideramos el cálculo de una EMA de la siguiente lista de muestras a intervalos t: 0,1,2,3,4. Deberíamos obtener el mismo resultado si usamos el intervalo 2t, donde los insumos se vuelven 0,2,4, a la derecha. Si la EMA hubiera asumido que en t 2 el valor había sido 2 desde t 0. Que sería el mismo que el cálculo del intervalo t cálculo en 0,2,2,4,4, lo que no lo hace. O es que tiene sentido en absoluto Puede alguien decirme cómo variar el alfa adecuadamente Por favor, muestre su trabajo. Es decir. Muéstrame las matemáticas que demuestran que tu método realmente está haciendo lo correcto. No deberías obtener el mismo EMA para diferentes entradas. Piense en EMA como un filtro, el muestreo en 2t es equivalente a muestreo hacia abajo, y el filtro va a dar una salida diferente. Esto es claro para mí ya que 0,2,4 contiene componentes de frecuencia más alta que 0,1,2,3,4. A menos que la pregunta es, cómo puedo cambiar el filtro sobre la marcha para hacer que dar la misma salida. Tal vez estoy perdiendo algo ndash freespace Jun 21 09 at 15:52 Pero la entrada no es diferente, it39s muestra sólo menos a menudo. 0,2,4 a intervalos 2t es como 0,, 2, 4 en los intervalos t, donde indica que la muestra es ignorada ndash Curt Sampson Jun 21 09 at 23:45 Esta respuesta basada en mi buena comprensión del paso bajo Filtros (media móvil exponencial es realmente sólo un filtro de paso simple de un solo polo), pero mi comprensión nebulosa de lo que estás buscando. Creo que lo siguiente es lo que quieres: Primero, puedes simplificar tu ecuación un poco (parece más complicado pero es más fácil en código). Im que van a utilizar Y para la salida y X para la entrada (en vez de S para la salida y Y para la entrada, como usted ha hecho). En segundo lugar, el valor de alpha aquí es igual a 1-e-Datat / tau donde Deltat es el tiempo entre muestras, y tau es la constante de tiempo del filtro de paso bajo. Digo igual entre comillas porque esto funciona bien cuando Deltat / tau es pequeño comparado con 1, y alpha 1-e-Datat / tau asymp Deltat / tau. (Pero no demasiado pequeño: se ejecuta en cuestiones de cuantificación, ya menos que recurrir a algunas técnicas exóticas que por lo general necesitan un N bits adicionales de resolución en su estado variable S, donde N - log 2 (alfa).) Para valores más grandes de Deltat / Tau el efecto de filtrado comienza a desaparecer, hasta llegar al punto en que el alfa está cerca de 1 y básicamente sólo se asigna la entrada a la salida. Esto debería funcionar correctamente con diferentes valores de Deltat (la variación de Deltat no es muy importante, siempre y cuando el alfa sea pequeño, de lo contrario se encontrará con algunos problemas más extraños de Nyquist / aliasing / etc.) y si está trabajando en un procesador Donde la multiplicación es más barata que la división, o cuestiones de punto fijo son importantes, precalculate omega 1 / tau, y considere tratar de aproximar la fórmula de alfa. Si realmente quiere saber cómo derivar la fórmula alfa 1-e-Datat / tau, considere su fuente de ecuaciones diferenciales: cuando X es una función de escalón unitario, tiene la solución Y 1 - e - t / tau. Para valores pequeños de Deltat, la derivada puede ser aproximada por DeltaY / Deltat, produciendo Y tau DeltaY / Deltat X DeltaY (XY) (Deltat / tau) alfa (XY) y la extrapolación de alfa 1-e - Detat / tau proviene de Tratando de igualar el comportamiento con el caso de función de paso de unidad. Podría por favor elaborar en el quottrying para coincidir con la parte de comportamiento que entiendo su solución de tiempo continuo Y 1 - exp (-t47) y su generalización a una función escalonada de escalón con magnitud xy condición inicial y (0). Pero no veo cómo juntar estas ideas para lograr su resultado. Ndash Rhys Ulerich May 4 13 at 22:34 Esto no es una respuesta completa, pero puede ser el comienzo de uno. Es tan lejos como llegué con esto en una hora o así de jugar Im publicarlo como un ejemplo de lo que estoy buscando, y tal vez una inspiración para otros que trabajan en el problema. Empiezo con S 0. Que es el promedio resultante del promedio anterior S -1 y la muestra Y 0 tomada en t 0. (T 1 - t 0) es mi intervalo de muestreo y alfa se ajusta a lo que sea apropiado para ese intervalo de muestra y el período sobre el cual deseo mediar. He considerado lo que sucede si me pierdo la muestra en t 1 y en su lugar tienen que conformarse con la muestra Y 2 tomada en t 2. Pues bien, podemos comenzar expandiendo la ecuación para ver lo que habría pasado si hubiéramos tenido Y 1: Observo que la serie parece extenderse infinitamente de esta manera, porque podemos sustituir indefinidamente el S n en el lado derecho: Ok , Por lo que no es realmente un polinomio (tonto yo), pero si multiplicamos el término inicial por uno, entonces vemos un patrón: Hm: es una serie exponencial. Quelle sorpresa Imagina que saliendo de la ecuación para una media móvil exponencial Así que de todos modos, tengo esta x 0 x 1 x 2 x 3. Cosa que va, y estoy seguro de que estoy oliendo e o un logaritmo natural dando patadas por aquí, pero no puedo recordar donde me dirigía después antes de que me quedé sin tiempo. Cualquier respuesta a esta pregunta, o cualquier prueba de corrección de tal respuesta, depende altamente de los datos que usted está midiendo. Si sus muestras se tomaron en t 0 0ms. T _ {1} 0,9ms y t _ {2} 2,1ms. Pero su elección de alfa se basa en intervalos de 1 ms, y por lo tanto desea un alpha n ajustado localmente. La prueba de corrección de la elección significaría conocer los valores de la muestra en t1ms y t2ms. Esto conduce a la pregunta: Puede usted interpolar sus datos resonably para tener sanas suposiciones de qué valores intermedios pudo haber sido? O usted puede incluso interpolar el promedio sí mismo? Si ninguno de éstos es posible, entonces por lo que yo lo veo, el lógico La elección de un valor intermedio Y (t) es el promedio calculado más recientemente. Es decir, Y (t) asımpona S n en la que n es maxmial tal que t n ltt. Esta elección tiene una consecuencia simple: Dejar alfa solo, no importa cuál era la diferencia de tiempo. Si, por otro lado, es posible interpolar sus valores, entonces esto le dará muestras de intervalo constante promedio. Por último, si es posible interpolar el promedio mismo, eso haría la pregunta sin sentido. Respondió Jun 21 09 at 15:08 balpha 9830 26.1k 9679 9 9679 84 9679 116 Creo que puedo interpolar mis datos: dado que I39m muestreo a intervalos discretos, I39m ya hacerlo con una EMA estándar De todos modos, asumir que necesito Un quotproofquot que muestra que funciona tan bien como un estándar EMA, que también tiene producirá un resultado incorrecto si los valores no están cambiando bastante suavemente entre períodos de muestra. Ndash Curt Sampson Jun 21 09 at 15:21 Pero eso es lo que estoy diciendo: Si consideras a la EMA una interpolación de tus valores, lo harás si dejas alfa tal cual (porque insertar el promedio más reciente como Y no cambia el promedio) . Si usted dice que necesita algo que funciona igual que un EMA estándar - lo que está mal con el original A menos que tenga más información acerca de los datos que está midiendo, cualquier ajuste local alfa será arbitrario. Ndash balpha 9830 Jun 21 09 at 15:31 Me gustaría dejar el valor de alpha solo, y rellenar los datos faltantes. Puesto que usted no sabe qué sucede durante el tiempo en que usted no puede probar, usted puede llenar esas muestras con 0s, o mantener el valor anterior estable y utilizar esos valores para el EMA. O una interpolación hacia atrás una vez que tenga una nueva muestra, rellene los valores faltantes y vuelva a calcular la EMA. Lo que estoy tratando de obtener es que tiene una entrada xn que tiene agujeros. No hay forma de evitar el hecho de que faltan datos. Por lo tanto, puede utilizar una retención de orden cero, o establecerla en cero, o algún tipo de interpolación entre xn y xnM. Donde M es el número de muestras faltantes y n el inicio de la brecha. Posiblemente incluso usando valores antes de n. De gastar una hora o así que mucking sobre un pedacito con la matemáticas para esto, pienso que el variar simplemente el alfa me dará realmente la interpolación apropiada entre los dos puntos que usted habla, pero en un Mucho más sencillo. Además, creo que la variación del alfa también tratará adecuadamente con las muestras tomadas entre los intervalos de muestreo estándar. En otras palabras, busco lo que describiste, pero tratando de usar las matemáticas para averiguar la forma sencilla de hacerlo. Ndash Curt Sampson Jun 21 09 at 14:07 No creo que haya una bestia como la interpolación quotproper. Simplemente no sabes lo que pasó en el momento en que no estás tomando muestras. Buena y mala interpolación implica algún conocimiento de lo que te perdiste, ya que tienes que medir en contra de eso para juzgar si una interpolación es buena o mala. A pesar de que dicho, usted puede colocar las limitaciones, es decir, con la aceleración máxima, velocidad, etc Creo que si usted sabe cómo modelar los datos que faltan, entonces sólo modelar los datos que faltan, a continuación, aplicar el algoritmo EMA sin cambio, más bien Que cambiar alfa. Just my 2c :) ndash freespace Jun 21 09 at 14:17 Esto es exactamente lo que estaba recibiendo en mi edición de la pregunta hace 15 minutos: quotYou simplemente don39t saber lo que pasó en el tiempo que no están muestreo, pero eso es cierto Incluso si usted muestra en cada intervalo designado. Así mi contemplación de Nyquist: mientras sepas que la forma de la onda no cambia las direcciones más que cada par de muestras, el intervalo real de la muestra no debería importar, y debería ser capaz de variar. La ecuación de EMA me parece exactamente para calcular como si la forma de onda cambió linealmente del último valor de la muestra al actual. Ndash Curt Sampson Jun 21 09 at 14:26 No creo que eso sea cierto. El teorema de Nyquist requiere un mínimo de 2 muestras por período para poder identificar de manera única la señal. Si no lo hace, obtendrá aliasing. Sería lo mismo que samplear fs1 por un tiempo, luego fs2, luego volver a fs1, y obtendrá aliasing en los datos cuando se muestre con fs2 si fs2 está por debajo del límite de Nyquist. También debo confesar que no entiendo lo que quieres decir con cambios de quotwaveform linealmente de la última muestra a la actual onequot. Podría por favor explicar Cheers, Steve. Ndash freespace Jun 21 09 at 14:36 ​​Esto es similar a un problema abierto en mi lista de tareas. Tengo un esquema elaborado en cierta medida, pero no tienen trabajo matemático para respaldar esta sugerencia todavía. Actualizar el resumen de amplificador: Quisiera mantener el factor de suavizado (alfa) independiente del factor de compensación (que me refiero como beta aquí). Jasons excelente respuesta ya aceptada aquí funciona muy bien para mí. Si también se puede medir el tiempo transcurrido desde la última muestra (en múltiplos redondeados de su tiempo de muestreo constante - 7,8 ms desde la última muestra sería de 8 unidades), que podría ser utilizado para aplicar el suavizado varias veces. Aplicar la fórmula 8 veces en este caso. Usted ha hecho efectivamente un suavizado más inclinado hacia el valor actual. Para obtener un mejor suavizado, tenemos que ajustar el alfa al aplicar la fórmula 8 veces en el caso anterior. Qué va a faltar esta aproximación de suavizado? Ya ha perdido 7 muestras en el ejemplo anterior Esto se aproximó en el paso 1 con una aplastada re-aplicación del valor actual un adicional de 7 veces Si definimos un factor de aproximación beta que se aplicará junto con alfa (Como alphabeta en lugar de sólo alfa), vamos a suponer que las 7 muestras perdidas estaban cambiando suavemente entre los valores de la muestra anterior y actual. Yo pensé en esto, pero un poco de mierda con las matemáticas me llevó al punto en el que creo que, en lugar de aplicar la fórmula ocho veces con el valor de la muestra, puedo hacer un cálculo De un nuevo alfa que me permitirá aplicar la fórmula una vez, y me dará el mismo resultado. Además, esto se ocuparía automáticamente de la cuestión de las muestras contrarrestadas por los tiempos de muestreo exactos. Ndash Curt Sampson Jun 21 09 at 13:47 La única solicitud está bien. Lo que no estoy seguro todavía es cómo es buena la aproximación de los 7 valores perdidos. Si el movimiento continuo hace que el valor de la fluctuación de fase a través de los 8 milisegundos, las aproximaciones pueden ser bastante fuera de la realidad. Pero, si usted está muestreando en 1ms (resolución más alta excluyendo las muestras retrasadas) ya ha calculado que el fluctuaciones dentro de 1ms no es relevante. Este razonamiento funciona para usted (todavía estoy tratando de convencer a mí mismo). Ndash nik Jun 21 09 at 14:08 Derecho. Ese es el factor beta de mi descripción. Un factor beta se calcularía sobre la base del intervalo de diferencia y de las muestras actuales y anteriores. El nuevo alfa será (alfabeto), pero se utilizará sólo para esa muestra. Mientras que usted parece ser el alfa en la fórmula, tienden hacia alfa constante (factor de suavizado) y una beta independientemente calculada (un factor de ajuste) que compensa las muestras faltadas apenas ahora. Ndash nik Jun 21 09 at 15: 23Uso de R para análisis de series temporales Análisis de series temporales Este folleto le explica cómo usar el software de estadística R para llevar a cabo algunos análisis simples que son comunes en el análisis de datos de series temporales. Este folleto supone que el lector tiene algunos conocimientos básicos de análisis de series de tiempo, y el foco principal del folleto no es explicar el análisis de series temporales, sino más bien explicar cómo realizar estos análisis con R. Si usted es nuevo en series temporales Análisis, y quiero aprender más sobre cualquiera de los conceptos presentados aquí, recomiendo encarecidamente el libro Open University 8220Time series8221 (código de producto M249 / 02), disponible en la Open University Shop. En este folleto, usaré series de datos de series de tiempo que Rob Hyndman ha proporcionado gentilmente en su biblioteca de datos de series de tiempo en robjhyndman / TSDL /. Si te gusta este folleto, también te gustaría consultar mi folleto sobre el uso de R para estadísticas biomédicas, a-little-book-of-r-for-biomedical-statistics. readthedocs. org/. Y mi folleto sobre el uso de R para el análisis multivariado, little-book-of-r-for-multivariate-analysis. readthedocs. org/. Lectura de datos de series de tiempo Lo primero que querrá hacer para analizar sus datos de series de tiempo será leerlo en R y trazar la serie de tiempo. Puede leer datos en R utilizando la función scan (), que asume que sus datos para puntos de tiempo sucesivos se encuentran en un archivo de texto simple con una columna. Por ejemplo, el archivo robjhyndman / tsdldata / misc / kings. dat contiene datos sobre la edad de muerte de sucesivos reyes de Inglaterra, empezando por Guillermo el Conquistador (fuente original: Hipel y Mcleod, 1994). El conjunto de datos tiene este aspecto: Sólo se han mostrado las primeras líneas del archivo. Las tres primeras líneas contienen algún comentario sobre los datos, y queremos ignorar esto cuando leemos los datos en R. Podemos usar esto usando el parámetro 8220skip8221 de la función scan (), que especifica cuántas líneas en la parte superior de El archivo a ignorar. Para leer el archivo en R, ignorando las tres primeras líneas, escribimos: En este caso la edad de muerte de 42 reyes sucesivos de Inglaterra se ha leído en la variable 8216kings8217. Una vez que haya leído los datos de la serie temporal en R, el siguiente paso es almacenar los datos en un objeto de serie temporal en R, de modo que pueda utilizar muchas funciones de R8217s para analizar datos de series temporales. Para almacenar los datos en un objeto de serie temporal, usamos la función ts () en R. Por ejemplo, para almacenar los datos en la variable 8216kings8217 como un objeto de serie temporal en R, tecleamos: A veces, el conjunto de datos de series de tiempo que usted Pueden haber sido recogidos a intervalos regulares que fueron menos de un año, por ejemplo, mensual o trimestral. En este caso, puede especificar el número de veces que los datos fueron recopilados por año utilizando el parámetro 8216frequency8217 en la función ts (). Para los datos de series temporales mensuales, se fija la frecuencia12, mientras que para los datos trimestrales de la serie temporal, se establece la frecuencia4. También puede especificar el primer año en que se recopilaron los datos y el primer intervalo en ese año utilizando el parámetro 8216start8217 en la función ts (). Por ejemplo, si el primer punto de datos corresponde al segundo trimestre de 1986, se establecería startc (1986,2). Un ejemplo es un conjunto de datos sobre el número de nacimientos por mes en la ciudad de Nueva York, de enero de 1946 a diciembre de 1959 (recogido originalmente por Newton). Estos datos están disponibles en el archivo robjhyndman / tsdldata / data / nybirths. dat Podemos leer los datos en R y almacenarlos como un objeto de serie temporal escribiendo: Similarmente, el archivo robjhyndman / tsdldata / data / fancy. dat contiene Ventas mensuales para una tienda de recuerdos en una ciudad balnearia en Queensland, Australia, para enero de 1987 a diciembre de 1993 (datos originales de Wheelwright y Hyndman, 1998). Podemos leer los datos en R escribiendo: Plotting Time Series Una vez que haya leído una serie de tiempo en R, el siguiente paso suele ser hacer un diagrama de los datos de series temporales, que puede hacer con la función plot. ts () En R. Por ejemplo, para trazar la serie de tiempo de la edad de muerte de 42 reyes sucesivos de Inglaterra, escribimos: Podemos ver a partir de la gráfica de tiempo que esta serie temporal podría describirse probablemente utilizando un modelo aditivo, ya que las fluctuaciones aleatorias En los datos son aproximadamente constantes en tamaño con el tiempo. Del mismo modo, para trazar la serie de tiempo del número de nacimientos por mes en la ciudad de Nueva York, que tipo: Podemos ver a partir de esta serie de tiempo que parece haber variación estacional en el número de nacimientos por mes: hay un pico cada verano , Y un abrevadero cada invierno. Una vez más, parece que esta serie temporal probablemente podría describirse usando un modelo aditivo, ya que las fluctuaciones estacionales son aproximadamente constantes en tamaño con el tiempo y no parecen depender del nivel de la serie temporal, y las fluctuaciones aleatorias también parecen ser Aproximadamente de tamaño constante en el tiempo. Del mismo modo, para trazar la serie de tiempo de las ventas mensuales de la tienda de recuerdos en una ciudad balnearia en Queensland, Australia, que tipo: En este caso, parece que un modelo aditivo no es apropiado para describir esta serie temporal, ya que el tamaño De las fluctuaciones estacionales y las fluctuaciones aleatorias parecen aumentar con el nivel de las series temporales. Por lo tanto, es posible que necesitamos transformar las series temporales para obtener una serie temporal transformada que se pueda describir utilizando un modelo aditivo. Por ejemplo, podemos transformar la serie cronológica calculando el registro natural de los datos originales: Aquí podemos ver que el tamaño de las fluctuaciones estacionales y las fluctuaciones aleatorias en la serie de tiempo log-transformada parecen ser aproximadamente constantes en el tiempo, y no No depende del nivel de la serie temporal. Por lo tanto, la serie de tiempo log-transformado puede describirse probablemente utilizando un modelo aditivo. Descomposición de series de tiempo La descomposición de una serie de tiempo significa separarla en sus componentes constituyentes, que suelen ser un componente de tendencia y un componente irregular, y si se trata de una serie temporal estacional, una componente estacional. Descomposición de datos no estacionales Una serie temporal no estacional consiste en un componente de tendencia y un componente irregular. La descomposición de las series temporales implica tratar de separar la serie temporal en estos componentes, es decir, estimar el componente de tendencia y el componente irregular. Para estimar el componente de tendencia de una serie temporal no estacional que se puede describir utilizando un modelo aditivo, es común utilizar un método de suavizado, como calcular el promedio móvil simple de las series temporales. La función SMA () en el paquete 8220TTR8221 R se puede utilizar para suavizar datos de series de tiempo utilizando una media móvil simple. Para utilizar esta función, primero debemos instalar el paquete 8220TTR8221 R (para obtener instrucciones sobre cómo instalar un paquete R, consulte Cómo instalar un paquete R). Una vez que haya instalado el paquete 8220TTR8221 R, puede cargar el paquete 8220TTR8221 R escribiendo: A continuación, puede utilizar la función 8220SMA () 8221 para suavizar los datos de series temporales. Para utilizar la función SMA (), debe especificar el orden (span) de la media móvil simple, utilizando el parámetro 8220n8221. Por ejemplo, para calcular una media móvil simple de orden 5, fijamos n5 en la función SMA (). Por ejemplo, como se discutió anteriormente, la serie de tiempo de la edad de muerte de 42 reyes sucesivos de Inglaterra aparece no es estacional, y probablemente se puede describir utilizando un modelo aditivo, ya que las fluctuaciones aleatorias en los datos son más o menos constante en tamaño más Tiempo: Por lo tanto, podemos tratar de estimar el componente de tendencia de esta serie de tiempo por suavizado utilizando un promedio móvil simple. Para suavizar la serie de tiempo usando una media móvil simple de orden 3, y trazar los datos de la serie de tiempo suavizado, escribimos: Todavía parece haber un montón de fluctuaciones aleatorias en la serie de tiempo alisado usando una media móvil simple de orden 3. Por lo tanto, para estimar el componente de tendencia con mayor precisión, es posible que desee tratar de suavizar los datos con un promedio móvil simple de un orden superior. Esto requiere un poco de prueba y error, para encontrar la cantidad correcta de suavizado. Por ejemplo, podemos intentar usar una media móvil simple de orden 8: Los datos suavizados con una media móvil simple de orden 8 dan una imagen más clara del componente de tendencia y podemos ver que la edad de muerte de los reyes ingleses parece Han disminuido de aproximadamente 55 años a cerca de 38 años durante el reinado de los primeros 20 reyes, y después aumentaron después de eso a cerca de 73 años para el final del reinado del 40.o rey en la serie de tiempo. Descomposición de datos estacionales Una serie temporal estacional consta de un componente de tendencia, un componente estacional y un componente irregular. La descomposición de las series de tiempo significa separar las series de tiempo en estos tres componentes: es decir, estimar estos tres componentes. Para estimar el componente de tendencia y el componente estacional de una serie temporal estacional que se puede describir usando un modelo aditivo, podemos utilizar la función 8220decompose () 8221 en R. Esta función estima la tendencia, los componentes estacionales e irregulares de una serie temporal que Se puede describir utilizando un modelo aditivo. La función 8220decompose () 8221 devuelve un objeto de lista como su resultado, donde las estimaciones del componente estacional, el componente de tendencia y el componente irregular se almacenan en los elementos con nombre de los objetos de lista, llamados 8220seasonal8221, 8220trend8221 y 8220random8221, respectivamente. Por ejemplo, como se analizó anteriormente, la serie temporal del número de nacimientos mensuales en la ciudad de Nueva York es estacional con un pico cada verano y cada invierno y probablemente se puede describir usando un modelo aditivo ya que las fluctuaciones estacionales y aleatorias parecen Para estimar la tendencia, los componentes estacionales e irregulares de esta serie temporal, tecleamos: Los valores estimados de los componentes estacionales, de tendencias e irregulares se almacenan ahora en las variables de los nacimientos, las series, los nacimientos, las series, la tendencia de las cotizaciones y los nacimientos. Por ejemplo, podemos imprimir los valores estimados del componente estacional escribiendo: Los factores estacionales estimados se dan para los meses enero-diciembre, y son los mismos para cada año. El mayor factor estacional es para julio (alrededor de 1,46), y el más bajo para febrero (alrededor de -2,08), lo que indica que parece haber un pico de nacimientos en julio y un mínimo en nacimientos en febrero de cada año. Podemos trazar la tendencia estimada, los componentes estacionales y los componentes irregulares de la serie temporal usando la función 8220plot () 8221, por ejemplo: La gráfica anterior muestra la serie temporal original (arriba), el componente de tendencia estimada (segundo desde arriba) El componente estacional estimado (tercero desde arriba) y el componente irregular estimado (parte inferior). Vemos que el componente de tendencia estimada muestra una pequeña disminución de aproximadamente 24 en 1947 a aproximadamente 22 en 1948, seguido por un aumento constante desde entonces a aproximadamente 27 en 1959. Ajuste estacional Si tiene una serie temporal estacional que se puede describir usando Un modelo aditivo, puede ajustar temporalmente la serie de tiempo estimando el componente estacional y restando el componente estacional estimado de la serie temporal original. Podemos hacer esto usando la estimación del componente estacional calculado por la función 8220decompose () 8221. Por ejemplo, para ajustar estacionalmente la serie temporal del número de nacimientos por mes en la ciudad de Nueva York, podemos estimar el componente estacional usando 8220decompose () 8221, y luego restar el componente estacional de la serie temporal original: Series temporales ajustadas estacionalmente usando la función 8220plot () 8221, escribiendo: Puede ver que la variación estacional ha sido eliminada de la serie temporal desestacionalizada. La serie temporal ajustada estacionalmente ahora solo contiene el componente de tendencia y un componente irregular. Pronósticos con suavizado exponencial El suavizado exponencial se puede usar para hacer pronósticos a corto plazo para datos de series temporales. Suavizado Exponencial Simple Si tiene una serie de tiempo que se puede describir utilizando un modelo aditivo con nivel constante y sin estacionalidad, puede utilizar el suavizado exponencial simple para hacer pronósticos a corto plazo. El método de suavizado exponencial simple proporciona una forma de estimar el nivel en el punto de tiempo actual. El suavizado es controlado por el parámetro alfa para la estimación del nivel en el punto de tiempo actual. El valor de alpha está entre 0 y 1. Los valores de alfa que están cerca de 0 significan que poco peso se coloca en las observaciones más recientes al hacer pronósticos de valores futuros. Por ejemplo, el archivo robjhyndman / tsdldata / hurst / precip1.dat contiene la precipitación anual total en pulgadas para Londres, de 1813 a 1912 (datos originales de Hipel y McLeod, 1994). Podemos leer los datos en R y trazarlos escribiendo: Se puede ver en la gráfica que hay un nivel aproximadamente constante (la media permanece constante en aproximadamente 25 pulgadas). Las fluctuaciones aleatorias en las series temporales parecen ser aproximadamente de tamaño constante en el tiempo, por lo que es probablemente apropiado describir los datos usando un modelo aditivo. Así, podemos hacer pronósticos usando el suavizado exponencial simple. Para hacer pronósticos usando el suavizado exponencial simple en R, podemos ajustar un modelo predictivo de suavización exponencial simple usando la función 8220HoltWinters () 8221 en R. Para usar HoltWinters () para el suavizado exponencial simple, necesitamos establecer los parámetros betaFALSE y gammaFALSE en el HoltWinters () (los parámetros beta y gamma se usan para el suavizado exponencial de Holt8217s o el suavizado exponencial de Holt-Winters, como se describe a continuación). La función HoltWinters () devuelve una variable de lista que contiene varios elementos con nombre. Por ejemplo, para usar el suavizado exponencial simple para hacer pronósticos para las series temporales de precipitaciones anuales en Londres, tecleamos: La salida de HoltWinters () nos dice que el valor estimado del parámetro alfa es aproximadamente 0.024. Esto es muy cercano a cero, diciéndonos que las previsiones se basan en observaciones recientes y menos recientes (aunque se hace un poco más de peso en las observaciones recientes). De forma predeterminada, HoltWinters () sólo hace previsiones para el mismo período cubierto por nuestra serie de tiempo original. En este caso, nuestra serie de tiempo original incluyó la lluvia para Londres desde 1813-1912, por lo que las previsiones son también para 1813-1912. En el ejemplo anterior, hemos almacenado la salida de la función HoltWinters () en la variable de lista 8220rainseriesforecasts8221. Las previsiones hechas por HoltWinters () se almacenan en un elemento con nombre de esta variable de lista denominada 8220fitted8221, por lo que podemos obtener sus valores escribiendo: Podemos trazar la serie de tiempo original con los pronósticos escribiendo: La gráfica muestra la serie de tiempo original en Negro, y las previsiones como una línea roja. La serie temporal de pronósticos es mucho más suave que la serie temporal de los datos originales aquí. Como una medida de la exactitud de las previsiones, podemos calcular la suma de errores cuadrados para los errores de pronóstico de la muestra, es decir, los errores de predicción para el período de tiempo cubierto por nuestras series temporales originales. La suma de cuadrado de errores se almacena en un elemento con nombre de la variable de lista 8220rainseriesforecasts8221 llamada 8220SSE8221, por lo que podemos obtener su valor escribiendo: Es decir, aquí la suma de cuadrado de errores es 1828.855. Es común en el suavizado exponencial simple utilizar el primer valor en la serie de tiempo como el valor inicial para el nivel. Por ejemplo, en la serie temporal de precipitaciones en Londres, el primer valor es 23.56 (pulgadas) para la precipitación en 1813. Puede especificar el valor inicial para el nivel en la función HoltWinters () mediante el parámetro 8220l. start8221. Por ejemplo, para hacer pronósticos con el valor inicial del nivel establecido a 23.56, escribimos: Como se explicó anteriormente, por defecto HoltWinters () sólo hace previsiones para el período cubierto por los datos originales, que es 1813-1912 para la precipitación series de tiempo. Podemos hacer pronósticos para otros puntos de tiempo utilizando la función 8220forecast. HoltWinters () 8221 en el paquete R 8220forecast8221. Para utilizar la función forecast. HoltWinters (), primero debemos instalar el paquete 8220forecast8221 R (para obtener instrucciones sobre cómo instalar un paquete R, consulte Cómo instalar un paquete R). Una vez que haya instalado el paquete 8220forecast8221 R, puede cargar el paquete 8220forecast8221 R escribiendo: Cuando utilice la función forecast. HoltWinters (), como su primer argumento (entrada), pasará el modelo predictivo que ya ha montado utilizando el método HoltWinters () función. For example, in the case of the rainfall time series, we stored the predictive model made using HoltWinters() in the variable 8220rainseriesforecasts8221. You specify how many further time points you want to make forecasts for by using the 8220h8221 parameter in forecast. HoltWinters(). For example, to make a forecast of rainfall for the years 1814-1820 (8 more years) using forecast. HoltWinters(), we type: The forecast. HoltWinters() function gives you the forecast for a year, a 80 prediction interval for the forecast, and a 95 prediction interval for the forecast. For example, the forecasted rainfall for 1920 is about 24.68 inches, with a 95 prediction interval of (16.24, 33.11). To plot the predictions made by forecast. HoltWinters(), we can use the 8220plot. forecast()8221 function: Here the forecasts for 1913-1920 are plotted as a blue line, the 80 prediction interval as an orange shaded area, and the 95 prediction interval as a yellow shaded area. The 8216forecast errors8217 are calculated as the observed values minus predicted values, for each time point. We can only calculate the forecast errors for the time period covered by our original time series, which is 1813-1912 for the rainfall data. As mentioned above, one measure of the accuracy of the predictive model is the sum-of-squared-errors (SSE) for the in-sample forecast errors. The in-sample forecast errors are stored in the named element 8220residuals8221 of the list variable returned by forecast. HoltWinters(). If the predictive model cannot be improved upon, there should be no correlations between forecast errors for successive predictions. In other words, if there are correlations between forecast errors for successive predictions, it is likely that the simple exponential smoothing forecasts could be improved upon by another forecasting technique. To figure out whether this is the case, we can obtain a correlogram of the in-sample forecast errors for lags 1-20. We can calculate a correlogram of the forecast errors using the 8220acf()8221 function in R. To specify the maximum lag that we want to look at, we use the 8220lag. max8221 parameter in acf(). For example, to calculate a correlogram of the in-sample forecast errors for the London rainfall data for lags 1-20, we type: You can see from the sample correlogram that the autocorrelation at lag 3 is just touching the significance bounds. To test whether there is significant evidence for non-zero correlations at lags 1-20, we can carry out a Ljung-Box test. This can be done in R using the 8220Box. test()8221, function. The maximum lag that we want to look at is specified using the 8220lag8221 parameter in the Box. test() function. For example, to test whether there are non-zero autocorrelations at lags 1-20, for the in-sample forecast errors for London rainfall data, we type: Here the Ljung-Box test statistic is 17.4, and the p-value is 0.6, so there is little evidence of non-zero autocorrelations in the in-sample forecast errors at lags 1-20. To be sure that the predictive model cannot be improved upon, it is also a good idea to check whether the forecast errors are normally distributed with mean zero and constant variance. To check whether the forecast errors have constant variance, we can make a time plot of the in-sample forecast errors: The plot shows that the in-sample forecast errors seem to have roughly constant variance over time, although the size of the fluctuations in the start of the time series (1820-1830) may be slightly less than that at later dates (eg. 1840-1850). To check whether the forecast errors are normally distributed with mean zero, we can plot a histogram of the forecast errors, with an overlaid normal curve that has mean zero and the same standard deviation as the distribution of forecast errors. To do this, we can define an R function 8220plotForecastErrors()8221, below: You will have to copy the function above into R in order to use it. You can then use plotForecastErrors() to plot a histogram (with overlaid normal curve) of the forecast errors for the rainfall predictions: The plot shows that the distribution of forecast errors is roughly centred on zero, and is more or less normally distributed, although it seems to be slightly skewed to the right compared to a normal curve. However, the right skew is relatively small, and so it is plausible that the forecast errors are normally distributed with mean zero. The Ljung-Box test showed that there is little evidence of non-zero autocorrelations in the in-sample forecast errors, and the distribution of forecast errors seems to be normally distributed with mean zero. This suggests that the simple exponential smoothing method provides an adequate predictive model for London rainfall, which probably cannot be improved upon. Furthermore, the assumptions that the 80 and 95 predictions intervals were based upon (that there are no autocorrelations in the forecast errors, and the forecast errors are normally distributed with mean zero and constant variance) are probably valid. Holt8217s Exponential Smoothing If you have a time series that can be described using an additive model with increasing or decreasing trend and no seasonality, you can use Holt8217s exponential smoothing to make short-term forecasts. Holt8217s exponential smoothing estimates the level and slope at the current time point. Smoothing is controlled by two parameters, alpha, for the estimate of the level at the current time point, and beta for the estimate of the slope b of the trend component at the current time point. As with simple exponential smoothing, the paramters alpha and beta have values between 0 and 1, and values that are close to 0 mean that little weight is placed on the most recent observations when making forecasts of future values. An example of a time series that can probably be described using an additive model with a trend and no seasonality is the time series of the annual diameter of women8217s skirts at the hem, from 1866 to 1911. The data is available in the file robjhyndman/tsdldata/roberts/skirts. dat (original data from Hipel and McLeod, 1994). We can read in and plot the data in R by typing: We can see from the plot that there was an increase in hem diameter from about 600 in 1866 to about 1050 in 1880, and that afterwards the hem diameter decreased to about 520 in 1911. To make forecasts, we can fit a predictive model using the HoltWinters() function in R. To use HoltWinters() for Holt8217s exponential smoothing, we need to set the parameter gammaFALSE (the gamma parameter is used for Holt-Winters exponential smoothing, as described below). For example, to use Holt8217s exponential smoothing to fit a predictive model for skirt hem diameter, we type: The estimated value of alpha is 0.84, and of beta is 1.00. These are both high, telling us that both the estimate of the current value of the level, and of the slope b of the trend component, are based mostly upon very recent observations in the time series. This makes good intuitive sense, since the level and the slope of the time series both change quite a lot over time. The value of the sum-of-squared-errors for the in-sample forecast errors is 16954. We can plot the original time series as a black line, with the forecasted values as a red line on top of that, by typing: We can see from the picture that the in-sample forecasts agree pretty well with the observed values, although they tend to lag behind the observed values a little bit. If you wish, you can specify the initial values of the level and the slope b of the trend component by using the 8220l. start8221 and 8220b. start8221 arguments for the HoltWinters() function. It is common to set the initial value of the level to the first value in the time series (608 for the skirts data), and the initial value of the slope to the second value minus the first value (9 for the skirts data). For example, to fit a predictive model to the skirt hem data using Holt8217s exponential smoothing, with initial values of 608 for the level and 9 for the slope b of the trend component, we type: As for simple exponential smoothing, we can make forecasts for future times not covered by the original time series by using the forecast. HoltWinters() function in the 8220forecast8221 package. For example, our time series data for skirt hems was for 1866 to 1911, so we can make predictions for 1912 to 1930 (19 more data points), and plot them, by typing: The forecasts are shown as a blue line, with the 80 prediction intervals as an orange shaded area, and the 95 prediction intervals as a yellow shaded area. As for simple exponential smoothing, we can check whether the predictive model could be improved upon by checking whether the in-sample forecast errors show non-zero autocorrelations at lags 1-20. For example, for the skirt hem data, we can make a correlogram, and carry out the Ljung-Box test, by typing: Here the correlogram shows that the sample autocorrelation for the in-sample forecast errors at lag 5 exceeds the significance bounds. However, we would expect one in 20 of the autocorrelations for the first twenty lags to exceed the 95 significance bounds by chance alone. Indeed, when we carry out the Ljung-Box test, the p-value is 0.47, indicating that there is little evidence of non-zero autocorrelations in the in-sample forecast errors at lags 1-20. As for simple exponential smoothing, we should also check that the forecast errors have constant variance over time, and are normally distributed with mean zero. We can do this by making a time plot of forecast errors, and a histogram of the distribution of forecast errors with an overlaid normal curve: The time plot of forecast errors shows that the forecast errors have roughly constant variance over time. The histogram of forecast errors show that it is plausible that the forecast errors are normally distributed with mean zero and constant variance. Thus, the Ljung-Box test shows that there is little evidence of autocorrelations in the forecast errors, while the time plot and histogram of forecast errors show that it is plausible that the forecast errors are normally distributed with mean zero and constant variance. Therefore, we can conclude that Holt8217s exponential smoothing provides an adequate predictive model for skirt hem diameters, which probably cannot be improved upon. In addition, it means that the assumptions that the 80 and 95 predictions intervals were based upon are probably valid. Holt-Winters Exponential Smoothing If you have a time series that can be described using an additive model with increasing or decreasing trend and seasonality, you can use Holt-Winters exponential smoothing to make short-term forecasts. Holt-Winters exponential smoothing estimates the level, slope and seasonal component at the current time point. Smoothing is controlled by three parameters: alpha, beta, and gamma, for the estimates of the level, slope b of the trend component, and the seasonal component, respectively, at the current time point. The parameters alpha, beta and gamma all have values between 0 and 1, and values that are close to 0 mean that relatively little weight is placed on the most recent observations when making forecasts of future values. An example of a time series that can probably be described using an additive model with a trend and seasonality is the time series of the log of monthly sales for the souvenir shop at a beach resort town in Queensland, Australia (discussed above): To make forecasts, we can fit a predictive model using the HoltWinters() function. For example, to fit a predictive model for the log of the monthly sales in the souvenir shop, we type: The estimated values of alpha, beta and gamma are 0.41, 0.00, and 0.96, respectively. The value of alpha (0.41) is relatively low, indicating that the estimate of the level at the current time point is based upon both recent observations and some observations in the more distant past. The value of beta is 0.00, indicating that the estimate of the slope b of the trend component is not updated over the time series, and instead is set equal to its initial value. This makes good intuitive sense, as the level changes quite a bit over the time series, but the slope b of the trend component remains roughly the same. In contrast, the value of gamma (0.96) is high, indicating that the estimate of the seasonal component at the current time point is just based upon very recent observations. As for simple exponential smoothing and Holt8217s exponential smoothing, we can plot the original time series as a black line, with the forecasted values as a red line on top of that: We see from the plot that the Holt-Winters exponential method is very successful in predicting the seasonal peaks, which occur roughly in November every year. To make forecasts for future times not included in the original time series, we use the 8220forecast. HoltWinters()8221 function in the 8220forecast8221 package. For example, the original data for the souvenir sales is from January 1987 to December 1993. If we wanted to make forecasts for January 1994 to December 1998 (48 more months), and plot the forecasts, we would type: The forecasts are shown as a blue line, and the orange and yellow shaded areas show 80 and 95 prediction intervals, respectively. We can investigate whether the predictive model can be improved upon by checking whether the in-sample forecast errors show non-zero autocorrelations at lags 1-20, by making a correlogram and carrying out the Ljung-Box test: The correlogram shows that the autocorrelations for the in-sample forecast errors do not exceed the significance bounds for lags 1-20. Furthermore, the p-value for Ljung-Box test is 0.6, indicating that there is little evidence of non-zero autocorrelations at lags 1-20. We can check whether the forecast errors have constant variance over time, and are normally distributed with mean zero, by making a time plot of the forecast errors and a histogram (with overlaid normal curve): From the time plot, it appears plausible that the forecast errors have constant variance over time. From the histogram of forecast errors, it seems plausible that the forecast errors are normally distributed with mean zero. Thus, there is little evidence of autocorrelation at lags 1-20 for the forecast errors, and the forecast errors appear to be normally distributed with mean zero and constant variance over time. This suggests that Holt-Winters exponential smoothing provides an adequate predictive model of the log of sales at the souvenir shop, which probably cannot be improved upon. Furthermore, the assumptions upon which the prediction intervals were based are probably valid. ARIMA Models Exponential smoothing methods are useful for making forecasts, and make no assumptions about the correlations between successive values of the time series. However, if you want to make prediction intervals for forecasts made using exponential smoothing methods, the prediction intervals require that the forecast errors are uncorrelated and are normally distributed with mean zero and constant variance. While exponential smoothing methods do not make any assumptions about correlations between successive values of the time series, in some cases you can make a better predictive model by taking correlations in the data into account. Autoregressive Integrated Moving Average (ARIMA) models include an explicit statistical model for the irregular component of a time series, that allows for non-zero autocorrelations in the irregular component. Differencing a Time Series ARIMA models are defined for stationary time series. Therefore, if you start off with a non-stationary time series, you will first need to 8216difference8217 the time series until you obtain a stationary time series. If you have to difference the time series d times to obtain a stationary series, then you have an ARIMA(p, d,q) model, where d is the order of differencing used. You can difference a time series using the 8220diff()8221 function in R. For example, the time series of the annual diameter of women8217s skirts at the hem, from 1866 to 1911 is not stationary in mean, as the level changes a lot over time: We can difference the time series (which we stored in 8220skirtsseries8221, see above) once, and plot the differenced series, by typing: The resulting time series of first differences (above) does not appear to be stationary in mean. Therefore, we can difference the time series twice, to see if that gives us a stationary time series: Formal tests for stationarity Formal tests for stationarity called 8220unit root tests8221 are available in the fUnitRoots package, available on CRAN, but will not be discussed here. The time series of second differences (above) does appear to be stationary in mean and variance, as the level of the series stays roughly constant over time, and the variance of the series appears roughly constant over time. Thus, it appears that we need to difference the time series of the diameter of skirts twice in order to achieve a stationary series. If you need to difference your original time series data d times in order to obtain a stationary time series, this means that you can use an ARIMA(p, d,q) model for your time series, where d is the order of differencing used. For example, for the time series of the diameter of women8217s skirts, we had to difference the time series twice, and so the order of differencing (d) is 2. This means that you can use an ARIMA(p,2,q) model for your time series. The next step is to figure out the values of p and q for the ARIMA model. Another example is the time series of the age of death of the successive kings of England (see above): From the time plot (above), we can see that the time series is not stationary in mean. To calculate the time series of first differences, and plot it, we type: The time series of first differences appears to be stationary in mean and variance, and so an ARIMA(p,1,q) model is probably appropriate for the time series of the age of death of the kings of England. By taking the time series of first differences, we have removed the trend component of the time series of the ages at death of the kings, and are left with an irregular component. We can now examine whether there are correlations between successive terms of this irregular component if so, this could help us to make a predictive model for the ages at death of the kings. Selecting a Candidate ARIMA Model If your time series is stationary, or if you have transformed it to a stationary time series by differencing d times, the next step is to select the appropriate ARIMA model, which means finding the values of most appropriate values of p and q for an ARIMA(p, d,q) model. To do this, you usually need to examine the correlogram and partial correlogram of the stationary time series. To plot a correlogram and partial correlogram, we can use the 8220acf()8221 and 8220pacf()8221 functions in R, respectively. To get the actual values of the autocorrelations and partial autocorrelations, we set 8220plotFALSE8221 in the 8220acf()8221 and 8220pacf()8221 functions. Example of the Ages at Death of the Kings of England For example, to plot the correlogram for lags 1-20 of the once differenced time series of the ages at death of the kings of England, and to get the values of the autocorrelations, we type: We see from the correlogram that the autocorrelation at lag 1 (-0.360) exceeds the significance bounds, but all other autocorrelations between lags 1-20 do not exceed the significance bounds. To plot the partial correlogram for lags 1-20 for the once differenced time series of the ages at death of the English kings, and get the values of the partial autocorrelations, we use the 8220pacf()8221 function, by typing: The partial correlogram shows that the partial autocorrelations at lags 1, 2 and 3 exceed the significance bounds, are negative, and are slowly decreasing in magnitude with increasing lag (lag 1: -0.360, lag 2: -0.335, lag 3:-0.321). The partial autocorrelations tail off to zero after lag 3. Since the correlogram is zero after lag 1, and the partial correlogram tails off to zero after lag 3, this means that the following ARMA (autoregressive moving average) models are possible for the time series of first differences: an ARMA(3,0) model, that is, an autoregressive model of order p3, since the partial autocorrelogram is zero after lag 3, and the autocorrelogram tails off to zero (although perhaps too abruptly for this model to be appropriate) an ARMA(0,1) model, that is, a moving average model of order q1, since the autocorrelogram is zero after lag 1 and the partial autocorrelogram tails off to zero an ARMA(p, q) model, that is, a mixed model with p and q greater than 0, since the autocorrelogram and partial correlogram tail off to zero (although the correlogram probably tails off to zero too abruptly for this model to be appropriate) We use the principle of parsimony to decide which model is best: that is, we assume that the model with the fewest parameters is best. The ARMA(3,0) model has 3 parameters, the ARMA(0,1) model has 1 parameter, and the ARMA(p, q) model has at least 2 parameters. Therefore, the ARMA(0,1) model is taken as the best model. An ARMA(0,1) model is a moving average model of order 1, or MA(1) model. This model can be written as: Xt - mu Zt - (theta Zt-1), where Xt is the stationary time series we are studying (the first differenced series of ages at death of English kings), mu is the mean of time series Xt, Zt is white noise with mean zero and constant variance, and theta is a parameter that can be estimated. A MA (moving average) model is usually used to model a time series that shows short-term dependencies between successive observations. Intuitively, it makes good sense that a MA model can be used to describe the irregular component in the time series of ages at death of English kings, as we might expect the age at death of a particular English king to have some effect on the ages at death of the next king or two, but not much effect on the ages at death of kings that reign much longer after that. Shortcut: the auto. arima() function The auto. arima() function can be used to find the appropriate ARIMA model, eg. type 8220library(forecast)8221, then 8220auto. arima(kings)8221. The output says an appropriate model is ARIMA(0,1,1). Since an ARMA(0,1) model (with p0, q1) is taken to be the best candidate model for the time series of first differences of the ages at death of English kings, then the original time series of the ages of death can be modelled using an ARIMA(0,1,1) model (with p0, d1, q1, where d is the order of differencing required). Example of the Volcanic Dust Veil in the Northern Hemisphere Let8217s take another example of selecting an appropriate ARIMA model. The file file robjhyndman/tsdldata/annual/dvi. dat contains data on the volcanic dust veil index in the northern hemisphere, from 1500-1969 (original data from Hipel and Mcleod, 1994). This is a measure of the impact of volcanic eruptions8217 release of dust and aerosols into the environment. We can read it into R and make a time plot by typing: From the time plot, it appears that the random fluctuations in the time series are roughly constant in size over time, so an additive model is probably appropriate for describing this time series. Furthermore, the time series appears to be stationary in mean and variance, as its level and variance appear to be roughly constant over time. Therefore, we do not need to difference this series in order to fit an ARIMA model, but can fit an ARIMA model to the original series (the order of differencing required, d, is zero here). We can now plot a correlogram and partial correlogram for lags 1-20 to investigate what ARIMA model to use: We see from the correlogram that the autocorrelations for lags 1, 2 and 3 exceed the significance bounds, and that the autocorrelations tail off to zero after lag 3. The autocorrelations for lags 1, 2, 3 are positive, and decrease in magnitude with increasing lag (lag 1: 0.666, lag 2: 0.374, lag 3: 0.162). The autocorrelation for lags 19 and 20 exceed the significance bounds too, but it is likely that this is due to chance, since they just exceed the significance bounds (especially for lag 19), the autocorrelations for lags 4-18 do not exceed the signifiance bounds, and we would expect 1 in 20 lags to exceed the 95 significance bounds by chance alone. From the partial autocorrelogram, we see that the partial autocorrelation at lag 1 is positive and exceeds the significance bounds (0.666), while the partial autocorrelation at lag 2 is negative and also exceeds the significance bounds (-0.126). The partial autocorrelations tail off to zero after lag 2. Since the correlogram tails off to zero after lag 3, and the partial correlogram is zero after lag 2, the following ARMA models are possible for the time series: an ARMA(2,0) model, since the partial autocorrelogram is zero after lag 2, and the correlogram tails off to zero after lag 3, and the partial correlogram is zero after lag 2 an ARMA(0,3) model, since the autocorrelogram is zero after lag 3, and the partial correlogram tails off to zero (although perhaps too abruptly for this model to be appropriate) an ARMA(p, q) mixed model, since the correlogram and partial correlogram tail off to zero (although the partial correlogram perhaps tails off too abruptly for this model to be appropriate) Shortcut: the auto. arima() function Again, we can use auto. arima() to find an appropriate model, by typing 8220auto. arima(volcanodust)8221, which gives us ARIMA(1,0,2), which has 3 parameters. However, different criteria can be used to select a model (see auto. arima() help page). If we use the 8220bic8221 criterion, which penalises the number of parameters, we get ARIMA(2,0,0), which is ARMA(2,0): 8220auto. arima(volcanodust, ic8221bic8221)8221. The ARMA(2,0) model has 2 parameters, the ARMA(0,3) model has 3 parameters, and the ARMA(p, q) model has at least 2 parameters. Therefore, using the principle of parsimony, the ARMA(2,0) model and ARMA(p, q) model are equally good candidate models. An ARMA(2,0) model is an autoregressive model of order 2, or AR(2) model. This model can be written as: Xt - mu (Beta1 (Xt-1 - mu)) (Beta2 (Xt-2 - mu)) Zt, where Xt is the stationary time series we are studying (the time series of volcanic dust veil index), mu is the mean of time series Xt, Beta1 and Beta2 are parameters to be estimated, and Zt is white noise with mean zero and constant variance. An AR (autoregressive) model is usually used to model a time series which shows longer term dependencies between successive observations. Intuitively, it makes sense that an AR model could be used to describe the time series of volcanic dust veil index, as we would expect volcanic dust and aerosol levels in one year to affect those in much later years, since the dust and aerosols are unlikely to disappear quickly. If an ARMA(2,0) model (with p2, q0) is used to model the time series of volcanic dust veil index, it would mean that an ARIMA(2,0,0) model can be used (with p2, d0, q0, where d is the order of differencing required). Similarly, if an ARMA(p, q) mixed model is used, where p and q are both greater than zero, than an ARIMA(p,0,q) model can be used. Forecasting Using an ARIMA Model Once you have selected the best candidate ARIMA(p, d,q) model for your time series data, you can estimate the parameters of that ARIMA model, and use that as a predictive model for making forecasts for future values of your time series. You can estimate the parameters of an ARIMA(p, d,q) model using the 8220arima()8221 function in R. Example of the Ages at Death of the Kings of England For example, we discussed above that an ARIMA(0,1,1) model seems a plausible model for the ages at deaths of the kings of England. You can specify the values of p, d and q in the ARIMA model by using the 8220order8221 argument of the 8220arima()8221 function in R. To fit an ARIMA(p, d,q) model to this time series (which we stored in the variable 8220kingstimeseries8221, see above), we type: As mentioned above, if we are fitting an ARIMA(0,1,1) model to our time series, it means we are fitting an an ARMA(0,1) model to the time series of first differences. An ARMA(0,1) model can be written Xt - mu Zt - (theta Zt-1), where theta is a parameter to be estimated. From the output of the 8220arima()8221 R function (above), the estimated value of theta (given as 8216ma18217 in the R output) is -0.7218 in the case of the ARIMA(0,1,1) model fitted to the time series of ages at death of kings. Specifying the confidence level for prediction intervals You can specify the confidence level for prediction intervals in forecast. Arima() by using the 8220level8221 argument. For example, to get a 99.5 prediction interval, we would type 8220forecast. Arima(kingstimeseriesarima, h5, levelc(99.5))8221. We can then use the ARIMA model to make forecasts for future values of the time series, using the 8220forecast. Arima()8221 function in the 8220forecast8221 R package. For example, to forecast the ages at death of the next five English kings, we type: The original time series for the English kings includes the ages at death of 42 English kings. The forecast. Arima() function gives us a forecast of the age of death of the next five English kings (kings 43-47), as well as 80 and 95 prediction intervals for those predictions. The age of death of the 42nd English king was 56 years (the last observed value in our time series), and the ARIMA model gives the forecasted age at death of the next five kings as 67.8 years. We can plot the observed ages of death for the first 42 kings, as well as the ages that would be predicted for these 42 kings and for the next 5 kings using our ARIMA(0,1,1) model, by typing: As in the case of exponential smoothing models, it is a good idea to investigate whether the forecast errors of an ARIMA model are normally distributed with mean zero and constant variance, and whether the are correlations between successive forecast errors. For example, we can make a correlogram of the forecast errors for our ARIMA(0,1,1) model for the ages at death of kings, and perform the Ljung-Box test for lags 1-20, by typing: Since the correlogram shows that none of the sample autocorrelations for lags 1-20 exceed the significance bounds, and the p-value for the Ljung-Box test is 0.9, we can conclude that there is very little evidence for non-zero autocorrelations in the forecast errors at lags 1-20. To investigate whether the forecast errors are normally distributed with mean zero and constant variance, we can make a time plot and histogram (with overlaid normal curve) of the forecast errors: The time plot of the in-sample forecast errors shows that the variance of the forecast errors seems to be roughly constant over time (though perhaps there is slightly higher variance for the second half of the time series). The histogram of the time series shows that the forecast errors are roughly normally distributed and the mean seems to be close to zero. Therefore, it is plausible that the forecast errors are normally distributed with mean zero and constant variance. Since successive forecast errors do not seem to be correlated, and the forecast errors seem to be normally distributed with mean zero and constant variance, the ARIMA(0,1,1) does seem to provide an adequate predictive model for the ages at death of English kings. Example of the Volcanic Dust Veil in the Northern Hemisphere We discussed above that an appropriate ARIMA model for the time series of volcanic dust veil index may be an ARIMA(2,0,0) model. To fit an ARIMA(2,0,0) model to this time series, we can type: As mentioned above, an ARIMA(2,0,0) model can be written as: written as: Xt - mu (Beta1 (Xt-1 - mu)) (Beta2 (Xt-2 - mu)) Zt, where Beta1 and Beta2 are parameters to be estimated. The output of the arima() function tells us that Beta1 and Beta2 are estimated as 0.7533 and -0.1268 here (given as ar1 and ar2 in the output of arima()). Now we have fitted the ARIMA(2,0,0) model, we can use the 8220forecast. ARIMA()8221 model to predict future values of the volcanic dust veil index. The original data includes the years 1500-1969. To make predictions for the years 1970-2000 (31 more years), we type: We can plot the original time series, and the forecasted values, by typing: One worrying thing is that the model has predicted negative values for the volcanic dust veil index, but this variable can only have positive values The reason is that the arima() and forecast. Arima() functions don8217t know that the variable can only take positive values. Clearly, this is not a very desirable feature of our current predictive model. Again, we should investigate whether the forecast errors seem to be correlated, and whether they are normally distributed with mean zero and constant variance. To check for correlations between successive forecast errors, we can make a correlogram and use the Ljung-Box test: The correlogram shows that the sample autocorrelation at lag 20 exceeds the significance bounds. However, this is probably due to chance, since we would expect one out of 20 sample autocorrelations to exceed the 95 significance bounds. Furthermore, the p-value for the Ljung-Box test is 0.2, indicating that there is little evidence for non-zero autocorrelations in the forecast errors for lags 1-20. To check whether the forecast errors are normally distributed with mean zero and constant variance, we make a time plot of the forecast errors, and a histogram: The time plot of forecast errors shows that the forecast errors seem to have roughly constant variance over time. However, the time series of forecast errors seems to have a negative mean, rather than a zero mean. We can confirm this by calculating the mean forecast error, which turns out to be about -0.22: The histogram of forecast errors (above) shows that although the mean value of the forecast errors is negative, the distribution of forecast errors is skewed to the right compared to a normal curve. Therefore, it seems that we cannot comfortably conclude that the forecast errors are normally distributed with mean zero and constant variance Thus, it is likely that our ARIMA(2,0,0) model for the time series of volcanic dust veil index is not the best model that we could make, and could almost definitely be improved upon Links and Further Reading Here are some links for further reading. For a more in-depth introduction to R, a good online tutorial is available on the 8220Kickstarting R8221 website, cran. r-project. org/doc/contrib/Lemon-kickstart . There is another nice (slightly more in-depth) tutorial to R available on the 8220Introduction to R8221 website, cran. r-project. org/doc/manuals/R-intro. html . You can find a list of R packages for analysing time series data on the CRAN Time Series Task View webpage . To learn about time series analysis, I would highly recommend the book 8220Time series8221 (product code M249/02) by the Open University, available from the Open University Shop . There are two books available in the 8220Use R8221 series on using R for time series analyses, the first is Introductory Time Series with R by Cowpertwait and Metcalfe, and the second is Analysis of Integrated and Cointegrated Time Series with R by Pfaff. Acknowledgements I am grateful to Professor Rob Hyndman. for kindly allowing me to use the time series data sets from his Time Series Data Library (TSDL) in the examples in this booklet. Many of the examples in this booklet are inspired by examples in the excellent Open University book, 8220Time series8221 (product code M249/02), available from the Open University Shop . Thank you to Ravi Aranke for bringing auto. arima() to my attention, and Maurice Omane-Adjepong for bringing unit root tests to my attention, and Christian Seubert for noticing a small bug in plotForecastErrors(). Thank you for other comments to Antoine Binard and Bill Johnston. Contact I will be grateful if you will send me (Avril Coghlan) corrections or suggestions for improvements to my email address alc 64 sanger 46 ac 46 uk License

No comments:

Post a Comment