Rossman Drugstore Sales Data Analysis.

Rossman Drugstores are a popular chain in Germany. Rossman shared their sales data for a competition through Kaggle which can be viewed here. The challenge for this competition is to predict potential sales in the future. In this python 3 Jupyter Notebook I use time series analysis and Facebook's prophet model to predict sales a few weeks in advance given two years worth of data.

In [1]:
#begin with standard imports
import pandas as pd
import seaborn as sb
%matplotlib inline
#Facebook Prophet for predictions
from fbprophet import Prophet
data = pd.read_csv('data/train.csv', skipinitialspace=True, low_memory=False)

Begin by converting the date column into an easier format to use.

In [2]:
data['Date'] = pd.to_datetime(data['Date'])
data.set_index('Date', inplace=True)
data['Year']=data.index.year
data['Month']=data.index.month
#focus on just one store for simplicity
store1 = data[data.Store==1]
store1.head()
Out[2]:
Store DayOfWeek Sales Customers Open Promo StateHoliday SchoolHoliday Year Month
Date
2015-07-31 1 5 5263 555 1 1 0 1 2015 7
2015-07-30 1 4 5020 546 1 1 0 1 2015 7
2015-07-29 1 3 4782 523 1 1 0 1 2015 7
2015-07-28 1 2 5011 560 1 1 0 1 2015 7
2015-07-27 1 1 6102 612 1 1 0 1 2015 7

Data Exploration and Mining.

This data has different metrics to help with our predictions. Changing the date to a time series helps with the analysis but this data also includes whether or not there was a promotion, if there was a holiday, amount of customers, etc.

Let's take a snapshot to see what sales were like on various days.

In [3]:
#Visualize if sales increased on days where there was a Promotion(promo=1). Filter out if the store was not open(open=0)
sb.factorplot(
    col='Open',
    x='Promo',
    y='Sales',
    data=store1,
    kind='violin'
)
Out[3]:
<seaborn.axisgrid.FacetGrid at 0x1f892745048>

The graph above shows the blue hue as sales on days without a promotion and the orange hue shows when there was a promotion. On days where there was a promotion the average sales for that day were higher than days where there was not a promotion. From the graph we can approximate 4,000/day without promotion and 5,000/day on days with a promotion.

In [4]:
#sort sales by if there was School Holiday (SchoolHoliday = 1)
#and leave out if the store was not open
sb.factorplot(
    col='Open',
    x='SchoolHoliday',
    y='Sales',
    data=store1,
    kind='violin'
)
Out[4]:
<seaborn.axisgrid.FacetGrid at 0x1f892962240>
In [5]:
#affect of sales by month if there was a promotion
sb.factorplot(
    col='Open',
    hue='Promo',
    x='Month',
    y='Sales',
    data=store1,
    kind='box'
)
Out[5]:
<seaborn.axisgrid.FacetGrid at 0x1f892a0b588>

Conclusion: school holidays as well as promos bring an increase in sales. The drugstore does not appear to be open during days where there are state holidays.

What about sales per day of the week?

In [6]:
sb.factorplot(
    col='Open',
    x='DayOfWeek',
    y='Sales',
    data=store1,
    kind='violin'
)
Out[6]:
<seaborn.axisgrid.FacetGrid at 0x1f8929aa940>

The above shows that the store is closed on Sunday and there is a large volume of sales on Monday when the store opens for business again.

Now diving deeper for the yearly trends...

In [7]:
#filter out days where the store was not open
store1_open=store1[store1.Open==1]
store1_open[['Sales']].plot()
Out[7]:
<matplotlib.axes._subplots.AxesSubplot at 0x1f89439a438>
In [8]:
#By amount of customers
store1_open[['Customers']].plot()
Out[8]:
<matplotlib.axes._subplots.AxesSubplot at 0x1f8944a2fd0>

It would appear sales pick up around Christmas time because there is a rather large spike in customers late in the year.

To better analyze the trends in the sales data it is sometimes best to use a 'rolling mean' which will help smooth out the drastic swings as well as identify patterns. For example, we don't want to compare late December sales data with the entire month but perhaps a few days surrounding that date which will help account a little better for the holiday rush.

In [9]:
data[['Sales']].resample('D').mean().rolling(window=10, center=True).mean().plot()
Out[9]:
<matplotlib.axes._subplots.AxesSubplot at 0x1f894586b70>

Are sales more correlated with the prior day, the prior month or similar day the prior year?

In [10]:
avg_daily_sales=data[['Sales', 'Open']].resample('D').mean()
print('Correlation with previous day: {}'.format(avg_daily_sales['Sales'].autocorr(lag=1)))
print('Correlation with previous month: {}'.format(avg_daily_sales['Sales'].autocorr(lag=30)))
print('Correlation with previous year: {}'.format(avg_daily_sales['Sales'].autocorr(lag=365)))
Correlation with previous day: -0.025858276006383588
Correlation with previous month: -0.12984245822530618
Correlation with previous year: 0.02023852944834456

As we see above as well as in the following graphs the previous month is a very low predictor of current sales, a previous day will help a little better at predicting current sales but the most accurate prediction of a day would be by going back to the previous year.

In [11]:
#plotting rolling average for two weeks at a time
data[['Sales']].resample('D').mean().rolling(window=14).mean().plot()
Out[11]:
<matplotlib.axes._subplots.AxesSubplot at 0x1f89463a7b8>

Lets identify the date with the largest drop in sales from the same date in the previous month while the store was open.

In [12]:
avg_daily_sales = data[['Sales', 'Open']].resample('D').mean()
avg_daily_sales['DiffVsLastMonth']=avg_daily_sales[['Sales']].diff(periods=30)
avg_daily_sales[avg_daily_sales.Open==1].sort_values(by='DiffVsLastMonth').head()
Out[12]:
Sales Open DiffVsLastMonth
Date
2014-12-31 4166.407487 1.0 -6825.005348
2015-01-14 7068.780269 1.0 -5908.097806
2014-12-24 4933.386096 1.0 -4714.009626
2015-01-17 5852.638565 1.0 -4637.427745
2015-01-15 6973.035874 1.0 -4386.386585

The biggest drop in sales when compared to the previous month would be from December 31st versus December 1st. The third biggest drop in sales would be on Christmas Eve which may show that Germans are done with their Christmas shopping before Christmas Eve. When I was growing up my family did most of their shopping on Christmas Eve.

Predictions!

Facebook has published a great model for forecasting time series data called the profit.

In [13]:
data = pd.read_csv('data/train.csv', low_memory=False)
#make a dataframe when the store was open and sales were generated
data = data[(data["Open"] !=0) & (data['Sales'] !=0)]
#focus on 1 store
store_1 = data[data.Store == 1].loc[:, ['Date', 'Sales']]
#properly format date
store_1['Date']=pd.DatetimeIndex(store_1['Date'])
#fit names to match model
store_1 = store_1.rename(columns = {'Date':'ds',
                             'Sales':'y'})
store_1.head()
Out[13]:
ds y
0 2015-07-31 5263
1115 2015-07-30 5020
2230 2015-07-29 4782
3345 2015-07-28 5011
4460 2015-07-27 6102

Facebook's prophet model requires specific names for columns so here Date is 'ds' and since Sales is our target variable we associate that with 'y'.

In [14]:
#prophet allows for holidays but we have to format them as well
state_dates = data[(data.StateHoliday == 'a') | (data.StateHoliday == 'b') & (data.StateHoliday == 'c')].loc[:, 'Date'].values
school_dates = data[data.SchoolHoliday == 1].loc[:, 'Date'].values

state = pd.DataFrame({'holiday': 'state_holiday',
                      'ds': pd.to_datetime(state_dates)})
school = pd.DataFrame({'holiday': 'school_holiday',
                      'ds': pd.to_datetime(school_dates)})

holidays = pd.concat((state, school))      
holidays.head()
Out[14]:
ds holiday
0 2015-06-04 state_holiday
1 2015-06-04 state_holiday
2 2015-06-04 state_holiday
3 2015-06-04 state_holiday
4 2015-06-04 state_holiday
In [15]:
model = Prophet(holidays=holidays)
model.fit(store_1)
#predict 4 weeks into the future
future = model.make_future_dataframe(periods = 4*7)
forecast = model.predict(future)
forecast.tail(14)
INFO:fbprophet.forecaster:Disabling daily seasonality. Run prophet with daily_seasonality=True to override this.
Out[15]:
ds trend trend_lower trend_upper yhat_lower yhat_upper holidays holidays_lower holidays_upper school_holiday ... state_holiday state_holiday_lower state_holiday_upper weekly weekly_lower weekly_upper yearly yearly_lower yearly_upper yhat
795 2015-08-15 4469.082584 4468.932109 4469.231264 3069.193489 5153.644867 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 275.335398 275.335398 275.335398 -652.030600 -652.030600 -652.030600 4092.387382
796 2015-08-16 4468.999865 4468.807422 4469.193625 2974.704233 5120.191480 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 260.727175 260.727175 260.727175 -646.045452 -646.045452 -646.045452 4083.681588
797 2015-08-17 4468.917146 4468.696385 4469.154323 3115.614270 5259.248136 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 351.952120 351.952120 351.952120 -638.444792 -638.444792 -638.444792 4182.424474
798 2015-08-18 4468.834427 4468.569249 4469.114757 2702.655689 4716.269382 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 -146.414974 -146.414974 -146.414974 -629.730021 -629.730021 -629.730021 3692.689432
799 2015-08-19 4468.751708 4468.461372 4469.067170 2499.133955 4722.030832 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 -263.654188 -263.654188 -263.654188 -620.417844 -620.417844 -620.417844 3584.679675
800 2015-08-20 4468.668990 4468.341948 4469.024435 2402.994482 4580.303654 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 -360.408349 -360.408349 -360.408349 -611.021959 -611.021959 -611.021959 3497.238682
801 2015-08-21 4468.586271 4468.217537 4469.007697 2745.350702 4873.928549 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 -117.537181 -117.537181 -117.537181 -602.034859 -602.034859 -602.034859 3749.014231
802 2015-08-22 4468.503552 4468.078306 4468.959625 3047.800626 5182.788846 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 275.335398 275.335398 275.335398 -593.910342 -593.910342 -593.910342 4149.928608
803 2015-08-23 4468.420833 4467.959429 4468.938477 3005.116062 5186.068297 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 260.727175 260.727175 260.727175 -587.047264 -587.047264 -587.047264 4142.100744
804 2015-08-24 4468.338114 4467.831283 4468.897639 3180.824686 5404.664483 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 351.952120 351.952120 351.952120 -581.775082 -581.775082 -581.775082 4238.515152
805 2015-08-25 4468.255396 4467.693166 4468.860288 2678.066994 4841.568243 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 -146.414974 -146.414974 -146.414974 -578.341651 -578.341651 -578.341651 3743.498770
806 2015-08-26 4468.172677 4467.577483 4468.847246 2565.273395 4712.533325 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 -263.654188 -263.654188 -263.654188 -576.903675 -576.903675 -576.903675 3627.614813
807 2015-08-27 4468.089958 4467.447199 4468.820306 2453.493452 4623.284726 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 -360.408349 -360.408349 -360.408349 -577.520149 -577.520149 -577.520149 3530.161460
808 2015-08-28 4468.007239 4467.300448 4468.776017 2832.725262 4796.706516 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 -117.537181 -117.537181 -117.537181 -580.149018 -580.149018 -580.149018 3770.321040

14 rows × 28 columns

In this case our 'yhat' is our prediction for sales and on the 15th of August we are predicting 4092 in sales.

Prophet has a handy tool to visual the results and their confidence in picks

In [16]:
model.plot(forecast);

This shows an added August column of dates Prophet predicted based on the preceding years. The blue lines show where the forecasted values are trending and the light blue shading shows the uncertainty intervals of our forecast.