To perform a time series decomposition, we can use automated procedures. The stats models library provides an implementation of the naive, or classical, decomposition method in a function called seasonal_decompose(). Additive or multiplicative methods are available.
We start importing the stats models library:
from statsmodels.tsa.seasonal import seasonal_decompose
In particular, we imported the seasonal_decompose module to perform seasonal decomposition using MAs. We perform the decomposition by applying the additive method:
DecompDataAdd = seasonal_decompose(data, model='additive', freq=1)
The seasonal component is first removed by applying a convolution filter to the data. The average of this smoothed series for each period is the returned seasonal component. Let's see what happened through the visualization of the components identified:
DecompDataAdd.plot()
plt.show()
The following graph shows the decomposition results by additive method:
In this figure, the three components of the time series are clearly represented: trend, seasonal, and residual. These attributes are contained in the object returned by the method seasonal_decompose(). This means that we can use the content of that object to remove the effect of seasonality from the time series. Let's see how:
SeasRemov= data-DecompDataAdd.seasonal
With this line of code, we have simplified the seasonal attribute returned by the seasonal_decompose() method from the data. At this point, we just have to visualize the result:
SeasRemov.plot()
plt.show()
The following graph shows the monthly milk production (pounds per cow from January 1962 – December 1975) net of seasonality:
In the graph obtained, the component due to seasonality has clearly been removed, while the one due to the trend is clearly visible.