Docsity

Data Analysis and Forecasting, Appunti di Analisi Dei Dati

Anteprima parziale del testo

Scarica Data Analysis and Forecasting e più Appunti in PDF di Analisi Dei Dati solo su Docsity!

    1. Geƫng started
    1. Time series graphics
    1. Time series decomposiƟon
    1. Time series features
    1. The forecaster’s toolbox
    1. Time series regression model
    1. ExponenƟal smoothing

1. Getting started

1.1. What can be forecast? Whatever the circumstances or time horizons involved, forecasting is an important aid to effective and efficient planning.  Forecasts can be required several years in advance (for the case of capital investments), or only a few minutes beforehand (for telecommunication routing) The predictability of an event or a quantity depends on several factors including:

  1. how well we understand the factors that contribute to it;
  2. how much data is available;
  3. how similar the future is to the past;
  4. whether the forecast can affect the thing we are trying to forecast _Example: short-term forecasts of residential electricity demand can be highly accurate as
  5. known of the contributing factors: electricity demand is driven largely by temperatures, with smaller effects for calendar variation such as holidays, and economic conditions.
  6. several years of data on electricity demand available, and many decades of data on weather conditions.
  7. for short-term forecasting, it can be assumed that demand behavior will be similar to what has already been seen.
  8. the demand forecasts have little or no effect on consumer behavior. However, we have a limited understanding of the factors that affect exchange rates, the future may be different to the past if there is a financial or political crisis, and forecasts of the exchange rate have a direct effect on the rates themselves._ Every environment is changing, and a good forecasting model captures the way in which things are changing What is normally assumed is that the way in which the environment is changing will continue into the future.

1.2. Forecasting, goals and planning Forecasting should be an integral part of the decision-making activities of management, as it can play an important role in many areas of a company. Forecasting is about predicting the future as accurately as possible, given all of the information available, including historical data and knowledge of any future events that might impact the forecasts. Goals: what you would like to have happen. Goals should be linked to forecasts and plans, but too often, goals are set without any plan for how to achieve them, and no forecasts for whether they are realistic. Planning is a response to forecasts and goals. Planning involves determining the appropriate actions that are required to make your forecasts match your goals. Time horizon  Short-term forecasts  needed for the scheduling of personnel, production and transportation. As part of the scheduling process, forecasts of demand are often also required.  Medium-term forecasts  needed to determine future resource requirements, in order to purchase raw materials, hire personnel, or buy machinery and equipment.  Long-term forecasts  used in strategic planning. Such decisions must take account of market opportunities, environmental factors and internal resources.

Predictor variables and time series forecasting Suppose we wish to forecast the hourly electricity demand (ED) of a hot region during the summer period. A model with predictor variables might be of the form. 𝐸𝐷 = 𝑓(𝑐𝑢𝑟𝑟𝑒𝑛𝑡 𝑡𝑒𝑚𝑝𝑒𝑟𝑎𝑡𝑢𝑟𝑒, 𝑠𝑡𝑟𝑒𝑛𝑔ℎ𝑡 𝑜𝑓 𝑒𝑐𝑜𝑛𝑜𝑚𝑦, 𝑝𝑜𝑝𝑢𝑙𝑡𝑖𝑜𝑛, 𝑡𝑖𝑚𝑒 𝑜𝑓 𝑑𝑎𝑦, 𝑑𝑎𝑦 𝑜𝑓 𝑤𝑒𝑒𝑘, 𝑒𝑟𝑟𝑜𝑟) 𝑦ෝ (^) ்ାଵ | ் = 𝑓(𝑥ଵ, … , 𝑥ଶ)

The “error” term on the right allows for random variation and the effects of relevant variables that are not included in the model. This is called an explanatory model because it helps explain what causes the variation in electricity demand. We could also use a time series model for forecasting. In this case, the time series forecasting equation is of the form: 𝐸𝐷௧ାଵ = 𝑓(𝐸𝐷௧, 𝐸𝐷௧ିଵ , 𝐸𝐷௧ିଶ , 𝐸𝐷௧ିଷ , … , 𝑒𝑟𝑟𝑜𝑟) 𝑦ෝ (^) ்ାଵ | ் = 𝑓(𝑦ଵ, … , 𝑦் )

t is the present hour  here the prediction is based on past values of a variable, but not on external variables that may affect the system There is also a third type of model that combines the features of the above models 𝐸𝐷௧ାଵ = 𝑓(𝐸𝐷௧, 𝑐𝑢𝑟𝑟𝑒𝑛𝑡 𝑡𝑒𝑚𝑝𝑒𝑟𝑎𝑡𝑢𝑟𝑒, 𝑡𝑖𝑚𝑒 𝑜𝑓 𝑑𝑎𝑦, 𝑑𝑎𝑦 𝑜𝑓 𝑤𝑒𝑒𝑘, 𝑒𝑟𝑟𝑜𝑟) 𝑦ෝ (^) ்ାଵ | ் = 𝑓(𝑦ଵ, … , 𝑦் , 𝑥ଵ, … , 𝑥ଶ)

These types of “mixed models”. They are known as dynamic regression models, panel data models , longitudinal models, transfer function models, and linear system models (assuming that f is linear). An explanatory model is useful because it incorporates information about other variables, rather than only historical values of the variable to be forecast. However, there are several reasons a forecaster might select a time series model rather than an explanatory or mixed model:  the system may not be understood, and even if it is understood it may be extremely difficult to measure the relationships that are assumed to govern its behavior  it is necessary to know or forecast the variable of interest  the main concern may be to predict what will happen and not why it happens  the time series model may give a more accurate forecast than the explanatory or mixed one. The model to be used in forecasting depends on the resources and data available, the accuracy of the competing models, and the way in which the forecasting model is to be used.

1.5. The basic steps in a forecasting task A forecasting task usually involves five basic steps. 1) Problem definition It is important to know the goal and all the possible details of the phenomenon you are working on.  requires an understanding of the way the forecasts will be used, who requires the forecasts, and how the forecasting function fits within the organization requiring the forecasts. 2) Gathering information a) numerical, statistical data  They can be collected by interviewing someone

b) the accumulated expertise of the people who collect the data and use the forecasts (i.e., data scientist) Often, it will be difficult to obtain enough historical data to be able to fit a good statistical model  judgmental forecasting methods. 3) Preliminary or exploratory/descriptive analysis Always start by analyzing graphing the data. Usually, there are different types of plots useful for time- series analysis.  Are there consistent patterns? Is there a significant trend? Is seasonality important? Is there evidence of the presence of business cycles? Are there any outliers in the data that need to be explained by those with expert knowledge? How strong are the relationships among the variables available for analysis? 4) Choosing and fitting models The best model to use depends on the availability of historical data, the strength of relationships between the forecast variable and any explanatory variables, and the way in which the forecasts are to be used. Regression models, exponential smoothing methods, Box-Jenkins ARIMA models, dynamic regression models, Hierarchical forecasting, several advanced methods including neural networks and vector autoregression

  1. Using and evaluating a forecasting model. Once a model has been selected and its parameters estimated, the model is used to make forecasts. There are possibilities to evaluate the accuracy of the model:
  1. Computing a computing interval, although this depends on some assumptions, so it might be not the right choice if you’re not sure about the assumptions.
  2. Comparing the forecast with the real data, we can have a training set to be compared with the corresponding test set. Then, the ideal situation is when the difference is very small. There are many possibilities to apply this method, one example is the cross-validation that uses more than one test set.  this method is preferred

1.6. The statistical forecasting perspective We treat the thing to forecast as a random variable  the thing we are trying to forecast is unknown. When we obtain a forecast, we are estimating the middle of the range of possible values the random variable could take.  Often, a forecast is accompanied by a prediction interval giving a range of values the random variable could take with relatively high probability

[1M] indicates monthly data

First, the month column is being converted from text to monthly time object with yearmonth(). Then, the data frame has been converted to a tsibble by identifying the index variable using as_tibble() Other time class functions can be used depending on the frequency of the observations.

The key variables A tsibble also allows multiple time series to be stored in a single object. Then, as the time series are uniquely identified by the keys, if you are interested in a specific data set you need to use the distinct() function in order to see the categories of each variable or combinations of variables. Suppose you are interested in a dataset containing the fastest running times for women’s and men’s track races at the Olympics, from 100m to 10000m [14] indicates the number of time series

[4Y] indicates the interval of these observation  4 years

Key indicates the key variable: length and sex

1916 we have NA as during the World War I Olympics were not held.

Frequency Function Annual start:end Quarterly yearquater() Monthly yearmonth() Weekly yearweek() Daily as_date(), ymd() Sub-daily as_daytime(), ymd_hms()

Working with tsibble objects We can use dplyr functions such as mutate(), filter(), select() and summarise() to work with tsibble objects. To illustrate these, we will use the PBS tsibble containing sales data on pharmaceutical products in Australia.

To know more information about the dataset we can use the command ?PBS  it works for all datasets

provided by the fpp3 package.

This contains monthly data on Medicare Australia prescription data from July 1991 to June 2008. These are classified according to various concession types, and Anatomical Therapeutic Chemical (ATC) indexes. For this example, we are interested in the Cost time series (total cost of scripts in Australian dollars).

  • filter() , this function is useful to get a specific dataset to work with, it allows us to select rows of the tsibble.
  • select() has the same function of filter() but select columns instead of rows.

Note that the index variable Month, and the keys Concession and Type, would be returned even if they were not explicitly selected as they are required for a tsibble (to ensure each row contains a unique combination of keys and index).

The original csv file stored the dates as individual days, although the data is actually quarterly, so we need to convert the Date variable to quarters.

NB: for a tsibble to be valid, it requires a unique index for each combination of keys. The tsibble() or as_tsibble() function will return an error if this is not true. The seasonal period The seasonal period is the number of observations before the seasonal pattern repeats. In most cases, this will be automatically detected using the time index variable. For quarterly, monthly and weekly data, there is only one seasonal period — the number of observations within each year.

If the data is observed more than once per week, then there is often more than one seasonal pattern in the data.

Time plots For time series data, the obvious graph to start with is a time plot : observations plotted against the time of observation, with consecutive observations joined by straight lines. It shows the weekly economy passenger loas on Ansett airlines between Melbourne and Sydney. In order to obtain the following plot, we use autoplot() command, it produces an appropriate plot. In this case it has recognized melsyd_economy as a time series so it produced a time plot.

What does it reveal?

  • Period in ‘89 when no passengers were carried  due to an industrial dispute.
  • Period of reduced load in ‘92  due to a trial in which some economy class seats were replaced by business class seats.
  • Large increase in passenger load occurred in the second half of ‘91.
  • There are some large dips in load around the start of each year  due to holiday effects.
  • There is a long-term fluctuation in the level of the series which increases during 1987, decreases in 1989, and increases again through ‘90 and ‘91.

Time series using a10 data

Here, there is a clear and increasing trend. There is also a strong seasonal pattern that increases in size as the level of the series increases. The sudden drop at the start of each year is caused by a government subsidization scheme that makes it cost-effective for patients to stockpile drugs at the end of the calendar year. Any forecasts of this series would need to capture the seasonal pattern, and the fact that the trend is changing slowly.

Possibly, if we had a much longer series, we would see that this downward trend is actually part of a long cycle, but when viewed over only 100 days it appears to be a trend.  Australian quarterly electricity production (bottom left) shows a strong increasing trend, with strong seasonality.

 Daily change in the Google closing stock price (bottom right) has no trend. There are random fluctuations which do not appear to be very predictable, and no strong patterns that would help with developing a forecasting model. How to build this grid with R

2.3. Seasonal plots A seasonal plot is similar to a time plot except that the data are plotted against the individual “seasons” in which the data were observed. A seasonal plot allows the underlying seasonal pattern to be seen more clearly, and is especially useful in identifying years in which the pattern changes. Example antidiabetic drug sales

  • There is a large jump in sales in January each yearthese are probably sales in late December as customers stockpile before the end of the calendar year, (sales are not registered until a week or two later).
  • The graph also shows that there was an unusually small number of sales in March 2008 (most other years show an increase between February and March)
  • The small number of sales in June 2008 is probably due to incomplete counting of sales at the time the data were collected. Multiple seasonal period Where the data has more than one seasonal pattern , the period argument can be used (in the function gg_season) to select which seasonal plot is required (i.e., day, week).

These data contain half-hourly electricity demand for the state of Victoria, in the case of the plot above we have the daily pattern. Note: the three days with 25 hours are when daylight saving ended in each year and so these days contained an extra hour. There were also three days with only 23 hours each (when daylight saving started) but these are hidden beneath all the other lines on the plot.

1) Autoplot

We can notice that Victoria and Queensland have opposite seasonality, probably because one state is most popular in winter and the other one in summer. These two states and New South Wales seem to be the most popular destination for overnight trips. It also makes clear that the southern states of Australia (Tasmania, Victoria and South Australia) have strongest tourism in Q1 (their summer), while the northern states (Queensland and the Northern Territory) have the strongest tourism in Q3 (their dry season).

  1. Season plot

2.5. Scatterplots Are useful to explore and visualize relationships between time series. Example We have two time series: one of half-hourly electricity demand and one of temperature, both from 2014, Victoria.

We can study the relationship between demand and temperature by plotting one series against the other.

This scatterplot helps us to visualize the relationship between the variables. It is clear that high demand occurs when temperatures are high due to the effect of air-conditioning. But there is also a heating effect, where demand increases for very low temperatures.

Correlation We use correlation to measure the strength of the linear relationship between two variables.

𝑟 =

ඥ∑(𝑥௧ − 𝑥̅)ଶ^ ඥ∑(𝑦௧ − 𝑦ത)ଶ

The value of r always lies between -1 and 1. Examples of different levels of correlation

Note: the correlation coefficient only measures the strength of the linear relationship between two variables, and can sometimes be misleading.  There’s not a strong linear relationship between electricity demand and temperature (0.28), but we ha a non-linear one Each of these plots have correlation coefficients of 0.82, but they have very different relationships. This shows how important it is to look at the plots of the data and not simply rely on correlation values.

Scatterplot matrices We use them when there are several potential predictor variables  useful to plot each variable against each other