-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathds_app_2.py
More file actions
1522 lines (1284 loc) · 57.6 KB
/
Copy pathds_app_2.py
File metadata and controls
1522 lines (1284 loc) · 57.6 KB
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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#basic packages
import streamlit as st
import math
import pandas as pd
import numpy as np
from numpy.ma.core import log
from datetime import datetime, timedelta
#changepoint detection library
import ruptures as rpt
import chart_studio.plotly as py
from plotly import graph_objs as go
from google.oauth2 import service_account
from google.cloud import bigquery
from st_aggrid import AgGrid, GridOptionsBuilder, GridUpdateMode, DataReturnMode, JsCode
#Page Configuration
st.set_page_config(
page_title='Snapchat Dynamic Scheduling',
page_icon = 'https://w7.pngwing.com/pngs/481/484/png-transparent-snapchat-logo-snap-inc-social-media-computer-icons-snapchat-text-logo-smiley.png',
layout='wide'
)
# header of the page
html_temp = """
<div style ="background-color:#00008B; border: 8px darkblue; padding: 18px; text-align: right">
<!<img src="https://www.rewindandcapture.com/wp-content/uploads/2014/04/snapchat-logo.png" width="100"/>>
<h1 style ="color:lightgrey;text-align:center;">Snapchat Dynamic Scheduling</h1>
</div>
"""
st.markdown(html_temp,unsafe_allow_html=True)
#Minor template configurations
css_background = """
<style>
h1 {color: darkblue;}
p {color: darkred;}
</style>
"""
st.markdown(css_background,unsafe_allow_html=True)
# Create API client.
credentials = service_account.Credentials.from_service_account_info(st.secrets["gcp_service_account"])
#Ignore warning
st.set_option('deprecation.showPyplotGlobalUse', False)
#Functions
#Functions powering the app
#Round to multiple
def round_to_multiple(number, multiple):
return multiple * math.ceil(number / multiple)
#Total view forecast
def forecast_totalview(choose_episode, choose_hours):
this_episode_df = df[df['story_id'].isin([choose_episode])].drop_duplicates(subset='interval_time')
this_episode_df['actual'] = this_episode_df['actual'].astype('float').fillna(np.nan)
#New variable for df for further data manipulation/cleaning
data = this_episode_df
#Historical df
historical = data[data['forecast_type'].isin(['history'])]
#Df conditions, daily predictions & momentum
#Episodes less than 10 rows of data
if len(historical) < 10 or len(data.loc[data['forecast_type'] == 'future']) <=0:
prediction = historical
total_prediction =None
daily_prediction =None
momentum =None
#Episodes fit for forecasting
else:
prediction = data.loc[data['true_hour'] <= choose_hours]
#Total Forecast
total_prediction = round(prediction.tail(1)['topsnap_views'].values[0])
#Daily Fcst
start_end = prediction.tail(25)
start = start_end.head(1)['topsnap_views'].values[0]
end = start_end.tail(1)['topsnap_views'].values[0]
#Momentum
momentum_df = prediction.tail(49)
if choose_hours <= 24:
daily_prediction = total_prediction
momentum=None
else:
daily_prediction = round(end-start)
if choose_hours == 48:
previous_day = float(momentum_df.loc[momentum_df['true_hour'] == choose_hours-24, ['topsnap_views']].head(1).values[0])
else:
m_start = momentum_df.head(1)['topsnap_views'].values[0]
m_end = float(momentum_df.loc[momentum_df['true_hour'] == choose_hours-24, ['topsnap_views']].head(1).values[0])
previous_day = round(m_end-m_start)
try:
momentum = (daily_prediction-previous_day)/previous_day
except ZeroDivisionError:
momentum = 0
if momentum > 0:
momentum = f'+{round(momentum*100, 2)}%'
else:
momentum = f'{round(momentum*100, 2)}%'
#Changepoint Detection
if this_episode_df['true_hour'].values[-1] < 24:
first_y = np.nan
first_x = np.nan
second_y = np.nan
second_x = np.nan
first_dy = np.nan
first_dx = np.nan
second_dy = np.nan
second_dx = np.nan
else:
#Add & Merge changepoint analysis & metrics
current = changepoint_df(choose_episode)
merged = prediction.merge(current[['true_hour','direction']], on='true_hour', how='left')
#Conditional logic for Change Point Detection (most recent 2 hot and cold change points)
up = merged.loc[merged['direction'] == 'upward change', ['interval_time', 'topsnap_views']]
down = merged.loc[merged['direction'] == 'downward change', ['interval_time', 'topsnap_views']]
#Up-tick
if len(up) == 0:
first_y = np.nan
first_x = np.nan
second_y = np.nan
second_x = np.nan
elif len(up) == 1:
first_y= up['topsnap_views'].values[-1]
first_x = pd.to_datetime(up['interval_time'].values[-1])
second_y = np.nan
second_x = np.nan
elif len(up) >= 2:
first_y= up['topsnap_views'].values[-1]
first_x = pd.to_datetime(up['interval_time'].values[-1])
second_y = up['topsnap_views'].values[-2]
second_x = pd.to_datetime(up['interval_time'].values[-2])
#Down-tick
if len(down) == 0:
first_dy = np.nan
first_dx = np.nan
second_dy = np.nan
second_dx = np.nan
elif len(down) == 1:
first_dy= down['topsnap_views'].values[-1]
first_dx = pd.to_datetime(down['interval_time'].values[-1])
second_dy = np.nan
second_dx = np.nan
elif len(down) >= 2:
first_dy= down['topsnap_views'].values[-1]
first_dx = pd.to_datetime(down['interval_time'].values[-1])
second_dy = down['topsnap_views'].values[-2]
second_dx = pd.to_datetime(down['interval_time'].values[-2])
yhat = go.Scatter(x = prediction['interval_time'],
y = prediction['future_fcst'],
#y = prediction['yhat24'],
mode = 'lines',
marker = {'color': 'blue'},
line = {'width': 4},
name = 'Future Forecast',
)
yhat_2 = go.Scatter(x = prediction['interval_time'],
y = prediction['historical_fcst'],
#y = prediction['yhat24'],
mode = 'lines',
marker = {'color': 'darkslateblue'},
line = {'width': 4},
name = 'Historical Forecast',
)
yhat_lower = go.Scatter(x = prediction['interval_time'],
y = prediction['confidence_interval_lower_bound'],
marker = {'color': 'powderblue'},
showlegend = False,
#hoverinfo = 'none',
)
yhat_upper = go.Scatter(x = prediction['interval_time'],
y = prediction['confidence_interval_upper_bound'],
fill='tonexty',
fillcolor = 'powderblue',
name = 'Confidence (80%)',
#hoverinfo = 'yhat_upper',
mode = 'none'
)
actual = go.Scatter(x = prediction['interval_time'],
y = prediction['actual'],
mode = 'markers',
marker = {'color': '#fffaef','size': 10,'line': {'color': '#000000',
'width': 0.8}},
name = 'Actual'
)
layout = go.Layout(yaxis = {'title': 'Topsnap Views',},
hovermode = 'x',
xaxis = {'title': 'Hours/Days'},
margin = {'t': 20,'b': 50,'l': 60,'r': 10},
legend = {'bgcolor': 'rgba(0,0,0,0)'})
layout_data = [yhat_lower, yhat_upper, yhat, yhat_2, actual]
# Get Episode Name
episode_name = this_episode_df.head(1)['title'].values[0]
#Get Channel Name
channel_df = benchmarks[benchmarks['name'].isin(this_episode_df.name)]
channel_name = channel_df.head(1)['name'].values[0]
#Banger Benchmark
banger = channel_df.loc[channel_df['true_hour'] == 168, ['topsnap_views_total']]
if len(banger) == 0:
banger_bench = 0
else:
banger_bench = banger['topsnap_views_total'].mean()*2
#Get current hour benchmark
def get_benchmarks(choose):
b_channel = channel_df.loc[channel_df['true_hour'] == choose, ['topsnap_views_total']]
if len(b_channel)<= 0:
channel_bench = 0
else:
channel_bench = b_channel['topsnap_views_total'].mean()
return channel_bench
if choose_hours <= 24:
channel_bench = get_benchmarks(24)
day = 'Day 1'
elif ((choose_hours > 24) and (choose_hours <= 48)):
channel_bench = get_benchmarks(48)
day = 'Day 2'
elif ((choose_hours > 48) and (choose_hours <= 72)):
channel_bench = get_benchmarks(72)
day = 'Day 3'
elif ((choose_hours > 72) and (choose_hours <= 96)):
channel_bench = get_benchmarks(96)
day = 'Day 4'
elif ((choose_hours > 96) and (choose_hours <= 120)):
channel_bench = get_benchmarks(120)
day = 'Day 5'
elif ((choose_hours > 120) and (choose_hours <= 144)):
channel_bench = get_benchmarks(144)
day = 'Day 6'
elif ((choose_hours > 144) and (choose_hours <= 168)):
channel_bench = get_benchmarks(168)
day = 'Day 7'
elif ((choose_hours > 168) and (choose_hours <= 192)):
channel_bench = get_benchmarks(192)
day = 'Day 8'
elif ((choose_hours > 192) and (choose_hours <= 216)):
channel_bench = get_benchmarks(216)
day = 'Day 9'
elif ((choose_hours > 216) and (choose_hours <= 240)):
channel_bench = get_benchmarks(240)
day = 'Day 10'
elif ((choose_hours > 240) and (choose_hours <= 264)):
channel_bench = get_benchmarks(264)
day = 'Day 11'
elif ((choose_hours > 264) and (choose_hours <= 288)):
channel_bench = get_benchmarks(288)
day = 'Day 12'
elif ((choose_hours > 288) and (choose_hours <= 312)):
channel_bench = get_benchmarks(312)
day = 'Day 13'
elif ((choose_hours > 312) and (choose_hours <= 336)):
channel_bench = get_benchmarks(336)
day = 'Day 14'
#Enough hours to forecast
if choose_hours < this_episode_df.tail(1)['true_hour'].values[0] and len(historical) >= 10:
if channel_bench == 0:
trending = None
elif channel_bench > 0:
trending = round(((total_prediction-channel_bench)/channel_bench)*100)
if trending > 0:
trending = f'+{round(trending):,}% above'
else:
trending = f'{round(trending):,}% below'
else:
trending = None
total_prediction = f'{round(total_prediction):,}'
daily_prediction = f'{round(daily_prediction):,}'
else:
total_prediction = 'Not enough data to forecast OR prediction is past 72 hours'
daily_prediction = None
momentum = None
trending = None
day = ''
#Store line graph layout
fig = go.Figure(data= layout_data, layout=layout)
#Update layout with metrics and benchmarks
fig.update_layout(title={'text': (f'<b>{episode_name} - {channel_name}</b><br><br><sup>Total Topsnap Prediction = <b>{total_prediction}</b> ({trending} Avg)<br>{day} Topsnap Prediction = <b>{daily_prediction}</b><br>Daily Momentum % = <b>{momentum}</b></sup>'),
'y':0.91,
'x':0.075,
'font_size':22,
})
fig.update_traces(hovertext=prediction.true_hour)
fig.add_hline(y=channel_bench, line_dash="dot", line_color='purple',
annotation_text=(f"Channel Avg at {choose_hours}hrs: <b>{round(channel_bench):,}</b>"),
annotation_position="bottom right",
annotation_font_size=14,
annotation_font_color="purple"
)
fig.add_hline(y=banger_bench, line_dash="dot", line_color='gold',
annotation_text="168hr Banger Benchmark",
annotation_position="bottom right",
annotation_font_size=14,
annotation_font_color="black"
)
fig.add_trace(
go.Scatter(
mode='markers+text',
x=[first_x, second_x],
y=[first_y, second_y],
name='improving trend',
text='🔥',
textposition='middle center',
marker=dict(
color='#FF4500',
size=5)
)
)
fig.add_trace(
go.Scatter(
mode='markers+text',
x=[first_dx, second_dx],
y=[first_dy, second_dy],
name='slowing trend',
text='🥶',
textposition='middle center',
marker=dict(
color='#1E90FF',
size=5)
)
)
fig.update_traces(textfont_size=22)
return fig
#Momentum chart function
def momentum_chart(choose_episode):
this_episode_df = df[df['story_id'].isin([choose_episode])].drop_duplicates(subset='interval_time')
this_episode_df['actual'] = this_episode_df['actual'].astype('float').fillna(np.nan)
tt = pd.Timestamp.today().floor('H')
np_today = tt.to_numpy()
today = np_today - np.timedelta64(4, 'h')
last_hour = int(this_episode_df.loc[this_episode_df['interval_time'] == today, ['true_hour']].values[0])
fcst_hour = round_to_multiple(last_hour, 24)
daily_df = this_episode_df.loc[this_episode_df['true_hour'].isin([24, 48, 72, 96, 120, 144, 168, 192, 216, 240, 264, 288, 312, 336]), ['name', 'title', 'interval_time', 'true_hour', 'topsnap_views']].reset_index().drop(columns=['index'])
daily_df = daily_df.loc[daily_df['true_hour'] <= fcst_hour]
channel_alleps = benchmarks[benchmarks['name'].isin(this_episode_df.name)]
channel_avg_list = []
day_list = []
for index, row in daily_df.iterrows():
channel_avg = round(int(channel_alleps.loc[channel_alleps['true_hour']<= 168, ['topsnap_daily_diff']].mean()))
if daily_df['true_hour'].values[index] == 24:
day = 'Day 1'
elif daily_df['true_hour'].values[index] == 48:
day = 'Day 2'
elif daily_df['true_hour'].values[index] == 72:
day = 'Day 3'
elif daily_df['true_hour'].values[index] == 96:
day = 'Day 4'
elif daily_df['true_hour'].values[index] == 120:
day = 'Day 5'
elif daily_df['true_hour'].values[index] == 144:
day = 'Day 6'
elif daily_df['true_hour'].values[index] == 168:
day = 'Day 7'
elif daily_df['true_hour'].values[index] == 192:
day = 'Day 8'
elif daily_df['true_hour'].values[index] == 216:
day = 'Day 9'
elif daily_df['true_hour'].values[index] == 240:
day = 'Day 10'
elif daily_df['true_hour'].values[index] == 264:
day = 'Day 11'
elif daily_df['true_hour'].values[index] == 288:
day = 'Day 12'
elif daily_df['true_hour'].values[index] == 312:
day = 'Day 13'
elif daily_df['true_hour'].values[index] == 336:
day = 'Day 14'
channel_avg_list.append(channel_avg)
day_list.append(day)
join_df = pd.DataFrame({'Day': day_list,
'Channel Daily Episode Avg': channel_avg_list
})
rough_df = daily_df.join(join_df)
rough_df['topsnap_lag'] = rough_df['topsnap_views'].shift(1).fillna(0)
rough_df['daily_performance'] = rough_df['topsnap_views'] - rough_df['topsnap_lag']
rough_df['prior_day'] = rough_df['daily_performance'].shift(1)
rough_df['momentum'] = round((rough_df['daily_performance'] - rough_df['prior_day']) / (rough_df['prior_day']), 2)
momentum_df = pd.DataFrame({'Channel': rough_df['name'],
'Episode': rough_df['title'],
'Interval Time': rough_df['interval_time'],
'Day': rough_df['Day'],
'Hour': rough_df['true_hour'],
'Daily Performance': rough_df['daily_performance'],
'Momentum %': rough_df['momentum'],
'Daily Channel Avg': rough_df['Channel Daily Episode Avg']
})
#Formatting
momentum_df['Momentum %'] = momentum_df['Momentum %'].map("{:,.2%}".format).replace('nan%', np.nan)
momentum_df['Daily Performance'] = momentum_df['Daily Performance'].map("{:,.0f}".format)
momentum_df['Daily Channel Avg'] = momentum_df['Daily Channel Avg'].map("{:,.0f}".format)
return momentum_df
#Changepoint function
def changepoint_df(choose_episode):
#Identify episode
story_id = choose_episode
channel_df = df[df.story_id.isin([story_id])]
history = channel_df.loc[channel_df['forecast_type'] == 'history']
#Create differences df
differences = channel_df.loc[:, ['story_id', 'name','title', 'interval_time', 'topsnap_views', 'forecast_type', 'true_hour']]
differences['lag'] = differences['topsnap_views'].shift(+1).fillna(0)
differences['topsnap_diff'] = differences['topsnap_views'] - differences['lag']
#Today
tt = pd.Timestamp.today().floor('H')
np_today = tt.to_numpy()
today = np_today - np.timedelta64(4, 'h')
last_hour = int(differences.loc[differences['interval_time'] == today, ['true_hour']].values[0])
window = round_to_multiple(last_hour, 24)
current = differences.loc[differences['true_hour'] <= window, ['interval_time', 'topsnap_views', 'topsnap_diff', 'true_hour']]
#PELT Change point analysis
ts = np.array(current['topsnap_diff'])
#Detect the change points
algo = rpt.Pelt(model="rbf").fit(ts)
change_location = algo.predict(pen=6)
#Identify true hours for change detection
true_hour_changes = []
for change in change_location:
c_true_hour = current.iloc[(change-1), 3]
true_hour_changes.append(c_true_hour)
#Conditional logic to create new field identifying change detection or not
current['change_detection'] = np.select(
[((current['true_hour'].isin(true_hour_changes[:-1])).astype('bool')),
((~current['true_hour'].isin(true_hour_changes[:-1])).astype('bool'))],
['change detected', np.nan],
default=np.nan
)
#Rolling 12-window averages (preceding and following) to compare actual changes and determine direction of change
window_size = 12
current['rolling_10_preceding'] = current['topsnap_diff'].rolling(window_size, min_periods=1).mean()
current['rolling_10_following'] = current['topsnap_diff'].rolling(window_size, min_periods=1).mean().shift(-window_size+1)[::-1]
#Conditional logic to identify the direction of the change
current['direction'] = np.select(
[(current['change_detection'].isin(['change detected']))
& ((current['rolling_10_following'])>=(current['rolling_10_preceding'])),
(current['change_detection'].isin(['change detected']))
& ((current['rolling_10_following'])<(current['rolling_10_preceding'])),
(~current['change_detection'].isin(['change detected']))
],
['upward change',
'downward change',
np.nan],
default=np.nan
)
change_df = current.loc[current['true_hour'] > 18]
return change_df
#Summary Table
def summary_table():
id_list = []
episode_list = []
channel_list = []
last_reported_list = []
hours_running = []
actual_list = []
actual_bench_list = []
actual_trend_list = []
fcst_hours_list = []
fcst_views_list = []
fcst_bench_list = []
fcst_trend_list = []
ctr_list = []
trend_sentiment_list = []
momentum_list = []
daily_perf_list = []
daily_avg_list = []
for story in df.story_id.unique():
channel_df = df[df.story_id.isin([story])]
historical = channel_df[channel_df['forecast_type'].isin(['history'])]
#story ID
id = channel_df.story_id.values[0]
id_list.append(id)
#Episode
episode = channel_df.title.values[0]
episode_list.append(episode)
#Channel
channel = channel_df.name.values[0]
channel_list.append(channel)
#Get today's value, and the difference between the last reported hour and the current hour for conditional logic
#Today
tt = pd.Timestamp.today().floor('H')
np_today = tt.to_numpy()
today = np_today - np.timedelta64(4, 'h')
#Published date
published = channel_df['published_at'].head(1).values[0]
#Last reported datetime
lst_actual_dt = int(channel_df.loc[channel_df['forecast_type'] == 'history', ['interval_time']].tail(1).values[0])
lst_actual_dt = pd.to_datetime(lst_actual_dt)
#Difference between last reported time and current time
difference = today - lst_actual_dt
hours_diff = int(difference/ np.timedelta64(1, 'h'))
#Hours running, last hour reported and performance
#Last actual if there isn't enough data for forecasting OR there is long delays in data reporting
if len(historical) < 10 or len(channel_df.loc[channel_df['forecast_type'] == 'future']) <=0:
last_hour = int(channel_df.loc[channel_df['forecast_type'] == 'history', ['true_hour']].tail(1).values[0])
last_reported = np.nan
actual_views = int(channel_df.loc[channel_df['forecast_type'] == 'history', ['topsnap_views']].tail(1).values[0])
#Metrics if there is long delays in data
elif hours_diff > 72:
actual_diff = today - published
last_hour = int(actual_diff / np.timedelta64(1, 'h'))
last_reported = int(channel_df.loc[channel_df['forecast_type'] == 'history', ['true_hour']].tail(1).values[0])
actual_views = int(channel_df.loc[channel_df['forecast_type'] == 'history', ['topsnap_views']].tail(1).values[0])
#ACTUAL current time and its corresponding hour
else:
tt = pd.Timestamp.today().floor('H')
np_today = tt.to_numpy()
today = np_today - np.timedelta64(4, 'h')
last_hour = int(channel_df.loc[channel_df['interval_time'] == today, ['true_hour']].values[0])
try:
last_reported = round(channel_df.loc[:, ['actual', 'true_hour']].dropna().tail(1)['true_hour'].values[0])
except IndexError:
last_reported = np.nan
actual_views = float(channel_df.loc[channel_df['true_hour'] == last_hour, ['topsnap_views']].values[0])
#Append variables outside if/then logic
last_reported_list.append(last_reported)
hours_running.append(last_hour)
actual_list.append(actual_views)
#Actual benchmark
channel_alleps = benchmarks[benchmarks['name'].isin(channel_df.name)]
channel_hour = channel_alleps.loc[channel_alleps['true_hour'] == last_hour, ['topsnap_views_total']]
actual_bench = channel_hour['topsnap_views_total'].mean()
try:
actual_bench = round(actual_bench)
except ValueError:
actual_bench = actual_bench
actual_bench_list.append(actual_bench)
#Actual Trend
try:
trending_actual = round(((actual_views - actual_bench) / actual_bench), 2)
except ValueError:
trending_actual = ((actual_views - actual_bench) / actual_bench)
actual_trend_list.append(trending_actual)
#Forecasted hours
fcst_hours = round_to_multiple(last_hour, 24)
fcst_hours_list.append(fcst_hours)
#Forecasted benchmark
channel_fcst_hour = channel_alleps.loc[channel_alleps['true_hour'] == fcst_hours, ['topsnap_views_total']]
fcst_bench = channel_fcst_hour['topsnap_views_total'].mean()
try:
fcst_bench = round(fcst_bench)
except ValueError:
fcst_bench = fcst_bench
fcst_bench_list.append(fcst_bench)
if len(historical) < 10 or len(channel_df.loc[channel_df['forecast_type'] == 'future']) <=0 or hours_diff > 72:
fcst_views = np.nan
trending = np.nan
momentum = np.nan
daily_prediction = np.nan
if len(channel_alleps['topsnap_daily_diff'].dropna()) == 0:
daily_avg = 0
else:
daily_avg = round(int(channel_alleps.loc[channel_alleps['true_hour']<= 168, ['topsnap_daily_diff']].mean()))
else:
#Forecasted topsnaps
try:
fcst_views = int(channel_df.loc[channel_df['true_hour'] == fcst_hours, ['topsnap_views']].values[0])
except IndexError:
fcst_views = np.nan
#Fcst Trend
try:
trending = round(((fcst_views - fcst_bench) / fcst_bench), 4)
except ValueError:
trending = (fcst_views - fcst_bench) / fcst_bench
#Momentum
current_df = channel_df.loc[channel_df.true_hour <= fcst_hours]
momentum_df = current_df.loc[current_df['true_hour'] >= fcst_hours-48]
#momentum_df =current_df.tail(49)
if fcst_hours <= 24:
momentum = np.nan
daily_prediction = np.nan
if len(channel_alleps['topsnap_daily_diff'].dropna()) == 0:
daily_avg = 0
else:
daily_avg = round(int(channel_alleps.loc[channel_alleps['true_hour']<= 120, ['topsnap_daily_diff']].mean()))
else:
start_end = current_df.tail(25)
start = start_end.head(1)['topsnap_views'].values[0]
end = start_end.tail(1)['topsnap_views'].values[0]
daily_prediction = round(end-start)
if len(channel_alleps['topsnap_daily_diff'].dropna()) == 0:
daily_avg = 1
else:
daily_avg = round(int(channel_alleps.loc[channel_alleps['true_hour']<= 120, ['topsnap_daily_diff']].mean()))
if fcst_hours == 48:
previous_day = float(momentum_df.loc[momentum_df['true_hour'] == fcst_hours-24, ['topsnap_views']].head(1).values[0])
else:
m_start = momentum_df.head(1)['topsnap_views'].values[0]
m_end = float(momentum_df.loc[momentum_df['true_hour'] == fcst_hours-24, ['topsnap_views']].head(1).values[0])
previous_day = round(m_end-m_start)
try:
momentum = round((daily_prediction-previous_day)/previous_day, 2)
except ZeroDivisionError:
momentum = 0
#Trend Sentiment
if channel_df['true_hour'].values[-1] < 24:
sentiment = np.nan
else:
cpd = changepoint_df(story)
sentiment = cpd.loc[cpd['interval_time']<= today]
last_36 = sentiment[-48:]
last_36['ranking'] = last_36.loc[last_36['direction'].isin(['upward change', 'downward change'])].groupby('direction')['interval_time'].rank(method='dense', ascending=False)
try:
most_recent = str(last_36.loc[last_36['ranking'] == 1, ['direction']].values[-1])
if most_recent == "['upward change']":
sentiment = '🔥'
if most_recent == "['upward change']" and daily_prediction > (daily_avg*1.5):
sentiment = '🔥🔥'
if most_recent == "['upward change']" and daily_prediction > (daily_avg*2):
sentiment = '🔥🔥🔥'
if most_recent == "['downward change']":
sentiment = '🥶'
if most_recent == "['downward change']" and daily_prediction < (daily_avg*0.5):
sentiment = '🥶🥶'
if most_recent == "['downward change']" and daily_prediction < (daily_avg*0.25):
sentiment = '🥶🥶🥶'
except IndexError:
sentiment = np.nan
#Append remaining variables outside of if/else statement
fcst_views_list.append(fcst_views)
fcst_trend_list.append(trending)
trend_sentiment_list.append(sentiment)
momentum_list.append(momentum)
daily_perf_list.append(daily_prediction)
daily_avg_list.append(daily_avg)
final_df = pd.DataFrame({'Story ID': id_list,
'Channel': channel_list,
'Episode': episode_list,
"Last Reported Hour": last_reported_list,
'Current Hour': hours_running,
'Current Performance': actual_list,
"Current Benchmark": actual_bench_list,
"% vs Bench": actual_trend_list,
'Fcst Period': fcst_hours_list,
'Forecast': fcst_views_list,
'Fcst Benchmark': fcst_bench_list,
'Fcst % vs Bench': fcst_trend_list,
'Trend Sentiment': trend_sentiment_list,
'Momentum %': momentum_list,
'Daily Performance': daily_perf_list,
'Daily Avg': daily_avg_list
})
#Create Decision logic
final_df['Consideration'] = np.select(
[ #Let It Ride
(~final_df['Channel'].isin(["Channels of Choice"]))
&(final_df['Fcst Period']==48)
&(final_df['Fcst % vs Bench']>=0.75)
&((final_df['Daily Performance'])>(final_df['Daily Avg']*0.6))
#48 hours
|(~final_df['Channel'].isin(["Channels of Choice"]))
&(final_df['Fcst Period']==48)
&(final_df['Fcst % vs Bench']>0.5)
&((final_df['Daily Performance'])>=(final_df['Daily Avg']*1.5))
#72 hours
|(final_df['Fcst Period']==72)
&(final_df['Fcst % vs Bench']>=0.75)
&((final_df['Daily Performance'])>=(final_df['Daily Avg']*0.8))
#72 hours
|(final_df['Fcst Period']==72)
&(final_df['Fcst % vs Bench']>=0.5)
&(final_df['Trend Sentiment']== '🔥🔥')
|(final_df['Fcst Period']>=72) &(final_df['Fcst Period']<=96)
&(final_df['Trend Sentiment']== '🔥🔥🔥')
#96 hours
|(final_df['Fcst Period']==96)
&(final_df['Fcst % vs Bench']>=1.0)
&((final_df['Daily Performance'])>=(final_df['Daily Avg']*0.9))
#96 hours
|(final_df['Fcst Period']==96)
&(final_df['Fcst % vs Bench']>0.5)
&(final_df['Trend Sentiment']== '🔥🔥🔥')
#120 and 168
|(final_df['Fcst Period']>=120) & (final_df['Fcst Period']<=168)
&(final_df['Fcst % vs Bench']>=1.0)
&((final_df['Daily Performance'])>=(final_df['Daily Avg']))
&(final_df['Trend Sentiment']!= '🥶')
#120 to 168
|(final_df['Fcst Period']>=120) & (final_df['Fcst Period']<=168)
&((((final_df['Daily Performance']) - (final_df['Daily Avg'])) / (final_df['Daily Avg'])) >= 1.0)
#120-168
|(final_df['Fcst Period']>=120) & (final_df['Fcst Period']<=168)
&(final_df['Trend Sentiment']== '🔥🔥🔥')
#168 and 192 hours
|(final_df['Fcst Period']>168) & (final_df['Fcst Period']<=192)
&(final_df['Fcst % vs Bench']>=1.5)
&((final_df['Daily Performance'])>(final_df['Daily Avg']))
#192
|(final_df['Fcst Period']==192)
&(final_df['Fcst % vs Bench']>=2.0)
&((final_df['Daily Performance'])>(final_df['Daily Avg']))
#216 and 240
|(final_df['Fcst Period']>=216) & (final_df['Fcst Period']<=240)
&(final_df['Fcst % vs Bench']>=3.0)
&((final_df['Daily Performance'])>(final_df['Daily Avg']))
#240
|(final_df['Fcst Period']>240) & (final_df['Fcst % vs Bench']>=4.0)
&((final_df['Daily Performance'])>(final_df['Daily Avg'])),
#Replace It
#48 hours
(final_df['Fcst Period']== 48)&(final_df['Fcst % vs Bench']<= -0.5)
&((final_df['Daily Performance'])<(final_df['Daily Avg']))
#48
|(final_df['Fcst Period']== 48)&(final_df['Fcst % vs Bench']<= -0.75)
#48
|(final_df['Fcst Period']== 48)&(final_df['Fcst % vs Bench'] < 0)
&((final_df['Daily Performance'])<(final_df['Daily Avg']*0.8))
#72hrs
|(final_df['Fcst Period']== 72)&(final_df['Fcst % vs Bench']< 0)
#72
|(final_df['Fcst Period']== 72)
&((final_df['Daily Performance'])<(final_df['Daily Avg']*0.75))
#72
|(final_df['Fcst Period']== 72)&(final_df['Fcst % vs Bench']< 0.25)
&((final_df['Daily Performance'])<(final_df['Daily Avg']*0.9))
#96hrs
|(final_df['Fcst Period']== 96)&(final_df['Fcst % vs Bench']< 0.5)
&((final_df['Daily Performance']) < (final_df['Daily Avg']*1.5))
#96
|(final_df['Fcst Period']== 96)
&(final_df['Trend Sentiment']== '🥶🥶🥶')
#96
|(final_df['Fcst Period']== 96)
&((final_df['Daily Performance'])<(final_df['Daily Avg']*0.9))
#96
|(final_df['Fcst Period']== 96)&(final_df['Fcst % vs Bench']< 0.75)
&((final_df['Daily Performance'])<(final_df['Daily Avg']))
#120-168hrs
|(final_df['Fcst Period']>= 120)&(final_df['Fcst Period']<= 168)
&(final_df['Fcst % vs Bench']<= 0.75)
#120-168
|(final_df['Fcst Period']>= 120)&(final_df['Fcst Period']<= 168)
&(final_df['Trend Sentiment']== '🥶🥶')
|(final_df['Fcst Period']>= 120)&(final_df['Fcst Period']<= 168)
&(final_df['Trend Sentiment']== '🥶🥶🥶')
#120-168
|(final_df['Fcst Period']>= 120)&(final_df['Fcst Period']<= 192)
&((final_df['Daily Performance'])<(final_df['Daily Avg']))
192hrs
|(final_df['Fcst Period'] == 192)
&(final_df['Fcst % vs Bench'] <2.0)
#192
|(final_df['Fcst Period'] == 192)
&((final_df['Daily Performance'])<(final_df['Daily Avg']))
#216-240hrs
|(final_df['Fcst Period'] >= 216) &(final_df['Fcst Period'] <= 240)
&(final_df['Fcst % vs Bench'] < 3.0)
#216hrs+
|(final_df['Fcst Period'] >= 216)
&((final_df['Daily Performance']) < (final_df['Daily Avg']))
#264+
|(final_df['Fcst Period'] >= 264)
&(final_df['Fcst % vs Bench'] < 4.0)
,
# Investigate - Bullish
#48 hours
(~final_df['Channel'].isin(['Channels of Choice']))
&(final_df['Fcst Period']==48)
&(final_df['Fcst % vs Bench']>=0.5)
&(final_df['Trend Sentiment']== '🔥')
#48
|(~final_df['Channel'].isin(['Channels of Choice']))
&(final_df['Fcst Period']==48)
&(final_df['Fcst % vs Bench']> 0) &(final_df['Fcst % vs Bench']< 0.5)
&((final_df['Daily Performance'])>=(final_df['Daily Avg']*1.5))
#48
|(~final_df['Channel'].isin(['Channels of Choice']))
&(final_df['Fcst Period']==48)
&(final_df['Fcst % vs Bench']>=0.25) & (final_df['Fcst % vs Bench']<=0.5)
&(final_df['Momentum %'] >= 0.5)
#48
|(~final_df['Channel'].isin(['What The Fork!?', 'Snacks & Hacks', 'The Shaba Kitchen', 'The Pun Guys']))
&(final_df['Fcst Period']==48)
&(final_df['Fcst % vs Bench']>0) & (final_df['Fcst % vs Bench']<=0.25)
&(final_df['Momentum %'] >= 0.75)
#72hrs
|(final_df['Fcst Period']==72)
&(final_df['Fcst % vs Bench']>=0.5) & (final_df['Fcst % vs Bench']<=0.75)
&((final_df['Daily Performance'])>=(final_df['Daily Avg']*1.75))
#72
|(final_df['Fcst Period']==72)
&(final_df['Fcst % vs Bench']>= 0.5) & (final_df['Fcst % vs Bench']<0.75)
&(final_df['Trend Sentiment']== '🔥')
#72
|(final_df['Fcst Period']==72)
&(final_df['Fcst % vs Bench']> 0) & (final_df['Fcst % vs Bench']<=0.5)
&(final_df['Trend Sentiment']== '🔥🔥')
#96hrs
|(final_df['Fcst Period'] == 96)
&(final_df['Fcst % vs Bench']>= 0.75) &(final_df['Fcst % vs Bench']<= 1.0)
&(final_df['Trend Sentiment']== '🔥🔥')
|(final_df['Fcst Period'] == 96)
&(final_df['Fcst % vs Bench']>= 0.75) &(final_df['Fcst % vs Bench']<= 1.0)
&(final_df['Trend Sentiment']== '🔥')
#96
|(final_df['Fcst Period']==96)
&(final_df['Fcst % vs Bench']>= 0.75) & (final_df['Fcst % vs Bench']< 1.0)
&(final_df['Trend Sentiment']== '🔥')
|(final_df['Fcst Period']==96)
&(final_df['Fcst % vs Bench']>= 0.75) & (final_df['Fcst % vs Bench']< 1.0)
&(final_df['Momentum %'] > 0)
#96
|(final_df['Fcst Period']==96)
&(final_df['Fcst % vs Bench']>0.25)
&(final_df['Trend Sentiment']== '🔥🔥🔥')
|(final_df['Fcst Period']==96)
&(final_df['Fcst % vs Bench']>0.25)
&(final_df['Trend Sentiment']== '🔥🔥')
|(final_df['Fcst Period']==96)
&(final_df['Fcst % vs Bench']>0.25)
&((final_df['Daily Performance'])>=(final_df['Daily Avg']*1.5))
#120-168
|(final_df['Fcst Period']>=120) &(final_df['Fcst Period']<=168)
&(final_df['Fcst % vs Bench']>=0.75) & (final_df['Fcst % vs Bench']<1.0)
&((((final_df['Daily Performance']) - (final_df['Daily Avg'])) / (final_df['Daily Avg'])) >= 0.5)
#120-168hrs
|(final_df['Fcst Period']>=120) &(final_df['Fcst Period']<=168)
&(final_df['Fcst % vs Bench']>=0.75) & (final_df['Fcst % vs Bench']<1.0)
&(final_df['Trend Sentiment']== '🔥')
|(final_df['Fcst Period']>=120) &(final_df['Fcst Period']<=168)
&(final_df['Fcst % vs Bench']>=0.75) & (final_df['Fcst % vs Bench']<1.0)
&(final_df['Trend Sentiment']== '🔥🔥')
#192hrs+
|(final_df['Fcst Period']==192)
&(final_df['Fcst % vs Bench'] >= 1.5)&(final_df['Fcst % vs Bench'] < 2.0)
&((final_df['Daily Performance'])>=(final_df['Daily Avg']*1.5)),
#Investigate - Bearish
#48 hrs
(~final_df['Channel'].isin(['Channels of Choice']))
&(final_df['Fcst Period']==48)
&(final_df['Fcst % vs Bench']< 0) & (final_df['Fcst % vs Bench']> -0.75)
&((final_df['Daily Performance']) < (final_df['Daily Avg']*1.25))
#48
|(~final_df['Channel'].isin(['Channels of Choice']))
&(final_df['Fcst Period']==48)
&(final_df['Fcst % vs Bench']< 0.75) & (final_df['Fcst % vs Bench']>= -0.25)
&(final_df['Trend Sentiment']== '🥶')
|(~final_df['Channel'].isin(['Channels of Choice']))
&(final_df['Fcst Period']==48)