forked from darwishoptly/Results-Dashboard-
/
exporter.py
795 lines (685 loc) · 32.4 KB
/
exporter.py
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
import xlsxwriter
import requests
import OptlyData
import datetime
import pickle
import os
# clean code and comment
# Graph over time stats
# Create summary page
debugging = False
GAE_Auth_Cookie = "AJKiYcG3nAApARZhVgWRWzZ58Vh2uJxJaXWIwEj8OqsV3Zwoe_iEAAvKgpouRdrbjGgjSZekMBptyaJULevIXk578cwmVwEsd7h3j9cU_GKT0SEUg8PldX6_yKgxkFHODBP-oLkkLuNmnHbq0X3M9awi_TdnVu6z3Clz5KYSVdipvmY-hlDaBCcZTcRjOo-Smnhv2V0-MhG6UEoJQ5Fk2MbIb4DUTwVcxE8AC0K7CSLivNqX08VGfg5U4VCflpdopjXF1Gc7zxwMBKErOUHgjfD1Qys5FXNCIpDhre-AWnotsX46QB4CNM3FtrlbviCDikIZZMAekD_WkqxAtyKbpDFr96MAnsXdk7VxfkAidvQcn8sOtQ7gZHllgTt3pFn8ycV53MhcPJDHqcMaHJMXQTSJfrld3uhni5xJTLkRw3P2oQue6OXA0eEJj9LxecRWUNuZTn1szXDwgS6d7CpcqgM8GdSrnN8gSlOTksqf1q-6lUq5KXBwsvHPfFTizjut9emQLSeSscqypZPPdVwzP_wQkfxCpkyE12FGaKQNhcRLwNs0q5vFLHHaz9wYX-Hl-NVxWXH53Us2sbi5kYE6-g6rhaaQurK02XdSaLZqZ_-kawE-JxgOd3fffUiEyDNGXETGzdem_XXEw3z3D5_EdZuauSk4j26xNw"
# optimizely_session = "fc7393a777c80660fb925303329039693509f167"
email = "cody@shopnastygal.com"
a_name = "NastyGal"
account_id = 183850804
project_id = 183850804
name = a_name+"_%s.xlsx" % str(datetime.date.today())
conversion_limit = 50 ## Minimum number of conversions needed in variation and original to be considered
print "************************** Running %s Dashboard **************************" % a_name
if debugging:
try:
D = pickle.load(open( "pickles/results%s" % (str(account_id) + "," + str(project_id)), "rb" ))
except Exception as e:
print e
D = OptlyData.client(GAE_Auth_Cookie, project_id, account_id, {"start": True, "email": email, "months_ago" : 12})
pickle.dump(D, open( "pickles/results%s" % (str(account_id) + "," + str(project_id)), "wb" ))
else:
D = OptlyData.client(GAE_Auth_Cookie, project_id, account_id, {"start": True, "email": email, "months_ago" : 12})
num_experiments = len(D.exp_descriptions.keys())
segment_names = {}
segment_value_maps = {} # exp: seg value map
segment_id_value_pairs = {}
def getSegmentNames():
s_names = {}
for segment in requests.get("https://www.optimizely.com/api/projects/%s/segments.json?default_segments=true&token=%s" % (str(project_id), D.account_token), cookies=D.cookies).json()["segments"]:
s_names[str(segment['id'])] = segment["name"]
return s_names
def getSegmentValueMaps():
s_maps = {}
for exp_id in D.exp_descriptions.keys():
print "segment_value_maps created: exp_id" , exp_id
s_maps[exp_id] = requests.get("https://api.optimizely.com/v1/segment_values/%s?token=%s" % (str(exp_id), D.token_hash[exp_id]), cookies=D.cookies).json()["segment_value_map"]
return s_maps
def get_segment_id_value_pairs():
s_id_value_pairs = {}
for exp_id in D.exp_descriptions.keys():
for s_id in segment_value_maps[exp_id]:
for s_val in segment_value_maps[exp_id][s_id]:
if (s_id, s_val) in s_id_value_pairs:
s_id_value_pairs[(s_id, s_val)] += 1
else:
s_id_value_pairs[(s_id, s_val)] = 1
return s_id_value_pairs
if debugging:
if os.path.isfile("pickles/segment_names%s" % (str(account_id) + "," + str(project_id))):
segments_names = pickle.load(open("pickles/segment_names%s" % (str(account_id) + "," + str(project_id)), "rb" ))
else:
segment_names = getSegmentNames()
pickle.dump(segment_names, open( "pickles/segment_names%s" % (str(account_id) + "," + str(project_id)), "wb" ))
else:
segment_names = getSegmentNames()
if debugging:
if os.path.isfile("pickles/segment_value_maps%s" % (str(account_id) + "," + str(project_id))):
segment_value_maps = pickle.load(open( "pickles/segment_value_maps%s" % (str(account_id) + "," + str(project_id)), "rb" ))
else:
segment_value_maps = getSegmentValueMaps()
pickle.dump(segment_value_maps, open( "pickles/segment_value_maps%s" % (str(account_id) + "," + str(project_id)), "wb" ))
else:
segment_value_maps = getSegmentValueMaps()
#SCHEMA ==> { s_id : {s_val : 0, count : 1 } }
# Create Segment ID, Val Pairs with frequency
segment_id_value_pairs = get_segment_id_value_pairs()
sorted_seg_pairs = sorted(segment_id_value_pairs.items(), key= lambda x: x[1], reverse=True)
## Filter out segment pairs that are not in atleast 25% of all experiments.
sorted_seg_pairs = [pair for pair in sorted_seg_pairs if float(pair[1]) / float(num_experiments) > .25]
## Segments
# Ignore Segments that are only applicable to one test
# Consider looking only at segment pairs that are in atleast 30% of experiments (Speeds things up a lot) + have over X number of visitors compared to the full experiment!
# Ignore experiments with a small number of visitors.
def removeLowExpVisitors(s, percent):
low_count = 0
for exp_id in s.exp_descriptions.keys():
total_visitors = D.visitor_count[exp_id]["total_visitors"]
if s.visitor_count[exp_id]["total_visitors"] < percent * total_visitors:
del s.exp_descriptions[exp_id]
del s.visitor_count[exp_id]
del s.goals[exp_id]
low_count += 1
print "REMOVED, " + low_count + " experiments"
S = []
def make_segment(segment_id, segment_value, m_ago):
s = OptlyData.client(GAE_Auth_Cookie, project_id, account_id, { "optimizely_session": D.optimizely_session,
"segment_id" : segment_id,
"segment_value": segment_value,
"segment_value_maps": segment_value_maps,
"token_hash" : D.token_hash,
"start" : False,
"exp_descriptions": D.exp_descriptions.copy(),
"account_token": D.account_token,
"D": D
})
s.setExperimentDescriptions(m_ago)
s.setVisitorCount()
# Removes Experiments where this segment id, value pair does not make up x% of traffic
removeLowExpVisitors(s, .05)
if len(s.exp_descriptions) == 0:
return None
s.makeExperimentsCall() ## sets variation names and original goals
## Finish building the hash
# {exp_id: "goals" { goal_id : { "name" : goal_name , variation_id: {"conversions": value, type: "type", "sum_of_squares" : SS_val_if_rev_goal, "conversion_rate" " X, "improvment" : X, "CTB" : X }}}}
s.makeRevenueCall()
# D.setGoals()
s.setResultStatistics()
s.setGoalNames()
return s
ERROR_SEGS = []
def makeSegments(m_ago=4):
Segs = []
i = 1
# pair = ('167439469' , 'unknown')
for pair in sorted_seg_pairs:
# print D.exp_descriptions
pair = pair[0]
print "PAIR: ", i, " out of" , str(len(sorted_seg_pairs)), pair[0], " : " , pair[1], "........", i
file_name = "pickles/results%s" % ",".join([str(item) for item in [account_id, project_id, pair[0], pair[1]]])
if debugging:
if os.path.isfile(file_name):
s = pickle.load(open(file_name, "rb" ))
if s:
Segs.append(s)
else:
continue
else:
try:
s = make_segment(pair[0], pair[1], m_ago)
if s:
pickle.dump(s, open(file_name, "wb" ))
S.append(s)
else:
continue
except Exception as e:
ERROR_SEGS.append((pair[0], pair[1], str(e)))
else:
try:
s = make_segment(str(pair[0]), str(pair[1]), m_ago)
Segs.append(s)
except Exception as e:
ERROR_SEGS.append((pair[0], pair[1], str(e)))
i = i + 1
return Segs
# return Segs
S = makeSegments(4)
i = 0
imp_goals_positive = []
imp_goals_negative = []
summary_num = 15
num_important = 3
common_goals = D.createGoalCount()
exp_ids = D.exp_descriptions.keys()
while i < len(common_goals):
goal_id, goal_count = common_goals[i][0], common_goals[i][1]
goal_ids = [goal_id]
positive = []
negative = []
while i < len(common_goals) - 2 and common_goals[i + 1][1] == goal_count:
i += 1
goal_ids.append(common_goals[i][0])
# print goal_ids
for g_id in goal_ids:
# print g_id
for exp_id in exp_ids:
if g_id in D.goals[exp_id]['goals']:
for var_id in D.visitor_count[exp_id]['variation'].keys():
if exp_id not in D.goals or var_id not in D.variation_names:
print "skipping for most imp: ", exp_id, g_id, var_id
continue
CTB = D.goals[exp_id]['goals'][g_id][var_id]['CTB']
imp = D.goals[exp_id]['goals'][g_id][var_id]['improvement']
baseline_id = D.exp_descriptions[exp_id]['baseline_id']
b_conversions = D.goals[exp_id]['goals'][g_id][baseline_id]['conversions']
if imp == "-" or D.goals[exp_id]['goals'][g_id][var_id]['conversions'] < conversion_limit or b_conversions < conversion_limit:
continue
elif CTB >= .95:
# print {"goal_id" : g_id, "exp_id" : exp_id, "var_id": var_id, "improvement" : imp }
positive.append({"goal_id" : g_id, "exp_id" : exp_id, "var_id": var_id, "improvement" : imp, "b_conversion_rate" : D.goals[exp_id]['goals'][g_id][baseline_id]['conversion_rate'] })
elif CTB <= .05:
negative.append({"goal_id" : g_id, "exp_id" : exp_id, "var_id": var_id, "improvement" : imp, "b_conversion_rate": D.goals[exp_id]['goals'][g_id][baseline_id]['conversion_rate'] })
imp_goals_positive += sorted(positive, key= lambda x: x["improvement"], reverse=True)[0:3]
imp_goals_negative += sorted(negative, key= lambda x: x["improvement"])[0:3]
i+=1
while len(imp_goals_positive) > summary_num:
imp_goals_positive.pop()
while len(imp_goals_negative) > summary_num:
imp_goals_negative.pop()
num_high = 0
num_low = 0
pos_undecided_goals = 0
h,l, p = [], [], []
for exp_id in D.exp_descriptions:
plus_low, plus_high, plus_undecided = True, True, True
for goal_id in D.goals[exp_id]['goals']:
for var_id in D.visitor_count[exp_id]['variation'].keys():
if exp_id not in D.goals or var_id not in D.variation_names:
print "skipping for most imp: ", exp_id, g_id, var_id
continue
imp = D.goals[exp_id]['goals'][goal_id][var_id]['improvement']
CTB = D.goals[exp_id]['goals'][goal_id][var_id]['CTB']
baseline_id = D.exp_descriptions[exp_id]['baseline_id']
b_conversions = D.goals[exp_id]['goals'][goal_id][baseline_id]['conversions']
# print imp, D.goals[exp_id]['goals'][goal_id][var_id]['conversions'] < 50, b_conversions < 50
if imp == "-" or D.goals[exp_id]['goals'][goal_id][var_id]['conversions'] < conversion_limit or b_conversions < conversion_limit:
continue
if imp > .05 and CTB > .95 and plus_high:
num_high += 1
plus_high = False
h.append(exp_id)
elif imp < -.05 and CTB < .05 and plus_low:
num_low += 1
print exp_id, goal_id, var_id, D.goals[exp_id]['goals'][goal_id][var_id]['conversions'], b_conversions, imp
plus_low = False
l.append(exp_id)
elif imp > .05 and plus_undecided and not plus_high:
plus_undecided = False
pos_undecided_goals += 1
p.append(exp_id)
def segmentWeight(s):
seg_visits = 0
total_visits = 0
for exp_id in s.exp_descriptions.keys():
seg_visits += s.visitor_count[exp_id]["total_visitors"]
total_visits += D.visitor_count[exp_id]["total_visitors"]
return float(seg_visits) / total_visits
# [s for s in S if s.segment_id == '285473938' and s.segment_value == 'true'][0].goals['383680670']['goals']['330456990']
deviant_segments = []
for s in S:
for exp_id in s.goals.keys():
for goal_id in s.goals[exp_id]["goals"].keys():
for var_id in s.goals[exp_id]["goals"][goal_id].keys():
if var_id not in D.variation_names or var_id == 'name' or goal_id not in s.goals[exp_id]["goals"] or s.goals[exp_id]["goals"][goal_id][var_id]["improvement"] == "-":
continue
else:
seg = s.goals[exp_id]["goals"][goal_id][var_id]["improvement"]
original = D.goals[exp_id]["goals"][goal_id][var_id]["improvement"]
difference = seg - original
conversions = s.goals[exp_id]["goals"][goal_id][var_id]["conversions"]
baseline_conversions = s.goals[exp_id]["goals"][goal_id][s.exp_descriptions[exp_id]['baseline_id']]["conversions"]
if abs(difference) > .1 and conversions > 250 and baseline_conversions > 250:
deviant_segments.append((s.segment_id, s.segment_value, goal_id, exp_id, var_id, float("{0:.2f}".format(difference)), segmentWeight(s) ))
print(exp_id, conversions, baseline_conversions)
deviant_segments = sorted(deviant_segments, key= lambda k: k[5], reverse=True)
count_deviant_segments = {}
for s in deviant_segments:
if (s[0], s[1]) in count_deviant_segments:
if s[3] not in count_deviant_segments[(s[0], s[1])]["exp_ids"]:
count_deviant_segments[(s[0], s[1])]["count"] += 1
count_deviant_segments[(s[0], s[1])]["exp_ids"].append(s[3])
else:
count_deviant_segments[(s[0], s[1])] = { "count" : 1, "exp_ids" : [s[3]], "weight": s[6]}
for s in count_deviant_segments:
i, v = s[0], s[1]
count_deviant_segments[(i, v)]["weighted_count"] = float(count_deviant_segments[(i, v)]["count"]) * count_deviant_segments[(i, v)]["weight"]
t = sorted(count_deviant_segments.items(), key = lambda x: x[1]["count"], reverse=True)
t2 = sorted(count_deviant_segments.items(), key = lambda x: x[1]["weight"], reverse=True)
t3 = sorted(count_deviant_segments.items(), key = lambda x: x[1]["weighted_count"], reverse=True)
# Provide a list of Experiments where a segment had a different winner that the overall
def getWinningVariation(results_object, exp_id, goal_id):
winning_variation = None
for var_id in results_object.goals[exp_id]["goals"][goal_id].keys():
if var_id not in D.variation_names or var_id == 'name' or var_id not in results_object.goals[exp_id]["goals"][goal_id] or 'improvement' not in results_object.goals[exp_id]["goals"][goal_id][var_id] or results_object.goals[exp_id]["goals"][goal_id][var_id]["improvement"] == "-":
continue
else:
# print exp_id, goal_id, var_id, winning_variation
if winning_variation == None or results_object.goals[exp_id]["goals"][goal_id][var_id]["improvement"] > results_object.goals[exp_id]["goals"][goal_id][winning_variation]["improvement"]:
winning_variation = var_id
if winning_variation and results_object.goals[exp_id]["goals"][goal_id][winning_variation]["CTB"] is not "-" and results_object.goals[exp_id]["goals"][goal_id][winning_variation]["CTB"] >= .95:
return winning_variation
else:
return None
alternate_wins = []
for exp_id in D.goals.keys():
for goal_id in D.goals[exp_id]["goals"].keys():
for segment_id in segment_value_maps[exp_id]:
segment_winner = None
overall_winner = getWinningVariation(D, exp_id, goal_id) or D.exp_descriptions[exp_id]['baseline_id']
for segment_value in segment_value_maps[exp_id][segment_id]:
s = [s for s in S if s.segment_id == segment_id and s.segment_value == segment_value]
if s == []:
print "skipping", segment_id, segment_value
continue
else:
s = s[0]
if exp_id not in s.goals or goal_id not in s.goals[exp_id]['goals']:
continue
# if goal_id not in map(lambda x: x[0], common_goals[0:5]):
# continue
print "a"
segment_value_winner = getWinningVariation(s, exp_id, goal_id)
if segment_value_winner is None:
continue
elif (segment_winner is None and segment_value_winner):
segment_winner = segment_value_winner
win_s = s
else:
val_imp = s.goals[exp_id]["goals"][goal_id][segment_value_winner]["improvement"]
win_imp = s.goals[exp_id]["goals"][goal_id][segment_winner]["improvement"]
if val_imp > win_imp or win_imp == "-":
segment_winner = segment_value_winner
win_s = s
print "here: ", segment_id, segment_value, segment_winner, overall_winner
if segment_winner is None or segment_winner == overall_winner:
continue
elif win_s.goals[exp_id]["goals"][goal_id][segment_winner]["improvement"] > D.goals[exp_id]["goals"][goal_id][overall_winner]["improvement"]:
lost_improvement = (win_s.goals[exp_id]["goals"][goal_id][segment_winner]["conversion_rate"] - win_s.goals[exp_id]["goals"][goal_id][overall_winner]["conversion_rate"]) * win_s.visitor_count[exp_id]['total_visitors'] / float(D.visitor_count[exp_id]['total_visitors']) / D.goals[exp_id]["goals"][goal_id][D.exp_descriptions[exp_id]['baseline_id']]["conversion_rate"]
lost_improvement = lost_improvement / 100 if "Revenue" in D.goal_names == 'revenue_goal' else lost_improvement
segment_improvement = win_s.goals[exp_id]["goals"][goal_id][segment_winner]["improvement"]
overall_improvement = win_s.goals[exp_id]["goals"][goal_id][overall_winner]["improvement"]
original_conversion_rate = D.goals[exp_id]["goals"][goal_id][D.exp_descriptions[exp_id]['baseline_id']]["conversion_rate"]
difference_in_improvement = segment_improvement - overall_improvement
alternate_wins.append((exp_id, D.goal_names[goal_id], segment_names[segment_id] if segment_id in segment_names else segment_id, segment_value, D.variation_names[overall_winner], D.variation_names[segment_winner], original_conversion_rate, overall_improvement, segment_improvement, difference_in_improvement, lost_improvement))
# record max improvement variation
alternate_wins = sorted(alternate_wins, key = lambda x: x[10], reverse=True)
def writeRange(worksheet, row, start_col, values, update=False, formats = []):
global col
i = 0
for v in values:
if len(formats) > 0:
f = formats[i]
i+=1
else:
f = workbook.add_format({});
worksheet.write(row, start_col, v, f)
start_col += 1
if update:
col = start_col
return
def addSpaceColumn(worksheet, column):
worksheet.set_column(column, column, 2)
global col
col += 1
return
def setGoalHeaders(worksheet, row, column, goals):
global col
col = column
for goal in goal_count:
goal_id = goal[0]
if goal_id in goals:
# merge the length of number of goal fields - 1
addSpaceColumn(worksheet, col)
f = combinedFormat(["center", "bottom", "font"])
worksheet.merge_range(row, col, row, col + 4 - 1, goal_names[goal_id], workbook.add_format(f))
col+=4
return
min_visits = 1000
goals_with_min_visits = sum([1 for exp in D.visitor_count if D.visitor_count[exp]['total_visitors'] > 1000])
avg_goals_exp = float(sum([len(D.goals[exp_id]['goals']) for exp_id in D.exp_descriptions if D.visitor_count[exp_id]['total_visitors'] > 1000])) / goals_with_min_visits
workbook = xlsxwriter.Workbook("output/" + name);
summary_sheet = workbook.add_worksheet("Summary")
segment_sheet = workbook.add_worksheet("Segments")
alt_segment_sheet = workbook.add_worksheet("Missed Segments")
worksheet = workbook.add_worksheet("Experiments Report - Detailed")
dump = workbook.add_worksheet("Dump")
formats = {
"percent" : {'num_format': '0.0%'},
"decimal" : {'num_format': '0.00'},
'fill_green': {'bg_color': '#E7EFD8'},
"fill_red" : {"bg_color" : '#F2DCDB'},
"center": {'align': 'center'},
"bottom": {'bottom':1},
"font": {"font_name": "Gill Sans Light"},
"font_bold": {"font_name": "Gill Sans"},
"wrap": {"text_wrap": "True"},
"fill_grey": {'bg_color': '#D9D9D9'},
"strong_bold": {"bold": "true"},
"bottom_heavy": {"bottom": 5},
"top" : {"top": 1},
"v_middle" : {"valign": "vcenter"},
"": {"font_name": "Gill Sans Light"}
}
def combinedFormat(list_formats): # ["percent", "fill_green"]
combined_format = {}
for f in list_formats: combined_format.update(formats[f])
return combined_format
def getGoalFormats(goal_name, CTB):
if CTB > .95 and CTB != "-":
percentage = workbook.add_format(combinedFormat(["percent", "fill_green", "font"]))
decimal = workbook.add_format(combinedFormat(["decimal", "fill_green", "font"]))
elif CTB < .05 and CTB != "-":
percentage = workbook.add_format(combinedFormat(["percent", "fill_red", "font"]))
decimal = workbook.add_format(combinedFormat(["decimal", "fill_red", "font"]))
else:
percentage = workbook.add_format(combinedFormat(["percent", "font"]))
decimal = workbook.add_format(combinedFormat(["decimal", "font"]))
if goal_name == "Total Revenue":
return [decimal, decimal, percentage, percentage]
else:
return [decimal, percentage, percentage, percentage]
row, col = 1, 1
segment_sheet.set_column(0, 0, 1)
segment_sheet.set_column(1, 11, 18)
segment_sheet.set_column(4, 6, 25)
segment_sheet.set_column(7, 11, 13)
segment_sheet.hide_gridlines(2)
segment_sheet.set_zoom(90)
empty = ["" for i in range(10)]
f = workbook.add_format(combinedFormat(["font_bold", "strong_bold", "bottom_heavy"]))
f_mats = [f for i in range(11)]
writeRange(segment_sheet, row, col, [a_name.upper() + " SEGMENT DISCOVERY"] + empty, False, f_mats)
f = workbook.add_format(combinedFormat(["font_bold", "bottom"]))
f_mats = [f for i in range(12)]
headers = ["Experiment ID",
"Segment Name",
"Segment Value",
"Experiment Name",
"Variation Name",
"Goal Name",
"Exp Visitors",
"Segment Visitors",
"Org. Improvement",
"+/- Improvement",
"Segment Weight"]
row += 2
writeRange(segment_sheet, row, col, headers, False, f_mats)
row+=1
for d in deviant_segments:
exp_id, var_id, goal_id = d[3], d[4], d[2]
segment = [s for s in S if s.segment_id == d[0] and s.segment_value == d[1]][0]
values = [
exp_id,
segment_names[d[0]] if d[0] in segment_names else d[0] ,
d[1],
D.exp_descriptions[d[3]]['description'],
D.variation_names[var_id],
D.goal_names[goal_id],
D.visitor_count[exp_id]["variation"][var_id],
segment.visitor_count[exp_id]["variation"][var_id],
D.goals[exp_id]["goals"][goal_id][var_id]["improvement"],
d[5],
count_deviant_segments[(segment.segment_id, segment.segment_value)]["weighted_count"]
]
imp = "fill_green" if goal_id in imp_goals_positive else "" # short for importance
tex = workbook.add_format(combinedFormat(["font", "v_middle", imp]))
tex_c = workbook.add_format(combinedFormat(["font", "v_middle", "center", imp]))
per = workbook.add_format(combinedFormat(["font", "v_middle", "percent", "center", imp]))
dec = workbook.add_format(combinedFormat(["font", "v_middle", "decimal", "center", imp]))
f_mats = [tex,tex, tex, tex, tex, tex, tex_c, dec, per, dec, dec ]
writeRange(segment_sheet, row, col, values, False, f_mats)
row += 1
segment_sheet.autofilter( 3, 1 , len(deviant_segments) + 3, 11)
# ALT SEGMENT SHEET
row, col = 1, 1
alt_segment_sheet.set_column(0, 0, 1)
alt_segment_sheet.set_column(1, 11, 18)
alt_segment_sheet.set_column(4, 6, 25)
alt_segment_sheet.set_column(7, 11, 13)
alt_segment_sheet.hide_gridlines(2)
alt_segment_sheet.set_zoom(90)
empty = ["" for i in range(10)]
f = workbook.add_format(combinedFormat(["font_bold", "strong_bold", "bottom_heavy"]))
f_mats = [f for i in range(11)]
writeRange(alt_segment_sheet, row, col, [a_name.upper() + " SEGMENT DISCOVERY"] + empty, False, f_mats)
f = workbook.add_format(combinedFormat(["font_bold", "bottom"]))
f_mats = [f for i in range(12)]
headers = ["Experiment ID",
"Goal Name",
"Segment Name",
"Segment Value",
"Overall Variation Winner",
"Segment Variation Winner",
"Original Conversion Rate",
"Overall Improvement",
"Segment Improvement",
"+/- Improvement",
"Lost Improvement"]
row += 2
writeRange(alt_segment_sheet, row, col, headers, False, f_mats)
row+=1
for a in alternate_wins:
values = a
imp = "fill_green" if goal_id in imp_goals_positive else "" # short for importance
tex = workbook.add_format(combinedFormat(["font", "v_middle", imp]))
tex_c = workbook.add_format(combinedFormat(["font", "v_middle", "center", imp]))
per = workbook.add_format(combinedFormat(["font", "v_middle", "percent", "center", imp]))
dec = workbook.add_format(combinedFormat(["font", "v_middle", "decimal", "center", imp]))
f_mats = [tex,tex, tex, tex, tex, tex, per, per, per, per, per]
writeRange(alt_segment_sheet, row, col, values, False, f_mats)
row += 1
alt_segment_sheet.autofilter( 3, 1 , len(deviant_segments) + 3, 11)
# alt segment sheet end
row, col = 1, 1
summary_sheet.set_column(0, 0, 1)
summary_sheet.set_column(1, 5, 18)
summary_sheet.set_column(6, 6, 1)
summary_sheet.set_column(7, 11, 18)
summary_sheet.set_column(12, 12, 1)
summary_sheet.set_column(13, 17, 18)
summary_sheet.hide_gridlines(2)
summary_sheet.set_zoom(90)
#Main Header and High Level Stats
empty = ["" for i in range(13)]
f = workbook.add_format(combinedFormat(["font_bold", "strong_bold", "bottom_heavy"]))
f_mats = [f for i in range(14)]
writeRange(summary_sheet, row, col, [a_name.upper() + " EXECUTIVE DASHBOARD"] + empty, False, f_mats)
f = workbook.add_format(combinedFormat(["font"]))
num = workbook.add_format(combinedFormat(["decimal", "font"]))
row, col = 2, 1
writeRange(summary_sheet, row, col, ["Date Run", "", "", str(datetime.date.today())], False, [f,f,f,f])
row, col = row + 1, 1
writeRange(summary_sheet, row, col, ["Criteria", "", "", "Modified in Last 60 days"], False, [f,f,f,f])
row, col = row + 2, 1
f = workbook.add_format(combinedFormat(["font"]))
num = workbook.add_format(combinedFormat(["decimal", "font"]))
stats = [("# Experiments Run w/ >%s visitors" % min_visits , goals_with_min_visits), ("Avg. Goals / Experiment", avg_goals_exp), ("# Experiments with Stat. Significant Winner", num_high), ("# Experiments with Stat. Significant Loser", num_low), ("# Experiments with no Winner but CVR Improvement > 5%: ", pos_undecided_goals) ]
for s in stats:
writeRange(summary_sheet, row, col, [s[0], "", "", s[1]], False, [f,f,f,num])
row, col = row + 1, 1
row += 1
#Set Headers for Stats
num_head = 4
summary_sheet.merge_range(row, col, row, 11, "EXPERIMENT SUMMARY STATISTICS", workbook.add_format(combinedFormat(["font_bold", "bottom", "top", "center"])))
col += 11 + 1
summary_sheet.merge_range(row, col, row, col+4, "SEGMENT SUMMARY STATISTICS", workbook.add_format(combinedFormat(["font_bold", "bottom", "top", "center"])))
row, col = row + 1, 1
summary_sheet.merge_range(row, col, row, col+4, "High Improvement Variations for Frequent Goals:", workbook.add_format(combinedFormat(["font_bold", "fill_green", "center"])))
col += 6
summary_sheet.merge_range(row, col, row, col+4, "Low Improvement Variations for Frequent Goals:", workbook.add_format(combinedFormat(["font_bold", "fill_red", "center"])))
col += 6
summary_sheet.merge_range(row, col, row, col+4, "Segment Value Pairs w/ >10% deviation :", workbook.add_format(combinedFormat(["font_bold", "fill_grey", "center"])))
row, col = row + 1, 1
f = workbook.add_format(combinedFormat(["font", "bottom", "center"]))
for i in range(2):
writeRange(summary_sheet, row, col, ["Experiment Name", " Variation", "Base CNV Rate","Improvement" , "Goal Name"], False, [f,f,f,f,f])
col+=6
writeRange(summary_sheet, row, col, ["Segment Name", "Segment Value", "# Expmts with deviation", "Avg % Total Visitors" , "Score"], False, [f,f,f,f,f])
row, col= row + 1, 1
data_start_row = row
for important_set in [imp_goals_positive, imp_goals_negative]:
for goal in important_set:
f = workbook.add_format(combinedFormat(["font", "wrap", "v_middle"]))
percent = workbook.add_format(combinedFormat(["percent", "font", "center", "v_middle"]))
n_format = workbook.add_format(combinedFormat(["decimal", "font", "center", "v_middle"])) if "Revenue" in D.goal_names[goal["goal_id"]] else percent
values = [D.exp_descriptions[goal["exp_id"]]["description"], D.variation_names[goal["var_id"]], goal["b_conversion_rate"], goal["improvement"], D.goal_names[goal["goal_id"]]]
writeRange(summary_sheet, row, col, values, False, [f, f, n_format, percent, f])
row += 1
row, col = data_start_row, col + 6
# important_segments = sorted(count_deviant_segments.items(), key = lambda x: x[1], reverse=True)
for s in t3[0:15]: # TODO change name
f = workbook.add_format(combinedFormat(["font", "wrap", "v_middle"]))
n = workbook.add_format(combinedFormat(["font", "wrap", "center", "v_middle"]))
p = workbook.add_format(combinedFormat(["font", "wrap", "center", "v_middle", "percent"]))
d = workbook.add_format(combinedFormat(["font", "wrap", "center", "v_middle", "decimal"]))
values = [segment_names[s[0][0]], s[0][1], s[1]["count"], s[1]["weight"], s[1]["weighted_count"] ]
writeRange(summary_sheet, row, col, values, False, [f, f, n, d, d])
row += 1
# percentage = workbook.add_format({'num_format': '0.0%'})
# two_digit_decimal = workbook.add_format({'num_format': '0.00'})
row, col = 0 , 0
goal_count = D.createGoalCount()
D.setGoalNames()
goal_names = D.goal_names
## Set up Headers
headers = ["Variation Name", "Visitors"]
f = workbook.add_format(combinedFormat(["font_bold", "fill_grey"]))
writeRange(worksheet, row, col, headers, True, [f,f])
addSpaceColumn(worksheet, col)
worksheet.set_column(0, 0, 30)
worksheet.set_column(1, 1, 12)
## Set up Goal Headers
fields = ["Conversions", "CNV Rate", "Improvement", "CTB"]
for i in range(0, D.maxGoals()):
col_old = col
center = workbook.add_format(combinedFormat(["center", "font_bold", "fill_grey"]))
writeRange(worksheet, row, col, fields, True, [center, center, center, center])
worksheet.set_column(col_old, col, 12)
addSpaceColumn(worksheet, col)
row += 2
col = 0
expIDSortedbyVisitorCount = sorted(D.visitor_count, key=lambda x: D.visitor_count[x]['total_visitors'], reverse=True)
for exp_id in expIDSortedbyVisitorCount:
# exp_id = '523462609'
print "ADDING: Experiment ID: ", exp_id
try:
D.visitor_count[exp_id]
except:
print ("ERROR:", exp_id, var_id)
continue
font = workbook.add_format(formats["font"])
font_bold = workbook.add_format(combinedFormat(["font_bold", "wrap"]))
worksheet.write(row, 0, D.exp_descriptions[exp_id]['description'] + " (" + str(exp_id) + ")", font_bold)
col+=2
goal_ids = D.goals[exp_id]["goals"].keys()
setGoalHeaders(worksheet, row, col, goal_ids)
row += 1
# sort variations with baseline first
var_ids = D.visitor_count[exp_id]['variation'].keys()
baseline_variation_id = filter(lambda var_id: var_id == D.exp_descriptions[exp_id]["baseline_id"] , var_ids)
baseline_variation_id = baseline_variation_id[0] if len(baseline_variation_id) > 0 else var_ids[0]
var_ids.remove(baseline_variation_id)
var_ids.insert(0, baseline_variation_id)
# Add Variation Names
for var_id in var_ids:
col = 0
if var_id not in D.variation_names:
print "..........VARIATION DELETED........ ", var_id
continue
writeRange(worksheet, row, col, [D.variation_names[var_id], D.visitor_count[exp_id]['variation'][var_id]], True, [font, font])
for goal in goal_count:
goal_id = goal[0]
if goal_id in goal_ids:
addSpaceColumn(worksheet, col)
g = D.goals[exp_id]["goals"][goal_id][var_id]
(conversions, conversion_rate, improvement, CTB) = g["conversions"], g["conversion_rate"], g["improvement"], g["CTB"]
goal_formats = getGoalFormats(D.goals[exp_id]["goals"][goal_id]["name"], CTB)
writeRange(worksheet, row, col, [conversions, conversion_rate, improvement, CTB], True, goal_formats)
row += 1
row += 1
col = 0
top_row = workbook.add_format(combinedFormat(["font_bold", "fill_grey"]))
worksheet.set_row(0, None, top_row)
worksheet.set_zoom(75)
worksheet.freeze_panes(1,2)
worksheet.hide_gridlines(2)
row, col = 0, 0
f = workbook.add_format(combinedFormat(["font_bold", "fill_grey", "center"]))
headers = ["Experiment ID",
"Variation ID",
"Experiment Name",
"Variation Name",
"Visitors",
"Conversions",
"Conversion Rate",
"Improvement",
"CTB",
"Segment Name",
"Segment Value"]
f_mats = [f for h in headers]
writeRange(dump, row, col, headers, False, f_mats)
row += 1
arr = [D] + S
skipped = []
for results_object in arr:
print results_object.segment_id, results_object.segment_value
for exp_id in results_object.exp_descriptions.keys():
for goal_id in results_object.goals[exp_id]['goals']:
for var_id in results_object.visitor_count[exp_id]['variation'].keys():
if exp_id not in results_object.goals or var_id not in results_object.variation_names:
skipped.append((exp_id, g_id, var_id))
continue
if results_object.segment_id == '':
seg_name = "Original"
elif results_object.segment_id not in segment_names:
seg_name = "Deleted"
else:
seg_name = segment_names[results_object.segment_id]
r = [exp_id,
var_id,
results_object.exp_descriptions[exp_id]["description"],
results_object.variation_names[var_id],
results_object.visitor_count[exp_id]['variation'][var_id],
results_object.goals[exp_id]['goals'][goal_id][var_id]["conversions"],
results_object.goals[exp_id]['goals'][goal_id][var_id]["conversion_rate"],
results_object.goals[exp_id]['goals'][goal_id][var_id]["improvement"],
results_object.goals[exp_id]['goals'][goal_id][var_id]["CTB"],
seg_name,
results_object.segment_value]
text = workbook.add_format(combinedFormat(["font"]))
num = workbook.add_format(combinedFormat(["decimal", "font"]))
percent = workbook.add_format(combinedFormat(["percent", "font"]))
f_mats = [num,
num,
text,
text,
num,
num,
percent,
percent,
percent,
text,
text]
writeRange(dump, row, col, r, False, f_mats)
row+=1
print "Skipped Experiment IDs for Dump ( e_id, g_id, v_id) ", skipped
dump.hide_gridlines(2)
dump.set_column(0, len(f_mats)-1, 14)
dump.autofilter(0, 1 , row, len(f_mats)-1)
workbook.close()