-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.Rmd
774 lines (574 loc) · 29.9 KB
/
index.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
---
title: "PokemonGo customer analytics"
author: '[Leonard Henriquez](https://github.com/leonard-henriquez/), [Adrien Lequiller](https://github.com/adrienlequiller) & [Eddy Ohayon](https://github.com/Eddoha55)'
date: "`r Sys.Date()`"
output: html_document
always_allow_html: yes
---
```{r message=FALSE, warning=FALSE, include=FALSE}
# Options
knitr::opts_chunk$set(cache = TRUE, warning=FALSE)
options(digits=4)
# Libraries
library(dplyr)
library(tidyr)
library(ggplot2)
library(caret)
library(xgboost)
library(reshape2)
library(leaps)
```
This assignment was originally given at EDHEC Business School. The wording is available [here](Assignment.pdf).
# Assignment I, Basetable
### Data importation and cleaning
1) First, let's start by reading the customer' data:
```{r}
# Import customers data
customer.raw<- read.csv("input/customerdata.csv" )
# Clean data
customer.raw$Registrationdate <- as.Date(customer.raw$Registrationdate)
customer.raw$fallbonus <- as.factor(customer.raw$fallbonus)
customer.raw$CustomerType <- as.factor(customer.raw$CustomerType)
customer.raw$Sex <- as.factor(customer.raw$Sex)
customer.raw$Income <- as.factor(customer.raw$Income)
#Let's create categories of Age (that could be relevant for the rest) :
customer.raw <- customer.raw %>%
mutate(Age_category=
ifelse(between(Age, 6, 17), '6-17',
ifelse(between(Age, 18, 23), '18-23',
ifelse(between(Age, 24, 35), '24-35',
ifelse(between(Age, 36, 50), '36-50', '>51'
)))))
customer.raw$Age_category <- factor(customer.raw$Age_category, levels=c('6-17', '18-23', '24-35', '36-50', '>51'))
customer <- customer.raw
# And let's check what we have
summary(customer)
```
2) Now let's check the transactions:
```{r}
# Import transactions
tx.fall <- read.csv("input/fallfintrx.csv" )
tx.summer <- read.csv("input/summerfintrx.csv" )
# We need to add monetary value and convert the date
# This is the list of prices for each ProductID
prices <- c(2.99, 4.99, 9.99, 25, 99)
tx.fall <- tx.fall %>% mutate(Value = prices[ProductID], Date = as.Date(Date))
tx.summer <- tx.summer %>% mutate(Value = prices[ProductID], Date = as.Date(Date))
# Then we create a data frame with all data
tx.all <- tx.fall %>% union(tx.summer)
# And let's check what we have
summary(tx.all)
```
For later we need to keep the dates of beginning and ending of the periods:
```{r}
# This will correspond to the history period to build the models
fall.begin <- min(tx.fall$Date)
fall.end <- max(tx.fall$Date)
# This will correspond to the forecast period to build and evaluate the models
summer.begin <- min(tx.summer$Date)
summer.end <- max(tx.summer$Date)
# This will correspond to the entire period to build the final model
all.begin <- min(tx.all$Date)
all.end <- max(tx.all$Date)
```
3) And finally the sessions:
```{r}
# Import sessions
sessions.fall <- read.csv("input/fallsesstrx.csv" )
sessions.summer <- read.csv("input/summersesstrx.csv")
sessions.fall$Date <- as.Date(sessions.fall$Date)
sessions.summer$Date <- as.Date(sessions.summer$Date)
sessions.all <- sessions.fall %>% union(sessions.summer)
```
### RFM Analysis
The point of this part is to calculate the RFM for all active customers.
We could base our RFM analysis either on sessions or on transactions. We opted for RFM analysis based on transactions because it is a better proxy for monetary value of a customer.
We defined:
* **Recency** as the number of days since last transaction
* **Frequency** as the number of transactions
* **Monetary** value as the total value of all products bought in the period
```{r}
# Calculated RFM based on all transactions (summer and fall)
# for each customer (who made at least one transaction)
customer.RFM <- tx.all %>%
group_by(CustomerID) %>%
summarise(Recency = as.numeric(all.end-max(Date)), Frequency = n(), Monetary = sum(Value))
summary(customer.RFM)
```
Attention: since this list is build from `tx.all` it will only contain customers that made **at least one transaction**.
Now let's create a list of active customers:
```{r}
# Get all customerIDs of people who played at least once during the summer
customerID.active <- sessions.summer %>%
select(CustomerID) %>%
distinct(CustomerID)
```
Now we have enough to create a RFM table of active customers but we might want other information on sessions played. So, let's create a table that summarize the information of the sessions played by customers:
```{r}
customer.stats <- sessions.all %>%
group_by(CustomerID) %>%
select(-c(X, PlayID, Date)) %>%
summarise_all(funs(sum))
summary(customer.stats)
```
Finally, we just need to combine the tables built previously to get our base table:
```{r}
# Add all informations to the table with all customers
recency.max = max(customer.RFM$Recency) + 1
customer <- customer %>%
left_join(customer.stats, by = "CustomerID") %>%
left_join(customer.RFM, by = 'CustomerID') %>%
select(-X) %>%
# We need to replace we 0 the missing values corresponding to customer who never bought any item
mutate(
Recency = replace_na(Recency, max(recency.max)),
Frequency = replace_na(Frequency, 0),
Monetary = replace_na(Monetary, 0)
)
# Filter only active customers
customer.active <- customer %>% filter(CustomerID %in% customerID.active$CustomerID)
# final basetable
summary(customer.active)
```
### Customer Lifetime Value
Customer Lifetime Value (CLV) is given by the formula:
$$\sum_{t=0}^{T} m \frac{r^{t}}{(1+d)^{t}}-AC$$
In order to calculate it we have 5 parameters to estimate:
* $d$: Discount rate (Cost of Capital)
* $AC$: Acquisition costs (per customer)
* $r$: Retention probability for the customer
* $T$: Number of years 'out'
* $m$: Customer recurring contribution margin (which is equal to recurring revenues less recurring costs)
Now let's make (reasonable) assumptions on those parameters.
First, we decided to estimate all parameters excepted $m$ by values common to all customers. For $d$ or $T$, we have no reason to consider a different cost of capital or number of year out for a customer or another. For $AC$ we have no information concerning marketing operations that may have impacted it excepted the fall bonus, but we believe that it had little cost, little opportunity cost and had mostly an impact on $r$. On the opposite, we decided to estimate $m$ at a customer level based on past purchasing behavior. For the purpose of this assignment we decided not to do the same technique for $r$ since we'll do it in assignment III.
**Discount Rate**
Since we are studying an industry where customers have relatively small lifespan (inferior to 3 years), cost of capital will have a relatively small impact on CLV. We decided to take $d$ = 10% which seems to be a reasonable assumption for the software industry according to a [NYU study](http://people.stern.nyu.edu/adamodar/New_Home_Page/datafile/wacc.htm).
```{r}
CLV.d <- 0.1
```
**Acquisition Cost** (per customer)
First, let's estimate the budget allocated to marketing given the assumption that it represents 15% of the revenues:
```{r}
# We'll need the period of time of transactions
days_in_period <- as.numeric(all.end - all.begin)
# Total daily revenues
total_daily_revenues <- sum(tx.all$Value) / days_in_period
# Total daily amount spend in marketing
total_daily_marketing_cost <- 0.15 * total_daily_revenues
```
Now given this daily marketing spending, let's estimate the cost of acquisition per customer:
```{r}
# We'll need the period of time of registration
days_in_registration_period <- as.numeric(max(sessions.all$Date) - min(as.Date(customer$Registrationdate)))
# Now we want to calculate the cost per customer
CLV.AC <- total_daily_marketing_cost * days_in_registration_period / nrow(customer)
sprintf("Acquisition Cost is estimated to: $%.2f", CLV.AC)
```
**Retention rate**
First we'll need to define when we consider that a customer has churned. In this assignment we decided to define churning based on activity (number of sessions played) and not on financial transactions. You may check assignment 3 if you are interested in a definition of churning based on transactions.
To do that we might want to look at an histogram of the average time (in days) between two sessions. Let's do that:
```{r}
customer.sessions <- sessions.all %>%
group_by(CustomerID) %>%
# avg_interval is the average interval in days between the first and the last session of a customer
summarise(first = min(Date), last = max(Date), count = n(), avg_interval = as.numeric(last - first)/count) %>%
# we can't calculate an interval with only one value so let's remove those lines
filter(count > 1)
# Now let's plot that
ggplot(customer.sessions) + geom_histogram(binwidth = 10) + aes(x = avg_interval)
```
We notice that more than 99% of customers have an average day interval between sessions inferior to 60 days. So let's define an active user as someone who played at least once in the last 60 days. Thus a user has churned if he has not played sessions in more than 60 days.
Now to determine retention. To do this:
1) We'll take a cohort of "active" as of June 30th (all the customers who played at least on session in may or June)
2) In this cohort we'll check which one are still "active" as of October 31st (all the customers who played at least one session in September or October)
3) The ratio of (2) over (1) represents the 4-month retention rate
4) We will need to transform it to the annual retention rate
```{r}
# 1) Cohort
cohort <- sessions.all %>%
filter(Date >= as.Date("2018-05-01"), Date < as.Date("2018-07-01")) %>%
group_by(CustomerID) %>%
distinct(CustomerID) %>%
select(CustomerID)
# 2) Customer in cohort still active as of October 31st
active <- sessions.all %>%
filter(Date >= as.Date("2018-09-01"), Date < as.Date("2018-11-01")) %>%
group_by(CustomerID) %>%
distinct(CustomerID) %>%
select(CustomerID)
cohort.active <- cohort %>% inner_join(active, by = "CustomerID")
# 3) 4-month retention rate
r.4m <- nrow(cohort.active) / nrow(cohort)
# 4) 1-year retention rate
CLV.r <- r.4m^(12/4)
sprintf("Retention rate is estimated to: %.2f percent", CLV.r*100)
```
**Number of years 'out'**
In order to take no risk we will take $T$ so that after $T$ years a customer has a probability of having churn superior to 90%. In mathematical language this gives us: $T = ln(0.1) / ln(r)$
```{r}
CLV.T <- log(0.1) / log(CLV.r)
sprintf("Number of years 'out' is estimated to: %.2f years", CLV.T)
```
**Customer recurring contribution margin**
Now we want to estimate the contribution margin generated by a customer.
For the purpose on this assignment we decided to assume that the recurring cost for all customers represented 10% of total revenues. So we applied calculation similar to $AC$
```{r}
CLV.rc <- 0.10 * total_daily_revenues * 365 / nrow(customer)
```
Now, let's focus on recurring revenues. First, we thought about estimating the recurring revenues by the average purchase by customer. But we figured that there were significant variation between the baskets of different customers. So we tried to apply the same reasoning at a customer level by estimating future purchases by past purchasing behavior. But that does not account for the fact that the average amount bought in previous periods is a poor estimator future purchases. Indeed, using such model a user that has never bought anything will never buy anything, so he has inevitably a negative CLV which should not always be the case.
So, in the end we chose to build a linear model to estimate how much a customer is likely to buy in October based on his purchasing behavior of the previous months.
First, let's build tables containing information of past purchases, by customer and by month:
```{r}
customerID.all <- data_frame(CustomerID=customer$CustomerID)
tx.all$Month = format(tx.all$Date, "%m")
columns <- c('05', '06', '07', '08', '09', '10')
monthly.tx.all <- customerID.all %>%
left_join(tx.all, by = "CustomerID") %>%
spread(Month, Value) %>%
select(-c(X:ProductID)) %>%
mutate_at(.vars = columns, funs(replace_na(.,0))) %>%
group_by(CustomerID) %>%
summarise_at(.vars = columns, funs(sum))
head(monthly.tx.all)
monthly.tx <-
tx.all %>%
spread(Month, Value) %>%
select(-c(X:Date, ProductID)) %>%
mutate_at(.vars = columns, funs(replace_na(.,0))) %>%
group_by(CustomerID) %>%
summarise_at(.vars = columns, funs(sum))
head(monthly.tx)
```
We comes the estimation of the recurring revenues of each customer:
```{r}
set.seed(11)
# select the indexes of the rows in the training set
train.index <- createDataPartition(
monthly.tx.all$`10`,
p = .9,
list = FALSE,
times = 1
)
# split the data
train <- monthly.tx.all[ train.index,]
test <- monthly.tx.all[-train.index,]
train.y <- train$`10`
test.y <- test$`10`
# build the model
# after trying different models we kept the linear model because it was more simple with very comparable results
# we decided to add an intercept variable to account for the fact that a user who never bought anything might start buying
# This has a HUGE impact on the final result:
# with intercept, a customer who as never bought as a CLV of 2.5
# without intercept, a customer who as never bought as a CLV of -5.5
# The answer
model.revenue <- lm(`10`~. - CustomerID, data=train)
# check the model
summary(model.revenue)
# check the performance of the model
train.pred <- predict(model.revenue, train)
test.pred <- predict(model.revenue, test)
sprintf("Average absolute error by customer (on training set): $%.2f", mean(abs(train.y-train.pred)))
sprintf("Average absolute error by customer (on testing set): $%.2f", mean(abs(test.y-test.pred)))
```
Not surprisingly, the results aren't incredible, but we wouldn't study Customer Analytics if it were possible to perfectly predict what a customer will buy in the future.
Still, it is a better estimator of what's he is going to buy than the average of what he bought the past months (see results below). And our model is surely more efficient to estimate what our customer will keep buying in the months after October.
```{r}
print(mean(abs(test.y-rowMeans(test[,-c(1,7)]))))
```
**Calculation of CLV**
Now that we have estimated all parameters:
```{r}
CLV.const = data_frame(AC=CLV.AC, rc=CLV.rc, r=CLV.r, T=CLV.T, d=CLV.d)
CLV.const
```
We can create the CLV function:
```{r}
CLV <- function (CLV.const, model, id) {
df_id <- data_frame(CustomerID=id)
model.input <- df_id %>% left_join(monthly.tx.all, by = "CustomerID")
# Period of time to convert revenue to (annual) recurring revenue
rr <- 12 * predict(model, model.input)
# Customer value
AC <- CLV.const$AC # Customer acquisition costs
rc <- CLV.const$rc # Recurring cost
m <- rr - CLV.const$rc # Customer recurring contribution margin
r <- CLV.const$r # Retention probability for the customer
t <- CLV.const$T # Number of years 'out' to estimate
d <- CLV.const$d # Discount rate (Cost of Capital)
# print(cbind(AC, rc, m, r, t, d))
clv <- -AC
for(i in 0:t) {
clv <- clv+((r^i)*m/(1+d)^i)
}
return(clv)
}
```
And calculate the CLV for every customer:
```{r}
customer.active <- customer.active %>% mutate(CLV = CLV(CLV.const, model.revenue, CustomerID))
summary(customer.active)
```
### Demographic Analysis & Profiling
We will sketch general profiles of the active customers.
First, let's have a look at how gender of the players are dispatched among the players :
```{r}
ggplot(customer.active)+aes(x=Sex)+geom_bar()
```
We can see that there are more male players overall.
Now, we will consider that the general profile of a player is a male and we'll now have a look at how they are dispatched through age categories.
```{r}
ggplot(customer.active %>% filter(Sex==0))+aes(x=Age_category)+geom_bar()
```
We can see that there are much more players between 24-35 overall. Thus, most of the players are male between 24-35.
Now, we'll compare the income level of male players between 24-35 :
```{r}
ggplot(customer.active %>% filter(Age_category == "24-35", Sex == 0)) + aes(x=Income) + geom_bar()
```
Thus, we can see that the number of players is quite the same per income level. There is no significant difference. We can deduce that a general player can have any level of income.
Thus, if we take into account the total number of players per demographic metrics, the profile of a general player would be a male between 24-35 and with any income level.
Now, let's add in our reasoning the type of player with the general demographic profile we found.
```{r}
ggplot(customer.active %>% filter(Age_category == "24-35", Sex == 0)) +aes(x=Age_category,fill=as.factor(CustomerType))+geom_bar()
```
Once again, we can see no significant difference between the customer type, even if the "Catchers" are the most numerous. Thus, we will consider that these players can be of any type.
Now, let's add in our reasoning the financial value using Monetary and Frequency for the demographic profile we chose.
```{r}
customer.active %>% filter(Age_category == "24-35", Sex == 0) %>% summarise(mean(Monetary),mean(Frequency),mean(CLV))
```
Thus, we can complete the general profile by saying that can the general profile is a player :
- male between 24-35
- spending on average 6.13 with a frequency of 0.61 on the period.
# Assignment II, Lifecycle grids:
In life cycle grids, we are focusing on the R & F of RFM. In other words, in frequent and recent purchases because frequency affects client's lifetime value and recency affects retention.
The purpose therefore is to provide a target offer to specific segments or customers.
### A small look at R & F distributions
*Note: the maximum of customer registration date is 30-04-2028 so we are sure that customer.active data doesn't contain customers that could have registered in the fall period...*
```{r}
#Initialisation: combining overall transactions with customer info
customer.LCG <- tx.all %>% select(-X) %>% inner_join(customer.active)
summary(customer.LCG)
```
```{r}
# Frequency distribution
ggplot(customer.LCG)+aes(x=Frequency)+geom_bar()
```
```{r}
#Recency Distribution (by days)
ggplot(customer.LCG)+aes(x=Recency)+geom_bar()
```
### Life Cycle grids
#### Introduction
Let's do now life cycle grids. In this part, we decided to consider frequency one by one until customers buy more that 5 products (because the gap between 1 and 2 products cannot be equally considered to the one between 5 and 6 products bought).
We use the 'same' principle to split the recency. More specifically, we decided segment them - regarding Niantic purposes - using relevant time periods:
- 0-6 days & 7-13: customers that can be considered as very frequent buyers
- 14-30 : customers that bought recently (during fall period but seems to have slowed down their use of their use of package to play)
- 31-50: customers that haven't bought for a quite long period and that could we should focus on to reengage
- 51-85: customers that stopped to buy after the summer period - we should especially look at those ones to improve the marketing strategy purpose between summer and fall periods
- 85: Finally, customers that can be considers as long-time buyers or those who follow the Pokemon Go trend of the summer but who were not really interested to evolve rapidly with Pokemon's packages
```{r}
#Creation of Grids
customer.LCG <- customer.LCG %>%
mutate(segm.freq=ifelse(Frequency == 1, '1',
ifelse(Frequency == 2, '2',
ifelse(Frequency == 3, '3',
ifelse(Frequency == 4, '4',
ifelse(Frequency == 5,'5','>5')))))) %>%
mutate(segm.rec=ifelse(between(Recency,0,6), '0-6 days',
ifelse(between(Recency,7,13), '7-13 days',
ifelse(between(Recency, 14,30), '14-30 days',
ifelse(between(Recency,31,50), '31-50 days',
ifelse(between(Recency,51,85), '51-85 days', '>85 days'))))))
# spliting into discrete groups with levels to make & identify grids later on
customer.LCG$segm.freq <- factor(customer.LCG$segm.freq, levels=c('>5','5','4','3','2','1'))
customer.LCG$segm.rec <- factor(customer.LCG$segm.rec, levels=c('>85 days','51-85 days','31-50 days','14-30 days','7-13 days','0-6 days'))
summary(customer.LCG)
```
We will first have a look at the volume of transactions regarding the period (recency) and the frequency.
#### Approach in Volume of transactions
```{r}
# General Overview
lcg.gen <- customer.LCG %>%
group_by(segm.rec, segm.freq) %>%
summarise(quantity=n()) %>%
mutate(client='client') %>%
ungroup()
#let's add sub-categories to better distinguish customer profiles in our grids
lcg.gen <- lcg.gen %>% mutate(rec.type = ifelse(segm.rec %in% c('>85 days', '51-85 days', '31-50 days'), 'not recent', 'recent'),
freq.type = ifelse(segm.freq %in% c('>5', '5', '4'), 'frequent', 'infrequent'),
customer.bh = interaction(rec.type, freq.type))
ggplot(lcg.gen, aes(x=client, y=quantity, fill=customer.bh))+
theme_bw() +
theme(panel.grid = element_blank())+
geom_bar(stat='identity', alpha=0.7) +
geom_rect(aes(fill = customer.bh), xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf, alpha = 0.1) +
geom_text(aes(y=max(quantity)/2, label=quantity), size=4) +
facet_grid(segm.freq ~ segm.rec)+
ggtitle("LifeCycle Grids: Number of transactions and underlying categorisation")
```
```{r}
lcg.bonus <- customer.LCG %>%
group_by(segm.rec, segm.freq,fallbonus) %>%
summarise(quantity=n()) %>%
mutate(client='client') %>%
ungroup()
ggplot(lcg.bonus, aes(x=client, y=quantity, fill=fallbonus))+
theme_bw() +
scale_fill_brewer(palette = 'Set1')+
theme(panel.grid = element_blank())+
geom_bar(stat='identity', position = 'fill', alpha=0.6) +
facet_grid(segm.freq ~ segm.rec)+
ggtitle("LifeCycle Grids: Number of transactions fallbonus (proportion)")
```
```{r}
lcg.type <- customer.LCG %>%
group_by(segm.rec, segm.freq, CustomerType) %>%
summarise(quantity=n()) %>%
mutate(client='client') %>%
ungroup()
ggplot(lcg.type, aes(x=client, y=quantity, fill=CustomerType))+
theme_bw() +
scale_fill_brewer(palette = 'Set1')+
theme(panel.grid = element_blank())+
geom_bar(stat='identity', position = 'fill', alpha=0.6) +
facet_grid(segm.freq ~ segm.rec)+
ggtitle("LifeCycle Grids: Number of transactions by CustomerType")
```
#### Approach in Monetary Value for transactions
The monetary value is very interesting to improve the marketing strategy.
For a this approach we will have to consider CLV we previsouly calculated on Assignment 1 for each customer (note that we already have it in the customer.active dataset that we then merged with tx.all to get customer.LCG)
Note that the CAC is always the same (this is the assumption we made in the first assignment because we don't have enough marketing financials information), so we won't consider it here.
```{r}
lcg.clv <- customer.LCG %>%
group_by(segm.rec, segm.freq) %>%
summarise(quantity=n(),clv_tot=round(sum(CLV)),clv_avg=round(mean(CLV))) %>%
mutate(client='client') %>%
ungroup()
ggplot(lcg.clv, aes(x=client, y=clv_tot, fill=client)) +
theme_bw() +
theme(panel.grid = element_blank())+
geom_bar(stat='identity', alpha=0.6) +
geom_text(aes(y=max(clv_tot)/2, label=clv_tot), size=3) +
facet_grid(segm.freq ~ segm.rec) +
ggtitle("LifeCycle Grids - CLV Total Value")
ggplot(lcg.clv, aes(x=client, y=clv_avg, fill=client)) +
theme_bw() +
theme(panel.grid = element_blank())+
geom_bar(stat='identity', alpha=0.6) +
geom_text(aes(y=max(clv_avg)/2, label=clv_avg), size=3) +
facet_grid(segm.freq ~ segm.rec) +
ggtitle("LifeCycle Grids - CLV Average")
```
Note that the width of bars depends on the quantity (i.e: the number of customers in this sub-category).
#### Lifecycle grids for sessions
In this case, it could be also interesting to consider sessions also to suggest maketing strategies for Niantic.
So let's do lifecycle grids but for sessions this time.
```{r}
# Data construction
customer.sessions.RF.no_purchase <- customer %>%
left_join(customer.sessions, by = 'CustomerID') %>%
filter(Frequency == 0, !is.na(count)) %>%
mutate(Recency = all.end - last, Frequency = count) %>%
select (CustomerID, Recency, Frequency)
summary(customer.sessions.RF.no_purchase)
```
```{r}
#Grids creation
customer.sessions.RF.no_purchase <- customer.sessions.RF.no_purchase %>%
mutate(segm.freq=ifelse(Frequency == 2, '2',
ifelse(Frequency == 3, '3',
ifelse(Frequency == 4, '4',
ifelse(Frequency == 5, '5',
ifelse(between(Frequency,6,7),'6-7','>7')))))) %>%
mutate(segm.rec=ifelse(between(Recency,0,6), '0-6 days',
ifelse(between(Recency,7,13), '7-13 days',
ifelse(between(Recency, 14,30), '14-30 days',
ifelse(between(Recency,31,50), '31-50 days',
ifelse(between(Recency,51,85), '51-85 days', '>85 days'))))))
# spliting into discrete groups with levels to make & identify grids later on
customer.sessions.RF.no_purchase$segm.freq <- factor(customer.sessions.RF.no_purchase$segm.freq, levels=c('>7','6-7','5','4','3','2'))
customer.sessions.RF.no_purchase$segm.rec <- factor(customer.sessions.RF.no_purchase$segm.rec, levels=c('>85 days','51-85 days','31-50 days','14-30 days','7-13 days','0-6 days'))
summary(customer.sessions.RF.no_purchase)
```
```{r}
lcg.sessions <- customer.sessions.RF.no_purchase %>%
group_by(segm.rec, segm.freq) %>%
summarise(quantity=n()) %>%
mutate(client='client') %>%
ungroup()
ggplot(lcg.sessions, aes(x=client, y=quantity, fill=quantity))+
theme_bw() +
theme(panel.grid = element_blank())+
geom_bar(stat='identity', alpha=0.7) +
geom_text(aes(y=max(quantity)/2, label=quantity), size=4) +
facet_grid(segm.freq ~ segm.rec)+
ggtitle("LifeCycle Grids: Number of sessions and underlying categorisation")
```
# Assigment III, Churn analysis
In this assignment we want to understand more what are the variables that have an impact on churn to be able to predict churn better.
First we need to be clear about churn definition. The definition provided in the assignment for churn is a customer who did not perform any transaction in fall 2018.
> Remider: we working on the "active" basetable composer of all customer that played at least once during the summer, regardless wether they made transactions in summer or not
```{r}
customerID.active.fall <- sessions.fall %>%
group_by(CustomerID) %>%
distinct(CustomerID) %>%
select(CustomerID)
customer.active <- customer.active %>%
mutate(Churned = ! CustomerID %in% customerID.active.fall$CustomerID)
```
Now let's build different models and compare them to find the best one. We will keep the most parsimonious one with an AIC comparable to the full model.
First let's build the full model to have a point of reference of what's a good AIC:
```{r}
model.churn.full <- glm(Churned ~ .,
family = binomial(link='logit'),
data = customer.active)
summary(model.churn.full)
```
So we want a model with an AIC as close as possible from this one.
First, let's build our first model only based on the fall bonus:
```{r}
model.churn.1 <- glm(Churned ~ fallbonus -1,
family = binomial(link='logit'),
data = customer.active)
summary(model.churn.1)
```
The fall bonus has indeed a significant impact on churn but it not be the only variable to consider to predict churn because the AIC is quite far from the full model's AIC.
Let's add the Recency criterium as one can imagine that a player who just bought an item has lower chances to churn:
```{r}
model.churn.2 <- glm(Churned ~ fallbonus + Recency -1,
family = binomial(link='logit'),
data = customer.active)
summary(model.churn.2)
```
Now we might want to add the Experience variable as a user that already played a lot is less likely to stop due to sunk cost fallacy:
```{r}
model.churn.3 <- glm(Churned ~ fallbonus + Recency + Experience -1,
family = binomial(link='logit'),
data = customer.active)
summary(model.churn.3)
```
This last model seems quite good as we have almost the same AIC criterion as the full model, which means that this model contains almost the same amount of information as the best one in the family of the logistic regression models.
Thus, we may conclude that the fall bonus, the recency of buying and the experience of the player are the three variables that explains most of the predictable churn.
### Recommendations to reduce future churning
To avoid churning in the future, we have imagined marketing strategies to maximize the experience gain by the players and minimize their recency.
For instance, we could give an experience bonus during the 15 days after a customer purchased purchase a product. This will give an incentive for the players to keep playing and purchasing, so it will decrease recency.
To maximize the experience of the player, the idea is to give bonus of experience for special quests achievements & challenges. We do not want to decrease the value of experience, it has to be a fair reward. Thus, we will propose, for instance, an experience bonus to the players who caught 10 pokemons of type Water during five days.
```{r}
customer.active %>% group_by(CustomerType) %>% summarise(mean(Monetary),mean(Frequency),mean(CLV))
```
# Key drivers of the valuation
```{r}
customer.model <- customer.raw %>% mutate(CLV = CLV(CLV.const, model.revenue, CustomerID)) %>% left_join(customer.sessions, by='CustomerID') %>% select(-X, -CustomerID)
model.CLV <- lm(CLV ~ count + Sex + fallbonus + Income -1, data=customer.model)
summary(model.CLV)
```
```{r}
selection <- regsubsets(CLV~. -1, data=customer.model, nvmax=15, method="forward")
# we display the BIC selection
plot(selection, scale="bic")
```
```{r}
summary(customer.model)
```
```{r}
customer.model %>% mutate('Sessions7+' = count > 7) %>% group_by('Sessions7+') %>% summarise(mean(CLV))
```