<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Grzegorz Skorupa on Medium]]></title>
        <description><![CDATA[Stories by Grzegorz Skorupa on Medium]]></description>
        <link>https://medium.com/@grzesiek.skorupa?source=rss-181415af2e50------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*SWMHLVTwRbbF_9J9</url>
            <title>Stories by Grzegorz Skorupa on Medium</title>
            <link>https://medium.com/@grzesiek.skorupa?source=rss-181415af2e50------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:35:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@grzesiek.skorupa/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Forecasting Time Series with Multiple Seasonalities using TBATS in Python]]></title>
            <link>https://medium.com/intive-developers/forecasting-time-series-with-multiple-seasonalities-using-tbats-in-python-398a00ac0e8a?source=rss-181415af2e50------2</link>
            <guid isPermaLink="false">https://medium.com/p/398a00ac0e8a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Grzegorz Skorupa]]></dc:creator>
            <pubDate>Mon, 14 Jan 2019 08:39:42 GMT</pubDate>
            <atom:updated>2019-01-14T08:39:42.841Z</atom:updated>
            <content:encoded><![CDATA[<p>There are two interesting time series forecasting methods called BATS and TBATS <a href="https://www.tandfonline.com/doi/abs/10.1198/jasa.2011.tm09771">[1]</a> that are capable of modeling time series with multiple seasonalities.</p><p>The names are acronyms for key features of the models: <strong>T</strong>rigonometric seasonality, <strong>B</strong>ox-Cox transformation,<strong> A</strong>RMA errors, <strong>T</strong>rend and <strong>S</strong>easonal components.</p><p><strong>TBATS</strong> model takes it roots in exponential smoothing methods and can be described by the following equations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yfruZnSYsNt1X1uyag46eQ.png" /></figure><p>Each seasonality is modeled by a trigonometric representation based on Fourier series. One major advantage of this approach is that it requires only 2 seed states regardless of the length of period. Another advantage is the ability to model seasonal effects of non-integer lengths. For example, given a series of daily observations, one can model leap years with a season of length 365.25.</p><p><strong>BATS</strong> differs from TBATS only in the way it models seasonal effects. In BATS we have a more traditional approach where each seasonality is modeled by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*D8KY2jQRmVRLHY5f4RNqKA.png" /></figure><p>This implies that BATS can only model integer period lengths. Approach taken in BATS requires <em>m_i</em> seed states for season <em>i</em>, if this season is long the model may become intractable.</p><h3>How Does TBATS Choose The Final Model</h3><p>Under the hood TBATS will consider various alternatives and fit quite a few models. It will consider models:</p><ul><li>with Box-Cox transformation and without it.</li><li>with and without Trend</li><li>with and without Trend Damping</li><li>with and without ARMA(p,q) process used to model residuals</li><li>non-seasonal model</li><li>various amounts of harmonics used to model seasonal effects</li></ul><p>The final model will be chosen using <a href="https://en.wikipedia.org/wiki/Akaike_information_criterion">Akaike information criterion</a> (AIC).</p><p>In particular auto ARMA is used to decide if residuals need modeling and what p and q values are suitable.</p><p>For more details we invite you to the original paper [1].</p><h3>Existing Implementation</h3><p>So far the only implementation has been available in R language, in <a href="https://www.rdocumentation.org/packages/forecast">forecast</a> package. Data Scientists using Python either had to resign from testing those models or were forced to use R wrapper such as <a href="https://rpy2.bitbucket.io/">rpy2</a> to run them.</p><h3><strong>New Implementation</strong></h3><p>We have created a new implementation of <strong>TBATS in Python</strong>, available at <a href="https://github.com/intive-DataScience/tbats">GitHub</a>. In the rest of the article we will provide the example usage and compare the performance of this implementation with the other methods.</p><h3>Time Series Dataset</h3><p>In order to test forecasting methods we need some time series data. Let us use time series from <a href="https://www.kaggle.com/c/demand-forecasting-kernels-only">Kaggle Store Item Demand Forecasting Challenge</a>. It is a playground challenge and the set is most likely artificial (see comments in <a href="https://www.kaggle.com/thexyzt/keeping-it-simple-by-xyzt">kernels</a> and <a href="https://www.kaggle.com/c/demand-forecasting-kernels-only/discussion/65967">discussions</a>). The data there contains daily sales of 50 items in 10 stores from a period of 5 years (500 different time series in total). For our purpose we need only one time series so I will arbitrarily take sales of Item 1 at Store 1.</p><pre>import pandas as pd</pre><pre>df = pd.read_csv(&#39;kaggle_sales.csv&#39;)<br>df = df[(df[&#39;store&#39;] == 1) &amp; (df[&#39;item&#39;] == 1)] # item 1 in store 1<br>df = df.set_index(&#39;date&#39;)<br>y = df[&#39;sales&#39;]</pre><pre>y_to_train = y.iloc[:(len(y)-365)]<br>y_to_test = y.iloc[(len(y)-365):] # last year for testing</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*FpiD59FEdRrdWZb0auofoQ.png" /><figcaption>Fig 1: Daily sales of Item 1 at Store 1</figcaption></figure><p>Sales data contains daily observations. It <strong>exhibits weekly and yearly seasonal patterns</strong>. It means we are dealing with time series containing multiple seasonal effects. One of those seasonalities is long and contains 365 (366 for leap year) observations. This is something TBATS was designed for.</p><h3>TBATS Model</h3><p>In order to start forecasting we need to install <a href="https://github.com/intive-DataScience/tbats">tbats</a> package and fit the model. The only thing that we have to manually provide to the model are season lengths:</p><pre>from tbats import TBATS, BATS</pre><pre># Fit the model<br>estimator = TBATS(seasonal_periods=(7, 365.25))<br>model = estimator.fit(y_to_train)</pre><pre># Forecast 365 days ahead<br>y_forecast = model.forecast(steps=365)</pre><p>You may have noticed that yearly season length is not an integer. It equals 365.25 to account for leap years, a feature TBATS is able to handle.</p><p>TBATS seems to have done a pretty good job in modeling both of seasonal effects:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*7rH9cl3tiXUmPjCnQh66aw.png" /><figcaption>Fig 2: 3 last years of sales data. TBATS is modeling yearly seasonal effect.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*z5KpBpem6L4p7Z2gdznJ1g.png" /><figcaption>Fig 3: 12 weeks of data. Weekly seasonal effect is also being modeled by TBATS.</figcaption></figure><p>If we take a look under the hood and review model parameters we will discover that 3 seasonal harmonics are used to model the weekly pattern and 11 harmonics are used to model the yearly pattern. TBATS has chosen to use Box-Cox transformation with lambda of 0.234955. Trend is not being modeled and ARMA is not used to model residuals as p, q are 0.</p><pre>Use Box-Cox: True<br>Use trend: False<br>Use damped trend: False<br>Seasonal periods: [  7.   365.25]<br>Seasonal harmonics [ 3 11]<br>ARMA errors (p, q): (0, 0)<br>Box-Cox Lambda 0.234955<br>Smoothing (Alpha): 0.015789</pre><h3>SARIMA Model With Weekly Seasonality</h3><p>Let us compare TBATS to another method that is widely used and broadly known: <a href="https://www.statsmodels.org/dev/generated/statsmodels.tsa.statespace.sarimax.SARIMAX.html">SARIMA</a>. SARIMA has proven to provide state of the art solutions to time series forecasting. Unfortunately it has two major drawbacks: (1) one can model only a single seasonal effect, (2) season length should not be too long.</p><p>Nevertheless lets build SARIMA model using auto_arima from <a href="https://github.com/tgsmith61591/pmdarima">pmdarima</a> package. We shall ignore yearly seasonality and focus on modeling weekly seasonal pattern:</p><pre>from pmdarima import auto_arima<br>arima_model = auto_arima(y_to_train, seasonal=True, m=7)<br>y_arima_forecast = arima_model.predict(n_periods=365)</pre><p>Auto arima has chosen SARIMA(0, 1, 1)x(1, 0, 1, 7) model. As expected yearly pattern is not modeled (see Fig 4).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*o3O16D6ETfft80F6wDaCAg.png" /><figcaption>Fig 4: SARIMA models only weekly pattern. Compare to Fig 2.</figcaption></figure><h3>SARIMAX with Fourier Terms</h3><p>One can apply a <a href="https://content.pivotal.io/blog/forecasting-time-series-data-with-multiple-seasonal-periods">trick</a> [4] to utilize exogenous variables in SARIMAX to model additional seasonalities with Fourier terms.</p><p>We will keep modeling the weekly pattern with seasonal part of SARIMA. For the yearly seasonal pattern we will use the above-mentioned trick. I have compared multiple choices for the number of Fourier terms and 2 provides the most accurate forecasts. Therefore we shall use 2 Fourier terms as exogenous variables.</p><pre># prepare Fourier terms<br>exog = pd.DataFrame({&#39;date&#39;: y.index})<br>exog = exog.set_index(pd.PeriodIndex(exog[&#39;date&#39;], freq=&#39;D&#39;))<br>exog[&#39;sin365&#39;] = np.sin(2 * np.pi * exog.index.dayofyear / 365.25)<br>exog[&#39;cos365&#39;] = np.cos(2 * np.pi * exog.index.dayofyear / 365.25)<br>exog[&#39;sin365_2&#39;] = np.sin(4 * np.pi * exog.index.dayofyear / 365.25)<br>exog[&#39;cos365_2&#39;] = np.cos(4 * np.pi * exog.index.dayofyear / 365.25)<br>exog = exog.drop(columns=[&#39;date&#39;])<br>exog_to_train = exog.iloc[:(len(y)-365)]<br>exog_to_test = exog.iloc[(len(y)-365):]</pre><pre># Fit model<br>arima_exog_model = auto_arima(y=y_to_train, exogenous=exog_to_train, seasonal=True, m=7)</pre><pre># Forecast<br>y_arima_exog_forecast = arima_exog_model.predict(n_periods=365, exogenous=exog_to_test)</pre><p>With the help of Fourier terms SARIMAX is able to model both seasonal patterns (Fig 5).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*rm8Ny7namlaaODyKxDq9Rw.png" /><figcaption>Fig 5: SARIMAX with Fourier terms models both weekly and yearly patterns</figcaption></figure><h3>Model Comparison</h3><p>So far we have been only looking at plots. Let us compare the models’ performance using the 365-days-ahead forecast. We will use Mean Absolute Error as our metric:</p><ul><li>TBATS: 3.8577</li><li>SARIMA: 7.2249</li><li>SARIMAX with 2 Fourier Terms: 3.9045</li></ul><p>As expected SARIMA provides a poor model as it is unable to model yearly seasonality. TBATS and SARIMAX with Fourier Terms provide much better models.</p><h3>Drawbacks</h3><p>Unfortunately BATS and TBATS capabilities do not come for free. The method is very generic. Under the hood it builds and evaluates many model candidates. This results in slowness of the computation. It may be crucial when one needs to train models for lots of parallel time series.</p><p>Unlike SARIMAX, BATS and TBATS do not allow for exogenous variables to be added to the model to improve forecasts. According to <a href="https://robjhyndman.com/hyndsight/tbats-with-regressors/">Rob J Hyndmann</a> it is not trivial to include them and not fall into <a href="https://robjhyndman.com/hyndsight/ets-regressors/">forecastability issues</a>.</p><h3>References</h3><ol><li>De Livera, A.M., Hyndman, R.J., &amp; Snyder, R. D. (2011), <a href="https://www.tandfonline.com/doi/abs/10.1198/jasa.2011.tm09771"><em>Forecasting time series with complex seasonal patterns using exponential smoothing</em></a>, Journal of the American Statistical Association, 106(496), 1513–1527.<br>Working Paper version is available at <a href="https://robjhyndman.com/papers/ComplexSeasonality.pdf">https://robjhyndman.com/papers/ComplexSeasonality.pdf</a></li><li>Python implementation of BATS and TBATS: <a href="https://github.com/intive-DataScience/tbats">https://github.com/intive-DataScience/tbats</a></li><li>TBATS in R forecast package: <a href="https://www.rdocumentation.org/packages/forecast/versions/8.4/topics/tbats">https://www.rdocumentation.org/packages/forecast/versions/8.4/topics/tbats</a></li><li>Forecasting Time Series Data with Multiple Seasonal Periods (Fourier Terms): <a href="https://content.pivotal.io/blog/forecasting-time-series-data-with-multiple-seasonal-periods">https://content.pivotal.io/blog/forecasting-time-series-data-with-multiple-seasonal-periods</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=398a00ac0e8a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/intive-developers/forecasting-time-series-with-multiple-seasonalities-using-tbats-in-python-398a00ac0e8a">Forecasting Time Series with Multiple Seasonalities using TBATS in Python</a> was originally published in <a href="https://medium.com/intive-developers">intive Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>