Script 33: Campaign ROAS Outlier Tagging
Purpose
The Python script identifies and tags campaigns with significantly lower Return on Advertising Spend (ROAS) compared to their peers within the same account.
To Elaborate
The script is designed to analyze advertising campaign performance data and identify campaigns that have an abnormally low Return on Advertising Spend (ROAS) compared to other campaigns within the same account. It uses a 30-day lookback period, excluding the most recent three days to account for conversion lag. The script calculates various performance metrics, such as cost per conversion, ROAS, conversion rate, and average cost per click. It then applies statistical methods to detect anomalies in these metrics, specifically focusing on ROAS. The script flags campaigns as outliers if their ROAS is significantly lower than the account average, helping marketers identify underperforming campaigns that may require optimization or further investigation.
Walking Through the Code
- Data Preparation
- The script begins by filtering the input data to include only the last 30 days, excluding the most recent three days.
- It reduces the dataset to essential columns and aggregates performance metrics by campaign and account.
- Campaigns with zero publication cost are removed from the dataset.
- Feature Calculation
- The script calculates key performance metrics such as cost per conversion, ROAS, conversion rate, and average CPC for each campaign.
- Anomaly Detection Functions
- The
get_feature_anomalies
function identifies anomalies in specified features using a statistical method (e.g., Interquartile Range). - The
is_anomaly_irq
function specifically detects outliers based on the Interquartile Range (IRQ) method.
- The
- Peer Anomaly Detection
- The
find_peer_anomaly
function checks for ROAS anomalies within each account, considering only campaigns with publication costs above the median. - It flags campaigns as outliers if their ROAS is significantly lower than the account average.
- The
- ROAS Anomaly Identification
- The script iterates over each account, calculates the median ROAS, and identifies campaigns with ROAS significantly below this median.
- Outliers are tagged with a descriptive message indicating their underperformance.
- Output Preparation
- If anomalies are found, the script prepares an output DataFrame containing the account, campaign, and anomaly information.
- If no anomalies are detected, an empty DataFrame is returned.
Vitals
- Script ID : 33
- Client ID / Customer ID: 1306920543 / 60268855
- Action Type: Bulk Upload (Preview)
- Item Changed: Campaign
- Output Columns: Account, Campaign, AUTOMATION - INFO
- Linked Datasource: M1 Report
- Reference Datasource: None
- Owner: Michael Huang (mhuang@marinsoftware.com)
- Created by Michael Huang on 2023-03-24 07:14
- Last Updated by Michael Huang on 2023-12-06 04:01
> See it in Action
Python Code
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
#
# Tag Campaign if ROAS performance is abnormally low within Account
#
#
# Author: Michael S. Huang
# Date: 2023-03-24
RPT_COL_CAMPAIGN = 'Campaign'
RPT_COL_DATE = 'Date'
RPT_COL_ACCOUNT = 'Account'
RPT_COL_CAMPAIGN_ID = 'Campaign ID'
RPT_COL_CAMPAIGN_TYPE = 'Campaign Type'
RPT_COL_CAMPAIGN_STATUS = 'Campaign Status'
RPT_COL_PUB_COST = 'Pub. Cost $'
RPT_COL_COST_PER_CONV = 'Cost/Conv. $'
RPT_COL_ROAS = 'ROAS'
RPT_COL_AVG_CPC = 'Avg. CPC $'
RPT_COL_CONV_RATE = 'Conv. Rate %'
RPT_COL_CTR = 'CTR %'
RPT_COL_CONV = 'Conv.'
RPT_COL_REVENUE = 'Revenue $'
RPT_COL_SEARCH_LOSTTOPISBUDGET = 'Search Lost Top IS (Budget) %'
RPT_COL_SEARCH_LOSTTOPISRANK = 'Search Lost Top IS (Rank) %'
RPT_COL_LOST_IMPRSHAREBUDGET = 'Lost Impr. Share (Budget) %'
RPT_COL_LOST_IMPRSHARERANK = 'Lost Impr. Share (Rank) %'
RPT_COL_DAILY_BUDGET = 'Daily Budget'
RPT_COL_AVG_BID = 'Avg. Bid $'
RPT_COL_HIST_QS = 'Hist. QS'
RPT_COL_IMPR = 'Impr.'
RPT_COL_CLICKS = 'Clicks'
BULK_COL_ACCOUNT = 'Account'
BULK_COL_CAMPAIGN = 'Campaign'
BULK_COL_AUTOMATION_INFO = 'AUTOMATION - INFO'
outputDf[BULK_COL_AUTOMATION_INFO] = numpy.nan
## Data Prep
print(inputDf[RPT_COL_DATE].min(), inputDf[RPT_COL_DATE].max())
# 30-day lookback without most recent 3 days due to conversion lag
start_date = pd.to_datetime(datetime.date.today() - datetime.timedelta(days=33))
end_date = pd.to_datetime(datetime.date.today() - datetime.timedelta(days=3))
df_reduced = inputDf[ (inputDf[RPT_COL_DATE] >= start_date) & (inputDf[RPT_COL_DATE] <= end_date) ]
if (df_reduced.shape[0] > 0):
print("reduced dates\\n", min(df_reduced[RPT_COL_DATE]), max(df_reduced[RPT_COL_DATE]))
else:
print("no more input to process")
# reduce to needed columns
df_reduced = df_reduced[[RPT_COL_ACCOUNT, RPT_COL_CAMPAIGN, RPT_COL_DATE, RPT_COL_PUB_COST, RPT_COL_CONV, RPT_COL_REVENUE, RPT_COL_CLICKS]].copy()
# sum metics across dates
df_campaign_perf = df_reduced.groupby([RPT_COL_ACCOUNT, RPT_COL_CAMPAIGN]).sum()
# remove rows without cost
df_campaign_perf = df_campaign_perf[(df_campaign_perf[RPT_COL_PUB_COST] > 0)]
# index by account
df_campaign_perf = df_campaign_perf.reset_index().set_index([RPT_COL_ACCOUNT]).sort_index()
# calculate features
df_campaign_perf[RPT_COL_COST_PER_CONV] = (df_campaign_perf[RPT_COL_PUB_COST] / df_campaign_perf[RPT_COL_CONV])
df_campaign_perf[RPT_COL_ROAS] = df_campaign_perf[RPT_COL_REVENUE] / df_campaign_perf[RPT_COL_PUB_COST]
df_campaign_perf[RPT_COL_CONV_RATE] = df_campaign_perf[RPT_COL_CONV] / df_campaign_perf[RPT_COL_CLICKS]
df_campaign_perf[RPT_COL_AVG_CPC] = (df_campaign_perf[RPT_COL_PUB_COST] / df_campaign_perf[RPT_COL_CLICKS])
## Define Anomaly Fuctions
# Finds anomalies using a certain function (e.g. sigma rule, IRQ etc.)
# data: DataFrame
# Dataset with features
# func: func
# Function to use to find anomalies
# features: list
# Feature list
# thresh: int
# Threshold value (e.g. 2/3 * sigma, 2/3 * IRQ)
# Returns: tuple
def get_feature_anomalies(data, func, features=None, thresh=3):
if features:
features_to_check = features
else:
features_to_check = data.columns
outliers_over = pd.Series(data=[False] * data.shape[0], index=data[features_to_check].index, name='is_outlier')
outliers_under = pd.Series(data=[False] * data.shape[0], index=data[features_to_check].index, name='is_outlier')
anomalies_summary = {}
for feature in features_to_check:
anomalies_mask_over, anomalies_mask_under, upper_bound, lower_bound = func(data, feature, thresh=thresh)
anomalies_mask_combined = pd.concat([anomalies_mask_over, anomalies_mask_under], axis=1).any(1)
anomalies_summary[feature] = [upper_bound, lower_bound, sum(anomalies_mask_combined), 100*sum(anomalies_mask_combined)/len(anomalies_mask_combined)]
outliers_over[anomalies_mask_over[anomalies_mask_over].index] = True
outliers_under[anomalies_mask_under[anomalies_mask_under].index] = True
anomalies_summary = pd.DataFrame(anomalies_summary).T
anomalies_summary.columns=['upper_bound', 'lower_bound', 'anomalies_count', 'anomalies_percentage']
anomalies_ration = round(anomalies_summary['anomalies_percentage'].sum(), 2)
return anomalies_summary, outliers_over, outliers_under
# Finds outliers/anomalies using IRQ
# data: DataFrame
# col: str
# thresh: int
# Number of IRQ to apply
# Returns: Series
# Boolean Series Mask of outliers
def is_anomaly_irq(data, col, thresh):
IRQ = data[col].quantile(0.75) - data[col].quantile(0.25)
upper_bound = data[col].quantile(0.75) + (thresh * IRQ)
lower_bound = data[col].quantile(0.25) - (thresh * IRQ)
anomalies_mask_over = data[col] > upper_bound
anomalies_mask_under = data[col] < lower_bound
# print("Anomalies mask: ", (anomalies_mask_over, anomalies_mask_under))
return anomalies_mask_over, anomalies_mask_under, upper_bound, lower_bound
def find_peer_anomaly(df_slice, features, irq_threshold=1.8, outliers_desired=(True, True)):
(want_outliers_over, want_outliers_under) = outliers_desired
if (df_slice.shape[0] < 3):
return
idx = df_slice.index.unique()
df_slice.reset_index(inplace=True)
anomalies_summary_irq, outlier_over_irq, outlier_under_irq = get_feature_anomalies( \
df_slice, \
func=is_anomaly_irq, \
features=features, \
thresh=irq_threshold)
median_cost = df_slice[RPT_COL_PUB_COST].median()
# include over/under outliers as desired
is_outlier_irq = np.logical_or(
np.logical_and(want_outliers_over, outlier_over_irq),
np.logical_and(want_outliers_under, outlier_under_irq)
)
# ignore anomaly from low spend adgroups (greater than campaign median)
is_outlier_irq = np.logical_and(is_outlier_irq, df_slice[RPT_COL_PUB_COST] > median_cost)
if sum(is_outlier_irq) > 0:
print(">>> ANOMALY", idx)
print(anomalies_summary_irq)
cols = [RPT_COL_CAMPAIGN, RPT_COL_PUB_COST, RPT_COL_CONV, RPT_COL_REVENUE] + features
print(df_slice.loc[is_outlier_irq, cols])
return is_outlier_irq
## Find ROAS Anomalies
print("input shape:", df_campaign_perf.shape)
df_anomalies = pd.DataFrame()
# annotate via Marin Dimensions
def rowFunc(row):
return '{}: ROAS {:,.2f} is much lower than account avg {:,.2f}'.format(
row[RPT_COL_ROAS], \
row[RPT_COL_ROAS + '_median'],
datetime.date.today()
)
for account_idx in df_campaign_perf.index.unique():
df_account = df_campaign_perf.loc[[account_idx]].copy()
df_account[RPT_COL_ROAS + '_median'] = df_account[RPT_COL_ROAS].mean()
df_account[BULK_COL_AUTOMATION_INFO] = np.nan
# dump data used for anomaly detection
print("checking account: ", account_idx, tableize(df_account))
outliers = find_peer_anomaly(df_account, [RPT_COL_ROAS], irq_threshold=0.75, outliers_desired=(False,True))
if outliers is not None and sum(outliers) > 0:
df_outliers = df_account.loc[outliers].copy()
df_outliers[BULK_COL_AUTOMATION_INFO] = df_outliers.apply(rowFunc, axis=1)
print(df_outliers)
df_anomalies = pd.concat([df_anomalies, df_outliers], axis=0)
## Prepare Output
if not df_anomalies.empty:
print(tableize(df_anomalies))
outputDf = df_anomalies[[RPT_COL_ACCOUNT, RPT_COL_CAMPAIGN, BULK_COL_AUTOMATION_INFO]]
else:
print("No anomalies found!")
outputDf = outputDf.iloc[0:0]
Post generated on 2024-11-27 06:58:46 GMT