"""
# Data Analysis and Forecasting of sales
Book selling dataset by guftugu was given and they have placed home delivery information of books for more than an year. I have tried small data analysis and this notebook will be updated with time so stay tuned. I am planning to use machine learning so that i can help with better understanding of data and may be we can predict future sales.
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
from fbprophet import Prophet

import os
BASE_DIR = '/kaggle/input/gufhtugu-publications-dataset-challenge/'
file_name = BASE_DIR + 'GP Orders - 2.csv'
df = pd.read_csv(file_name, encoding='cp1252')
df
"""
Here, We are visualizing the success of deliveries in the data set. How many orders were sucessful?
"""
plt.hist(df['Order Status'])
print('No of Completed Orders: ', len(df[df['Order Status'] == 'Completed']))
print('No of Returned Orders: ', len(df[df['Order Status'] == 'Returned']))
print('No of Canceled Orders: ', len(df[df['Order Status'] == 'Canceled']))
plt.show()
"""
Top 10 cities having maximum order. For now, karachi has most no of orders. In future, we can relate it to no of population so that we can calculate the popularity of guftgu city wise. It will tell us where we need to work hard.
"""
max_orders_per_city = dict({(city, len(df[df['City (Billing)'] == city]))
                          for city in df['City (Billing)'].unique()})
top_orders_per_city = sorted(max_orders_per_city.items(), key=lambda x:x[1], reverse=True)[:10]
top_orders_per_city
"""
Returned orders by top 10 cities. Karachi is leading here too.
"""
returned_orders = df[df['Order Status'] == 'Returned']
returned_per_city = dict({(city, len(returned_orders[returned_orders['City (Billing)'] == city]))
                          for city in returned_orders['City (Billing)'].unique()})
top_returned_per_city = sorted(returned_per_city.items(), key=lambda x:x[1], reverse=True)[:10]
top_returned_per_city
"""
Converting date to python datetime object so that i can handle it for time series sale.
"""
df["Order Date"] = df["Order Date"].apply(datetime.strptime, args=('%m/%d/%Y %H:%M',))
for i in range(len(df)):
    df.loc[i, 'Order Date'] = df.loc[i, 'Order Date'].date()
"""
Here, I am going to create a dataframe that will have no of orders each day. I will try time series forcasting that can help me to predict no of orders that can happen in future on any day
"""
dates = df['Order Date'].unique()
orders_pre_date = [len(df[df['Order Date'] == date]) for date in dates]
df2 = pd.DataFrame(list(zip(dates, orders_pre_date)), 
               columns =['ds', 'y'])
df2 = df2.sort_values(['ds']).reset_index(drop=True)
df2
"""
Here is graph of no of orders on each day
"""
plt.figure(figsize=(20,10))
plt.plot(df2['ds'], df2['y'])
"""
I am going to check my dataset on facebook's opensource time series forcasting library that will help us to predict no of orders in future.
"""
m = Prophet()
m.fit(df2)
future = m.make_future_dataframe(periods=10)
forecast = m.predict(future)
forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()
m.plot(forecast)
"""
**Forecasting is not much better. Will try different methods**

# ****WORK IN PROGRESS****
"""