Skip to content
ImagineWorld

Introduction to Time Series

node_idnode-book_building-statistical-models-in-python_chapter-10-introduction-to-time-series
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num10
chapter_titleIntroduction to Time Series
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 10 — Introduction to Time Series

Section titled “Chapter 10 — Introduction to Time Series”

In Chapter 9, Discriminant Analysis, we concluded our overview of statistical classification modeling by introducing conditional probability using Bayes’ theorem, Linear Discriminant Analysis (LDA), and Quadratic Discriminant Analysis (QDA). In this chapter, we will introduce time series, the underlying statistical concepts, and how to apply them in everyday analysis. We will introduce the topic with the distinction between time-series data and what we have discussed up to this point in the book. We then provide an overview of what to expect with time-series modeling and the goals it can be leveraged to achieve. Within the context of time series, we then reintroduce the mean and variance statistical parameters, in addition to correlation. We provide an overview of linear differencing, cross-correlation, and autoregressive (AR) and moving average (MA) properties and how to identify their ordering using autocorrelation function (ACF) and partial ACF (PACF) plots. After, we provide an overview of the introductory white-noise model. We conclude the chapter with a detailed, formal overview of the concept of stationarity, arguably the most important precursor to successful time-series forecasting.

In this chapter, we’re going to cover the following main topics:

  • What is a time series?
  • Goals of time-series analysis
  • Statistical measurements
  • The white-noise model
  • Stationarity

In this chapter and the next few chapters, we will work with a type of data called time-series data. Up until this point, we have worked with independent data—that is, data consisting of samples that are not related. A time series is typically a measurement of the same sample taken over time, which makes the samples in this type of data related. There are many time series present around us every day. A few common examples of time series are daily temperature measurements, stock price ticks, and the heights of ocean tides. While a time series does not need to be measured at fixed intervals, in this book, we will primarily be concerned with measurements taken at fixed intervals, such as daily or every second.

Let’s look at some notation. In the following equation, we have a variable that is repeatedly sampled over time. The subscripts enumerate the sample points (sample 1 through sample ), and the whole series of samples is denoted. The subscript value is commonly called the lag of the variable. For example, could be referred to as the second lag of the variable:

In general, the points can be univariate or multivariate. For example, we could take a temperature reading over time that would result in a univariate time series, meaning each term would correspond to a single temperature value. We could also take a more holistic set of weather readings such as temperature, humidity, rainfall, and sunshine, which would result in a multivariate time series, meaning each term would correspond to a temperature, humidity, rainfall, and sunshine value.

Our discussions on time series start with single variable analysis in this chapter and Chapter 11, ARIMA Models. But as with the chapters on regression, we will start with a single-variable approach and proceed to work with multivariate time series. Just as with the chapters on regression, we may find the multiple variables in a time series are related to the outcome of a variable of interest. In Chapter 12, Multivariate Time Series, we will deal with the extra complexity of multivariate time series and extend the single-variable models discussed in Chapter 11 to multiple variables in Chapter 12. In this chapter, we will cover the basics of time series.

Time series typically exhibit a property called serial correlation, which means that previous knowledge provides some knowledge about the future of the time series. We can measure serial correlation by comparing the current value of a time series to the previous values in the series to determine if present values are correlated with previous values. This type of correlation is also called autocorrelation. We will discuss more on autocorrelation later in this chapter, including how to determine if a series exhibits autocorrelation. Later in this chapter, we will look at how to make the calculations to determine whether data exhibits serial correlation and to calculate autocorrelation. However, let’s first discuss what we intend to achieve with time-series analysis.

There are two goals in time-series analysis:

  • Identifying any patterns in the time series
  • Forecasting future values of the time series

We can use time-series analysis methods to uncover the nature of a time series. At the most basic level, we may want to know if a series appears to be random or if a time series appears to exhibit a pattern. If a time series has a pattern, we can determine if it has seasonal behavior, cyclical patterns, or exhibits trending behavior. We will investigate the behaviors of time series both by observation and by the results of fitting models. Models can provide insight into the nature of a series and allow us to forecast the future values of a time series.

The other goal of time-series analysis is forecasting. We see examples of forecasting in many common situations, such as weather forecasting and stock price forecasting. It is important to keep in mind that the methods of forecasting we cover in this book are not infallible. Great care should be taken when communicating results from forecasting models. Predictions from models are always uncertain. Predictions should always be contextualized with an understanding of the model uncertainty. We will endeavor to reinforce this concept through the use of prediction intervals and model error rates.

Now, with the context of what we hope to achieve with time-series analysis, let’s start looking at tools for analyzing univariate time series.

When using time-series models to work with serially correlated data sets, we need to understand mean and variance – within the context of time – in addition to autocorrelation and cross-correlation. Understanding these variables helps build an intuition about how time-series models work and when they are more useful than models that do not account for time.

In time-series analysis, the sample mean of a series is the sum of all values across each point in time in the series divided by the count of values. Where t represents each discrete time step and n is the total number of time steps, we can calculate the sample mean of a time series as follows:

There are two types of processes generating time series; one is an ergodic process and the other is non-ergodic. An ergodic process has consistent output independent of time, whereas a non-ergodic process does not necessarily have consistent output over time. The sample mean of an ergodic process converges to the true population mean as the sample size increases. However, the sample mean of a non-ergodic process does not converge as the sample size increases; the sample mean of one end-to-end phase of a process’s output may not converge toward the process population mean similarly to the sample mean of another end-to-end phase of the same process. One example of a non-ergodic process is a machine that requires frequent recalibration as output quality diminishes due to factors such as moisture or vibration. The tools introduced in this chapter, and expanded in the next, will help an analyst overcome limitations presented by this natural constraint presented in process-driven time-series data.

In time-series analysis, the mean is commonly referred to as the signal. With respect to forecasting, the mean must be constant across time. We discussed in Chapter 6*, Simple Linear Regression* – as we will later in this chapter and in the next – the concept of first-order differencing, which is a low-pass linear filter used to remove high-frequency data from our output and pass through low-frequency data. When a signal is not constant, as when it is monotonically increasing or decreasing, for example, a first-order difference can often be applied—and repeated as needed—to produce a constant. This is one requirement of a stationary time series. We will discuss all components of stationarity in the Stationarity section of this chapter. Once a mean is constant, the variance around it can be assessed for autocorrelation. If autocorrelation exists within the variance around the mean, we can produce models to learn the patterns of the process producing it. We can also forecast the process’s future patterns. A model with a constant mean and no autocorrelation can often be forecasted with the mean using a white-noise model. For all times, t, in a series, the formulation for a first-order linear difference is this:

Since the first-order difference is a numerical differentiation, it will result in the removal of one data point from the time series, so must be applied prior to any modeling. Here is an example of a first-order difference in tabular data:

Raw DataFirst-Order Difference
1.7
1.4-0.3
1.90.5
2.30.4
2.1-0.2

Figure 10.1 – First-order difference in tabular data

Here, we have an example of data transformed with a first-order difference. The numpy diff() function can be used as follows, where n=1 prescribes a first-order difference:

numpy.diff(array_x, n=1)

Variance is a statistic for measuring the dispersion of data around a mean for a given distribution. Within the context of time-series analysis, variance is distributed around the mean across time. If we have a discrete and stationary process, we can calculate the variance of the sample mean as follows:

Here, n is the length of the time series, k is the number of lags to be included in the series autocorrelation (serial correlation) calculation and is the autocorrelation for that lookback horizon. This variance calculation can be obtained through model construction, which we will walk through in Chapter 11*, ARIMA Models*. It is in model construction – where we build the characteristic equations for the time series – that the measurement of variance becomes most important. Otherwise, we focus on autocorrelation to build intuition about the variance and the process producing it. Oftentimes, we have what is referred to as white-noise variance, which is a random distribution of variance generated from a stochastic process. White-noise variance has no autocorrelation across the time horizon. In the case of white-noise variance, we have only the following calculation for variance, which is the same calculation for data that is not serially correlated:

Data exhibiting white-noise variance can often be modeled with an average as there are no correlated errors. However, there may be transformations required in order to use an average, such as a first-order difference or a seasonal difference.

One common hypothesis test used in time-series analysis to assess if the variance in a series is white noise is the Ljung-Box test, created by Greta Ljung and George Box. The Ljung-Box test has the following hypotheses:

  • Data points are independently distributed with no serially correlated errors
  • Data points are not independently distributed and thus present serially correlated errors

This test can be applied to the residuals of any time-series model—for example, a linear model that uses time as an input or an autoregressive integrated moving average (ARIMA) model. If the result of the Ljung-Box test is the validation of the null hypothesis, the model tested is assumed to be valid. If the null hypothesis is rejected, a different model may be required. The Ljung-Box test statistic is shown here:

Here, n is the sample size, k corresponds to each lag in the test, h is the total time horizon being tested, and is the sample autocorrelation for each lag. The test follows the Chi-Square () distribution and thus places more emphasis on more recent lags than those in the distant past. The Ljung-Box test statistic is compared to distribution with h degrees of freedom, as follows:

Here, h is the tested horizon. A Q-statistic greater than the critical value results in rejecting the null hypothesis. The Ljung-Box test can also be applied to data without a model to test whether it is constant, zero-mean data with white-noise variance. Otherwise, the test is performed on the residuals of a model. Let’s generate a random, normally distributed sample of 1,000 data points having a mean of 0 and a standard deviation of 1 so that we can test using Ljung-Box whether the data is stationary white noise:

import numpy as np
import matplotlib.pyplot as plt
from statsmodels.graphics.tsaplots import plot_acf
random_white_noise = np.random.normal(loc=0, scale=1, size=1000)

We can observe based on the raw data that the mean is constant. We can also see that the autocorrelation structure appears to have no significant lags, which is a strong indication the variance is randomly distributed white noise. In model development, this lack of autocorrelation is what you would want to see from the residuals to help verify a model fits the process’s data well:

fig, ax = plt.subplots(1,2, figsize=(10, 5))
ax[0].plot(random_white_noise)
ax[0].axhline(0, color='r')
ax[0].set_title('Raw Data')
plot_acf(random_white_noise, ax=ax[1])

In Figure 10*.2,* we can see the original white noise data and the ACF plot, which exhibits no statistically significant autocorrelation across lags:

Figure 10.2 – Visual analysis of random white noise

Now, let’s use the Ljung-Box test to check our assumptions about autocorrelation. We perform this test with the acorr_ljungbox() function from statsmodels. We apply the lags=[50] argument to test if the autocorrelation is 0 out to 50 lags:

from statsmodels.stats.diagnostic import acorr_ljungbox
acorr_ljungbox(random_white_noise, lags=[50], return_df=True)

The test returns an insignificant p-value, seen here. Therefore, we can assert that at a 95% level of confidence, the data has no autocorrelation and is thus white noise:

lb_statlb_pvalue
5051.1526560.428186

Figure 10.3 – Ljung-Box test results for autocorrelation on white noise data

As we’ve mentioned to this point, autocorrelation, also called serial correlation, is a measure of correlation for a given point corresponding to previous points in the time-constrained sequence of data. It is called “auto” as it refers to a variable’s correlation with itself at a previous lag. Autocorrelation across all preceding lags in the specified horizon—as opposed to for a specific lag—is referred to as autocorrelation structure. Here, we have, for any given lag k greater than zero, the ACF,:

We discussed autocorrelation in Chapter 6*, Simple Linear Regression*, within the context of identifying serial correlation as a violation of the required assumption of sampling independence for linear regression. Here, we note that autocorrelation is a core component of time-series data. We previously visually explored this data in both Chapter 6 and this chapter using the ACF plot. We also discussed first-order differencing. Let’s explore these two concepts in depth using the United States Macroeconomic data set from statsmodels, which we used in Chapter 6. Here, we select realinv and realdpi, converting both variables to a 32-bit float:

import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
df = sm.datasets.macrodata.load().data
df['realinv'] = round(df['realinv'].astype('float32'), 2)
df['realdpi'] = round(df['realdpi'].astype('float32'), 2)
df_mod = df[['realinv','realdpi']]

Next, let’s plot the data and its ACF using 50 lags (lags=50) and a 5% level of significance (alpha=0.05):

from statsmodels.graphics.tsaplots import plot_acf
from statsmodels.graphics.tsaplots import plot_pacf
fig, ax = plt.subplots(2,2, figsize=(15,10))
plot_acf(df_mod['realinv'], alpha=0.05, lags=50, ax=ax[0,1])
ax[0,1].set_title('Original ACF')
ax[0,0].set_title('Original Data')
ax[0,0].plot(df_mod['realinv'])
plot_acf(np.diff(df_mod['realinv'], n=1), alpha=0.05, lags=50, ax=ax[1,1])
ax[1,1].set_title('Once-Differenced ACF')
ax[1,0].set_title('Once-Differenced Data')
ax[1,0].plot(np.diff(df_mod['realinv'], n=1))

We get the resulting plot as follows:

Figure 10.4 – realinv: original and first-difference data and ACFs

We can observe in the first plot of Figure 10*.4* a positive, deterministic signal highlighting an overall upward trend in investment. We can also observe that—especially as the time nears lag 0—some variance around the data. These two components of the data are what we would initially attempt to model. In the original data’s ACF, we can see a significant, dampening autocorrelation structure, which is characteristic of exponential growth. However, because of the strong trend that dominates the autocorrelation, we aren’t able to observe any information about the correlation in the variance, such as potential seasonality, for example. To remove the strong signal, we apply a first difference using the numpy.diff() function so that we can observe the variance’s autocorrelation structure. Looking at the ACF for the differenced data, we can see some autocorrelation in the variance extending to lag 3 when applying a 95% confidence level.

At this point, it is worth mentioning autoregressive moving average (ARMA) modeling, which we will use in Chapter 11, ARIMA Models. As we can see in the ACF plot, there is a long horizon of autocorrelation present. Going back to the autocorrelation equation we noted earlier, we can see the calculation does not control for specific lags in the time series since the errors across each point are all summed together prior to dividing by the variance. This is why the original ACF shows a dampening effect; it is reasonable to assume that lag 0 is not smoothly serially correlated, individually, with each previous lag. Because the ACF does not control for autocorrelation between specific lags, we can use this correlation information to build a moving average function that can help model the noise component of the data across a long period.

However, if we want to be able to construct a component of a model that allows us to define the relationship from point to point within the framework of ARMA models, we will want to also observe the PACF, which does control for the correlation between lags. Note in Figure 10*.5* the original data and its PACF. It shows a much different level of granularity than the ACF plot does; whereas in the PACF we don’t see a continued significant correlation with lag 0 and those beyond lag 4 until we near lag 30, we do see significant correlation in the ACF until almost lag 20. However, the original data is not very helpful because it is not stationary, which is why we see almost as much correlation between lag 0 and lag 45 as we do lag 0 and lag 1, which suggests we would not be able to build a model that converges without transformation (the first-order difference, in this case):

Figure 10.5 – realinv: original and first-difference data and PACFs

The result of the ACF in Figure 10*.4* for the transformed (differenced) data suggests a moving average component up to an order of 3 (MA(3)) could be useful (although an MA(1) may be better). The result of the PACF in Figure 10*.5* for the transformed data suggests an autoregressive component of order 1 (AR(1)) may be useful. Using the PACF, we could also conclude an AR(10) may be useful, but selecting an order this high will often result in overfitting. A rule of thumb is to not use an AR or MA component with an order greater than approximately 5 for process modeling. Model order, however, depends on the analyst and the process details. While we will discuss this concept in depth in Chapter 11*, ARIMA Models*, if we are building an ARIMA model for this data, we would have a model of order (2,1,3) following the AR(p) and MA(q) construct we selected with an integrated difference, d, for the first-order difference we applied illustrated as an order (p,d,q) model. The orders are used to build characteristic polynomial equations based on the model that we can then use to assess stationarity and invertibility, which helps identify model uniqueness and assess its ability to converge toward a solution, using the roots of the equations’ factored forms.

Moving on, we have, for any given lag k greater than zero, the cross-correlation function (CCF) that can be used to identify the correlation between two variables across points in time. This analysis can be used to facilitate the identification of leading or lagging indicators. The CCF for two one-dimensional vectors, i and j, for a given lag, k,, is shown here:

In considering a case of linear regression where we have two ordered, sequence-based input variables predicting an ordered, sequenced-based dependent variable, we evaluate the input and output variables at the same time, t. However, if using cross-correlation to identify a leading or lagging indicator, we can identify the lag, k, at which the leading variable leads and modify its series position by k indices. For example, if the time unit of our model is in weeks and we build a regression model to predict sales using advertising as an input, we may find that in any given week, advertising has no impact on sales. However, after performing a cross-correlation analysis, we find a strong lag of 1 exists between advertising and sales such that investment in advertising in 1 week directly impacts sales in the following week. We then use this information to shift forward the advertising expenditure variable by 1 week and rerun the regression model to leverage the strong correlation between advertising expense and sales to predict market behavior. This is what we can refer to as a lag effect.

Let’s look at an example of this in practice with Python. First, we need to assess the data. Let’s load the data to begin. We need to convert the values to a float type. We can round to two decimals and select realinv and realdpi, the variables for real gross private domestic investment and real private disposable income, respectively:

import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
df = sm.datasets.macrodata.load().data
df['realinv'] = round(df['realinv'].astype('float32'), 2)
df['realdpi'] = round(df['realdpi'].astype('float32'), 2)
df_mod = df[['realinv','realdpi']]

After plotting the data, here, we can see both series have what appears to be a strong, deterministic signal, which is the primary influence on the autocorrelations. It can easily be argued that the two variables are positively correlated, and both are increasing over time, which is mostly true. However, there is more to the data than meets the eye, in that regard; the mean (signal) is deterministic, but we need to assess the variance around the mean to truly understand how the two processes are correlated beyond the trend component. Note that in the following code, we use a lag of 50 when calculating the ACFs. A general rule of thumb in measuring ACFs is to not exceed a lag of 50 points, although this may differ based on context:

from statsmodels.graphics.tsaplots import plot_acf
fig, ax = plt.subplots(2,2, figsize=(20,8))
fig.suptitle('Raw Data')
ax[0,0].plot(df_mod['realinv'])
ax[0,0].set_title('Realization')
ax[1,0].set_xlabel('realinv')
ax[0,1].plot(df_mod['realdpi'])
ax[0,1].set_title('Realization')
ax[1,1].set_xlabel('realdpi')
plot_acf(df_mod['realinv'], alpha=0.05, lags=50, ax=ax[1,0])
plot_acf(df_mod['realdpi'], alpha=0.05, lags=50, ax=ax[1,1])

We get the following plot:

Figure 10.6 – Comparing realinv to realdpi: raw data and ACF plots

We can see in Figure 10*.6* that in addition to the strong deterministic signal, the ACF plots for both have exponentially dampening autocorrelations that are significant at the 95% confidence (outside of the shaded area) level. Based on this information in the ACFs, we should perform at least a first-order difference. We may need to perform two first-order differences if the ACFs exhibit the same behavior after one first-order linear difference.

Let’s create the differenced data:

df_diff = pd.DataFrame()
df_diff['realinv'] = np.diff(df_mod['realinv'], n=1)
df_diff['realdpi'] = np.diff(df_mod['realdpi'], n=1)

Now, reusing the previous plotting code, we can see the data in Figure 10*.7*:

Figure 10.7 – Comparing differenced realinv to differenced realdpi

Based on Figure 10*.7*, we can see the deterministic signal that was previously dominating the autocorrelation in Figure 10*.6 is now removed*. There are a few points slightly outside the 95% confidence interval, although the level of significance is small (we do not consider lag 0 as lag 0 is 100% correlated with itself). Because some autocorrelation remains, we can consider their behaviors to not be entirely random. Thus, they could be cross-correlated. Since we addressed the issue of the deterministic signal, we can now assess the cross-correlation between the two series. Note that the means of the two series have been differenced to a constant zero. This is one condition of stationarity. Another is constant variance. We can see the differenced data has minimal autocorrelation, but that it is beyond the 95% confidence limit. Thus, we can ascertain additional ARIMA modeling may be useful, but we could also argue for using an average for modeling. However, we can also see that the third requirement of stationarity—constant covariance between periods—does not seem to be met; as the series continues across time steps, the variance fluctuates. We will discuss stationarity in more depth in the following section. For now, let’s turn our attention to cross-correlation.

Now that we have removed the deterministic signal and the variance is the dominating behavior in the ACF plots, let’s compare the two time series to see if they have a lagging or leading relationship. Here, we construct a CCF for graphically plotting that. We have three options for the confidence interval using a dictionary, zscore_vals, to build the z-scores we use to build these confidence intervals—90%, 95%, and 99%:

from scipy.signal import correlate
import matplotlib.pyplot as plt
def plot_ccf(data_a, data_b, lag_lookback, percentile):
n = len(data_a)
ccf = correlate(data_a - np.mean(data_a), data_b - np.mean(data_b), method='direct') / (np.std(data_a) * np.std(data_b) * n)
_min = (len(ccf)-1)//2 - lag_lookback
_max = (len(ccf)-1)//2 + (lag_lookback-1)
zscore_vals={90:1.645,
95:1.96,
99:2.576}
plt.figure(figsize=(15, 5))
markers, stems, baseline = plt.stem(np.arange(-lag_lookback,(lag_lookback-1)), ccf[_min:_max], markerfmt='o', use_line_collection = True)
plt.setp(baseline, color='r', linewidth=1)
baseline.set_xdata([0,1])
baseline.set_transform(plt.gca().get_yaxis_transform())
z_score_95pct = zscore_vals.get(percentile)/np.sqrt(n) #1.645 for 90%, 1.96 for 95%, and 2.576 for 99%
plt.title('Cross-Correlation')
plt.xlabel('Lag')
plt.ylabel('Correlation')
plt.axhline(y=-z_score_95pct, color='b', ls='--')# Z-statistic for 95% CL LL
plt.axhline(y=z_score_95pct, color='b', ls='--')# Z-statistic for 95% CL UL
plt.axvline(x=0, color='black', ls='-')
;
import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
df = sm.datasets.macrodata.load().data
df['realinv'] = round(df['realinv'].astype('float32'), 2)
df['realdpi'] = round(df['realdpi'].astype('float32'), 2)
df_mod = df[['realinv','realdpi']]
df_diff = pd.DataFrame()
df_diff['realinv'] = np.diff(df_mod['realinv'], n=1)
df_diff['realdpi'] = np.diff(df_mod['realdpi'], n=1)
plot = plot_ccf(data_a=df_diff['realdpi'], data_b=df_diff['realinv'], lag_lookback=50, percentile=95)

We can observe in Figure 10*.8* many points of correlation beyond the 95% confidence interval we applied. However, we observe the highest level of correlation is at lag 0. There may be multiple correct answers depending on the data domain or forecast error when a model is applied, but using the statistics, our study indicates the series are most correlated at lag 0 and thus, neither is a leading nor lagging indicator of the other. It is important to note the practical significance of a roughly 0.20 correlation is low; it explains very little variance. Therefore, short-term influence is minimal:

Figure 10.8 – Cross-correlation between realinv and realdpi

Since we’ve assessed that short-term cross-correlation between the two series’ variances is minimal and we might still be interested in the strength of correlation overall, we could at this point use Pearson’s correlation coefficient to compare the two trends, which would measure correlation between the two long-run linear trends. Recall the equation for Pearson’s correlation coefficient to observe the relationship to the long-run mean:

Let’s suppose, however, there was a leading indicator present in our data. Let’s shift realdpi forward by one place. Notice the pandas function shift() here, performing this operation:

plot = plot_ccf(data_a=df_diff['realdpi'].shift(1).iloc[1:], data_b=df_diff['realinv'].iloc[1:], lag_lookback=50, percentile=95)

We get the result as follows:

Figure 10.9 – Shifted cross-correlation with leading indicator

After shifting realdpi forward one position, we can identify in Figure 10*.9* that realinv is now a leading indicator, by a lag of one. If this were our original, differenced data, we might decide to apply a shift to the realinv variable—keeping in mind the practicality of the level of correlation—then use realdpi and the shifted realinv variable when using one variable to forecast the values of the other.

Any time series can be considered to process two fundamental elements: signal and noise. We can present this mathematically as follows:

The signal is some predictable pattern that we can model with a mathematical function. But the noise element in a time series is unpredictable and so cannot be modeled. Thinking of a time series this way leads to two consequential points:

  1. Before attempting to model, we should verify that the time series is not consistent with noise.
  2. Once we have fit a model to a time series, we should verify that the residuals are consistent with noise.

Regarding the first point, if a time series is consistent with noise, there is no predictable pattern to model, and attempting to model the time series could lead to misleading results. About the second point, if the residuals of a time-series model are not consistent with noise, then there are additional patterns we can further model, and the current model is not sufficient to explain the patterns in the signal. Of course, to make these assessments, we first need to understand what noise is. In this section, we will discuss the white-noise model.

White noise is a time series where the samples are independent and have a fixed variance with a mean of zero. This means that each sample of the time series is random. So, how do we assess whether a series is random? Let’s work through an example. Take a look at the series in Figure 10*.10*. Do you think this series is random or a signal?

Figure 10.10 – A sample time series

The time series in Figure 10*.10* is a random series generated with numpy. This is not clear from just observing the time series. Let’s take a look at how to determine whether a series is noise.

As mentioned previously, the samples in a time series are independent. This means that the sample should not be autocorrelated. We can check the autocorrelation of this series with an ACF plot. The results are shown in Figure 10*.11*:

Figure 10.11 – ACF plot of time series in Figure 10.10

The ACF plot shows that the series does not appear to exhibit autocorrelation. This is a strong indication that the time series does not have a pattern to model and may just be noise.

Another assessment we have is the Ljung-Box test for autocorrelation. This is a statistical test for autocorrelation in the lags of a time series. The null hypothesis is there is no autocorrelation, and the alternative hypothesis is there is a correlation. Since autocorrelation is appear at any lag of the time series, the Ljung-Box test provides a p-value for the autocorrelation at each lag. Performing the test on this series, we get the following p-values for the first 10 lags: [0.41, 0.12, 0.21, 0.31, 0.44, 0.53, 0.5, 0.57, 0.26, 0.2]. Each of these values is large, which indicates this series is likely noise.

Both methods discussed previously indicate that the series shown is noise, which is the correct result (we know this series is randomly generated). As we progress with modeling time series, we will use these methods to determine whether a series is noise as part of model assessment. We will close this chapter with a discussion on the concept of time series stationarity.

In this section, we provide an overview of stationary and non-stationary time series. Broadly speaking, the main difference between these two types of time series is the statistical properties such as mean, variance, and autocorrelation. They do not vary across time in stationary time series but do change through time in non-stationary time series. Particularly, time series with a trend or seasonality is non-stationary because the trend or seasonality will affect the statistical properties. The following examples illustrate the behaviors of stationary versus non-stationary time series [1]:

Figure 10.12 – Examples of stationary and non-stationary time series

In order to check the stationary properties, we will check the three following conditions:

  • The mean is independent of time:

for all

  • The variance is independent of time:

for all

  • No autocorrelation with time—the correlation between and only depends on how far apart they are on time,

We will now explore the analysis in Pytho n using the Air Passengers dataset (https://www.kaggle.com/datasets/chirag19/air-passengers) providing monthly totals of US airline passengers from 1949 to 1960 that can be downloaded from Kaggle or can be found in GitHub repository of the book (https://github.com/PacktPublishing/Building-Statistical-Models-in-Python/blob/main/chapter_10/airline-passengers.csv). First, we import the data to a Python notebook, change the index type to datetime, and plot the dataset:

import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv('airline-passengers.csv', header=0, index_col =0)
data.index = pd.to_datetime(data.index, format='%Y-%m-%d')
plt.plot(data)

Figure 10.13 – Visualization of passengers using US airlines 1949-1960

From the plot, we can see there are trends and seasonal effects here. Then, it is clearly non-stationary. In the statsmodels package, there is a function called seasonal_decompose to help us break the original data into different plots for visualization purposes. You can see it in action here:

from statsmodels.tsa.seasonal import seasonal_decompose
season_trend = seasonal_decompose(data)
season_trend.plot()
plt.show()

We get the resulting plot as follows:

Figure 10.14 – Trend and seasonality visualization of passengers using US airlines 1949-1960

The trend plot shows that the number of passengers using US airlines increases over time. It appears to oscillate seasonally, with summers being the peak. There is a level of dependency between the data points and time, and the variances seem to be smaller earlier (fewer passengers using US airlines in the early 1950s) and greater later (more passengers using the services in the late 1950s). These observations show us that conditions 1 and 2 (constant mean and constant variance with time) are violated. Looking at the non-constant variance differently, we can create boxplots for each year from 1949 to 1960 for visualization, as follows:

import seaborn as sns
fig, ax = plt.subplots(figsize=(24,10))
sns.boxplot(x = data.index.year,y = data['Passengers'], ax = ax, color = "cornflowerblue")
ax.set(xlabel='Year', ylabel='Number of Passengers')

For the preceding code, we get the following result:

Figure 10.15 – Boxplot: passengers using US airlines 1949-1960

To check autocorrelation, we use the following code:

from statsmodels.graphics.tsaplots import plot_acf
plot_acf(data, lags= 20, alpha=0.05)
plt.show()

We get the result as shown in Figure 10*.16*:

Figure 10.16 – ACF visualization of passengers using US airlines 1949-1960

However, the trend dominates the data. After removing the trend and rerunning the code, we get the Figure 10*.17* ACF plot. There appears to be a strong seasonal component. The autocorrelation cycles are similarly repeated after some lag counts and spaces over time steps:

Figure 10.17 – ACF visualization of passengers using US airlines 1949-1960

The Ljung-Box test that we discussed in the Variance and Autocorrelation sections can also be used to check autocorrelation. Using that test, we get lb_pvalue = 0. Therefore, the data has autocorrelation.

This chapter started with an introduction to time series. We provided an overview of what a time series is and how it can be used to meet specific goals. We also discussed the criteria for differentiating time-series data from data that does not depend on time. We also discussed stationarity, which factors are important for stationarity, how to measure them, and how to resolve cases where stationarity does not exist. From there, we were able to understand the primary functions of ACF and PACF analysis and for making inferences about processes using variance around the mean. Additionally, we provided an introduction to time-series modeling with an overview of the white-noise model and the basic concepts behind autoregressive and moving average components, which help form the basis of ARIMA and seasonal autoregressive integrated moving average (SARIMA) time-series models.

In Chapter 11*, ARIMA Models*, we will also move deeper into the discussion of autoregressive, moving average, and ARMA models with conceptual overviews and step-by-step examples in Python. We also work on integrated SARIMA models, as well as methods for the evaluation of fit for these models.

[1] André Bauer, Automated Hybrid Time Series Forecasting: Design, Benchmarking, and Use Cases, University of Chicago, 2021.