Optimization Samples

The code samples below provide examples of common optimization functions using the AdWords API. Client Library.

Estimate keyword traffic

#!/usr/bin/env python
#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This example retrieves keyword traffic estimates.

The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
section of our README.

"""

from googleads import adwords


def main(client):
  # Initialize appropriate service.
  traffic_estimator_service = client.GetService(
      'TrafficEstimatorService', version='v201710')

  # Construct selector object and retrieve traffic estimates.
  keywords = [
      {'text': 'mars cruise', 'matchType': 'BROAD'},
      {'text': 'cheap cruise', 'matchType': 'PHRASE'},
      {'text': 'cruise', 'matchType': 'EXACT'}
  ]
  negative_keywords = [
      {'text': 'moon walk', 'matchType': 'BROAD'}
  ]
  keyword_estimate_requests = []
  for keyword in keywords:
    keyword_estimate_requests.append({
        'keyword': {
            'xsi_type': 'Keyword',
            'matchType': keyword['matchType'],
            'text': keyword['text']
        }
    })

  for keyword in negative_keywords:
    keyword_estimate_requests.append({
        'keyword': {
            'xsi_type': 'Keyword',
            'matchType': keyword['matchType'],
            'text': keyword['text']
        },
        'isNegative': 'true'
    })

  # Create ad group estimate requests.
  adgroup_estimate_requests = [{
      'keywordEstimateRequests': keyword_estimate_requests,
      'maxCpc': {
          'xsi_type': 'Money',
          'microAmount': '1000000'
      }
  }]

  # Create campaign estimate requests.
  campaign_estimate_requests = [{
      'adGroupEstimateRequests': adgroup_estimate_requests,
      'criteria': [
          {
              'xsi_type': 'Location',
              'id': '2840'  # United States.
          },
          {
              'xsi_type': 'Language',
              'id': '1000'  # English.
          }
      ],
  }]

  # Create the selector.
  selector = {
      'campaignEstimateRequests': campaign_estimate_requests,
  }

  # Optional: Request a list of campaign-level estimates segmented by
  # platform.
  selector['platformEstimateRequested'] = True

  # Get traffic estimates.
  estimates = traffic_estimator_service.get(selector)

  campaign_estimate = estimates['campaignEstimates'][0]

  # Display the campaign level estimates segmented by platform.
  if 'platformEstimates' in campaign_estimate:
    platform_template = ('Results for the platform with ID: "%d" and name: '
                         '"%s".')
    for platform_estimate in campaign_estimate['platformEstimates']:
      platform = platform_estimate['platform']
      DisplayEstimate(platform_template % (platform['id'],
                                           platform['platformName']),
                      platform_estimate['minEstimate'],
                      platform_estimate['maxEstimate'])

  # Display the keyword estimates.
  if 'adGroupEstimates' in campaign_estimate:
    ad_group_estimate = campaign_estimate['adGroupEstimates'][0]
    if 'keywordEstimates' in ad_group_estimate:
      keyword_estimates = ad_group_estimate['keywordEstimates']
      keyword_template = ('Results for the keyword with text "%s" and match '
                          'type "%s":')

      keyword_estimates_and_requests = zip(keyword_estimates,
                                           keyword_estimate_requests)

      for keyword_tuple in keyword_estimates_and_requests:
        if keyword_tuple[1].get('isNegative', False):
          continue
        keyword = keyword_tuple[1]['keyword']
        keyword_estimate = keyword_tuple[0]
        DisplayEstimate(keyword_template % (keyword['text'],
                                            keyword['matchType']),
                        keyword_estimate['min'], keyword_estimate['max'])


def _CalculateMean(min_est, max_est):
  if min_est and max_est:
    return (float(min_est) + float(max_est)) / 2.0
  else:
    return None


def _FormatMean(mean):
  if mean:
    return '%.2f' % mean
  else:
    return 'N/A'


def DisplayEstimate(message, min_estimate, max_estimate):
  """Displays mean average cpc, position, clicks, and total cost for estimate.

  Args:
    message: str message to display for the given estimate.
    min_estimate: sudsobject containing a minimum estimate from the
      TrafficEstimatorService response.
    max_estimate: sudsobject containing a maximum estimate from the
      TrafficEstimatorService response.
  """
  # Find the mean of the min and max values.
  mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'],
                                 max_estimate['averageCpc']['microAmount'])
                  if 'averageCpc' in min_estimate else None)
  mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'],
                                 max_estimate['averagePosition'])
                  if 'averagePosition' in min_estimate else None)
  mean_clicks = _CalculateMean(min_estimate['clicksPerDay'],
                               max_estimate['clicksPerDay'])
  mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'],
                                   max_estimate['totalCost']['microAmount'])

  print message
  print '  Estimated average CPC: %s' % _FormatMean(mean_avg_cpc)
  print '  Estimated ad position: %s' % _FormatMean(mean_avg_pos)
  print '  Estimated daily clicks: %s' % _FormatMean(mean_clicks)
  print '  Estimated daily cost: %s' % _FormatMean(mean_total_cost)


if __name__ == '__main__':
  # Initialize client object.
  adwords_client = adwords.AdWordsClient.LoadFromStorage()

  main(adwords_client)

Get campaign criterion bid modifier simulations

#!/usr/bin/env python
#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Gets all available campaign criterion bid modifier landscapes for a campaign.

To get campaigns, run basic_operations/get_campaigns.py.

The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
section of our README.

"""

from googleads import adwords


CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
PAGE_SIZE = 100


def main(client, campaign_id):
  # Initialize appropriate service.
  data_service = client.GetService('DataService', version='v201710')

  # Get all the campaigns for this account.
  selector = {
      'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate',
                 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions',
                 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions',
                 'RequiredBudget'],
      'paging': {
          'startIndex': 0,
          'numberResults': PAGE_SIZE
      },
      'predicates': [{
          'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id]
      }]
  }

  # Set initial values.
  offset = 0
  more_pages = True

  while more_pages is True:
    num_landscape_points = 0
    page = data_service.getCampaignCriterionBidLandscape(selector)

    # Display results.
    if 'entries' in page:
      for bid_modifier_landscape in page['entries']:
        num_landscape_points = 0
        print ('Found campaign-level criterion bid modifier landscapes for '
               'criterion with ID "%d", start date "%s", end date "%s", and '
               'landscape points:') % (bid_modifier_landscape['criterionId'],
                                       bid_modifier_landscape['startDate'],
                                       bid_modifier_landscape['endDate'])
        for landscape_point in bid_modifier_landscape['landscapePoints']:
          num_landscape_points += 1
          print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, '
                 'total clicks: %d, total cost: %d, total impressions: %d, '
                 'and required budget: %f') % (
                     landscape_point['bidModifier'], landscape_point['clicks'],
                     landscape_point['cost']['microAmount'],
                     landscape_point['impressions'],
                     landscape_point['totalLocalClicks'],
                     landscape_point['totalLocalCost']['microAmount'],
                     landscape_point['totalLocalImpressions'],
                     landscape_point['requiredBudget']['microAmount'])
    else:
      print 'No bid modifier landscapes found.'

    # Need to increment by the total # of landscape points within the page,
    # NOT the number of entries (bid landscapes) in the page.
    offset += num_landscape_points
    selector['paging']['startIndex'] = str(offset)
    more_pages = num_landscape_points >= PAGE_SIZE


if __name__ == '__main__':
  # Initialize client object.
  adwords_client = adwords.AdWordsClient.LoadFromStorage()

  main(adwords_client, CAMPAIGN_ID)

Get keyword bid simulations

#!/usr/bin/env python
#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This example gets a bid landscape for an ad group and a criterion.

To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py.

The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
section of our README.

"""

from googleads import adwords


AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
CRITERION_ID = 'INSERT_CRITERION_ID_HERE'
PAGE_SIZE = 100


def main(client, ad_group_id, criterion_id):
  # Initialize appropriate service.
  data_service = client.GetService('DataService', version='v201710')

  # Construct bid landscape selector object and retrieve bid landscape.
  selector = {
      'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid',
                 'LocalClicks', 'LocalCost', 'LocalImpressions'],
      'predicates': [
          {
              'field': 'AdGroupId',
              'operator': 'EQUALS',
              'values': [ad_group_id]
          },
          {
              'field': 'CriterionId',
              'operator': 'EQUALS',
              'values': [criterion_id]
          }
      ],
      'paging': {
          'startIndex': 0,
          'numberResults': PAGE_SIZE
      }
  }

  # Set initial values.
  offset = 0
  more_pages = True

  while more_pages:
    num_landscape_points = 0
    page = data_service.getCriterionBidLandscape(selector)

    if page and 'entries' in page:
      entries = page['entries']
      print 'Bid landscape(s) retrieved: %d.' % len(entries)

      for bid_landscape in entries:
        print ('Retrieved keyword bid landscape with ad group ID "%d", '
               'keyword ID "%d", start date "%s", end date "%s", '
               'with landscape points:' % (
                   bid_landscape['adGroupId'], bid_landscape['criterionId'],
                   bid_landscape['startDate'], bid_landscape['endDate']))
        for bid_landscape_point in bid_landscape['landscapePoints']:
          num_landscape_points += 1
          print ('  bid: %s => clicks: %s, cost: %s, impressions: %s'
                 % (bid_landscape_point['bid']['microAmount'],
                    bid_landscape_point['clicks'],
                    bid_landscape_point['cost']['microAmount'],
                    bid_landscape_point['impressions']))

    # Need to increment by the total # of landscape points within the page,
    # NOT the number of entries (bid landscapes) in the page.
    offset += num_landscape_points
    selector['paging']['startIndex'] = str(offset)
    more_pages = num_landscape_points >= PAGE_SIZE


if __name__ == '__main__':
  # Initialize client object.
  adwords_client = adwords.AdWordsClient.LoadFromStorage()

  main(adwords_client, AD_GROUP_ID, CRITERION_ID)

Get keyword ideas

#!/usr/bin/env python
#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This example retrieves keywords that are related to a given keyword.

The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
section of our README.

"""

from googleads import adwords


# Optional AdGroup ID used to set a SearchAdGroupIdSearchParameter.
AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'
PAGE_SIZE = 100


def main(client, ad_group_id=None):
  # Initialize appropriate service.
  targeting_idea_service = client.GetService(
      'TargetingIdeaService', version='v201710')

  # Construct selector object and retrieve related keywords.
  selector = {
      'ideaType': 'KEYWORD',
      'requestType': 'IDEAS'
  }

  selector['requestedAttributeTypes'] = [
      'KEYWORD_TEXT', 'SEARCH_VOLUME', 'CATEGORY_PRODUCTS_AND_SERVICES']

  offset = 0
  selector['paging'] = {
      'startIndex': str(offset),
      'numberResults': str(PAGE_SIZE)
  }

  selector['searchParameters'] = [{
      'xsi_type': 'RelatedToQuerySearchParameter',
      'queries': ['space cruise']
  }]

  # Language setting (optional).
  selector['searchParameters'].append({
      # The ID can be found in the documentation:
      # https://developers.google.com/adwords/api/docs/appendix/languagecodes
      'xsi_type': 'LanguageSearchParameter',
      'languages': [{'id': '1000'}]
  })

  # Network search parameter (optional)
  selector['searchParameters'].append({
      'xsi_type': 'NetworkSearchParameter',
      'networkSetting': {
          'targetGoogleSearch': True,
          'targetSearchNetwork': False,
          'targetContentNetwork': False,
          'targetPartnerSearchNetwork': False
      }
  })

  # Use an existing ad group to generate ideas (optional)
  if ad_group_id is not None:
    selector['searchParameters'].append({
        'xsi_type': 'SeedAdGroupIdSearchParameter',
        'adGroupId': ad_group_id
    })

  more_pages = True
  while more_pages:
    page = targeting_idea_service.get(selector)

    # Display results.
    if 'entries' in page:
      for result in page['entries']:
        attributes = {}
        for attribute in result['data']:
          attributes[attribute['key']] = getattr(
              attribute['value'], 'value', '0')
        print ('Keyword with "%s" text and average monthly search volume '
               '"%s" was found with Products and Services categories: %s.'
               % (attributes['KEYWORD_TEXT'],
                  attributes['SEARCH_VOLUME'],
                  attributes['CATEGORY_PRODUCTS_AND_SERVICES']))
      print
    else:
      print 'No related keywords were found.'
    offset += PAGE_SIZE
    selector['paging']['startIndex'] = str(offset)
    more_pages = offset < int(page['totalNumEntries'])


if __name__ == '__main__':
  # Initialize client object.
  adwords_client = adwords.AdWordsClient.LoadFromStorage()

  main(adwords_client, int(AD_GROUP_ID) if AD_GROUP_ID.isdigit() else None)

Send feedback about...

AdWords API
AdWords API
Need help? Visit our support page.