-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmin-roas-bidding.js
369 lines (282 loc) · 11.1 KB
/
min-roas-bidding.js
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
// Version: V3.0 New Script Experience
/***********
MIT License
Copyright (c) 2016-2022 Alex Czartoryski
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
**********/
var AVG_CONV_VALUE = 40.0; // Average conversion value.
var HIGH_COST_THRESHOLD = AVG_CONV_VALUE; // How much is too much, before you lower your bids
var USE_ACTUAL_CONVERSION_VALUE = true;
// Performance Targets
var MIN_ROAS = 4.0 // Minium Return on Ad Spend
var MAX_COS = 1/MIN_ROAS; // Maximum Ad Spend as a % Cost of Sales.
var MAX_BID_INCREASE = 0.10; // Bids will be increased by at most this amount.
var MIN_BID = 0.05; // The minimum CPC bid to decrease to
var MIN_CONVERSIONS = 5; // Minimum number of conversions required to make a bid increase.
var AGGRESSIVE_BIDDING = false; // When set to true, bids will not be lowered unless the current CPA is over MAX_COSHIGHCOST_VALUE or MAX_COS
// LABELS
var LABEL_PROCESSING = 'Processing';
var TAG_IGNORE = '';
var TAG_INCLUDE = '';
// CAMPAIGN FILTERS
var CAMPAIGN_INCLUDE = ''; // Only include Adgroups and keywords in Campaigns with this text string in the name
var CAMPAIGN_EXCLUDE = ''; // Exclude Adgroups and keywords in Campaigns with this text string in the name
function main() {
initLabels();
Logger.log('\n***** 7 DAYS *****');
setAdGroupsToMax("LAST_7_DAYS");
decreaseHighCostAdGroups("LAST_7_DAYS");
Logger.log('\n***** 14 DAYS *****');
setAdGroupsToMax("LAST_14_DAYS");
decreaseHighCostAdGroups("LAST_14_DAYS");
Logger.log('\n***** 30 DAYS *****');
setAdGroupsToMax("LAST_30_DAYS");
decreaseHighCostAdGroups("LAST_30_DAYS");
Logger.log('\n***** 90 DAYS *****');
setAdGroupsToMax(LAST_90_DAYS(), TODAY());
decreaseHighCostAdGroups(LAST_90_DAYS(), TODAY());
Logger.log('\n***** 1 YEAR *****');
setAdGroupsToMax(LAST_YEAR(), TODAY());
decreaseHighCostAdGroups(LAST_YEAR(), TODAY());
cleanup();
}
//
// Set the Processing label
//
function initLabels() {
checkLabelExists();
var itemsToLabel = [AdsApp.adGroups(), AdsApp.shoppingAdGroups()];
for (i = 0; i < itemsToLabel.length; i++) {
var iterator = getSelector(itemsToLabel[i]).get();
while (iterator.hasNext()) {
iterator.next().applyLabel(LABEL_PROCESSING);
}
}
}
//
// Create the processing label if it does not exist
//
function checkLabelExists() {
var labelIterator = AdsApp.labels()
.withCondition("Name = '" + LABEL_PROCESSING + "'" )
.get();
if( !labelIterator.hasNext()) {
AdsApp.createLabel(LABEL_PROCESSING, "AdWords Scripts label used to process bids")
}
var labelIterator = AdsApp.labels()
.withCondition("Name = '" + TAG_IGNORE + "'" )
.get();
if( !labelIterator.hasNext()) {
AdsApp.createLabel(TAG_IGNORE, "AdWords Scripts label used to ignore script processing")
}
}
//
// Remove Processing label
//
function cleanup() {
var cleanupList = [AdsApp.adGroups(), AdsApp.shoppingAdGroups()];
for (i = 0; i < cleanupList.length; i++) {
// Cleanup AdGoups
var iterator = cleanupList[i].withCondition("LabelNames CONTAINS_ANY ['" + LABEL_PROCESSING + "']").get();
while (iterator.hasNext()) {
iterator.next().removeLabel(LABEL_PROCESSING);
}
}
}
//
// Increase AdGroup bids to maximum supported by conversion value
//
function setAdGroupsToMax(dateRange, dateRangeEnd) {
Logger.log('increaseAdGroupsToMax');
var adGroupTypes = [AdsApp.adGroups(), AdsApp.shoppingAdGroups()];
for (i = 0; i < adGroupTypes.length; i++) {
// Only process adGroups that have:
// - More conversions than MIN_CONVERSIONS
// - Are marked for Processing
// - Have at least one click
// - And who's avg position is worst than the StopLimit
var adGroupIterator = adGroupTypes[i]
.forDateRange(dateRange, dateRangeEnd)
.withCondition("Conversions > " + (MIN_CONVERSIONS-1))
.withCondition("LabelNames CONTAINS_ANY ['" + LABEL_PROCESSING + "']")
.withCondition("Clicks > 0");
adGroupIterator = adGroupIterator.get();
Logger.log('Total adGroups found : ' + adGroupIterator.totalNumEntities());
while (adGroupIterator.hasNext()) {
var adGroup = adGroupIterator.next();
var stats = adGroup.getStatsFor(dateRange, dateRangeEnd);
var cost = stats.getCost();
var clicks = stats.getClicks();
var current_cpc = adGroup.bidding().getCpc();
var conversionValue = getAdGroupConversionValue(adGroup, dateRange, dateRangeEnd);
var costOfSales = cost / conversionValue;
max_cpc = getMaxCpcBid(current_cpc, conversionValue, clicks);
// If Aggressive bidding is set, only lower the bid if costOfSales is too high
if( AGGRESSIVE_BIDDING && costOfSales < MAX_COS ) {
max_cpc = Math.max(max_cpc, current_cpc);
}
adGroup.bidding().setCpc(max_cpc);
// Remove processing label even if no changes made, as the keyword
// is still performing well, so we don't want further back looking
// functions to reduce the bid
adGroup.removeLabel(LABEL_PROCESSING);
}
}
}
//
// Get the total Conversion Value for this adgroup and date range
//
function getAdGroupConversionValue(adGroup, dateRange, dateRangeEnd) {
var reportName = "ADGROUP_PERFORMANCE_REPORT";
if( adGroup.getEntityType == "ShoppingAdGroup") {
reportName = "SHOPPING_PERFORMANCE_REPORT";
}
var report = AdsApp.report(
"SELECT ConversionValue, Conversions " +
"FROM " + reportName + " " +
"WHERE AdGroupId = " + adGroup.getId() + " " +
"DURING " + dateRangeToString(dateRange, dateRangeEnd));
var convVals = report.rows();
if(convVals.hasNext()) {
var data = convVals.next();
var conversions = parseFloat(data.Conversions);
var conversionValue = parseFloat(data.ConversionValue.replace(',',''));
if( USE_ACTUAL_CONVERSION_VALUE ) {
return conversionValue;
} else {
return conversions * AVG_CONV_VALUE;
}
} else {
return 0
}
}
//
// Reset high cost AdGroups
//
function decreaseHighCostAdGroups(dateRange, dateRangeEnd) {
Logger.log('\nHigh Cost AdGroups : ' + dateRangeToString(dateRange, dateRangeEnd));
var adGroupTypes = [AdsApp.adGroups(), AdsApp.shoppingAdGroups()];
for (i = 0; i < adGroupTypes.length; i++) {
// Only process adGroups that have:
// - Less conversions than MIN_CONVERSIONS
// - Are marked for Processing
// - Have at least one click
// - And who have a high cost
var adGroupIterator = adGroupTypes[i]
.forDateRange(dateRange, dateRangeEnd)
.withCondition("Conversions < " + MIN_CONVERSIONS)
.withCondition("LabelNames CONTAINS_ANY ['" + LABEL_PROCESSING + "']")
.withCondition("Clicks > 0")
.withCondition("Cost > " + HIGH_COST_THRESHOLD)
.get();
Logger.log('Total adGroups found : ' + adGroupIterator.totalNumEntities());
while (adGroupIterator.hasNext()) {
var adGroup = adGroupIterator.next();
var stats = adGroup.getStatsFor(dateRange, dateRangeEnd);
var clicks = stats.getClicks();
var current_cpc = adGroup.bidding().getCpc();
// Add default value of a conversion, to calculate new max CPC optimistically that we
// might get an average conversion on the next click
var conversionValue = getAdGroupConversionValue(adGroup, dateRange, dateRangeEnd);
conversionValue = conversionValue + AVG_CONV_VALUE;
max_cpc = getMaxCpcBid(current_cpc, conversionValue, clicks);
if( max_cpc < current_cpc) {
adGroup.bidding().setCpc(max_cpc);
// Do not remove processing label. Give a chance for more data
// to increase the bid
//adGroup.removeLabel(LABEL_PROCESSING);
}
}
}
}
//
// Return Keyword or AdGroup Selector, filtered by Campaign filters
//
function getSelector(selector) {
var aSelector = selector
.withCondition("Status = ENABLED")
.withCondition("CampaignStatus = ENABLED")
.withCondition("AdGroupStatus = ENABLED");
if( TAG_INCLUDE.length > 0 ) {
aSelector = aSelector.withCondition("LabelNames CONTAINS_ALL ['" + TAG_INCLUDE + "']");
}
if( TAG_IGNORE.length > 0 ) {
aSelector = aSelector.withCondition("LabelNames CONTAINS_NONE ['" + TAG_IGNORE + "']");
}
if( CAMPAIGN_INCLUDE.length > 0 ) {
aSelector = aSelector.withCondition("CampaignName CONTAINS_IGNORE_CASE '" + CAMPAIGN_INCLUDE + "'");
}
if( CAMPAIGN_EXCLUDE.length > 0 ) {
aSelector = aSelector.withCondition("CampaignName DOES_NOT_CONTAIN_IGNORE_CASE '" + CAMPAIGN_EXCLUDE + "'");
}
return aSelector;
}
//
// Return the max COC bid based on the current bid, conversion value, and num clicks
//
function getMaxCpcBid(current_cpc, conversionValue, clicks)
{
var MaxBidIncreaseLimit = current_cpc + MAX_BID_INCREASE;
var ProfitMarginLimit = (conversionValue / clicks) * MAX_COS;
var maxCpcBid = Math.min(MaxBidIncreaseLimit, ProfitMarginLimit);
// Ensure bid is above 0.01 or MIN_BID
return Math.max(maxCpcBid, MIN_BID, 0.01);
}
//
// Date range helper functions
// Returns today's date.
//
function TODAY() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
return {year: yyyy, month: mm, day: dd};
}
//
// Date range helper functions
// Returns date 1 year ago
//
function LAST_YEAR() {
var today = TODAY();
today.year = today.year-1;
return today;
}
//
// Date range helper functions
// Returns date 90 days ago
//
function LAST_90_DAYS() {
var date = new Date();
date.setDate(date.getDate() - 90);
var dd = date.getDate();
var mm = date.getMonth()+1; //January is 0!
var yyyy = date.getFullYear();
return {year: yyyy, month: mm, day: dd};
}
//
// Date range helper function - Reports
// Returns a date range that will work in the DURING clause of the reporting query langugae
//
function dateRangeToString(dateRange, dateRangeEnd) {
if( dateRange == "LAST_7_DAYS" || dateRange == "LAST_14_DAYS" || dateRange == "LAST_30_DAYS") {
return dateRange;
} else {
return dateRange.year.toString() + ("0" + dateRange.month).slice(-2) + ("0" + dateRange.day).slice(-2) + ","
+ dateRangeEnd.year.toString() + ("0" + dateRangeEnd.month).slice(-2) + ("0" + dateRangeEnd.day).slice(-2);
}
}