Commit 4f0428d7 authored by Shivanthi Fernando's avatar Shivanthi Fernando

Customer Retention

parent ccf3b12b
......@@ -52,3 +52,7 @@ class MyForm3(forms.Form):
class MyFormNew(forms.Form):
inputdate = forms.DateField(widget=DateInput)
#Customer Frequency
class MyForm(forms.Form):
customerid = forms.IntegerField(label='Enter Customer ID' )
......@@ -16,5 +16,6 @@ urlpatterns = [
path('Forecasting/', responseapp_views.Forecasting),
path('Result/', responseapp_views.Forecasting),
path('Customer_Data/', responseapp_views.Customer_Data),
path('Customer_Frequency/', responseapp_views.Customer_Frequency),
path('', admin.site.urls),
]
\ No newline at end of file
......@@ -27,13 +27,14 @@ from statsmodels.tsa.stattools import adfuller
from statsmodels.tsa.arima.model import ARIMA
from pandas.tseries.offsets import DateOffset
import warnings
warnings.filterwarnings("ignore")
# Start CompanyHome
def Homepage(request):
return render(request, 'Admin/Homepage.html');
# End CompanyHome
# Employee_Efficency
def Employee_Data(request):
data1 = pd.read_csv('Data/WorkHistory.csv')
......@@ -214,6 +215,131 @@ def Customer_Data(request):
context = {'d': arr}
return render(request, 'Admin/Customer_Data.html',context);
# Customer Frequency
def Customer_Frequency(request):
if request.method == 'POST':
myForm = MyForm(request.POST)
if myForm.is_valid():
# Loading the data
df = pd.read_csv('Data/CustomerDataset.csv')
# Drop the missing data in `df`
df_data = df.dropna()
# Convert the date field, InvoiceDate to datetime object
df_data.InvoiceDate = pd.to_datetime(df_data.InvoiceDate)
ctm_bhvr_dt = df_data[(df_data.InvoiceDate < pd.Timestamp(2021, 10, 8)) # dataset End date
& (df_data.InvoiceDate >= pd.Timestamp(2021, 2, 12))].reset_index(
drop=True) # dataset start date
ctm_next_quarter = df_data[(df_data.InvoiceDate < pd.Timestamp(2022, 4, 8)) # predict date Till
& (df_data.InvoiceDate >= pd.Timestamp(2021, 10, 8))].reset_index(
drop=True) # dataset End date
# Get the distinct customers in the dataframe ctm_bhvr_dt
ctm_dt = pd.DataFrame(ctm_bhvr_dt['CustomerID'].unique())
# Rename the column to CustomerID.
ctm_dt.columns = ['CustomerID']
# Create a dataframe with CustomerID and customers first purchase
# date in the dataset ctm_next_quarter
ctm_1st_purchase_in_next_quarter = ctm_next_quarter.groupby('CustomerID').InvoiceDate.min().reset_index()
ctm_1st_purchase_in_next_quarter.columns = ['CustomerID', 'MinPurchaseDate']
# Create a dataframe with CustomerID and customers last purchase
# date in the dataset ctm_bhvr_dt
ctm_last_purchase_bhvr_dt = ctm_bhvr_dt.groupby('CustomerID').InvoiceDate.max().reset_index()
ctm_last_purchase_bhvr_dt.columns = ['CustomerID', 'MaxPurchaseDate']
# Merge two dataframes ctm_last_purchase_bhvr_dt and ctm_1st_purchase_in_next_quarter
ctm_purchase_dates = pd.merge(ctm_last_purchase_bhvr_dt, ctm_1st_purchase_in_next_quarter, on='CustomerID',
how='left')
# Get the difference in days from MinPurchaseDate and MaxPurchaseDate for each customer
ctm_purchase_dates['NextPurchaseDay'] = (
ctm_purchase_dates['MinPurchaseDate'] - ctm_purchase_dates['MaxPurchaseDate']).dt.days
# Update the dataframe ctm_dt by merging it with the NextPurchaseDay column of the dataframe ctm_purchase_dates
ctm_dt = pd.merge(ctm_dt, ctm_purchase_dates[['CustomerID', 'NextPurchaseDay']], on='CustomerID',
how='left')
ctm_dt = ctm_dt.fillna("Not Returning")
newloaded = ctm_dt.head()
print("-----------------Next Purchase Day-----------------")
# print(newloaded)
# Feature Engineering
# Recency
# Get the maximum purchase date of each customer and create a dataframe with it together with the customer's id.
ctm_max_purchase = ctm_bhvr_dt.groupby('CustomerID').InvoiceDate.max().reset_index()
ctm_max_purchase.columns = ['CustomerID', 'MaxPurchaseDate']
# Find the recency of each customer in days
ctm_max_purchase['Recency'] = (
ctm_max_purchase['MaxPurchaseDate'].max() - ctm_max_purchase['MaxPurchaseDate']).dt.days
# Find the recency in days
ctm_max_purchase['Recency'] = (
ctm_max_purchase['MaxPurchaseDate'].max() - ctm_max_purchase['MaxPurchaseDate']).dt.days
# Merge the dataframes ctm_dt and ctm_max_purchase[['CustomerID', 'Recency']] on the CustomerID column.
ctm_dt = pd.merge(ctm_dt, ctm_max_purchase[['CustomerID', 'Recency']], on='CustomerID')
Recency = ctm_dt.head()
# Frequency
# Get service booking counts for each user and create a dataframe with it
ctm_frequency = df_data.groupby('CustomerID').InvoiceDate.count().reset_index()
ctm_frequency.columns = ['CustomerID', 'Frequency']
# Update the dataframe ctm_dt by merging it with the dataframe ctm_frequency
ctm_dt = pd.merge(ctm_dt, ctm_frequency, on='CustomerID')
Frequency = ctm_dt.head()
print(Frequency)
# print(ctm_dt)
# Monetary Value/Revenue
# Create a new label, Revenue of each item bought
# customer value persontage
# print(Frequency)
df2 = pd.read_csv('Data/CustomerDataset.csv')
ctm_dt = pd.merge(ctm_dt, df2, on='CustomerID')
# Merge the dataframe ctm_revenue with ctm_dt
# ctm_dt = pd.merge(ctm_dt, ctm_revenue, on='CustomerID')
# Monetary = ctm_dt.head()
# print(Monetary)
# Building Machine Learning Models
# get data of Entered Customer
customerid = myForm.cleaned_data['customerid']
dfz = ctm_dt[(ctm_dt["CustomerID"] == customerid) ]
Frequency = dfz.head(1)
print(Frequency)
df = Frequency
# data = data.to_html()
json_records = df.reset_index().to_json(orient='records')
arr = []
arr = json.loads(json_records)
a = 2
form = MyForm()
context = { 'form': form, 'd': arr}
return render(request, 'Admin/Customer_Frequency.html', context)
else:
form = MyForm()
return render(request, 'Admin/Customer_Frequency.html', {'form': form});
def AdminHome(request):
return render(request,'Admin/AdminHome.html')
......
{% extends 'Admin/Sidebar2.html' %}
{% block content %}
{% load widget_tweaks %}
{%load static%}
<head>
<!-- Font special for pages-->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i,800,800i" rel="stylesheet">
<!-- Main CSS-->
<link href="{% static "css/main.css" %}"rel="stylesheet" media="all">
</head>
<div class=" >
<div class="wrapper wrapper 0">
<div style="margin-left: 0px;" class="card card-5">
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li {% if message.tags %} class=" {{ message.tags }} " {% endif %}> {{ message }} </li>
{% endfor %}
</ul>
{% endif %}
<div class="card-heading">
<h2 class="title mt-3" style="color: #02111f;"> PREDICT CUSTOMER RETENTION </h2>
</div>
<div class="card-body">
<form action="/Admin/Customer_Frequency/" method="post">
{% csrf_token %}
<table class="table table-light">
{{form.as_table}}
</table>
<input type="submit" value="PREDICT" class="btn btn--radius-2" style="background: #02111f;"/>
</form> <br><div class="text-right">
<input name="b_print" type="button" class="btn btn-print" onClick="printdiv('div_print');" value=" Print " style="background: #02111f;">
</div>
<br>
</div>
</div>
</div>
<div id="myDiv">
<div id="div_print">
<div class="card card-body printableArea">
<div role="alert" >
<div class="container" style="overflow-x:auto;">
<table class="table table-striped">
<thead>
<tr>
<th> Customer ID </th>
<th> Customer Name </th>
<th> Vehicle Number </th>
<th> Vehicle Type </th>
<th> Next Return In </th>
<th> Return Frequency </th>
</tr>
</thead>
<tbody>
{% if d %}
{% for i in d %}
<tr>
<td> {{i.CustomerID}} </td>
<td> {{i.CustomerName}} </td>
<td> {{i.VehicleNo}} </td>
<td> {{i.VehicleType}} </td>
<td> {{i.NextPurchaseDay}} </td>
<td>{{i.Frequency}}</td>
</tr>
{% endfor %}
{% endif %}
</tbody>
</table>
</div>
</div>
</div></div></div>
<script language="javascript">
function printdiv(printpage) {
var headstr = "<html><head><title></title></head><body>";
var footstr = "</body>";
var newstr = document.all.item(printpage).innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr + newstr + footstr;
window.print();
document.body.innerHTML = oldstr;
location.reload();
return false;
}
</script>
<div class="alert alert-primary fixed-bottom mb-0 text-center" style="background: #747578; border: none; color: white;" role="alert" > © SERVPORT 2022 </div>
</div>
{% endblock content %}
......@@ -187,7 +187,7 @@ body{
<li><a style="text-decoration:none;" href="#"><i class="fas fa-eye"></i> Highest Demand </a>
<li><a style="text-decoration:none;" href="/Admin/PurchaseHistory/"><i class="fas fa-cubes"></i> Purchase History </a>
<li><a style="text-decoration:none;" href="/Admin/Customer_Data/"><i class="fas fa-user"></i> Customer Data </a>
<li><a style="text-decoration:none;" href="/Admin/Customer_Frequency/"><i class="fas fa-chart-bar"></i> Customer Frequency </a>
</ul>
</div>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment