Monday 20 November 2017

Four Period Centered Moving Average


Moving Average Forecasting Introducción. Como usted podría adivinar, estamos estudiando algunos de los enfoques más primitivos para la predicción. Pero espero que estas sean al menos una introducción valiosa a algunos de los problemas de computación relacionados con la implementación de pronósticos en hojas de cálculo. En este sentido, continuaremos comenzando desde el principio y comenzando a trabajar con las previsiones de Media móvil. Pronósticos de media móvil. Todo el mundo está familiarizado con los pronósticos de promedio móvil, independientemente de si creen que son. Todos los estudiantes universitarios lo hacen todo el tiempo. Piense en los resultados de su examen en un curso en el que va a tener cuatro pruebas durante el semestre. Supongamos que tienes un 85 en tu primera prueba. Qué predecirías para tu segundo puntaje de prueba? Qué crees que tu maestro predijo para tu siguiente puntaje de prueba? Qué crees que tus amigos podrían predecir para tu siguiente puntaje de prueba? Qué crees que tus padres podrían predecir para tu próximo puntaje de prueba? Todo el blabbing que usted puede hacer a sus amigos y padres, él y su profesor son muy probables esperar que usted consiga algo en el área de los 85 que usted acaba de conseguir. Bueno, ahora vamos a suponer que a pesar de su autopromoción a sus amigos, usted se sobreestimar y la figura que puede estudiar menos para la segunda prueba y por lo que se obtiene un 73. Ahora lo que todos los interesados ​​y despreocupados va a Anticipar que usted conseguirá en su tercer examen Hay dos acercamientos muy probables para que desarrollen una estimación sin importar si lo compartirán con usted. Pueden decir a sí mismos: "Este tipo siempre está soplando el humo de su inteligencia. Hes va a conseguir otro 73 si hes suerte. Tal vez los padres tratarán de ser más solidarios y decir: "Bueno, hasta ahora has conseguido un 85 y un 73, por lo que tal vez debería figura en obtener sobre un (85 73) / 2 79. No sé, tal vez si usted hizo menos Fiesta y werent meneando la comadreja en todo el lugar y si comenzó a hacer mucho más estudiando que podría obtener una puntuación más alta. quot Ambos de estos estimados son en realidad las previsiones de promedio móvil. El primero es usar sólo su puntaje más reciente para pronosticar su rendimiento futuro. Esto se denomina pronóstico de media móvil utilizando un período de datos. El segundo es también un pronóstico de media móvil, pero utilizando dos períodos de datos. Vamos a asumir que todas estas personas estallando en su gran mente tienen tipo de molesto y usted decide hacer bien en la tercera prueba por sus propias razones y poner una puntuación más alta en frente de sus quotalliesquot. Usted toma la prueba y su puntuación es en realidad un 89 Todos, incluido usted mismo, está impresionado. Así que ahora tiene la prueba final del semestre que viene y como de costumbre se siente la necesidad de incitar a todos a hacer sus predicciones acerca de cómo youll hacer en la última prueba. Bueno, espero que veas el patrón. Ahora, espero que puedas ver el patrón. Cuál crees que es el silbido más preciso mientras trabajamos? Ahora volvemos a nuestra nueva compañía de limpieza iniciada por su hermana separada llamada Whistle While We Work. Tiene algunos datos de ventas anteriores representados en la siguiente sección de una hoja de cálculo. Primero presentamos los datos para un pronóstico de media móvil de tres periodos. La entrada para la celda C6 debe ser Ahora puede copiar esta fórmula de celda abajo a las otras celdas C7 a C11. Observe cómo el promedio se mueve sobre los datos históricos más recientes, pero utiliza exactamente los tres períodos más recientes disponibles para cada predicción. También debe notar que realmente no necesitamos hacer las predicciones para los períodos pasados ​​con el fin de desarrollar nuestra predicción más reciente. Esto es definitivamente diferente del modelo de suavizado exponencial. He incluido las predicciones anteriores porque las usaremos en la siguiente página web para medir la validez de la predicción. Ahora quiero presentar los resultados análogos para un pronóstico de media móvil de dos periodos. La entrada para la celda C5 debe ser Ahora puede copiar esta fórmula de celda abajo a las otras celdas C6 a C11. Observe cómo ahora sólo se usan las dos más recientes piezas de datos históricos para cada predicción. Nuevamente he incluido las predicciones anteriores para fines ilustrativos y para uso posterior en la validación de pronósticos. Algunas otras cosas que son importantes de notar. Para una predicción de promedio móvil del período m sólo se usan los m valores de datos más recientes para hacer la predicción. Nada más es necesario. Para una predicción media móvil del período m, al hacer predicciones quotpast, observe que la primera predicción ocurre en el período m 1. Ambas cuestiones serán muy significativas cuando desarrollemos nuestro código. Desarrollo de la función de media móvil. Ahora necesitamos desarrollar el código para el pronóstico del promedio móvil que se puede usar con más flexibilidad. El código sigue. Observe que las entradas son para el número de períodos que desea utilizar en el pronóstico y la matriz de valores históricos. Puede guardarlo en cualquier libro que desee. Función MovingAverage (Histórica, NumberOfPeriods) Como única Declaración e inicialización de variables Dim Item como variante Dim Contador como Entero Dim Acumulación como único Dim HistoricalSize As Entero Inicialización de variables Counter 1 Acumulación 0 Determinación del tamaño del historial HistoricalSize Historical. Count For Counter 1 To NumberOfPeriods Acumular el número apropiado de los valores observados anteriormente más recientes Acumulación Acumulación Histórica (HistoricalSize - NumberOfPeriods Counter) MovingAverage Acumulación / NumberOfPeriods El código se explicará en la clase. Desea posicionar la función en la hoja de cálculo para que aparezca el resultado del cálculo donde quiera lo siguiente. Promedios de movimiento: Cuáles son? Entre los indicadores técnicos más populares, las medias móviles se utilizan para medir la dirección de la tendencia actual. Cada tipo de media móvil (comúnmente escrito en este tutorial como MA) es un resultado matemático que se calcula promediando un número de puntos de datos pasados. Una vez determinado, el promedio resultante se traza en un gráfico para permitir a los operadores ver los datos suavizados en lugar de centrarse en las fluctuaciones de precios cotidianas que son inherentes a todos los mercados financieros. La forma más simple de una media móvil, apropiadamente conocida como media móvil simple (SMA), se calcula tomando la media aritmética de un conjunto dado de valores. Por ejemplo, para calcular una media móvil básica de 10 días, sumaría los precios de cierre de los últimos 10 días y luego dividiría el resultado por 10. En la Figura 1, la suma de los precios de los últimos 10 días (110) es Dividido por el número de días (10) para llegar al promedio de 10 días. Si un comerciante desea ver un promedio de 50 días en lugar, el mismo tipo de cálculo se haría, pero incluiría los precios en los últimos 50 días. El promedio resultante a continuación (11) tiene en cuenta los últimos 10 puntos de datos con el fin de dar a los comerciantes una idea de cómo un activo tiene un precio en relación con los últimos 10 días. Quizás usted se está preguntando porqué los comerciantes técnicos llaman a esta herramienta una media móvil y no apenas una media regular. La respuesta es que cuando los nuevos valores estén disponibles, los puntos de datos más antiguos deben ser eliminados del conjunto y los nuevos puntos de datos deben entrar para reemplazarlos. Por lo tanto, el conjunto de datos se mueve constantemente para tener en cuenta los nuevos datos a medida que estén disponibles. Este método de cálculo garantiza que sólo se contabilice la información actual. En la figura 2, una vez que se agrega el nuevo valor de 5 al conjunto, el cuadro rojo (que representa los últimos 10 puntos de datos) se desplaza a la derecha y el último valor de 15 se deja caer del cálculo. Debido a que el valor relativamente pequeño de 5 reemplaza el valor alto de 15, se esperaría ver el promedio de la disminución de conjunto de datos, lo que hace, en este caso de 11 a 10. Cómo se ven los valores promedio móviles Una vez que los valores de la MA se han calculado, se representan en un gráfico y luego se conectan para crear una línea de media móvil. Estas líneas curvas son comunes en las cartas de los comerciantes técnicos, pero la forma en que se utilizan puede variar drásticamente (más sobre esto más adelante). Como se puede ver en la Figura 3, es posible agregar más de una media móvil a cualquier gráfico ajustando el número de períodos de tiempo utilizados en el cálculo. Estas líneas curvas pueden parecer distracción o confusión al principio, pero youll acostumbra a ellos como el tiempo pasa. La línea roja es simplemente el precio medio en los últimos 50 días, mientras que la línea azul es el precio promedio en los últimos 100 días. Ahora que usted entiende lo que es un promedio móvil y lo que parece, bien introducir un tipo diferente de media móvil y examinar cómo se diferencia de la mencionada media móvil simple. La media móvil simple es muy popular entre los comerciantes, pero como todos los indicadores técnicos, tiene sus críticos. Muchas personas argumentan que la utilidad de la SMA es limitada porque cada punto en la serie de datos se pondera de la misma, independientemente de dónde se produce en la secuencia. Los críticos sostienen que los datos más recientes son más significativos que los datos anteriores y deberían tener una mayor influencia en el resultado final. En respuesta a esta crítica, los comerciantes comenzaron a dar más peso a los datos recientes, que desde entonces ha llevado a la invención de varios tipos de nuevos promedios, el más popular de los cuales es el promedio móvil exponencial (EMA). Promedio móvil exponencial El promedio móvil exponencial es un tipo de media móvil que da más peso a los precios recientes en un intento de hacerla más receptiva A nueva información. Aprender la ecuación algo complicada para calcular un EMA puede ser innecesario para muchos comerciantes, ya que casi todos los paquetes de gráficos hacen los cálculos para usted. Sin embargo, para los geeks de matemáticas que hay, aquí es la ecuación EMA: Cuando se utiliza la fórmula para calcular el primer punto de la EMA, puede observar que no hay ningún valor disponible para utilizar como la EMA anterior. Este pequeño problema se puede resolver iniciando el cálculo con una media móvil simple y continuando con la fórmula anterior desde allí. Le hemos proporcionado una hoja de cálculo de ejemplo que incluye ejemplos reales de cómo calcular una media móvil simple y una media móvil exponencial. La diferencia entre la EMA y la SMA Ahora que tiene una mejor comprensión de cómo se calculan la SMA y la EMA, echemos un vistazo a cómo estos promedios difieren. Al mirar el cálculo de la EMA, notará que se hace más hincapié en los puntos de datos recientes, lo que lo convierte en un tipo de promedio ponderado. En la Figura 5, el número de periodos de tiempo utilizados en cada promedio es idéntico (15), pero la EMA responde más rápidamente a los precios cambiantes. Observe cómo el EMA tiene un valor más alto cuando el precio está subiendo, y cae más rápidamente que el SMA cuando el precio está disminuyendo. Esta capacidad de respuesta es la razón principal por la que muchos comerciantes prefieren utilizar la EMA sobre la SMA. Qué significan los diferentes días? Las medias móviles son un indicador totalmente personalizable, lo que significa que el usuario puede elegir libremente el tiempo que desee al crear el promedio. Los períodos de tiempo más comunes utilizados en las medias móviles son 15, 20, 30, 50, 100 y 200 días. Cuanto más corto sea el lapso de tiempo utilizado para crear el promedio, más sensible será a los cambios de precios. Cuanto más largo sea el lapso de tiempo, menos sensible o más suavizado será el promedio. No hay un marco de tiempo adecuado para usar al configurar sus promedios móviles. La mejor manera de averiguar cuál funciona mejor para usted es experimentar con una serie de diferentes períodos de tiempo hasta encontrar uno que se adapte a su estrategia. Medios móviles: Cómo utilizarlos Suscribirse a las noticias para utilizar para las últimas ideas y análisis Gracias por inscribirse en Investopedia Insights - Noticias de uso. Cuando se calcula una media móvil en ejecución, colocar el promedio en el período de tiempo medio tiene sentido En el anterior Por ejemplo, calculamos el promedio de los 3 primeros períodos de tiempo y lo colocamos al lado del período 3. Podríamos haber colocado el promedio en el medio del intervalo de tiempo de tres períodos, es decir, al lado del período 2. Esto funciona bien con el tiempo impar Períodos, pero no tan bueno para incluso períodos de tiempo. Entonces, dónde colocaríamos el primer promedio móvil cuando M 4 Técnicamente, el promedio móvil caería en t 2,5, 3,5. Para evitar este problema, suavizar las MA utilizando M 2. Así, suavizar los valores suavizados Si la media de un número par de términos, tenemos que suavizar los valores suavizados La siguiente tabla muestra los resultados utilizando M 4.Moving Promedios y centrado Media móvil Un par de puntos sobre la estacionalidad en una serie de tiempo se repiten, incluso si parecen obvias. Una es que el término 8220season8221 no se refiere necesariamente a las cuatro estaciones del año que resultan de la inclinación del eje Earth8217s. En la analítica predictiva, 8220season8221 a menudo significa precisamente eso, porque muchos de los fenómenos que estudiamos varían con la progresión de la primavera a través del invierno: ventas de engranajes de invierno o de verano, incidencia de ciertas enfermedades generalizadas, eventos meteorológicos causados ​​por la ubicación del Corriente de chorro y cambios en la temperatura del agua en el Océano Pacífico oriental, y así sucesivamente. Igualmente, los acontecimientos que ocurren regularmente pueden actuar como estaciones meteorológicas, a pesar de que sólo tienen una conexión tenue con los solsticios y los equinoccios. Los turnos de ocho horas en hospitales y fábricas a menudo se expresan en la incidencia de consumos y gastos de energía allí, una temporada es de ocho horas de duración y las estaciones ciclo todos los días, no todos los años. Las fechas de vencimiento de los impuestos señalan el inicio de una inundación de dólares en los tesoros municipales, estatales y federales, la temporada puede ser de un año (impuestos a la renta personal), seis meses (impuestos sobre la propiedad en muchos estados), trimestrales ), y así. Es un poco extraño que tengamos la palabra 8220season8221 para referirnos generalmente al período de tiempo que se repite regularmente, pero no hay término general para el período de tiempo durante el cual ocurre una vuelta completa de las estaciones. 8220Cycle8221 es posible, pero en analítica y pronóstico ese término se suele considerar un período de duración indeterminada, como un ciclo económico. En ausencia de un término mejor, se utilizó en este y en los siguientes capítulos. Esto no es sólo reflexión terminológica. Las formas en que identificamos las estaciones y el período de tiempo durante el cual las estaciones tienen repercusiones reales, aunque a menudo menores, en cómo medimos sus efectos. En las siguientes secciones se discute cómo algunos analistas varían la forma en que calculan los promedios móviles según si el número de estaciones es impar o incluso. Usando los promedios móviles en lugar de los promedios simples Suponga que una gran ciudad está considerando la reasignación de su policía de tránsito para abordar mejor la incidencia de la conducción mientras está deteriorada, lo que la ciudad cree que ha ido aumentando. Hace cuatro semanas, entró en vigor una nueva legislación que legalizaba la posesión y el uso recreativo de la marihuana. Desde entonces, el número diario de arrestos por tráfico de DWI parece estar subiendo. La complicación es el hecho de que el número de detenciones parece aumentar los viernes y los sábados. Para ayudar a planificar los requerimientos de mano de obra en el futuro, le gustaría prever cualquier tendencia subyacente que se establezca. A usted también le gustaría tiempo el despliegue de sus recursos para tener en cuenta cualquier temporada relacionada con el fin de semana que ocurra. La Figura 5.9 tiene los datos relevantes con los que tiene que trabajar. Figura 5.9 Con este conjunto de datos, cada día de la semana constituye una temporada. Incluso observando el gráfico de la figura 5.9. Usted puede decir que la tendencia del número de detenciones diarias está para arriba. You8217ll tiene que planificar para ampliar el número de oficiales de tráfico, y esperamos que la tendencia se estabilice pronto. Además, los datos corroboran la idea de que más arrestos ocurren rutinariamente los viernes y sábados, por lo que su asignación de recursos necesita abordar esos picos. Pero usted necesita cuantificar la tendencia subyacente, para determinar cuántos policías adicionales tienen que traer. También es necesario para cuantificar el tamaño esperado de los picos de fin de semana, para determinar cuántos policías adicionales que necesita para ver los conductores erráticos en esos días. El problema es que aún no sabes cuánto del aumento diario se debe a la tendencia y cuánto se debe a ese efecto de fin de semana. Usted puede comenzar por detrending la serie de tiempo. Anteriormente en este capítulo, en 8220Simple Seasonal Averages, 8221 usted vio un ejemplo de cómo detrend una serie de tiempo con el fin de aislar los efectos estacionales usando el método de promedios simples. En esta sección usted verá cómo hacerlo utilizando promedios móviles, probablemente, el enfoque de promedios móviles se usa más a menudo en el análisis predictivo que el enfoque de promedios simples. Hay varias razones para la mayor popularidad de las medias móviles, entre ellas, que el enfoque de las medias móviles no le pide que colapse sus datos en el proceso de cuantificación de una tendencia. Recordemos que el ejemplo anterior hizo necesario colapsar los promedios trimestrales con los promedios anuales, calcular una tendencia anual y luego distribuir una cuarta parte de la tendencia anual en cada trimestre del año. Este paso era necesario para eliminar la tendencia de los efectos estacionales. Por el contrario, el enfoque de las medias móviles le permite desviar la serie de tiempo sin recurrir a ese tipo de maquinación. La figura 5.10 muestra cómo funciona el enfoque de las medias móviles en el presente ejemplo. Figura 5.10 El promedio móvil en el segundo gráfico aclara la tendencia subyacente. La Figura 5.10 añade una columna de media móvil y una columna para estaciones específicas. Al conjunto de datos de la figura 5.9. Ambas adiciones requieren cierta discusión. Los picos en los arrestos que tienen lugar los fines de semana le da razón para creer que usted está trabajando con temporadas que se repiten una vez cada semana. Por lo tanto, comience por obtener el promedio para el período que abarca8212, es decir, las primeras siete temporadas, de lunes a domingo. La fórmula para el promedio en la celda D5, la primera media móvil disponible, es la siguiente: Esta fórmula se copia y se pega a través de la celda D29, por lo que tiene 25 promedios móviles basados ​​en 25 ciclos de siete días consecutivos. Observe que para mostrar las primeras y últimas observaciones de la serie temporal, he ocultado las filas 10 a 17. Puede mostrarlas, si lo desea, en el libro de este capítulo, disponible en el sitio web del editor. Haga una selección múltiple de filas visibles 9 y 18, haga clic con el botón secundario en uno de sus encabezados de fila y elija Mostrar en el menú contextual. Cuando ocultas las filas de una hoja de trabajo, como he hecho en la figura 5.10. Los datos cartografiados en las filas ocultas también se ocultan en el gráfico. Las etiquetas del eje x sólo identifican los puntos de datos que aparecen en el gráfico. Debido a que cada promedio móvil en la Figura 5.10 abarca siete días, ningún promedio móvil se empareja con las tres primeras o últimas tres observaciones reales. Copiar y pegar la fórmula en la celda D5 hasta un día a la celda D4 lo hace fuera de las observaciones8212 no hay ninguna observación registrada en la celda C1. Del mismo modo, no hay media móvil registrada por debajo de la celda D29. Copiar y pegar la fórmula en D29 en D30 requeriría una observación en la celda C33, y no hay observación disponible para el día que la célula representaría. Sería posible, por supuesto, acortar la longitud de la media móvil a, digamos, cinco en lugar de siete. Hacerlo significaría que las fórmulas de promedio móvil en la Figura 5.10 podrían comenzar en la celda D4 en lugar de D5. Sin embargo, en este tipo de análisis, desea que la duración de la media móvil sea igual al número de estaciones: siete días en una semana para eventos que se repiten semanalmente implica un promedio móvil de siete y cuatro trimestres en un año para eventos que Recur anualmente implica un promedio móvil de longitud cuatro. En líneas similares, generalmente cuantificamos los efectos estacionales de tal manera que se suman a cero dentro del período de tiempo abarcador. Como se vio en la primera sección de este capítulo, en los promedios simples, esto se hace calculando el promedio de (digamos) los cuatro trimestres de un año y luego restando el promedio del año de cada cifra trimestral. De este modo se asegura que el total de los efectos estacionales es cero. A su vez, ese 8217s útil porque pone los efectos estacionales en un pie de igualdad 8212a efecto de verano de 11 es tan lejos de la media como un efecto de invierno de 821111. Si desea promedio de cinco estaciones en lugar de siete para obtener su promedio móvil, you8217re mejor De encontrar un fenómeno que se repite cada cinco temporadas en lugar de cada siete. Sin embargo, cuando se toma el promedio de los efectos estacionales más tarde en el proceso, es improbable que estos promedios sumen a cero. Es necesario en ese punto recalibrar, o normalizar. Los promedios para que su suma sea cero. Cuando se hace esto, los promedios promedio estacionales expresan el efecto en un período de tiempo de pertenecer a una estación particular. Una vez normalizados, los promedios estacionales se denominan los índices estacionales que este capítulo ya ha mencionado varias veces. En la Figura 5.10 también se muestra lo que se conoce como estaciones estacionales específicas en la columna E. Estas son las que quedan después de restar el promedio móvil de la observación real. Para tener una idea de lo que representan los temporales específicos, considere el promedio móvil en la celda D5. Es la media de las observaciones en C2: C8. Las desviaciones de cada observación de la media móvil (por ejemplo, C2 8211 D5) se garantiza que suman a cero 8212 que es una característica de un promedio. Por lo tanto, cada desviación expresa el efecto de estar asociado con ese día en particular en esa semana en particular. Es una temporada específica, entonces específica porque la desviación se aplica a ese lunes o martes particular y así sucesivamente, y estacional, porque en este ejemplo se trata cada día como si fuera una estación en el período abarcador de una semana. Debido a que cada temporada específica mide el efecto de estar en esa temporada frente a la media móvil para ese grupo de (aquí) siete temporadas, puede posteriormente mediar las estaciones específicas de una temporada en particular (por ejemplo, todos los viernes en su Series temporales) para estimar ese efecto general, más que específico, de la temporada. Ese promedio no se confunde con una tendencia subyacente en la serie temporal, ya que cada estación específica expresa una desviación de su propio promedio móvil. Alinear los promedios móviles también es la cuestión de alinear las medias móviles con el conjunto de datos original. En la Figura 5.10. He alineado cada promedio móvil con el punto medio de la gama de observaciones que incluye. Así, por ejemplo, la fórmula en la celda D5 promedia las observaciones en C2: C8 y la he alineado con la cuarta observación, el punto medio del rango promedio, colocándolo en la fila 5. Esta disposición se denomina una media móvil centrada . Y muchos analistas prefieren alinear cada media móvil con el punto medio de las observaciones que promedia. Tenga en cuenta que en este contexto, 8220midpoint8221 se refiere a la mitad de un período de tiempo: El jueves es el punto medio de lunes a domingo. No se refiere a la mediana de los valores observados, aunque, por supuesto, podría funcionar de esa manera en la práctica. Otro enfoque es el promedio móvil de arrastre. En ese caso, cada media móvil se alinea con la observación final de que promedia 8212 y, por lo tanto, sigue detrás de sus argumentos. Esta es a menudo la disposición preferida si se desea utilizar un promedio móvil como pronóstico, como se hace con el suavizado exponencial, porque su promedio móvil final coincide con la observación disponible final. Centrado Medios móviles con números pares de las estaciones Normalmente adoptamos un procedimiento especial cuando el número de estaciones es incluso en lugar de impar. Ese es el estado típico de las cosas: tienden a haber incluso números de estaciones en el período abarcador para temporadas típicas, como meses, trimestres y períodos cuadrienales (para las elecciones). La dificultad con un número par de estaciones es que no hay punto medio. Dos no es el punto medio de un rango que comienza en 1 y termina en 4, y tampoco es 3 si se puede decir que tiene uno, su punto medio es 2,5. Seis no es el punto medio de 1 a 12, y tampoco es 7 su punto medio puramente teórico es 6,5. Para actuar como si existiera un punto medio, debe agregar una capa de promediación encima de los promedios móviles. Vea la Figura 5.11. Figura 5.11 Excel ofrece varias maneras de calcular una media móvil centrada. La idea detrás de este enfoque para conseguir una media móvil que se centró en un punto medio existente, cuando hay un número par de temporadas, es tirar de ese punto medio hacia delante por la mitad de una temporada. Usted calcula un promedio móvil que sería centrado en, digamos, el tercer punto en el tiempo si cinco estaciones en lugar de cuatro constituyeran una vuelta completa del calendario. Esto se realiza tomando dos promedios móviles consecutivos y haciendo un promedio de ellos. Así en la Figura 5.11. Hay un promedio móvil en la celda E6 que promedia los valores en D3: D9. Debido a que hay cuatro valores estacionales en D3: D9, el promedio móvil en E6 se considera centrado en la temporada imaginaria 2.5, medio punto por debajo de la primera temporada candidata disponible, 3. (Las estaciones 1 y 2 no están disponibles como puntos medios para Falta de datos al promedio antes de la Temporada 1.) Tenga en cuenta, sin embargo, que el promedio móvil en la celda E8 promedia los valores en D5: D11, el segundo a través del quinto en la serie de tiempo. Ese promedio se centra en (imaginario) punto 3.5, un período completo por delante de la media centrada en 2,5. Mediante el promedio de los dos promedios móviles, por lo que el pensamiento va, puede tirar el punto central del primer promedio móvil hacia adelante por medio punto, de 2,5 a 3. That8217s lo que los promedios en la columna F de la figura 5.11 hacer. La celda F7 proporciona el promedio de las medias móviles en E6 y E8. Y el promedio en F7 está alineado con el tercer punto de datos en la serie de tiempo original, en la celda D7, para enfatizar que el promedio se centra en esa temporada. Si se expande la fórmula en la celda F7, así como las medias móviles en las celdas E6 y E8, verá que resulta ser un promedio ponderado de los primeros cinco valores de la serie temporal, con el primer y el quinto valor dados un peso De 1 y el segundo a cuarto valores dado un peso de 2. Eso nos lleva a una forma más rápida y sencilla de calcular una media móvil centrada con un número par de estaciones. Todavía en la Figura 5.11. Los pesos se almacenan en el rango H3: H11. Esta fórmula devuelve el primer promedio móvil centrado, en la celda I7: Esa fórmula devuelve 13.75. Que es idéntico al valor calculado por la fórmula de doble promedio en la celda F7. Haciendo la referencia a los pesos absolutos, por medio de los signos de dólar en H3: H11. Puede copiar la fórmula y pegarla en la medida de lo necesario para obtener el resto de las medias móviles centradas. Detrender la serie con los promedios móviles Cuando haya substraído las medias móviles de las observaciones originales para obtener las estaciones específicas, ha eliminado la tendencia subyacente de la serie. Lo que se deja en las estaciones estacionales es normalmente una serie horizontal y estacionaria con dos efectos que hacen que los estacionales específicos se aparten de una línea absolutamente recta: los efectos estacionales y el error aleatorio en las observaciones originales. La figura 5.12 muestra los resultados de este ejemplo. Figura 5.12 Los efectos estacionales específicos para el viernes y el sábado permanecen claros en la serie de tendencias. El gráfico superior de la figura 5.12 muestra las observaciones diarias originales. Tanto la tendencia general al alza como los picos estacionales del fin de semana son claros. El gráfico inferior muestra los datos estacionales específicos: el resultado de la detrensión de la serie original con un filtro de media móvil, como se describió anteriormente en 8220. Entendiendo las estaciones específicas.8221 Puede ver que la serie detrended es ahora prácticamente horizontal (una línea de tendencia lineal para los estacionales específicos Tiene una ligera desviación hacia abajo), pero los picos estacionales del viernes y del sábado todavía están en su lugar. El siguiente paso es pasar de los datos estacionales específicos a los índices estacionales. Vea la Figura 5.13. Figura 5.13 Los efectos estacionales específicos se promedian primero y luego se normalizan para alcanzar los índices estacionales. En la figura 5.13. Las series estacionales específicas en la columna E se reordenan en la forma tabular mostrada en el intervalo H4: N7. El propósito es simplemente hacer más fácil calcular los promedios estacionales. Estos promedios se muestran en H11: N11. Sin embargo, las cifras en H11: N11 son promedios, no desviaciones de un promedio, y por lo tanto podemos esperar que suman a cero. Todavía tenemos que ajustarlos para que expresen desviaciones de un gran medio. Esa gran media aparece en la celda N13, y es el promedio de los promedios estacionales. Podemos llegar a los índices estacionales restando la media grande en N13 de cada uno de los promedios estacionales. El resultado está en el rango H17: N17. Estos índices estacionales ya no son específicos de un promedio móvil determinado, como es el caso de las estaciones específicas en la columna E. Debido a que se basan en un promedio de cada instancia de una temporada dada, expresan el efecto promedio de una temporada dada a lo largo de la temporada Cuatro semanas en la serie de tiempo. Además, son medidas de una estación, un día en las detenciones de tráfico frente a la media durante un período de siete días. Ahora podemos usar esos índices estacionales para desestacionalizar la serie. Utilizaremos la serie desestacionalizada para obtener pronósticos a través de la regresión lineal o el método Holt8217s de suavizar las series de tendencias (discutidas en el Capítulo 4). Entonces simplemente agregamos los índices estacionales de nuevo en los pronósticos para reseasonalized ellos. Todo esto aparece en la figura 5.14. Figura 5.14 Después de tener los índices estacionales, los toques finales que se aplican aquí son los mismos que en el método de promedios simples. Los pasos ilustrados en la figura 5.14 son en gran parte los mismos que los de las figuras 5.6 y 5.7. En las siguientes secciones. Desestacionalización de las observaciones Reste los índices estacionales de las observaciones originales para desestacionalizar los datos. Puede hacerlo como se muestra en la Figura 5.14. En el que las observaciones originales y los índices estacionales se disponen como dos listas que comienzan en la misma fila, las columnas C y F. Esta disposición hace que sea un poco más fácil estructurar los cálculos. También puede hacer la resta como se muestra en la Figura 5.6. En el que se muestran en un formato tabular las observaciones trimestrales originales (C12: F16), los índices trimestrales (C8: F8) y los resultados desestacionalizados (C20: F24). Ese arreglo hace que sea un poco más fácil concentrarse en los índices estacionales y los trimestres desastrosos. Pronóstico de las observaciones desestacionalizadas En la Figura 5.14. Las observaciones desestacionalizadas están en la columna H y en la figura 5.7 se encuentran en la columna C. Independientemente de si se desea usar un enfoque de regresión o un enfoque de suavizado para el pronóstico, es mejor organizar las observaciones desestacionalizadas en una lista de una sola columna. En la Figura 5.14. Las previsiones están en la columna J. La siguiente fórmula de matriz se introduce en el rango J2: J32. Anteriormente en este capítulo, señalé que si omite el argumento x-values ​​de los argumentos de la función TREND () function8217s, Excel proporciona los valores predeterminados 1. 2. N. Donde n es el número de valores y. En la fórmula dada, H2: H32 contiene 31 valores y. Dado que falta el argumento que normalmente contiene los valores x, Excel proporciona los valores predeterminados 1. 2. 31. Estos son los valores que queremos utilizar de todos modos, en la columna B, por lo que la fórmula dada es equivalente a TREND (H2: H32, B2: B32). Y eso 8217s la estructura utilizada en D5: D24 de la Figura 5.7: Haciendo el pronóstico de un paso hacia adelante Hasta ahora se han arreglado para los pronósticos de las series temporales desestacionalizadas de t 1 a t 31 en la figura 5.14. Y de t 1 a t 20 en la figura 5.7. Estas previsiones constituyen información útil para diversos fines, incluida la evaluación de la exactitud de las previsiones mediante un análisis RMSE. Pero su propósito principal es pronosticar por lo menos el siguiente período de tiempo aún no observado. Para conseguirlo, puede pronosticar primero desde la función TREND () o LINEST () si utiliza la regresión o desde la fórmula de suavizado exponencial si utiliza el método Holt8217s. A continuación, puede agregar el índice estacional asociado al pronóstico de regresión o suavizado, para obtener un pronóstico que incluya tanto la tendencia como el efecto estacional. En la Figura 5.14. Se obtiene el pronóstico de regresión en la celda J33 con esta fórmula: En esta fórmula, los valores y en H2: H32 son los mismos que en las otras fórmulas TREND () en la columna J. Así son los valores x (por defecto) de 1 A través de 32. Ahora, sin embargo, suministra un nuevo valor x como el tercer argumento de la función 8217, que le indica a TREND () que busque en la celda B33. It8217s 32. El siguiente valor de t. Y Excel devuelve el valor 156.3 en la celda J33. La función TREND () en la celda J33 indica a Excel, en efecto, 8220Cálculo de la ecuación de regresión para los valores en H2: H32 regresó a los valores t de 1 a 31. Aplique esa ecuación de regresión al nuevo valor de x de 32 y devuelva el resultado.8221 Usted encontrará el mismo enfoque tomado en la celda D25 de la Figura 5.7. Donde la fórmula para obtener el pronóstico de un paso adelante es la siguiente: Adición de los índices estacionales Volver En El paso final es reseasonalize los pronósticos mediante la adición de los índices estacionales a las previsiones de tendencia, invirtiendo lo que hizo cuatro pasos atrás cuando se resta el Índices de las observaciones originales. Esto se hace en la columna F en la figura 5.7 y la columna K en la figura 5.14. No olvide agregar el índice estacional apropiado para el pronóstico de un paso adelante, con los resultados mostrados en la celda F25 en la Figura 5.7 y en la celda K33 en la Figura 5.14. (I8217ve shaded the one-step-ahead cells in both Figure 5.7 and Figure 5.14 to highlight the forecasts.) You can find charts of three representations of the traffic arrest data in Figure 5.15. the deseasonalized series, the linear forecast from the deseasonalized data, and the reseasonalized forecasts. Note that the forecasts incorporate both the general trend of the original data and its Friday/Saturday spikes. Figure 5.15 Charting the forecasts.2.4: Trend and Seasonal Components Fore 133.an ancient term of warning bearing the threat of harm at worst, and uncertainty at best, to those within potential range. Cast 133 serving up a projectile to the unseen and usually unknown beneath the deceptive surface Forecast. . a warning to those who use it. a confession of uncertainty (or deception) by those who create it. a threat of harm to those in its path From Tom Brown in Getting the Most of Forecasting 2.1: Introduction to Forecasting Although the quantitative methods of business can be studied as independent modules, I believe it is appropriate that the text places the forecasting material right after decision analysis. Recall in our decision analysis problems, the states of nature generally referred to varying levels of demand or some other unknown variable in the future. Predicting, with some measure of accuracy or reliability, what those levels of demand will be is our next subject. Forecasts are more than simple extrapolations of past data into the future using mathematical formulas, or gathering trends from experts133. Forecasts are mechanisms of arriving at measures for planning the future. When done correctly, they provide an audit trail and a measure of their accuracy. When not done correctly, they remind us of Tom Browns clever breakdown of the term repeated at the opening of these notes. Not only do forecasts help us plan, they help us save money I am aware of one company that reduced its investment in inventory from 28 million to 22 million by adopting a formal forecasting method that reduced forecast error by 10. This is an example of forecasts helping product companies replace inventory with information, which not only saves money but improves customer response and service. When we use the term forecasting in a quantitative methods course, we are generally referring to quantitative time series forecasting methods . These models are appropriate when: 1) past information about the variable being forecast is available, 2) the information can be quantified, and 3) it is assumed that patterns in the historical data will continue into the future. If the historical data is restricted to past values of the response variable of interest, the forecasting procedure is called a time series method. For example, many sales forecasts rely on the classic time series methods that we will cover in this module. When the forecast is based on past sales, we have a time series forecast. A side note: although I said sales above, whenever possible, we try to forecast sales based on past demand rather than sales133 why Suppose you own a T-shirt shop at the beach. You stock 100 Spring Break 2000 T-shirts getting ready for Spring Break. Further suppose that 110 Spring Breakers enter your store to buy Spring Break 2000 T-shirts. What are your sales Thats right, 100. But what is your demand Right again, 110. You would want to use the demand figure, rather than the sales figure, in preparing for next year as the sales figures do not capture your stock outs. So why do many companies make sales forecasts based on past sales and not demand The chief reason is cost - sales are easily captured at the check out station, but you need some additional feature on your management information system to capture demand. Back to the introduction. The other major category of forecasting methods that rely on past data are regression models . often referred to as causal models as in our text. These models base their prediction of future values of the response variable, sales for example, on related variables such as disposable personal income, gender, and maybe age of the consumer. You studied regression models in the statistics course, so we will not cover them in this course. However, I do want to say that we should use the term causal with caution, as age, gender, or disposable personal income may be highly related to sales, but age, gender or disposable personal income may not cause sales. We can only prove causation in an experiment. The final major category of forecasting models includes qualitative methods which generally involve the use of expert judgment to develop the forecast. These methods are useful when we do not have historical data, such as the case when we are launching a new product line without past experience. These methods are also useful when we are making projections into the far distant future. We will cover one of the qualitative models in this introduction. First, lets examine a simple classification scheme for general guidelines in selecting a forecasting method, and then cover some basic principles of forecasting. Selecting a Forecasting Method The following table illustrates general guidelines for selecting a forecasting method based on time span and purpose criteria. Trend Projection Moving Average Exponential Smoothing Please understand that these are general guidelines. You may find a company using trend projection to make reliable forecasts for product sales 3 years into the future. It should also be noted that since companies use computer software time series forecasting packages rather than hand computations, they may try several different techniques and select the technique which has the best measure of accuracy (lowest error). As we discuss the various techniques, and their properties, assumptions and limitations, I hope that you will gain an appreciation for the above classification scheme. Forecasting Principles Classification schemes such as the one above are useful in helping select forecasting methods appropriate to the time span and purpose at hand. There are also some general principles that should be considered when we prepare and use forecasts, especially those based on time series methods. Oliver W. Wight in Production and Inventory Control in the Computer Age . and Thomas H. Fuller in Microcomputers in Production and Inventory Management developed a set of principles for the production and inventory control community a while back that I believe have universal application. 1. Unless the method is 100 accurate, it must be simple enough so people who use it know how to use it intelligently (understand it, explain it, and replicate it). 2. Every forecast should be accompanied by an estimate of the error (the measure of its accuracy). 3. Long term forecasts should cover the largest possible group of items restrict individual item forecasts to the short term. 4. The most important element of any forecast scheme is that thing between the keyboard and the chair. The first principle suggests that you can get by with treating a forecast method as a black box, as long as it is 100 accurate. That is, if an analyst simply feeds historical data into the computer and accepts and implements the forecast output without any idea how the computations were made, that analyst is treating the forecast method as a black box. This is ok as long as the forecast error (actual observation - forecast observation) is zero. If the forecast is not reliable (high error), the analyst should be, at least, highly embarrassed by not being able to explain what went wrong. There may be much worse ramifications than embarrassment if budgets and other planning events relied heavily on the erroneous forecast. The second principle is really important. In section 2.2 we will introduce a simple way to measure forecast error, the difference between what actually occurs and what was predicted to occur for each forecast time period. Here is the idea. Suppose an auto company predicts sales of 30 cars next month using Method A. Method B also comes up with a prediction of 30 cars. Without knowing the measure of accuracy of the two Methods, we would be indifferent as to their selection. However, if we knew that the composite error for Method A is /- 2 cars over a relevant time horizon and the composite error for Method B is /- 10 cars, we would definitely select Method A over Method B. Why would one method have so much error compared to another That will be one of our learning objectives in this module. It may be because we used a smoothing method rather than a method that incorporates trend projection when we should not have - such as when the data exhibits a growth trend. Smoothing methods such as exponential smoothing, always lag trends which results in forecast error. The third principle might best be illustrated by an example. Suppose you are Director of Operations for a hospital, and you are responsible for forecasting demand for patient beds. If your forecast was going to be for capacity planning three years from now, you might want to forecast total patient beds for the year 2003. On the other hand, if you were going to forecast demand for patient beds for April 2000, for scheduling purposes, then you would need to make separate forecasts for emergency room patient beds, surgery recovery patient beds, OB patient beds, and so forth. When much detail is required, stick to a short term forecast horizon aggregate your product lines/type of patients/etc. when making long term forecasts. This generally reduces the forecast error in both situations. We should apply the last principle to any quantitative method. There is always room for judgmental adjustments to our quantitative forecasts. I like this quote from Alfred North Whitehead in An Introduction to Mathematics . 1911: 91T93here is no more common error than to assume that, because prolonged and accurate mathematical calculations have been made, the application of the result to some fact of nature is absolutely certain. Of course, judgment can be off too. How about this forecast made in 1943 by IBM Chairman Thomas Watson: I think theres a world market for about five computers. How can we improve the application of judgment That is our next subject. The Delphi Method of Forecasting The Delphi Method of forecasting is a qualitative technique made popular by the Rand Corporation. It belongs to the family of techniques that include methods such as Grass Roots, Market Research Panel, Historical Analogy, Expert Judgment, and Sales Force Composite. The thing in common with these approaches is the use of the opinions of experts, rather than historical data, to make predictions and forecasts. The subjects of these forecasts are typically the prediction of political, social, economic or technological developments that might suggest new programs, products, or responses from the organization sponsoring the Delphi study. My first experience with expert judgment forecasting techniques was at my last assignment during my past career in the United States Air Force. In that assignment, I was Director of Transportation Programs at the Pentagon. Once a year, my boss, the Director of Transportation, would gather senior leadership (and their action officers) at a conference to formulate transportation plans and programs for the next five years. These programs then became the basis for budgeting, procurement, and so forth. One of the exercises we did was a Delphi Method to predict developments that would have significant impact on Air Force Transportation programs. I recall one of the developments we predicted at a conference in the early 1980s was the accelerated movement from decentralized to centralized strategic transportation systems in the military. As a result, we began to posture the Air Force for the unified transportation command several years before it became a reality. Step 1. The Delphi Method of Forecasting, like the other judgment techniques, begins with selecting the experts. Of course, this is where these techniques can fail - when the experts are really not experts at all. Maybe the boss is included as an expert for the Delphi study, but while the boss is great at managing resources, he or she may be terrible at reading the environment and predicting developments. Step 2. The first formal step is to obtain an anonymous forecast on the topic of interest. This is called Round 1 . Here, the experts would be asked to provide a political, economic, social or technological developments of interest to the organization sponsoring the Delphi Method. The anonymous forecasts may be gathered through a Web Site, via e-mail or by questionnaire. They may also be gathered in a live group setting but the halo effect may stifle the free flow of the predictions. For example, it would be common for the group of experts gathered at the Pentagon to include general officers. Several of the generals were great leaders in the field, but not great visionaries when it came to logistics developments. On the other hand, their lieutenant colonel action officers were very good thinkers and knew much about what was on the horizon for logistics and transportation systems. However, because of the classic respect for rank, the younger officers might not have been forthcoming if we did not use an anonymous method to get the first round of forecasts. Step 3. The third step in the Delphi Method involves the group facilitator summarizing and redistributing the results of the Round One forecasts. This is typically a laundry list of developments. The experts are then asked to respond to the Round One laundry list by indicating the year in which they believed the development would occur or to state this development will never occur. This is called Round 2 . Step 4. The fourth step, Round 3 . involves the group facilitator summarizing and redistributing the results of the Round Two. This includes a simple statistical display, typically the median and interquartile range, for the data (years a development will occur) from Round 2. The summary would also include the percent of experts reporting never occur for a particular development. In this Round, the experts are asked to modify, if they wish, their predictions. The experts are also given the opportunity to provide arguments challenging or supporting the never occur predictions for a particular development, and to challenge or support the years outside the interquartile range. Step 5. The fifth step, Round 4 . repeats Round 3 - the experts receive a new statistical display with arguments - and are requested to provide new forecasts and/or counter arguments. Step 6. Round 4 is repeated until consensus is formed, or at least, a relatively narrow spread of opinions. My experience is that by Round 4, we had a good idea of the developments we should be focusing upon. If the original objective of the Delphi Method is to produce a number rather than a development trend, then Round 1 simply asks the experts for their first prediction. This might be to predict product demand for a new product line for a consumer products company or to predict the DJIA one year out for a mutual fund company managing a blue chip index fund. Lets do a for fun (not graded and purely volunteer) Delphi Exercise. Suppose you are a market expert and wish to join the other experts in our class in predicting what the DJIA will be on April 16, 2001 (as close to tax due date as possible). I will post a Conference Topic called DJIA Predictions on the course Web Board, within the Module 2 conference. Please reply to that conference topic by simply stating what you think the DJIA will close at on April 16, 2001. Please respond by January 27, 2001, so I can post the summary statistics before we leave the forecasting material on February 3rd. We will now begin our discussion of quantitative time series forecasting methods. 2.2: Smoothing Methods In this section we want to cover the components of a time series naive, moving average and exponential smoothing methods of forecasting and measuring forecast accuracy for each of the methods introduced. Pause and Reflect Recall that there are three general classes of forecasting or prediction models. Qualitative methods, including the Delphi, rely on expert judgment and opinion, not historical data. Regression models rely on historical information about both predictor variables and the response variable of interest. Quantitative time series forecasting methods rely on historical numerical information about the variable of interest and assume patterns in the past will continue into the future. This section begins our study of the time series models, beginning with patterns or components of time series. Components of a Time Series The patterns that we may find in a time series of historical data include the average, trend, seasonal, cyclical and irregular components . The average is simply the mean of the historical data. Trend describes real growth or decline in average demand or other variable of interest, and represents a shift in the average. The seasonal component reflects a pattern that repeats within the total time frame of interest. For example, 15 years ago in Southwest Florida, airline traffic was much higher in January - April, peaking in March. October was the low month. This seasonal pattern repeated through 1988. Between 1988 and 1992, January - April continued to repeat each year as high months, but the peaks were not as high as before, nor the off-season valleys as low as before, much to the delight of the hotel and tourism industries. The point is, seasonal peaks repeat within the time frame of interest - usually monthly or quarterly seasons within a year, although there can be daily seasonality in the stock market (Mondays and Fridays showing higher closing averages than Tuesdays - Thursdays) as an example. The cyclical component shows recurring values of the variable of interest above or below the average or long-run trend line over a multiyear planning horizon. The length of cycles is not constant, as with the length of seasonal peaks and valleys, making economic cycles much tougher to predict. Since the patterns are not constant, multiple variable models such as econometric and multiple regression models are better suited to predict cyclical turning points than time series models. The last component is whats left The irregular component is the random variation in demand that is unexplained by the average, trend, seasonal and/or cyclical components of a time series. As in regression models, we try to make the random variation as low as possible. Quantitative models are designed to address the various components covered above. Obviously, the trend projection technique will work best with time series that exhibit an historical trend pattern. Time series decomposition, which decomposes the trend and seasonal components of a time series, works best with times series having trend and seasonal patterns. Where does that leave our first set of techniques, smoothing methods Actually, smoothing methods work well in the presence of average and irregular components. We start with them next. Before we start, lets get some data. This time series consists of quarterly demand for a product. Historical data is available for 12 quarters, or three years. Table 2.2.1 provides the history. Figure 2.2.1 provides a graph of the time series. This graph was prepared in Excel using the Chart Wizards Line Plot chart assistant. It is not important what software is used to graph the historical time series - but it is important to look at the data. Even making a pen and paper sketch is useful to get a feel for the data, and see if there might be trend and/or seasonal components in the time series. Moving Average Method A simple technique which works well with data that has no trend, seasonality nor cyclic components is the moving average method. Admittedly, this example data set has trend (note the overall growth rate from period 1 to 12), and seasonality (note that every third quarter reflects a decrease in historical demand). But lets apply the moving average technique to this data so we will have a basis for comparison with other methods later on. A three period moving average forecast is a method that takes three periods of data and creates an average. That average is the forecast for the next period. For this data set, the first forecast we can compute is for Period 4, using actual historical data from Periods 1, 2 and 3 (since its a three period moving average). Then, after Period 4 occurs, we can make a forecast for Period 5, using historical data from Periods 2, 3, and 4. Note that Period 1 dropped off, hence the term moving average. This technique then assumes that actual historical data in the far distant past, is not as useful as more current historical data in making forecasts. Before showing the formulas and illustrating this example, let me introduce some symbols. In this module, I will be using the symbol F t to represent a forecast for period t. Thus, the forecast for period 4 would be shown as F 4 . I will use the symbol Y t to represent the actual historical value of the variable of interest, such as demand, in period t. Thus, the actual demand for period 1 would be shown as Y 1 . Now to carry forward the computations for a three period moving average. The forecast for period four is: To generate the forecast for period five: We continue through the historical data until we get to the end of Period 12 and make our forecast for Period 13 based on actual demand from Periods 10, 11 and 12. Since Period 12 is the last period for which we have data, this ends our computations. If someone was interested in making a forecast for Periods 14, 15, and 16, as well as Period 13, the best that could be done with the moving average method would be to make the out period forecasts the same as the most current forecast. This is true because moving average methods cannot grow or respond to trend. This is the chief reason these types of methods are limited to short term applications, such as what is the demand for the next period. The forecast calculations are summarized in Table 2.2.2. Since we are interested in measuring the magnitude of the error to determine forecast accuracy, note that I square the error to remove the plus and minus signs. Then, we simple average the squared errors. To compute an average or a mean, first s um the s quared e rrors (SSE) . then divide by the number of errors to get the m ean s quared e rror (MSE) . then take the square root of the error to get the R oot M ean S quare E rror (RMSE). SSE (235.1 608.4 . 625.0 455.1) 9061.78 MSE 9061.78 / 9 1006.86 RMSE Square Root (1006.86) 31.73 From your statistics course(s), you will recognize the RMSE as simply the standard deviation of forecast errors and the MSE is simply the variance of the forecast errors. Like the standard deviation, the lower the RMSE the more accurate the forecast. Thus, the RMSE can be very helpful in choosing between forecast models. We can also use the RMSE to do some probability analysis. Since the RMSE is the standard deviation of the forecast error, we can treat the forecast as the mean of a distribution, and apply the important empirical rule . assuming that forecast errors are normally distributed. I will bet that some of you remember this rule: 68 of the observations in a bell-shaped symmetric distribution lie within the area: mean /- 1 standard deviation 95 of the observations lie within: mean /- 2 standard deviations 99.7 (almost all of the observations) lie within: mean /- 3 standard deviations Since the mean is the forecast, and the standard deviation is the RMSE, we can express the empirical rule as follows: 68 of actual values are expected to fall within: Forecast /- 1 RMSE 454.3 /- 31.73 423 to 486 95 of the actual values are expected to fall within: Forecast /- 2 RMSE 454.3 /- (231.73) 391 to 518 99.7 of the actual values are expected to fall within: Forecast /- 3 RMSE 454.3 /- (331.73) 359 to 549 As in studying the mean and standard deviation in descriptive statistics, this is very important and has similar applications. One thing we can do is use the 3 RMSE values to determine if we have any outliers in our data that need to be replaced. Any forecast that is more than 3 RMSEs from the actual figure (or has an error greater than the absolute value of 3 31.73 or 95 is an outlier. That value should be removed since it inflates the RMSE. The simplest way to remove an outlier in a time series is to replace it by the average of the value just before the outlier and just after the outlier. Another very hand use for the RMSE is in the setting of safety stocks in inventory situations. Lets draw out the 2 RMSE region of the empirical rule for this forecast: 2.5 95 2.5 359. 391. 454. 518. 549 Since the middle 95 of the observations fall between 391 and 518, 5 of the observations fall below 391 and above 518. Assuming the distribution is bell shaped, 2.5 of the observations fall below 391 and 2.5 fall above 518. Another way of stating this is that 97.5 of the observations fall below 518 (when measuring down to negative infinity, although the actual data should stop at 359. Bottom line . if the firm anticipates actual demand to be 518 (2 RMSEs above the forecast), then by stocking an inventory of 518 they will cover 97.5 of the actual demands that theoretically could occur. That is, the are operating at a 97.5 customer service level . In only 2.5 of the demand cases should they expect a stock out. Thats really slick, isnt it. Following the same methodology, if the firm stocks 549 items, or 3 RMSEs above the forecast, they are virtually assured they will not have a stock out unless something really unusual occurs (we call that an outlier is statistics). Finally, if the firm stocks 486 items (2 RMSEs above the forecast), they will have a stock out in 16 of the cases, or cover 84 of the demands that should occur (100 - 16). In this case, they are operating at an 84 customer service level. 16 68 16 359. 423. 454. 486. 549 We could compute other probabilities associated with other areas under the curve by finding the cumulative probability for z scores, z (observation - forecast) / RMSE (do you remember that from the stat course(s)). For our purposes here, it is only important to illustrate the application from the statistics course. Using The Management Scientist Software Package We will be using The Management Scientist Forecasting Module to do the actual forecasts and RMSE computations. To illustrate the package for the first example, click Windows Start/Programs/The Management Scientist/The Management Scientist Icon/Continue/Select Module 11 Forecasting/OK/File/New and you are ready to load the example problem. The next dialog screen asks you to enter the number of time periods - that is how many observations to you have - 12 in this case. Click OK . and start entering your data (numbers and decimal points only - the dialog screen will not allow alpha characters or commas). Next, click Solution/Solve/Moving Average and enter 3 where it asks for number of moving periods. You should get the following solution: FORECASTING WITH MOVING AVERAGES THE MOVING AVERAGE USES 3 TIME PERIODS TIME PERIOD TIME SERIES VALUE FORECAST FORECAST ERROR THE MEAN SQUARE ERROR 1,006.86 THE FORECAST FOR PERIOD 13 454.33 Please note that the software returns the Mean Square Error . and to get the more useful Root Mean Square Error . you need to take the square root of the Mean Square Error, 1006.83 in this case. Also note that the software provides just one forecast value, recognizing the limitation of moving average methods that limit the projection to one time period. Finally note that I put the data into an html table only so you can read it better - this is only necessary in going from the OUT file to html, not to an e-mail insertion of the OUT file or copying an OUT file into a WORD document. As with the decision analysis module solutions, you may then select Solution/Print Solution and either select Printer to print, or Text File to save for inserting into an e-mail to me, or into a Word Document. Before we do one more moving average example, take a look at the forecast error column. Note that most of the errors are positive. Since error is equal to actual time series value minus the forecasted values, positive errors mean that the actual demand is generally greater than the forecasted demand - we are under forecasting. In this case, we are missing a growth trend in the data. As pointed out earlier, moving average techniques do not work well with time series data that exhibit trends. Figure 2.2.2 illustrates the lag that is present when using the moving average technique with a time series that exhibits a trend. Five Period Moving Average Forecast Here is The Management Scientist solution for using 5 periods to construct the moving average forecast. FORECASTING WITH MOVING AVERAGES THE MOVING AVERAGE USES 5 TIME PERIODS TIME PERIOD TIME SERIES VALUE FORECAST FORECAST ERROR THE MEAN SQUARE ERROR 1,349.37 THE FORECAST FOR PERIOD 13 453.60 The RMSE for the Five-Period Moving Average forecast is 36.7, which is about 16 worse than the error of the three - period model. The reason for this is that there is a growth trend in this data. As we increase the number of periods in the computation of the moving average, the average begins to lag the growth trend by greater amounts. The same would be true if the historical data exhibited a downward trend. The moving average would lag the trend and provide forecasts that would be above the actual. Pause and Reflect The moving average forecasting method is simple to use and understand, and it works well with time series that do not have trend, seasonal or cyclical components. The technique requires little data, only enough past observations to match the number of time periods in in the moving average. Forecasts are usually limited to one period ahead. The technique does not work well with data that is not stationary - data that exhibits trend, seasonality, and/or cyclic patterns. One-Period Moving Average Forecast or the Naive Forecast A naive forecast would be one where the number of periods in the moving average is set equal to one. That is, the next forecast is equal to the last actual demand. Dont laugh This technique might be useful in the case of rapid growth trend the forecast would only lag the actual by one quarter or by one month, whatever the time period of interest. Of course, it would be much better to use a model that can make a trend projection if the trend represents a real move from a prior stationary pattern - we will get to that a bit later. Here is The Management Scientist result for the One-Period Moving Average Forecast. FORECASTING WITH MOVING AVERAGES THE MOVING AVERAGE USES 1 TIME PERIODS TIME PERIOD TIME SERIES VALUE FORECAST FORECAST ERROR THE MEAN SQUARE ERROR 969.91 THE FORECAST FOR PERIOD 13 473.00 This printout reflects a slightly lower RMSE than the three period moving average. That concludes our introduction to smoothing techniques by examining the class of smoothing methods called moving averages. The last smoothing method we will examine is called exponential smoothing , which is a form of a weighted moving average method. Exponential Smoothing This smoothing model became very popular with the production and inventory control community in the early days of computer applications because it did not need much memory, and allowed the manager some judgment input capability. That is, exponential smoothing includes a smoothing parameter that is used to weight either past forecasts (places emphasis on the average component) or the last observation (places emphasis on a rapid growth or decline trend component). The exponential smoothing model is: F t1 forecast of the time series for period t 1 Y t actual value of the time series in period t F t forecast of the time series for period t a smoothing constant or parameter (0 lt a lt 1) The smoothing constant or parameter, a . is shown as the Greek symbol alpha in the text - I am limited to alpha characters. In any case, if the smoothing constant is set at 1, the formula becomes the naive model we already studied: If the smoothing constant is set at 0, the formula becomes a weighted average model which gives most weight to the most recent forecast, with diminishing weight the farther back in the time series. Setting a can be done by trial and error, perhaps trying 0.1, 0.5 and 0.9, recording the RMSE for each run, then choosing the value of a that gives forecasts with the lowest RMSE. Some guidelines are, set a relatively high when there is a trend and you want the model to be responsive set a relatively low when there is just the irregular component so the model will not be responding to random movements. Lets do some exponential smoothing forecasts with a set at 0.6, relatively high. To get the model started, we begin by making a forecast for Period 2 simply based on the actual demand for Period 1 (first shown in Table 2.2.1, but often repeated with each demonstration). Then the first exponential smoothing forecast is actually made for Period 3, using information from Period 2. Thus t 2, t1 3, and F t1 F 21 F 3 . For this forecast, we need the actual demand for Period 2 (Y t Y 2 395), the forecast for Period 2 (F 2 398. The result is: The next forecast is for Period 4: This continues through the data until we get to the end of Period 12 and are ready to make our last forecast for Period 13. Note that all we have to maintain in historical data is the last forecast, the last actual demand and the value of the smoothing parameter - that is why the technique was so popular since it did not take much data. However, I do not subscribe to throwing away data files today - they should be archived for audit trail purposes. Anyway, the forecast for Period 13: Thankfully today, we have software like The Management Scientist to do the computations. To use The Management Scientist . select the Forecasting Module and load the data as previously described in the Three Period Moving Average demonstration. Next, click Solution/Solve/Exponential Smoothing and enter 0.6 where it asks for the value of the smoothing constant. Printout 2.2.4 illustrates the computer output with a smoothing constant of 0.6. FORECASTING WITH EXPONENTIAL SMOOTHING THE SMOOTHING CONSTANT IS 0.6 TIME PERIOD TIME SERIES VALUE FORECAST FORECAST ERROR THE MEAN SQUARE ERROR 871.52 THE FORECAST FOR PERIOD 13 459.74 This model provides a single forecast since, like the moving average techniques, it does not have the capability to address the trend component. The Root Mean Square Error is 29.52, (square root of the mean square error), or slightly better than the best results of the moving average and naive techniques. However, since the time series shows trend, we should be able to do much better with the trend projection model that is demonstrated next. Pause and Reflect The exponential smoothing technique is a simple technique that requires only five to ten historical observations to set the value of the smoothing parameter, then only the most recent actual observation and forecasting values. Forecasts are usually limited to one period ahead. The technique works best for time series that are stationary, that is, do not exhibit trend, seasonality and/or cyclic components. While historical data is generally used to fit the model - that is set the value of a . analysts may adjust that value in light of information reflecting changes to time series patterns. 2.3: Trend Projections When a time series reflects a shift from a stationary pattern to real growth or decline in the time series variable of interest (e. g. product demand or student enrollment at the university), that time series is demonstrating the trend component. The trend projection method of time series forecasting is based on the simple linear regression model. However, we generally do not require the rigid assumptions of linear regression (normal distribution of the error component, constant variance of the error component, and so forth), only that the past linear trend pattern will continue into the future. Note that is the trend pattern reflects a curve, we would have to rely on the more sophisticated features of multiple regression. The trend projection model is: T t Trend value for variable of interest in Period t b 0 Intercept of the trend projection line b 1 Slope, or rate of change, for the trend projection line While the text illustrates the computational formulas for the trend projection model, we will use The Management Scientist . To use The Management Scientist . select the Forecasting Module and load the data as previously described in the Three Period Moving Average demonstration. Next, click Solution/Solve/Trend Projection and enter 4 where it asks for Number of Periods to Forecast. Note, this is the first method that we have covered that the software asks this question, as it is assumed that all of the smoothing methods covered in this course are limited to forecasting just one period ahead. Printout 2.3.1 illustrates the trend projection printout from The Management Scientist . FORECASTING WITH LINEAR TREND THE LINEAR TREND EQUATION: T 367.121 7.776 t where T trend value of the time series in period t TIME PERIOD TIME SERIES VALUE FORECAST FORECAST ERROR THE MEAN SQUARE ERROR 449.96 THE FORECAST FOR PERIOD 13 468.21 THE FORECAST FOR PERIOD 14 475.99 THE FORECAST FOR PERIOD 15 483.76 THE FORECAST FOR PERIOD 16 491.54 Now we are getting somewhere with a forecast Note the mean square error is down to 449.96, giving a root mean square error of 21.2. Compared to the three period moving average RMSE of 31.7, we have a 33 improvement in the accuracy of the forecast over the relevant period. Now, if this were products such as automobiles, to achieve a customer service level of 97.5, we would create a safety stock of 2 times the RMSE above the forecast. So, for Period 13, the forecast plus 2 times the RMSE is 468.21 (2 21.2) or 511 cars. With the three period moving average method, the same customer service level inventory position would be: 454.3 (2 31.7) or 518. The safety stocks are 2 times 21 (42 for the trend projection) compared to 2 times 31.7 (63 for the three period moving average). This is a difference of 21 cars which could represent significant inventory carrying cost that could be avoided with the better forecasting method. Note that the software provides the trend equation, showing the intercept of 367.121 and the slope of 7.776. The slope is interpreted as in simple linear regression, demand goes up 7.776 per unit increase in time. This means that over the course of the time series, demand is increasing about 8 units a quarter. The intercept is only of interest in placing the trend projection line on a time series graph. I used the Chart Wizard in Excel to produce such a graph for the trend projection model: Note in this figure that demand falls below the trend projection line in Periods 3, 7 and 11. This is confirmed by looking at The Management Scientist computer Printout 2.3.1, where the errors are negative in the same periods. That is a pattern Since our data is quarterly, we would suspect that there is a seasonal pattern that results in a valley in the time series in every third quarter. To capture that pattern, we need the time series decomposition model that breaks down, analyzes and forecasts the seasonal as well as the trend components. We do that in the last section of this notes modules. Pause and Reflect The trend projection model is appropriate when the time series exhibits a linear trend component that is assumed to continue into the future. While rules of thumb suggest 20 observations to compute and test parameters of linear regression models, the simple trend projection model can be created with a minimum of 10 observations. The trend projection model is generally used to make multiple period forecasts for the short range, although some firms use it for the intermediate range as well. 2.4: Trend and Seasonal Components The last time series forecasting method that we examine is very powerful in that it can be used to make forecasts with time series that exhibit trend and seasonal components. The method is most often referred to as Time Series Decomposition, since the technique involves breaking down and analyzing a time series to identify the seasonal component in what are called seasonal indexes . The seasonal indexes are used to deseasonalize the time series. The deseasonalized time series is then used to identify the trend projection line used to make a deseasonalized projection. Lastly, seasonal indexes are used to seasonalize the trend projection. Lets illustrate how this works. As usual, we will use The Management Scientist to do our work after the illustration. The Seasonal Component The seasonal component may be found by using the centered moving average approach as presented in the text, or by using the season average to grand average approach described here. The latter is a simpler technique to understand, and comes very close to the centered moving average approach for most time series. The first step is to gather observations from the same quarter and find their average. I will repeat Table 2.2.1 as Table 2.4.1, so we can easily find the data: To compute the average demand for Quarter 1, we gather all observations for Quarter 1 and find their average, then repeat for Quarters 2, 3 and 4: Quarter 1 Average (398 410 465) / 3 424.3 Quarter 2 Average (395 402 460) / 3 419 Quarter 3 Average (361 378 430) / 3 389.7 Quarter 4 Average (400 440 473) / 3 437.7 The next step is to find the seasonal indexes for each quarter. This is done by dividing the quarterly average from above, by the grand average of all observations. Grand Average (398395361400410402378 440465460430473) / 12 417.7 Seasonal Index, Quarter 1 424.3 / 417.7 1.016 Seasonal Index, Quarter 2 419 / 417.7 1.003 Seasonal Index, Quarter 3 389.7 / 417.7 0.933 Seasonal Index, Quarter 4 437.7/ 417.7 1.048 These indexes are interpreted as follows. The overall demand for Quarter 4 is 4.5 percent above the average demand, thus making Quarter 4 a peak quarter. The overall demand for Quarter 3 is 6.7 percent below the average demand, thus making Quarter 3 an off peak quarter. This confirms our suspicion that demand is seasonal, and we have quantified the nature of the seasonality for planning purposes. Please note The Management Scientist software Printout 2.4.1 provides indexes of 1.046, 1.009, 0.920, and 1.025. The peaks and off peaks are similar to the above computations, although the specific values are a bit different. The centered moving average approach used by the software requires more data for computations - at least 4 or 5 repeats of the seasons, we only have 3 repeats (12 quarters gives 3 years of data). We will let the computer program do the next steps, but I will illustrate with a couple of examples. The next task is to deseasonalize the data. We do this by dividing each actual observation by the appropriate seasonal index. So for the first observation, where actual demand was 398, we note that it is a first quarter observation. The deseasonalized value for 398 is: Deseasonalized Y 1 398 / 1.016 391.7 Actual demand would have been 391.7 if there was no seasonal effects. Lets do four more: Deseasonalized Y 2 395 / 1.003 393.8 Deseasonalized Y 3 361 / 0.933 386.9 Deseasonalized Y 4 400 / 1.048 381.7 Deseasonalized Y 5 410 / 1.016 403.6 I am sure you have seen deseasonalized numbers in articles in the Wall Street Journal or other popular business press and journals. This is how those are computed. The next step is to find the trend line projection based on the deseasonalized observations. This trend line is a bit more accurate than the trend line projection based on the actual observations since than line contains seasonal variation. The Management Scientist gives the following trend line for this data: This trend line a close to the line we computed in Section 2.3, when the line was fit to the actual, rather than the seasonal data: T t 367 7.8 t. Once we have the trend line, making a forecast is easy. Lets say we want to make a forecast for time period 2. Of course, The Management Scientist does all this for us. To use The Management Scientist . select the Forecasting Module and load the data as previously described in the Three Period Moving Average demonstration. Next, click Solution/Solve/Trend and Seasonal . then enter 4 where it asks for number of seasons, and 4 where it asks for number of periods to forecast. - click OK to get the solution. Note that number of seasons is 4 for quarterly data, 12 for monthly data, and so forth. Here is the printout. Printout 2.4.1 FORECASTING WITH TREND AND SEASONAL COMPONENTS SEASON SEASONAL INDEX THE MEAN SQUARE ERROR 87.25 THE FORECAST FOR PERIOD 13 494.43 THE FORECAST FOR PERIOD 14 485.44 THE FORECAST FOR PERIOD 15 450.64 THE FORECAST FOR PERIOD 16 510.40 The Mean Square Error of 87.25, gives a root mean square error of 9.3, a spectacular improvement over the other techniques. A sketch of the actual and forecast data shows how well the trend and seasonal model can do at responding to the trend and the seasonal turn points. Note how the four period out forecast continues the response to both components. Pause and Reflect The trend and seasonal components method is appropriate when the time series exhibits a linear trend and seasonality. This model, compared to the others, does require significantly more historical data. It is suggested that you should have enough data to see at least four or five repetitions of the seasonal peaks and off peaks (with quarterly data, there should be 16 to 20 observations with monthly data, there should be 48 to 60 observations). Well, thats it to the introduction to times series forecasting material. Texts devoted entirely to this subject go into much more detail, of course. For example, there are exponential smoothing models that incorporate trend and time series decomposition models that incorporate the cyclic component. A good reference for these is Wilson and Keating, Business Forecasting . 2nd ed. Irwin (1994). Two parting thoughts. In each of the Pause and Reflect paragraphs, I gave suggestions for number of observations in the historical data base. There is always some judgment required here. While we need a lot of data to fit the trend and trend and seasonal models, a lot of data may mean going far into the past. When we go far into the past, the patterns in the data may be different, and the time series forecasting models assume that any patterns in the past will continue into the future (not the values of the past observations, but the patterns such as slope and seasonal indexes). When worded on forecasts for airport traffic, we would love to go back 10 years, but tourist and permanent resident business travel is different today than 10 years ago so we must balance the need for a lot of data with the assumption of forecasting. The second thought is to always remember to measure the accuracy of your models. We ended with a model that had a root mean square error that was a 75 improvement over the 5-period moving average. I know one company that always used a 5-period moving average for their sales forecasts - scary, isnt it You should be ready to tackle the assignment for Module 2, Forecasting Lost Sales, in the text, pp. 210-212. The case answers via e-mail and The Management Scientist computer output files are due February 10, 2001. If you want free review of your draft responses/output, please forward as a draft by Tuesday, February 6, 2001. Module Schedule

No comments:

Post a Comment