-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextended-devices-locations-and-audiences-bidding.js
More file actions
473 lines (398 loc) · 14.1 KB
/
extended-devices-locations-and-audiences-bidding.js
File metadata and controls
473 lines (398 loc) · 14.1 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
// ID: a0febe50e9cc72bec9c28dd90239fa0a
/**
*
* Extended Devices, Locations and Audiences Bidding
*
* Automatically apply modifiers to your devices, locations, in-market and remarketing audiences based on performance.
* It analyses search and display campaigns only.
*
* Version: 1.1
* Google Ads Script maintained on brainlabsdigital.com
*
**/
// Use this if you want to exclude some campaigns. Case insensitive.
// For example ["Brand"] would ignore any campaigns with "brand" in the name,
// while ["Brand","Competitor"] would ignore any campaigns with "brand" or
// "competitor" in the name.
// Leave as [] to not exclude any campaigns.
var CAMPAIGN_NAME_DOES_NOT_CONTAIN = [];
// Use this if you only want to look at some campaigns. Case insensitive.
// For example ["Brand"] would only look at campaigns with "brand" in the name,
// while ["Brand","Generic"] would only look at campaigns with "brand" or "generic"
// in the name.
// Leave as [] to include all campaigns.
var CAMPAIGN_NAME_CONTAINS = [];
// Set true or false for the following targeting options in order to enable them
var DO_DEVICES = true; // campaign level
var DO_LOCATIONS = true; // campaign level
var DO_IN_MARKET_AUDIENCES = true; // campaign or ad group level
var DO_OTHER_AUDIENCES = true; // campaign or ad group level
// Use this to determine the relevant date range for your data.
// See here for the possible options:
// https://developers.google.com/google-ads/scripts/docs/reference/adwordsapp/adwordsapp_campaignselector#forDateRange_1
var DATE_RANGE = "LAST_30_DAYS";
// Use this to determine the minimum number of impressions, conversions and cost
// a campaign or an ad group should have before being considered.
var MINIMUM_IMPRESSIONS = 0;
var MINIMUM_CONVERSIONS = 0;
var MINIMUM_COST = 0;
// Use this to define the lower and upper bounds that bid modifiers must fall within
var MIN_BID_MODIFIER = -0.4; // -40%
var MAX_BID_MODIFIER = 0.4; // +40%
// Use this to configure bid modifiers' weights with respect to the number
// of specific device, location or audience conversions.
// E.g. if there are 15 conversions through a tablet device over the defined time period DATE_RANGE
// the bid modifier weighted down by multiplying it by 0.8
var CAMPAIGN_BID_MODIFIER_WEIGHTS = [
{ "lower": 0, "upper": 10, "weight": 0.6 },
{ "lower": 10, "upper": 20, "weight": 0.8 },
{ "lower": 20, "upper": 100000, "weight": 1 }
]
var ADGROUP_BID_MODIFIER_WEIGHTS = [
{ "lower": 0, "upper": 10, "weight": 0.6 },
{ "lower": 10, "upper": 20, "weight": 0.8 },
{ "lower": 20, "upper": 100000, "weight": 1 }
]
var AUDIENCE_MAPPING_CSV_DOWNLOAD_URL = "https://developers.google.com/google-ads/api/data/tables/in-market-categories.tsv";
function main() {
Logger.log("Validating settings...");
validateInputs();
Logger.log("Success");
Logger.log("Getting in-market audience mapping");
var audienceMapping =
getInMarketAudienceMapping(AUDIENCE_MAPPING_CSV_DOWNLOAD_URL);
Logger.log("Getting campaign performance");
var campaignPerformance = getCampaignPerformance();
Logger.log("Getting ad group performance");
var adGroupPerformance = getAdGroupPerformance();
Logger.log("Starting making operations and applying bids");
makeOperationsAndApplyBids(
audienceMapping,
campaignPerformance,
adGroupPerformance
);
}
function validateInputs() {
if ((typeof (DO_DEVICES) != "boolean") ||
(typeof (DO_LOCATIONS) != "boolean") ||
(typeof (DO_IN_MARKET_AUDIENCES) != "boolean") ||
(typeof (DO_OTHER_AUDIENCES) != "boolean")) {
throw ("DO_DEVICES, DO_LOCATION, DO_IN_MARKET_AUDIENCES and DO_OTHER_AUDIENCES " +
"variables must be set to either true or false.");
}
if ((typeof (MINIMUM_IMPRESSIONS) != "number") ||
(typeof (MINIMUM_CONVERSIONS) != "number") ||
(typeof (MINIMUM_COST) != "number")) {
throw ("MINIMUM_IMPRESSIONS, MINIMUM_CONVERSIONS, MINIMUM_COST must be a number, e.g. 0, 1, 15");
}
if ((typeof (MIN_BID_MODIFIER) != "number") ||
(MIN_BID_MODIFIER < -0.9) ||
(MIN_BID_MODIFIER > 0)) {
throw ("MIN_BID_MODIFIER must be a number between -0.9 and 0, e.g. -0.85, -0.6, -0.3");
}
if ((typeof (MAX_BID_MODIFIER) != "number") ||
(MAX_BID_MODIFIER < 0) ||
(MAX_BID_MODIFIER > 9)) {
throw ("MAX_BID_MODIFIER must be a number between 0 and 9.0, e.g. 0.6, 1.4, 2.7");
}
var weights = [CAMPAIGN_BID_MODIFIER_WEIGHTS, ADGROUP_BID_MODIFIER_WEIGHTS];
weights.forEach(function (entityWeights) {
entityWeights.forEach(function (row) {
var keys = ["lower", "upper", "weight"];
if (Object.keys(row).toString() !== keys.toString()) {
throw ("CAMPAIGN_BID_MODIFIER_WEIGHTS and AD_GROUP_BID_MODIFIER_WEIGHTS " +
"rows must be in the following format: " +
"{\"lower\": number, \"upper\": number, \"weight\": number}");
}
keys.forEach(function (key) {
if (typeof (row[key]) !== "number") {
throw ("\"" + key + "\" value in bid modifiers weights must be a number, e.g. 1, 5, 15");
}
});
});
});
}
function getInMarketAudienceMapping(downloadCsvUrl) {
var csv = Utilities.parseCsv(
UrlFetchApp.fetch(downloadCsvUrl).getContentText(),
"\t"
);
var headers = csv[0];
var indexOfId = headers.indexOf("Criterion ID");
var indexOfName = headers.indexOf("Category");
if ((indexOfId === -1) || (indexOfName === -1)) {
throw new Error("The audience CSV does not have the expected headers");
}
var mapping = {};
for (var i = 1; i < csv.length; i++) {
var row = csv[i];
mapping[row[indexOfId]] = row[indexOfName];
}
return mapping;
}
function getCampaignPerformance() {
return getEntityPerformance("CampaignId", "CAMPAIGN_PERFORMANCE_REPORT");
}
function getAdGroupPerformance() {
return getEntityPerformance("AdGroupId", "ADGROUP_PERFORMANCE_REPORT");
}
function getEntityPerformance(entityIdFieldName, reportName) {
var performance = {};
var query = "SELECT " + entityIdFieldName + ", CostPerAllConversion " +
"FROM " + reportName + " " +
"WHERE Impressions > " + String(MINIMUM_IMPRESSIONS) + " " +
"AND Conversions > " + String(MINIMUM_CONVERSIONS) + " " +
"AND Cost > " + String(MINIMUM_COST) + " "
CAMPAIGN_NAME_DOES_NOT_CONTAIN.forEach(function (part) {
query += "AND CampaignName DOES_NOT_CONTAIN_IGNORE_CASE '"
+ part.replace(/"/g, '\\\"') + "' "
});
CAMPAIGN_NAME_CONTAINS.forEach(function (part) {
query += "AND CampaignName CONTAINS_IGNORE_CASE '"
+ part.replace(/"/g, '\\\"') + "' "
});
query += "DURING " + DATE_RANGE;
var rows = AdsApp.report(query).rows();
while (rows.hasNext()) {
var row = rows.next();
performance[row[entityIdFieldName]] = row.CostPerAllConversion;
}
return performance;
}
function makeOperationsAndApplyBids(
audienceMapping,
campaignPerformance,
adGroupPerformance
) {
var devicesAndLocationsOperations = [];
var audiencesOperations = [];
var campaignIds = Object.keys(campaignPerformance);
var campaigns = getEntities(AdsApp.campaigns(), campaignIds);
while (campaigns.hasNext()) {
var campaign = campaigns.next();
Logger.log("");
Logger.log("Processing campaign " + campaign.getName())
if (DO_DEVICES) {
Logger.log("Making devices operations");
var devicesOperations = makeCampaignDevicesOperations(
campaign,
campaignPerformance[campaign.getId()]
)
devicesAndLocationsOperations = devicesAndLocationsOperations.concat(devicesOperations);
}
if (DO_LOCATIONS) {
Logger.log("Making locations operations");
var locationsOperations = makeCampaignLocationsOperations(
campaign,
campaignPerformance[campaign.getId()]
)
devicesAndLocationsOperations = devicesAndLocationsOperations.concat(locationsOperations);
}
if (DO_IN_MARKET_AUDIENCES || DO_OTHER_AUDIENCES) {
var campaignAudiencesOperations = makeAllAudiencesOperations(
campaign,
campaignPerformance[campaign.getId()],
adGroupPerformance,
audienceMapping
)
audiencesOperations = audiencesOperations.concat(campaignAudiencesOperations);
}
}
Logger.log(" ");
Logger.log("Total of " + devicesAndLocationsOperations.length + " devices and locations operations");
Logger.log("Total of " + audiencesOperations.length + " audiences operations");
Logger.log("Applying bids");
applyDevicesAndLocationsBids(devicesAndLocationsOperations);
applyAudiencesBids(audiencesOperations);
Logger.log("Finished");
}
function getEntities(entitySelector, ids) {
var entities = entitySelector.withIds(ids).get();
return entities;
}
function makeCampaignDevicesOperations(campaign, campaignCpa) {
var operations = [];
var devices = campaign
.targeting()
.platforms()
.forDateRange(DATE_RANGE)
.get()
while (devices.hasNext()) {
var device = devices.next();
var operation = makeOperation(campaign, campaignCpa, device);
if (operation) {
operations.push(operation);
}
}
return operations;
}
function makeCampaignLocationsOperations(campaign, campaignCpa) {
var operations = [];
var locations = campaign
.targeting()
.targetedLocations()
.forDateRange()
.get()
while (locations.hasNext()) {
var location = locations.next();
var operation = makeOperation(campaign, campaignCpa, location);
if (operation) {
operations.push(operation);
}
}
return operations;
}
function makeAllAudiencesOperations(campaign, campaignCpa, adGroupPerformance, audienceMapping) {
var operations = [];
// Can't have both ad-group-level and campaign-level
// audiences on any given campaign.
if (campaignHasAnyCampaignLevelAudiences(campaign)) {
Logger.log("Campaign level audiences");
var audiences = getAudiencesFromEntity(campaign, audienceMapping);
var operationsFromCampaign = makeEntityAudiencesOperations(
campaign,
campaignCpa,
audiences
)
operations = operations.concat(operationsFromCampaign);
} else {
Logger.log("Ad group level audiences");
var adGroupIds = Object.keys(adGroupPerformance);
var adGroups = getEntities(campaign.adGroups(), adGroupIds)
while (adGroups.hasNext()) {
var adGroup = adGroups.next();
Logger.log("Processing ad group " + adGroup.getName());
var audiences = getAudiencesFromEntity(adGroup, audienceMapping);
var operationsFromAdGroup = makeEntityAudiencesOperations(
adGroup,
adGroupPerformance[adGroup.getId()],
audiences
);
operations = operations.concat(operationsFromAdGroup);
}
}
return operations;
}
function campaignHasAnyCampaignLevelAudiences(campaign) {
var totalNumEntities = campaign
.targeting()
.audiences()
.get()
.totalNumEntities();
return totalNumEntities > 0;
}
function getAudiencesFromEntity(entity, audienceMapping) {
var inMarketIds = Object.keys(audienceMapping);
var allAudiences = entity
.targeting()
.audiences()
.forDateRange()
.get()
var inMarketAudiences = [];
var otherAudiences = [];
while (allAudiences.hasNext()) {
var audience = allAudiences.next();
if (isAudienceInMarketAudience(audience, inMarketIds)) {
inMarketAudiences.push(audience);
} else {
otherAudiences.push(audience);
}
}
audiences = {};
audiences.inMarket = inMarketAudiences;
audiences.other = otherAudiences;
return audiences;
}
function isAudienceInMarketAudience(audience, inMarketIds) {
return inMarketIds.indexOf(audience.getAudienceId()) > -1;
}
function makeEntityAudiencesOperations(entity, entityCpa, audiences) {
var operations = [];
if (DO_IN_MARKET_AUDIENCES) {
Logger.log("Doing in-market audiences operations");
var inMarketAudiencesOperations = makeAudiencesOperations(
entity,
entityCpa,
audiences.inMarket
);
operations = operations.concat(inMarketAudiencesOperations);
}
if (DO_OTHER_AUDIENCES) {
Logger.log("Doing other audiences operations");
var otherAudiencesOperations = makeAudiencesOperations(
entity,
entityCpa,
audiences.other
);
operations = operations.concat(otherAudiencesOperations);
}
return operations;
}
function makeAudiencesOperations(entity, entityCpa, audiences) {
operations = [];
audiences.forEach(function (audience) {
var operation = makeOperation(entity, entityCpa, audience);
if (operation) {
operations.push(operation);
}
});
return operations;
}
function makeOperation(entity, entityCpa, targetingEntity) {
var stats = targetingEntity.getStatsFor(DATE_RANGE);
var targetingConversions = stats.getConversions();
if (targetingConversions === 0) {
return;
}
var targetingCpa = stats.getCost() / targetingConversions;
entityCpa = parseFloat(entityCpa);
var modifier = entityCpa / targetingCpa;
var bidModifierWeight = getBidModifierWeight(
targetingConversions,
entity.getEntityType()
);
var weightedModifier = (modifier - 1) * bidModifierWeight + 1;
var finalModifier = ensureWithinBounds(weightedModifier);
var operation = {};
operation.targetingEntity = targetingEntity;
operation.modifier = finalModifier;
return operation;
}
function getBidModifierWeight(conversions, entityType) {
if (entityType === "Campaign") {
weights = CAMPAIGN_BID_MODIFIER_WEIGHTS;
}
if (entityType === "AdGroup") {
weights = ADGROUP_BID_MODIFIER_WEIGHTS
}
var weight = 1;
for (var index in weights) {
var weightRange = weights[index];
if ((conversions >= weightRange["lower"]) &&
(conversions < weightRange["upper"])) {
weight = weightRange["weight"];
break;
}
}
return weight;
}
function ensureWithinBounds(modifier) {
if (modifier < (1 + MIN_BID_MODIFIER)) {
return 1 + MIN_BID_MODIFIER;
}
else if (modifier > (1 + MAX_BID_MODIFIER)) {
return 1 + MAX_BID_MODIFIER;
} else {
return modifier;
}
}
function applyDevicesAndLocationsBids(operations) {
operations.forEach(function (operation) {
operation.targetingEntity.setBidModifier(operation.modifier);
});
}
function applyAudiencesBids(operations) {
operations.forEach(function (operation) {
operation.targetingEntity.bidding().setBidModifier(operation.modifier);
});
}