<?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[Time Series Analysis - Medium]]></title>
        <description><![CDATA[Some learnings related to time series. - Medium]]></description>
        <link>https://medium.com/vijendra-1893?source=rss----74c44fc30449---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Time Series Analysis - Medium</title>
            <link>https://medium.com/vijendra-1893?source=rss----74c44fc30449---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:50:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/vijendra-1893" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Time Series Forecasting — EDA and Decomposition]]></title>
            <link>https://medium.com/vijendra-1893/time-series-forecasting-eda-and-decomposition-26bfab478339?source=rss----74c44fc30449---4</link>
            <guid isPermaLink="false">https://medium.com/p/26bfab478339</guid>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Vijendra]]></dc:creator>
            <pubDate>Thu, 10 Sep 2020 04:56:40 GMT</pubDate>
            <atom:updated>2020-09-10T04:56:40.500Z</atom:updated>
            <content:encoded><![CDATA[<h3>Time Series Forecasting — EDA and Decomposition</h3><p>This article is about Time Series Forecasting. We will do Exploratory Data Analysis and Decomposition of the monthly Sales of Shampoo.</p><p>This dataset describes the monthly number of sales of shampoo over a 3 year period.</p><p>The units are a sales count and there are 36 observations. The original dataset is credited to Makridakis, Wheelwright, and Hyndman (1998). The dataset can be downloaded from the below link:</p><p><a href="https://machinelearningmastery.com/time-series-datasets-for-machine-learning/">7 Time Series Datasets for Machine Learning - Machine Learning Mastery</a></p><p>Jupyter Notebook files can be downloaded from below Github repository link:</p><p><a href="https://github.com/vijendra-code/Time-Series-Forecasting">https://github.com/vijendra-code/Time-Series-Forecasting</a></p><p>We will now follow step by step process to read the dataset, do exploratory data analysis, decompose the dataset:</p><ol><li>Reading the dataset.</li><li>Exploratory Data Analysis</li><li>Decomposing the Data Set</li></ol><h3>1. Reading the Dataset</h3><p>Importing Libraries, Reading the dataset</p><pre><strong>import</strong> <strong>numpy</strong> <strong>as</strong> <strong>np</strong><br><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong><br><strong>import</strong> <strong>matplotlib.pyplot</strong> <strong>as</strong> <strong>plt</strong><br>%<strong>matplotlib</strong> inline<br><strong>import</strong> <strong>seaborn</strong> <strong>as</strong> <strong>sns</strong><br><strong>from</strong> <strong>pylab</strong> <strong>import</strong> rcParams</pre><p>Reading the dataset:</p><pre>df = pd.read_csv(&#39;Shampoo.csv&#39;)</pre><p>Checking the first 5-rows of the dataset:</p><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*L5JnL-TxK5OHvjy41PMdMg.png" /></figure><p>Checking last 5 rows of the dataset:</p><pre>df.tail()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/175/1*x0XC85R12efMH1sW0saqxA.png" /></figure><p><em>Data refers from Jan 2001 to Dec 2003. It’’s a monthly sales data. We will now create monthly dates for timestamp from Jan 2001 to Dec 2003.</em></p><pre>date = pd.date_range(start=&#39;1/1/2001&#39;, end=&#39;12/31/2003&#39;, freq=&#39;M&#39;)<br>date</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*EeShyJz7eVuumypsV1TZ0g.png" /></figure><p>Creating Timestamp</p><pre>df[&#39;Time_Stamp&#39;] = pd.DataFrame(date,columns=[&#39;Date&#39;])<br>df.tail()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*88dRo0Ug-ru5OIPn_Oo8DQ.png" /></figure><p>Setting the Timestamp column as index</p><pre>df = df.set_index(&#39;Time_Stamp&#39;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*yVaf7kFnG6EWwUWl8buVYQ.png" /></figure><p>Dropping the month column, and creating the final data frame</p><pre>df_final = df.drop([&#39;Month&#39;], axis=1)<br>df_final.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*YOcD-BiYdyStp0uPELa0Mw.png" /></figure><p>Plotting the Time-Series</p><pre><em>#Plotting the time-series</em><br>df_final.plot(figsize=(20,8))<br>plt.grid();<br>plt.xlabel(&#39;Timestamp&#39;,fontsize=15)<br>plt.ylabel(&#39;Sales&#39;,fontsize=15)<br>plt.rc(&#39;xtick&#39;,labelsize=15)<br>plt.rc(&#39;ytick&#39;,labelsize=15)<br>plt.legend(fontsize=&quot;x-large&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*8vd7NZiN8duK_Dtuv2zdOQ.png" /></figure><p><em>There seems to be a trend (increasing) with seasonality as well.</em></p><p>Checking the missing values</p><pre>df_final.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/1*3LPfK1cQSIUy17HwaTFEaw.png" /></figure><p><em>There are no missing values in the dataset.</em></p><h3>2. Exploratory Data Analysis</h3><p><strong>Statistical Description of the data:</strong></p><pre>round(df_final.describe(),3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/155/1*OpWGNgRTcoOYBXvvyNorcw.png" /></figure><p><em>→ Sales of shampoo range from 119.3 units to 682 units, hinting huge variation in sales across months.</em></p><p><em>→ Mean sales are 312.6</em></p><p><strong>Yearly Boxplot:</strong></p><pre>_, ax = plt.subplots(figsize=(22,8))<br>sns.boxplot(x = df_final.index.year,y = df_final.values[:,0],ax=ax)<br>plt.grid();<br>plt.xlabel(&#39;Years&#39;,fontsize=15)<br>plt.ylabel(&#39;Sales&#39;,fontsize=15)<br>plt.rc(&#39;xtick&#39;,labelsize=15)<br>plt.rc(&#39;ytick&#39;,labelsize=15)<br>plt.legend(fontsize=&quot;x-large&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*O3uEniNjmWBIP-YPW3lpZQ.png" /></figure><p><em>The above plot suggests that the series has a significant trend. Every year sales are increasing.</em></p><p><strong>Monthly Boxplot</strong></p><pre>_, ax = plt.subplots(figsize=(22,8))<br>sns.boxplot(x = df_final.index.month_name(),y = df_final.values[:,0],ax=ax)<br><br>plt.grid();<br>plt.xlabel(&#39;Month&#39;,fontsize=15)<br>plt.ylabel(&#39;Yearly Wine Sales Variation&#39;,fontsize=15)<br>plt.rc(&#39;xtick&#39;,labelsize=15)<br>plt.rc(&#39;ytick&#39;,labelsize=15)<br>plt.legend(fontsize=&quot;x-large&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*gGLzlVqcqqtgpO4GavWYgA.png" /></figure><p><em>It appears that we have a seasonal component each year. Also, we see that there are no outliers present.</em></p><p><strong>Monthly sales across years</strong></p><p>We will now calculate a pivot table:</p><pre>monthly_sales_across_years = pd.pivot_table(df_final, values = &#39;Sales&#39;, columns = df_final.index.month_name(), index = df_final.index.year)<br>monthly_sales_across_years</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*0rVs8hLQhkPa-NbnRNtOjg.png" /></figure><p>Plotting the pivot table:</p><pre>monthly_sales_across_years.plot(figsize=(20,10))<br>plt.grid()<br>plt.legend(loc=&#39;best&#39;);<br>plt.xlabel(&#39;Years&#39;,fontsize=15)<br>plt.ylabel(&#39;Sales&#39;,fontsize=15)<br>plt.rc(&#39;xtick&#39;,labelsize=15)<br>plt.rc(&#39;ytick&#39;,labelsize=15)<br>plt.legend(fontsize=&quot;x-large&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*TyF2FqagstTUPGpV3hWJtw.png" /></figure><p><em>Till 2002 there is no significant trend, but from 2002 to 2003 there is a significant trend seen.</em></p><p><strong>Quarterly sales across years</strong></p><p>Creating the pivot table quarterly sales</p><pre>quarterly_turnover = pd.pivot_table(df_final, values = &quot;Sales&quot;, columns = df_final.index.quarter, index = df_final.index.year)</pre><pre>quarterly_turnover</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*vVFIxwzEAG0R5E8XzILKNA.png" /></figure><p>Plotting the pivot table:</p><pre>quarterly_turnover.plot(figsize=(20,10))<br>plt.grid()<br>plt.legend(loc=&#39;best&#39;);<br>plt.xlabel(&#39;Years&#39;,fontsize=15)<br>plt.ylabel(&#39;Quarterly Sale Variation&#39;,fontsize=15)<br>plt.rc(&#39;xtick&#39;,labelsize=15)<br>plt.rc(&#39;ytick&#39;,labelsize=15)<br>plt.legend(fontsize=&quot;x-large&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*y_McXTkN4_BxIy9ITPXtgA.png" /></figure><p><em>As seen from the above plot, Q4 has the highest sales. After that Q3. Q1 and Q2 have the lowest sales.</em></p><h4>Plotting the time series month- plot to understand the spread of sales across different years and within different months across years:</h4><pre><strong>from</strong> <strong>pylab</strong> <strong>import</strong> rcParams<br>rcParams[&#39;figure.figsize&#39;] =17,8<br><strong>from</strong> <strong>statsmodels.graphics.tsaplots</strong> <strong>import</strong> month_plot<br>plt.rc(&#39;xtick&#39;,labelsize=15)<br>plt.rc(&#39;ytick&#39;,labelsize=15)<br>month_plot(df_final[&#39;Sales&#39;],ylabel=&#39;Sales&#39;)<br>plt.grid();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*0tahzbc33Apj-4sdZ-8PQg.png" /></figure><p><em>For most of the month&#39;s sales for a month is significantly increasing in the next year.</em></p><p><strong>Plotting the Empirical Cumulative Distribution:</strong></p><pre><strong>from</strong> <strong>statsmodels.distributions.empirical_distribution</strong> <strong>import</strong> ECDF<br>plt.figure(figsize = (18, 8))<br>cdf = ECDF(df_final[&#39;Sales&#39;])<br>plt.plot(cdf.x, cdf.y, label = &quot;statmodels&quot;);<br>plt.grid()<br>plt.rc(&#39;xtick&#39;,labelsize=15)<br>plt.rc(&#39;ytick&#39;,labelsize=15)<br>plt.xlabel(&#39;Sales&#39;, fontsize = 15);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*Yt07iR0pJHK2cyDnr0tjTQ.png" /></figure><p><em>Around 60% of all the months had 300 units or lesser sales. Around 50% of all the months had 450 units or lesser sales.</em></p><h4>Plot the average sales per month and the month on month percentage change of sales:</h4><pre><em># group by date and get average Customers, and precent change</em><br>average    = df_final.groupby(df_final.index)[&quot;Sales&quot;].mean()</pre><pre>pct_change = df_final.groupby(df_final.index)[&quot;Sales&quot;].sum().pct_change()<br><br>fig, (axis1,axis2) = plt.subplots(2,1,sharex=<strong>True</strong>,figsize=(15,8))<br><br><em># plot average Customers over time(year-month)</em><br>ax1 = average.plot(legend=<strong>True</strong>,ax=axis1,marker=&#39;o&#39;,title=&quot;Average Sales&quot;,grid=<strong>True</strong>)<br>ax1.set_xticks(range(len(average)))<br>ax1.set_xticklabels(average.index.tolist())</pre><pre><em># plot precent change for Customers over time(year-month)</em><br>ax2 = pct_change.plot( legend=<strong>True</strong>,ax=axis2,marker=&#39;o&#39;, colormap=&quot;summer&quot;, title=&quot;Sales Percent Change&quot;, grid=<strong>True </strong>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*vkGdLatbEiTOK_C6MFO-nA.png" /></figure><p><em>There is a huge percentage change in sales every month.</em></p><h4>Plot sales for every year</h4><pre><em>## Plot sales for every year</em><br>fig, (axis1) = plt.subplots(1,figsize=(15,4))<br><br>sns.barplot(x=df_final.index.year, y=df_final.values[:,0], data=df_final, ax=axis1);<br>plt.rc(&#39;xtick&#39;,labelsize=15)<br>plt.rc(&#39;ytick&#39;,labelsize=15)<br>plt.xlabel(&#39;Year&#39;, fontsize = 15);<br>plt.ylabel(&#39;Avg Monthly Sales&#39;, fontsize = 15);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*f9B3l5Prcsc2r-VXl0UpUA.png" /></figure><p><em>It can be seen that, the average monthly sales increases as we move from 2001 to 2003.</em></p><h4>Yearly Total Sales</h4><p>Creating the monthly sales pivot table:</p><pre>monthly_sales_across_years = pd.pivot_table(df_final, values = &#39;Sales&#39;, columns = df_final.index.month_name(), index = df_final.index.year)</pre><pre>yearly_total_sales = monthly_sales_across_years.sum(axis = 1, skipna = <strong>True</strong>) </pre><pre>yearly_total_sales</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*ONMTYpooYdKkNSREaY1UNA.png" /></figure><p>Plotting the pivot table:</p><pre>yearly_total_sales.plot(figsize=(20,10))<br>plt.grid()<br><br>plt.xlabel(&#39;Years&#39;,fontsize=15)<br>plt.ylabel(&#39;Total Sales&#39;,fontsize=15)<br>plt.rc(&#39;xtick&#39;,labelsize=15)<br>plt.rc(&#39;ytick&#39;,labelsize=15)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*8ld0Rot54o7dzdEZwgR6LQ.png" /></figure><p><em>As it can be seen that total sales every year sales is increasing.</em></p><h4>3. Decomposing the Time Series and plotting the different components.</h4><p><strong>Assuming Additive Decomposition:</strong></p><p>An additive model suggests that the components are added together. it is linear where changes over time are consistently made by the same amount.</p><p>Actual = Trend + Seasonality + Residual</p><pre><strong>from</strong>    <strong>statsmodels.tsa.seasonal</strong> <strong>import</strong>   seasonal_decompose<br>decomposition = seasonal_decompose(df_final,model=&#39;additive&#39;)<br>decomposition.plot();<br>plt.rcParams[&#39;axes.labelsize&#39;] = 16<br>plt.rcParams[&#39;axes.titlesize&#39;] = 16</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*1tB-5rcs55zpA_zGcYGNFA.png" /></figure><p><strong>Assuming Multiplicative Decomposition:</strong></p><p>A multiplicative model suggests that the components are multiplied together. It is non-linear such as quadratic or exponential.</p><p>Actual = Trend x Seasonality x Residual</p><pre>decomposition = seasonal_decompose(df_final,model=&#39;multiplicative&#39;)<br>decomposition.plot();<br>plt.rcParams[&#39;axes.labelsize&#39;] = 16<br>plt.rcParams[&#39;axes.titlesize&#39;] = 16</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*qhW6QJX6XLZWZTlLyHc80w.png" /></figure><p><em>In the multiplicative model, We observe that the trend and seasonality are clearly separated and the scale of noise is small. In the additive model, there are outliers present in the residual. So the series is multiplicative.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26bfab478339" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vijendra-1893/time-series-forecasting-eda-and-decomposition-26bfab478339">Time Series Forecasting — EDA and Decomposition</a> was originally published in <a href="https://medium.com/vijendra-1893">Time Series Analysis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>