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.
#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.
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()
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.
#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'
)
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.
#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'
)
#affect of sales by month if there was a promotion
sb.factorplot(
col='Open',
hue='Promo',
x='Month',
y='Sales',
data=store1,
kind='box'
)
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?
sb.factorplot(
col='Open',
x='DayOfWeek',
y='Sales',
data=store1,
kind='violin'
)
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...
#filter out days where the store was not open
store1_open=store1[store1.Open==1]
store1_open[['Sales']].plot()
#By amount of customers
store1_open[['Customers']].plot()
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.
data[['Sales']].resample('D').mean().rolling(window=10, center=True).mean().plot()
Are sales more correlated with the prior day, the prior month or similar day the prior year?
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)))
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.
#plotting rolling average for two weeks at a time
data[['Sales']].resample('D').mean().rolling(window=14).mean().plot()
Lets identify the date with the largest drop in sales from the same date in the previous month while the store was open.
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()
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.
Facebook has published a great model for forecasting time series data called the profit.
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()
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'.
#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()
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)
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
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.