<?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 Jerry Paul on Medium]]></title>
        <description><![CDATA[Stories by Jerry Paul on Medium]]></description>
        <link>https://medium.com/@jevpau1?source=rss-963289cf7f45------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JVq6PpG0mhmI5ZP_apdV1A.jpeg</url>
            <title>Stories by Jerry Paul on Medium</title>
            <link>https://medium.com/@jevpau1?source=rss-963289cf7f45------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 13:12:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jevpau1/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[A Blueprint for Time Series Forecasting]]></title>
            <link>https://medium.com/data-science/a-blueprint-for-time-series-9f865609bfa2?source=rss-963289cf7f45------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f865609bfa2</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[arima]]></category>
            <category><![CDATA[exponential-smoothing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <dc:creator><![CDATA[Jerry Paul]]></dc:creator>
            <pubDate>Sat, 19 Jun 2021 20:02:44 GMT</pubDate>
            <atom:updated>2021-07-10T12:50:18.883Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong><em>An exploration of exponential smoothing and ARIMA models</em></strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cMLrvsLVKpSNnfzk" /><figcaption>Photo by <a href="https://unsplash.com/@dandimmock?utm_source=medium&amp;utm_medium=referral">Dan Dimmock</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As mentioned in my <a href="https://towardsdatascience.com/tableau-your-time-series-forecast-with-tabpy-5c09c151477f">previous story</a> where I discussed how to ‘Tableau’ your predictions, let’s get onboard with time series forecasting.</p><p>Let’s start with the basics. What is a time series?</p><p>Time Series represents data that is <strong><em>ordered</em></strong> over a period of time, that is to say, we have observed data at<strong><em> equal intervals</em></strong> of time. Why does the <strong><em>order</em></strong> matter? This is because we assume what has happened today is dependent on what happened yesterday and so on. Since the chronology is important here, it isn’t right to consider a time series event as a random process. This implies that we cannot make a random sampling distribution from time series data.</p><p>Why would one use time series instead of predictive modeling like regression techniques? Hmm.</p><p>Sometimes, we may not have enough information (predictors) available to predict the future(target). Also, we may not establish significant correlation between the available predictors and our target variable.</p><p>So unlike predictive modeling, where you have predictors for explaining your target variable, time series forecasting rely on the target variable itself from previous time periods ( also called lags) for making predictions.</p><blockquote>Illustration:</blockquote><blockquote><strong>Predictive modelling: Revenue = 1.78*Profit + 2.5 </strong><em>(</em>This is a simple linear regression equation that predicts revenue from information available from profits).Assume we do not have profit information.We turn to time series.</blockquote><blockquote><strong>Time series model: Revenue(t+1) = a*Revenue(t) + a(a-1)*Revenue(t-1) + .. </strong>(In this model, revenue is dependent on the previous time periods’ revenue with a decaying weight as we go back in time by using a smoothing parameter <strong>‘a’</strong>)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X5IYKOyWiHkYDklf" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s get started with looking at our data. We will fire up our Jupyter notebook.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/440306d41c683d77d690caab145f3441/href">https://medium.com/media/440306d41c683d77d690caab145f3441/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0q8JxRiANM08oax1l89ueQ.png" /><figcaption>Top 5 records of our superstore dataset</figcaption></figure><p>Let’s have a quick look at our metadata.</p><pre>superstore.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q727r7wTfMp9IzGsb7jO1A.png" /><figcaption>We are going to work with Sales and Order Date for time series</figcaption></figure><p>We are safe to use Order Date and Sales without having to go for any missing value treatment. Let’s build our time series.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8bc377c3161b3ac211e80902dc4705f/href">https://medium.com/media/f8bc377c3161b3ac211e80902dc4705f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*3z5ISpjOhJcmU2XJjaQN0w.png" /><figcaption>We are aggregating Sales for each month</figcaption></figure><p>Time for visualization.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7Ejevpau1%2F20.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7Ejevpau1%2F20%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9fae12c5836f601e8ac2ae4fd93ef14/href">https://medium.com/media/d9fae12c5836f601e8ac2ae4fd93ef14/href</a></iframe><p>There are many libraries for visualizing your data in python, the most widely used are matplotlib and seaborn. Here I have used plotly which renders an interactive visual. If you are interested to know more about plotly go <a href="https://plotly.com/chart-studio/">here</a>. You can use the code below :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1de94109f9c0b899abdf393f679f5a69/href">https://medium.com/media/1de94109f9c0b899abdf393f679f5a69/href</a></iframe><p>Alright. Let’s dig deeper into the components of a time series. We will explore sample plots to understand the concepts better.</p><p>The main components of a time series are : <strong><em>Trend</em></strong>, <strong><em>Seasonality, Cyclic </em></strong>and <strong><em>White Noise (error) </em></strong>components. Trend, seasonality and cyclicity are the systematic components which can be modeled and the error is the random component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*_RXc1WZwnRxTP1Ic58getQ.png" /><figcaption>There is a clear upward trend</figcaption></figure><p><strong><em>Trend</em></strong> quantifies the overall upward or downward movement of the series.</p><p><strong><em>Seasonality</em></strong> quantifies the <strong><em>intra-year</em></strong> fluctuations in your data that repeats every year. For example, umbrella sales go up during every rainy season of the year, ice cream sales during summer and a distribution company tends to bill more every quarter of the year; these are most likely to happen every year. <strong><em>Question</em></strong> :Will a yearly time series have seasonality? No.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6MdV60pF3Py2mXdC_2XolA.png" /><figcaption>Seasonality in champagne sales</figcaption></figure><p>A <strong>cyclic</strong> pattern exists when data exhibit rises and falls that are <strong><em>not of fixed period</em></strong>. Hence it is different from seasonality where we see a fixed pattern in the latter. Also, the average length of a cycle is much longer than seasons and generally span over years.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NNOrxTGvcvEHh_5iB4a_nQ.png" /><figcaption>Mostly exhibiting cyclic behaviour over the years without a fixed pattern</figcaption></figure><p>Lastly, <strong><em>White Noise </em></strong>is the random error component that is assumed to have a normal distribution of mean <strong><em>µ = 0 </em></strong>and constant<strong> </strong>variance <em>𝛔².</em></p><p>We will focus on Trend, Seasonality and White Noise. Cyclic components are complex to model (at least to my knowledge so far) and we will try to explain the model using the other three components. Many times, cyclic components are explained by trend itself.</p><p>We can combine the components in two ways :</p><p><strong><em>Additive Model</em></strong> : <em>Y(t) = Trend(t) + Seasonality(t) + Error(t)</em></p><p><strong><em>Multiplicative Model</em></strong> : <em>Y(t) = Trend(t) * Seasonality(t) * Error(t)</em></p><p>Additive model will assume more or less constant seasonality over time. On the other hand multiplicative model will see significant changes in seasonality along with trend over time. Multiplicative models are more realistic. However in order to work with a multiplicative model, we will log transform our data to make it an additive model and then we can easily extract the trend and seasonality components. If you are familiar with logarithms, you should be able to relate to the below equations:</p><p>log(<em>Y(t)</em>) = log(<em>Trend(t) * Seasonality(t) * Error(t))</em></p><p>log(<em>Y(t)</em>) = log(<em>Trend(t)) + log(Seasonality(t)) + log(Error(t))</em></p><p>Visualization is a good start to understand the nature of our time series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*zFjR-sYO7TjmQvSebc6kMA.gif" /><figcaption>This looks like a multiplicative model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2jenMunf7G5byOmSJrX3qg.png" /><figcaption>Illustration for additive model ( What’s your take on cyclic pattern? Yes or No ?)</figcaption></figure><p>Visualizations have their own limits. We need a way to quantify and confirm our findings — enter <strong>Decomposition</strong>.</p><blockquote>Decomposition helps us to extract and quantify the components of time series. It also helps us understand what is more significant in explaining the time series.</blockquote><p>Let’s get back to our superstore. After looking at the series, I will go ahead with an additive model. Let’s decompose our series : I have illustrated two among the various methods used.</p><p><strong>Classic decomposition</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62de5cc0b1abe21481c38eaad4bbdc98/href">https://medium.com/media/62de5cc0b1abe21481c38eaad4bbdc98/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9PzVJmyCSVRiHmln84XzAg.png" /><figcaption>Decomposing our time series</figcaption></figure><p>Observe the trend and seasonal components carefully. We can see an upward trend and more or less constant seasonality across time. Also the residuals are centred around <strong><em>zero</em></strong><em>. </em>This substantiates our assumption of additive model.</p><p><strong>STL — robust method</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58eeef5ed67ba145a7a1a2aa6c4acf17/href">https://medium.com/media/58eeef5ed67ba145a7a1a2aa6c4acf17/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQRlijVuzJOHC_juwedzsA.png" /><figcaption>STL will work only with additive models; if we have multiplicative model, we use log transformations. We won’t explore that in this story.</figcaption></figure><p>I’d like to highlight another way to identify seasonality in particular. We can leverage <em>month_plot</em> to see if any months have significant repetitive patterns across the years.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c00e30ebeb01a81f8561a697f28a76c/href">https://medium.com/media/1c00e30ebeb01a81f8561a697f28a76c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ONVNuDCtd42wu4naUrDGrg.png" /><figcaption>Seasonal behaviour observed with (Jan,Feb) with lowest sales and (Sept, Nov, Dec) with highest sales</figcaption></figure><p>Let’s explore various models we can work with for forecasting. We will walk through <strong><em>exponential smoothing</em></strong> methods and <strong><em>ARIMA</em></strong> to forecast our time series.</p><p><strong>Exponential Smoothing Models</strong></p><p>In exponential smoothing, we forecast values based on weighted averages of past observations. These weights decay as we go back in time. This implies that we give more significance to recent observations. Parameters are used to calculate the weights and they take a value between 0 and 1.</p><p><strong>Simple Exponential Smoothing</strong></p><p>This is used when there is neither significant trend nor seasonality in the data. We simply try to smoothen the level of the series by using the parameter <strong><em>⍺</em></strong>. Level is nothing but the local mean. Mathematically we can represent this like below:</p><p><strong><em>Y(t+1) = ⍺*Y(t) + ⍺(⍺-1)*Y(t-1) + ⍺(⍺-1)²*Y(t-2) + ………..</em></strong> The weights decay as we go back in time and ⍺ is the smoothing parameter used that can be tuned between <strong>0</strong> and <strong>1</strong>.</p><p>Let’s code this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fdddc084a1f7363e5dba5dbc5fcdb9b/href">https://medium.com/media/2fdddc084a1f7363e5dba5dbc5fcdb9b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U96-sjbDHnvFHz9S4UVatA.png" /><figcaption>SES Model</figcaption></figure><pre>#Let&#39;s check accuracy score by using RMSE<br>Root mean squared error = 36203.014759074365</pre><p>You can see that the forecast isn’t great. You can try tuning <strong><em>⍺ </em></strong>to see if you get a better forecast. Simple exponential smoothing will always give a flat forecast and hence should be used only to predict for the next data point.</p><p><strong>Holt’s Model or Double Exponential Smoothing</strong></p><p>Here we consider two attributes : Level and Trend — this implies that we will have two smoothing parameters, <strong><em>⍺ </em></strong>and<strong><em> β </em></strong>respectively. We apply this type of model when there is trend but no seasonality.</p><p>Let’s jump right into the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46ffe043dd1f7168d5eed48e6ca8f44f/href">https://medium.com/media/46ffe043dd1f7168d5eed48e6ca8f44f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_xZCql4ib800w9cnb0xFQ.png" /><figcaption>Holt’s Linear Trend Model</figcaption></figure><pre>#Let&#39;s check accuracy score by using RMSE<br>Root mean squared error = 19269.25908614305</pre><p>We can see that the forecast is doing better with a lower RMSE. There is also a linear trend component without any seasonality.</p><p>Other than the inability to capture seasonality, this method also doesn&#39;t stabilize or rather ‘dampen’ the trend over time. It will simply shoot higher and higher into the future periods. This is not advisable, especially when we forecast for a long period. One workaround to this is to add a damping parameter. This is an extension to Holt’s linear trend model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58a4019b8aa2c09c8503b67611722d68/href">https://medium.com/media/58a4019b8aa2c09c8503b67611722d68/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yU11sjDFnwdBTAYw6OCFfw.png" /><figcaption>Holt’s Linear Trend with damping</figcaption></figure><pre>#Let&#39;s check accuracy score by using RMSE<br>Root mean squared error = 19646.815465033545</pre><pre>#You can see our RMSE has suffered to some extent due to damping. #This is a trade off that we need to consider while selecting the #model.</pre><p><strong>Holt-Winter’s Model or Triple Exponential Smoothing</strong></p><p>Let’s bring back our seasonality. This model takes into account the level, trend and seasonality in the series. Since trend and seasonality are present, Holt-Winter’s model can be additive or multiplicative. There are three smoothing parameters : <strong><em>⍺</em></strong>, <strong><em>β</em></strong> and <strong><em>𝜸 </em></strong>for level, trend and seasonality respectively. If you recall that our superstore data had both trend and seasonal components in the decomposition plot, we can expect this model to give us better accuracy. Also we assumed an additive model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b5d36a70d0e4d4d726777ecb8b65e99/href">https://medium.com/media/5b5d36a70d0e4d4d726777ecb8b65e99/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FrJgqJiuz_36iNOJuf3HGQ.png" /><figcaption>Holt Winter’s Model</figcaption></figure><pre>#Let&#39;s check accuracy score by using RMSE<br>Root mean squared error = 17660.235617816732</pre><pre>#Note that the model automatically applies smoothing parameters; you #can manually tune them by specifying smoothing_level, #smoothing_slope and smoothing_seasonal values.</pre><p>You can observe that the model has captured both trend and seasonality in the plot. Our RMSE score has also improved.</p><blockquote>In a nutshell, we have seen that our model has both trend and seasonal components and they are stitched in an ‘additive’ manner. Consequently, Holt-Winter’s model gave us the best results. Next we will have a look at a more sophisticated auto regression models.</blockquote><p><strong>ARIMA model</strong></p><p>ARIMA stands for Auto-Regressive Integrated Moving Average. Let’s break it down.</p><p>An <strong>Auto Regressive </strong>model tries to identify significant correlations with its lags( previous time periods ) that make up the <strong>AR(p) </strong>component. For example, an <strong>AR(1) </strong>process will imply that<strong> </strong>the value at time t is a linear function of the value at time t−1(in other words, lag 1). Mathematically, an AR(1) model will look like:</p><blockquote><strong><em>Y(t) = 𝛿 + ɸ*Y(t-1) +w(t)</em></strong><em>, where w(t) is the white noise at time (t) which is normally distributed with N(0,</em>𝛔²<em>)</em></blockquote><p>But what is <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;ved=2ahUKEwilwc7ewKPxAhUGfisKHf5oBpcQFjAAegQIBBAD&amp;url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FCorrelation_and_dependence&amp;usg=AOvVaw2d26feV-KieUEgGVjAy7pj"><strong>correlation</strong></a> and how is it calculated? Let’s have a look at the formula. Consider two variables x and y. The correlation is given by:</p><blockquote><strong><em>Correlation = Cov(x,y)/(𝛔x * 𝛔y)</em></strong></blockquote><p>The numerator is the <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;ved=2ahUKEwiStezGwKPxAhUPbn0KHbVQAEMQFjACegQIBhAD&amp;url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FCovariance&amp;usg=AOvVaw35yB5Pbo71eFBEZ_fnRsCe"><strong>covariance</strong></a><strong> </strong>of x and y, and denominator is the product of standard deviations of x and y. The correlation coefficient, which is the result of this formula, gives an estimate of how well x and y are associated taking values between -1 and 1. If you are familiar with Pearson’s r , you will find the similarity here. For AR(p) process, x and y are nothing but Y(t) and Y(t-p).</p><p>A <strong>Moving Average</strong> term <strong>MA(q)</strong> in a time series model is a past error (multiplied by a coefficient). Each of the error terms at the corresponding lags are assumed to have normal distribution with constant variance and mean zero. Mathematically, an <strong>MA(1)</strong> process will look like:</p><blockquote><strong><em>Y(t) = µ + w(t) + 𝛉*w(t-1)</em></strong><em>, where w(t) is the white noise at time (t) which is normally distributed with N(0,</em>𝛔²<em>) and</em><strong><em> </em></strong><em>µ is the mean of the series</em></blockquote><p><strong>Integrated</strong> stands for the number of times the series is differenced. Differencing is a process of subtracting the value of the current time period with the previous time period. This will make a differencing of order one. We can do it ‘d’ number of times which makes our series a differenced series of order ’d’. But why do we difference our series — <strong>enter the concept of stationarity which is a mandatory criteria for auto regressive models.</strong></p><p>So let’s understand stationarity.</p><p>A series is stationary if and only if :</p><p><em>a)</em><strong><em>The mean of time series is a constant</em></strong> — this implies that time series with trend or seasonality are non-stationary. A trend or seasonal component will affect the value of time series at different periods.</p><p><em>b)</em><strong><em>The variance/covariance is constant over time</em></strong></p><p><em>c)</em><strong><em>The correlation between time period (lag) t and t + mth is always a constant</em></strong> — this implies that January and November will have the same correlation as December and October.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xdblkZyg6YmmReAkZHUksw.png" /><figcaption>Source : <a href="https://beingdatum.com/time-series-forecasting/">beingdatum.com</a></figcaption></figure><blockquote>Overall, a stationary series is one where the statistical properties do not change over time.</blockquote><p>There are couple of ways to make a non-stationary series stationary. These are log transformations ( for smoothing the variance ), eliminating trend &amp; seasonality after decomposition, calculating moving averages and differencing the series. Among the above stated approaches, <strong>differencing</strong> is widely used for making a series stationary which we have already described.</p><p>Let’s test our data for stationarity. We will use Augmented Dickey-Fuller test to test our null hypothesis that our series is not stationary. If we get a significant p value, we will reject our null hypothesis and establish that our series is stationary. On the contrary, if we fail to reject our null hypothesis, we will difference the series and run the test again.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0db287ebd0f98bf1e4fac464ed2796e3/href">https://medium.com/media/0db287ebd0f98bf1e4fac464ed2796e3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*ystK9k7ydBnYKu4SnFLe0g.png" /><figcaption>Test Statistic well over the critical value with 99% confidence</figcaption></figure><p>After looking at the results, our null hypothesis can be rejected. We can say with 99% confidence that our data is stationary.</p><blockquote>If we were to use decomposition instead of differencing, we can test for stationarity of the residuals using the same method</blockquote><p>Let’s move on. The next step is to explore ACF ( auto-correlation function ) and PACF ( partial auto-correlation function ). Remember we talked about AR(p) and MA(q) processes? ACF and PACF plots help us identify the orders p and q.</p><p>ACF looks for correlations with the lags of the series. A series with lag 1 is that which is shifted by one time period. The below table illustrates lagged series of order 1,2,3 and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MPGDfFw791nkRiINxMmL9w.png" /><figcaption>An illustration of lags</figcaption></figure><p><strong>ACF</strong> plots the correlations between original Series and Lag 1, Lag 2 etc. Let’s see how to do it in python.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50dda72fd210620f9cad4cd1ffc82176/href">https://medium.com/media/50dda72fd210620f9cad4cd1ffc82176/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*38L24d978mjJ6hpcM_xHYg.png" /><figcaption>We can see that lag(1) is significant</figcaption></figure><p>Any spike above the blue bands is significant. We can see that lag(1) and lag(12) are significant. Also, we can see that there are rises and falls across lags with gradual decay in correlations (observe every12th lag). There is a high chance that correlation between say, lag(1) and lag(4) are influenced by the effects of in-between lags — lag(2) and lag(3). Hence it is important to eliminate these and get a true picture — <strong>PACF </strong>plots are used for the same purpose.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bc7e8c40d818bc65db9c6c508d2fa3b/href">https://medium.com/media/5bc7e8c40d818bc65db9c6c508d2fa3b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dSQQnyfX8R_tkn5UvSa98A.png" /><figcaption>We can see that lag(1) is significant among other shocks</figcaption></figure><p>The above PACF plot shows lag(1) is significant among other signals or shocks. Lag(12) is significant here as well.</p><p><strong>How do we interpret ACF and PACF plots?</strong></p><p>The below matrix should help us choose our best order:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*pUYkmOs13YGxjysi8dkX3Q.png" /><figcaption>Here ‘m’ is the seasonal cycle</figcaption></figure><p>Based on our plots, it looks like there are both seasonal and non-seasonal components. Spike at each 12th lag denote seasonality and we may have to difference it. We can iterate through different combinations and check the AIC (Akaike Information Criteria) and BIC (Bayesian Information Criteria) scores. Our goal is to minimize these scores for better model performance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7989ca8fb4df60f735b38cd8fda4423a/href">https://medium.com/media/7989ca8fb4df60f735b38cd8fda4423a/href</a></iframe><pre>#Call the function and fine tune parameters<br># d=0 as we did not difference the series<br>#Try with p=1, q=1 based on our ACF and PACF plots<br>#Alternatively, start with (1,0,0) AR model and (0,0,1) MA model</pre><pre>arima_model(1,0,1) #ARMA model</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jK4_U9tTfTGCQP-PguKKNg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BQ8dZQQ6QKJif90k9q935g.png" /><figcaption>ARMA model that forecasts for 6 months</figcaption></figure><pre>#MAPE<br>0.6571285433084803</pre><pre>#RMSE<br>23037.553921953575</pre><p>The accuracy isn’t great. We can try different combinations to see what gives us the best accuracy scores. Also, the MA(1) coefficient isn’t statistically significant. We can drop it and look at our results again. This iteration can go on until we find an optimal accuracy. Note that we haven’t included seasonality yet. This paves way for seasonal ARIMA.</p><p>Let’s have a look at Seasonal ARIMA. We will use the parameters for non -seasonal arima <strong>(p,d,q)</strong> and add a corresponding seasonal order <strong>(P,D,Q)m</strong> where m is the seasonal cycle; since our data is at monthly level and the patterns repeat every year, m=12.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63091cdae4e1c7e037fc544554ffc723/href">https://medium.com/media/63091cdae4e1c7e037fc544554ffc723/href</a></iframe><pre>#Since we saw significant spikes at 12th lag in our ACF and PACF #plots, we can try the following</pre><pre>sarimamodel(0,1,0,12)<br>sarimamodel(1,0,0,12)<br>sarimamodel(0,0,1,12)</pre><pre>#We need to minimize our AIC and BIC values</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X7jIgAvVNdXHMb6aba-chg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4hKFCUWIrFv4lwTnCRFW0w.png" /><figcaption>We can see a significant improvement in MAPE</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*im65mvBrlitCyKQeuaN_DA.png" /><figcaption>Analyze residuals to see if they are normally distributed</figcaption></figure><p>We can see a significant improvement in AIC, BIC, MAPE scores after bringing in seasonality in the model. The model residuals also follow almost a normal distribution as explained by :</p><p><strong>Q-Q plot</strong>-this is a scatterplot of two sets of quantiles against one another. If both sets of quantiles came from the same distribution, we should see the points forming a line that’s roughly straight.</p><p><strong>Standardized residuals</strong>-this shows that our residuals after being standardized, are centred around zero.</p><p><strong>Histogram and KDE</strong> plots the distribution of standardized residual and compares it with a normal distribution.</p><p><strong>Correlogram</strong> is used to see if there are any significant auto correlations among residuals; we don’t have any. This implies that residuals are stationary and do not have any pattern.</p><blockquote>Stationarity of residuals is a must for finalizing a model</blockquote><p>However, if you observe the results, we still do not have significant coefficients and we should iterate for other combinations.</p><p>Fortunately, python provides an inbuilt function auto_arima (part of pmdarima package) which saves us time from identifying the optimal order of ARIMA. Below is an illustration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e0f779f88731a11b1d5a5fbdce6e57c/href">https://medium.com/media/9e0f779f88731a11b1d5a5fbdce6e57c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DT3br33bnrN3jMoDh5jPkA.png" /><figcaption>Automatically searches for the best model that minimizes AIC</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ydw4HdrbXiVxIMNWH6b2w.png" /><figcaption>Normality of residuals</figcaption></figure><p>We can see that auto_arima has chosen ARIMA(1,0,1)(1,0,0)[12] as the best model. The residuals also look stationary. If you do not get statistically significant parameters, we can differentiate the series and run the ARIMA model again by following the same steps. On quickly running auto_arima, it gave me ARIMA(2,1,0)(1,0,0)[12]. I will leave it at that and encourage you to try differencing and modeling.</p><pre>#Differencing<br>data_diff = data-data.shift()<br>plt.plot(data_diff)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N7axvD7D-qWmO-8m6pgPcw.png" /><figcaption>Differenced series</figcaption></figure><blockquote>Note that auto_arima doesn’t do so well in capturing seasonality. Hence simply relying on auto_arima will not yield the best model. We have to carefully examine the ACF and PACF plots, understand seasonal effects if any, plot auto_arima for further experimentation and apply business domain knowledge to finalize the model parameters.</blockquote><p>I hope this gives an idea to start implementing time series forecasting. I’d like to highlight that we did not split the data into train and test in ARIMA model. This is because we did not have the luxury of many data points to model. It is a decision that you make depending on the volume of data you can work with.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f865609bfa2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-blueprint-for-time-series-9f865609bfa2">A Blueprint for Time Series Forecasting</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tableau your Time Series Forecast with TabPy!]]></title>
            <link>https://medium.com/data-science/tableau-your-time-series-forecast-with-tabpy-5c09c151477f?source=rss-963289cf7f45------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c09c151477f</guid>
            <category><![CDATA[tableau]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jerry Paul]]></dc:creator>
            <pubDate>Thu, 20 May 2021 22:23:40 GMT</pubDate>
            <atom:updated>2021-06-20T04:20:16.511Z</atom:updated>
            <content:encoded><![CDATA[<h4>Complement your predictions with Tableau’s speed to insight!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ph4U8AE3ZtOSsEbW" /><figcaption>Photo by <a href="https://unsplash.com/@julianhochgesang?utm_source=medium&amp;utm_medium=referral">Julian Hochgesang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Welcome to a quick and short (hopefully) illustration of how one can integrate data science models with Tableau using TabPy. We will specifically look at time series forecasting in this story.</p><blockquote>We will use three time series models which are built in python using the superstore dataset ( retail industry data ). We will use Jupyter notebook to build our python codes and then move on to Tableau.</blockquote><p>This article is aimed at demonstrating how a model can be integrated with Tableau’s analytics extensions and make it seamless for consumption.</p><blockquote>Why Tableau? Well, I love it and I can’t stress enough on how easy it is to explore your data.</blockquote><p>Let’s start by looking at the data :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecc70ad3a52b879c62650a62b233951a/href">https://medium.com/media/ecc70ad3a52b879c62650a62b233951a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4o_qHmAU1M2eZhOUy4bSuQ.png" /></figure><p>We simply keep our date and sales columns for building a time series object. The below code sorts the sales figures in ascending order and aggregates the data at a month level.</p><pre>#fetching required columns<br>data = superstore[[‘Order Date’,’Sales’]] <br>data = data.sort_values(by = &#39;Order Date&#39;)</pre><pre>#creating a ts object<br>data[&#39;Order Date&#39;] = pd.to_datetime(data[&#39;Order Date&#39;])<br>data.index = data[&#39;Order Date&#39;]<br>data = data.resample(&#39;M&#39;).sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*CfLHHBM3fpMk31DVXJPCYg.png" /></figure><p>We are ready to visualize the time series:</p><pre>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><pre>plt.subplots(figsize = (17,7))<br>sns.lineplot(x = “Order Date”, y = “Sales”, data = data)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JqMha9QMZG7ONtq6_HK5wQ.png" /></figure><p>The above is our time series plot. There are three important components to time series : Trend, Seasonality and Error. We can look at the series as an ‘additive model’ or a ‘multiplicative model’ depending on the nature of the series and the hypothesis we postulate. I will be parking the model building and forecasting methods in the <a href="https://towardsdatascience.com/a-blueprint-for-time-series-9f865609bfa2">next article</a> as a continuation of this one where we will cover different techniques, decomposition, stationarity testing, auto-correlation and partial auto-correlation factors and model summary.</p><p>For now, I will share the code I had written to finalize the model before I switch gears to Tableau.</p><blockquote>As mentioned in the beginning of the article, we will use three models. These are Holt’s Linear Model, Holt-Winter’s Model and ARIMA. The first two are exponential smoothing methods and ARIMA stands for Auto Regressive Integrated Moving Average which is a regression method.</blockquote><p>Below is the python code for Holt’s Linear Method :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53591ab39303b924146f0e18ee98666a/href">https://medium.com/media/53591ab39303b924146f0e18ee98666a/href</a></iframe><p>The model is trained on 42 months and the last 6 months are used for predictions. Model parameters can be tuned for accuracy.The model appends both and gives the entire series back to us.</p><h3>How do we tie this with Tableau?</h3><p>Tableau has inbuilt analytics extensions that allow integration with other platforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*f0tkSoxA6b01PXgAXUmVXQ.png" /></figure><p>In our case we choose TabPy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*POFkiwpIVjiv7RB-_DyOHw.png" /></figure><p>Make sure to install TabPy and start the same in your terminal as laid out in the below resource :</p><p><a href="https://tableau.github.io/TabPy/docs/server-install.html">TabPy Installation Instructions</a></p><p>You can test the connection in Tableau in the pop-up described above.</p><p>We also import TabPyClient in our python environment to create a connection object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac33588dc99f69c9ca9efc48b634b341/href">https://medium.com/media/ac33588dc99f69c9ca9efc48b634b341/href</a></iframe><p>We will be using this connection object to deploy our models on the TabPy Server that we initiated.</p><p>Let’s look at the modified code for Holt’s Linear method that can be deployed on TabPy.</p><p><strong><em>Holt’s Linear Method</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98ac72f362291a9492eb722fed776e8f/href">https://medium.com/media/98ac72f362291a9492eb722fed776e8f/href</a></iframe><p>We have created a function that returns the model output. Since we will be reading data from Tableau, we have used parameters that take in values we shall pass from Tableau. You will note that we have used the connection object to deploy the model in TabPy. Similarly, you can create functions for other models.</p><p><strong><em>Holt-Winter’s Method</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04b7ad793aae4c33b4e3e14c1f83e30c/href">https://medium.com/media/04b7ad793aae4c33b4e3e14c1f83e30c/href</a></iframe><p><strong><em>ARIMA</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec96b205fc92d69e16d4e759796e6862/href">https://medium.com/media/ec96b205fc92d69e16d4e759796e6862/href</a></iframe><p>Now that we have deployed these models in TabPy, let’s consume it in Tableau. We will create a calculated field that looks like below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n5X_g-tlLIYih5c6P5mxcg.png" /></figure><blockquote>Tableau uses four functions, namely SCRIPT_REAL, SCRIPT_STR, SCRIPT_BOOL and SCRIPT_INT for return types real, string, boolean and integer respectively. The above code tells Tableau to run the ‘Seasonal ARIMA Method’ which is deployed on TabPy with 3 parameters (Date, Sales and Months to Forecast) and return the ‘response’ to Tableau’s calculated field.</blockquote><p>Similarly, we define calculated fields for the other 2 models. If we want to see all at a glance in Tableau, it will look like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g9OQkVt1OXYyRghGwsvvTA.gif" /></figure><p>Note that you can dynamically change the forecast period as you want and see the predictions. You want to choose the model that gives you the best accuracy. You can optionally create a parameter in Tableau to toggle among models.</p><p>A key point to note is that we need to accommodate the forecast period (in months in our case) in Tableau so that we make space for the returned values from TabPy.This is because the original dataset does not have these null records for the future dates when we pass values from Tableau. I have tweaked the data to extend the date range as shown below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JZ6t42KrPaXPGuFX2-pibw.png" /></figure><p>The above code essentially extends the date range after adding the required months to forecast and passes it to TabPy. Also, we choose ‘Show Missing Values’ for this calculated date field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*k4rqcrU5IaHhov7e_4fFIQ.png" /></figure><blockquote>There is a small trade off here.Since we extend the date range, the last date and sales figures get pushed to the new forecast end date. However, we are only interested in the forecast; we can exclude this datapoint or use LAST()=FALSE in the filter box. Feel free to come up with ideas for the same.</blockquote><p><strong><em>Let’s finally plug this into our dashboard :</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m9r90knhD1jN4dm9X8H3Yw.gif" /></figure><p>There you go! We have a well integrated forecasting model sitting inside Tableau’s visual discovery. You can definitely bring in accuracy scores and model parameters to Tableau and make this jazzier!</p><p>As mentioned, more to come in my <a href="https://towardsdatascience.com/a-blueprint-for-time-series-9f865609bfa2">next story</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c09c151477f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/tableau-your-time-series-forecast-with-tabpy-5c09c151477f">Tableau your Time Series Forecast with TabPy!</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>