Java
// Copyright 2023 Google LLC // // 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 // // https://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. package com.google.ads.googleads.examples.planning; import com.beust.jcommander.Parameter; import com.google.ads.googleads.examples.utils.ArgumentNames; import com.google.ads.googleads.examples.utils.CodeSampleParams; import com.google.ads.googleads.lib.GoogleAdsClient; import com.google.ads.googleads.v18.common.DateRange; import com.google.ads.googleads.v18.common.KeywordInfo; import com.google.ads.googleads.v18.enums.KeywordMatchTypeEnum.KeywordMatchType; import com.google.ads.googleads.v18.enums.KeywordPlanNetworkEnum.KeywordPlanNetwork; import com.google.ads.googleads.v18.errors.GoogleAdsError; import com.google.ads.googleads.v18.errors.GoogleAdsException; import com.google.ads.googleads.v18.services.BiddableKeyword; import com.google.ads.googleads.v18.services.CampaignToForecast; import com.google.ads.googleads.v18.services.CampaignToForecast.CampaignBiddingStrategy; import com.google.ads.googleads.v18.services.CriterionBidModifier; import com.google.ads.googleads.v18.services.ForecastAdGroup; import com.google.ads.googleads.v18.services.GenerateKeywordForecastMetricsRequest; import com.google.ads.googleads.v18.services.GenerateKeywordForecastMetricsResponse; import com.google.ads.googleads.v18.services.KeywordForecastMetrics; import com.google.ads.googleads.v18.services.KeywordPlanIdeaServiceClient; import com.google.ads.googleads.v18.services.ManualCpcBiddingStrategy; import com.google.ads.googleads.v18.utils.ResourceNames; import java.io.FileNotFoundException; import java.io.IOException; import org.joda.time.DateTime; /** * Generates forecast metrics for keyword planning. * * <p>Guide: * https://developers.google.com/google-ads/api/docs/keyword-planning/generate-forecast-metrics */ public class GenerateForecastMetrics { private static class GenerateForecastMetricsParams extends CodeSampleParams { @Parameter(names = ArgumentNames.CUSTOMER_ID) public Long customerId; } public static void main(String[] args) { GenerateForecastMetricsParams params = new GenerateForecastMetricsParams(); if (!params.parseArguments(args)) { // Optional, specify the customer ID under which to create a new keyword plan. params.customerId = Long.valueOf("INSERT_CUSTOMER_ID"); } GoogleAdsClient googleAdsClient = null; try { googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build(); } catch (FileNotFoundException fnfe) { System.err.printf( "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe); System.exit(1); } catch (IOException ioe) { System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe); System.exit(1); } try { new GenerateForecastMetrics().runExample(googleAdsClient, params.customerId); } catch (GoogleAdsException gae) { // GoogleAdsException is the base class for most exceptions thrown by an API request. // Instances of this exception have a message and a GoogleAdsFailure that contains a // collection of GoogleAdsErrors that indicate the underlying causes of the // GoogleAdsException. System.err.printf( "Request ID %s failed due to GoogleAdsException. Underlying errors:%n", gae.getRequestId()); int i = 0; for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) { System.err.printf(" Error %d: %s%n", i++, googleAdsError); } System.exit(1); } } /** * Runs the code example. * * @param googleAdsClient the Google Ads API client. * @param customerId the client customer ID. */ private void runExample(GoogleAdsClient googleAdsClient, Long customerId) { CampaignToForecast campaignToForecast = createCampaignToForecast(googleAdsClient); GenerateKeywordForecastMetricsRequest request = GenerateKeywordForecastMetricsRequest.newBuilder() .setCustomerId(String.valueOf(customerId)) .setCampaign(campaignToForecast) .setForecastPeriod( DateRange.newBuilder() // Sets the forecast start date to tomorrow. .setStartDate(new DateTime().plusDays(1).toString("yyyy-MM-dd")) // Sets the forecast end date to 30 days from today. .setEndDate(new DateTime().plusDays(30).toString("yyyy-MM-dd"))) .build(); try (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = googleAdsClient.getLatestVersion().createKeywordPlanIdeaServiceClient()) { GenerateKeywordForecastMetricsResponse response = keywordPlanIdeaServiceClient.generateKeywordForecastMetrics(request); KeywordForecastMetrics metrics = response.getCampaignForecastMetrics(); System.out.printf( "Estimated daily clicks: %s%n", metrics.hasClicks() ? metrics.getClicks() : null); System.out.printf( "Estimated daily impressions: %s%n", metrics.hasImpressions() ? metrics.getImpressions() : null); System.out.printf( "Estimated average CPC (micros): %s%n", metrics.hasAverageCpcMicros() ? metrics.getAverageCpcMicros() : null); } } /** * Creates the campaign to forecast. A campaign to forecast lets you try out various * configurations and keywords to find the best optimization for your future campaigns. Once * you've found the best campaign configuration, create a serving campaign in your Google Ads * account with similar values and keywords. For more details, see: * * <p>https://support.google.com/google-ads/answer/3022575 * * @param googleAdsClient * @return */ private CampaignToForecast createCampaignToForecast(GoogleAdsClient googleAdsClient) { CampaignToForecast.Builder campaignToForecastBuilder = CampaignToForecast.newBuilder() .setKeywordPlanNetwork(KeywordPlanNetwork.GOOGLE_SEARCH) .setBiddingStrategy( CampaignBiddingStrategy.newBuilder() .setManualCpcBiddingStrategy( ManualCpcBiddingStrategy.newBuilder().setMaxCpcBidMicros(1_000_000L))); // See https://developers.google.com/google-ads/api/reference/data/geotargets for the list of // geo target IDs. campaignToForecastBuilder.addGeoModifiers( CriterionBidModifier.newBuilder() // Geo target constant 2840 is for USA. .setGeoTargetConstant(ResourceNames.geoTargetConstant(2840))); // See https://developers.google.com/google-ads/api/reference/data/codes-formats#languages for // the list of language criteria IDs. Language constant 1000 is for English. campaignToForecastBuilder.addLanguageConstants(ResourceNames.languageConstant(1000)); // Create forecast ad group based on themes such as creative relevance, product category, or // cost per click. ForecastAdGroup.Builder forecastAdGroupBuilder = ForecastAdGroup.newBuilder(); forecastAdGroupBuilder.addBiddableKeywords( BiddableKeyword.newBuilder() .setMaxCpcBidMicros(2_500_000) .setKeyword( KeywordInfo.newBuilder() .setText("mars cruise") .setMatchType(KeywordMatchType.BROAD))); forecastAdGroupBuilder.addBiddableKeywords( BiddableKeyword.newBuilder() .setMaxCpcBidMicros(1_500_000) .setKeyword( KeywordInfo.newBuilder() .setText("cheap cruise") .setMatchType(KeywordMatchType.PHRASE))); forecastAdGroupBuilder.addBiddableKeywords( BiddableKeyword.newBuilder() .setMaxCpcBidMicros(1_990_000) .setKeyword( KeywordInfo.newBuilder() .setText("jupiter cruise") .setMatchType(KeywordMatchType.BROAD))); forecastAdGroupBuilder.addNegativeKeywords( KeywordInfo.newBuilder().setText("moon walk").setMatchType(KeywordMatchType.BROAD)); campaignToForecastBuilder.addAdGroups(forecastAdGroupBuilder.build()); return campaignToForecastBuilder.build(); } }
C#
// Copyright 2023 Google LLC // // 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. using CommandLine; using Google.Ads.Gax.Examples; using Google.Ads.GoogleAds.Lib; using Google.Ads.GoogleAds.V18.Common; using Google.Ads.GoogleAds.V18.Errors; using Google.Ads.GoogleAds.V18.Resources; using Google.Ads.GoogleAds.V18.Services; using System; using static Google.Ads.GoogleAds.V18.Enums.KeywordMatchTypeEnum.Types; using static Google.Ads.GoogleAds.V18.Enums.KeywordPlanNetworkEnum.Types; namespace Google.Ads.GoogleAds.Examples.V18; /// <summary> /// This code example generates forecast metrics for keyword planning. /// Guide: https://developers.google.com/google-ads/api/docs/keyword-planning/generate-forecast-metrics /// </summary> public class GenerateForecastMetrics : ExampleBase { /// <summary> /// Command line options for running the <see cref="GenerateForecastMetrics"/> example. /// </summary> public class Options : OptionsBase { /// <summary> /// The customer ID for which the call is made. /// </summary> [Option("customerId", Required = true, HelpText = "The customer ID for which the call is made.")] public long CustomerId { get; set; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { Options options = ExampleUtilities.ParseCommandLine<Options>(args); GenerateForecastMetrics codeExample = new GenerateForecastMetrics(); Console.WriteLine(codeExample.Description); codeExample.Run(new GoogleAdsClient(), options.CustomerId); } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description => "This code example generates forecast metrics for keyword planning."; /// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The customer ID for which the call is made.</param> public void Run(GoogleAdsClient client, long customerId) { CampaignToForecast campaignToForecast = CreateCampaignToForecast(); KeywordPlanIdeaServiceClient keywordPlanIdeaService = client.GetService(Services.V18.KeywordPlanIdeaService); GenerateKeywordForecastMetricsRequest request = new GenerateKeywordForecastMetricsRequest() { CustomerId = customerId.ToString(), Campaign = campaignToForecast, ForecastPeriod = new DateRange() { // Set the forecast start date to tomorrow. StartDate = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"), // Set the forecast end date to 30 days from today. EndDate = DateTime.Now.AddDays(30).ToString("yyyy-MM-dd"), } }; try { GenerateKeywordForecastMetricsResponse response = keywordPlanIdeaService.GenerateKeywordForecastMetrics(request); KeywordForecastMetrics metrics = response.CampaignForecastMetrics; Console.WriteLine($"Estimated daily clicks: {metrics.Clicks}."); Console.WriteLine($"Estimated daily impressions: {metrics.Impressions}."); Console.WriteLine($"Estimated average cpc (micros): {metrics.AverageCpcMicros}."); } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } } /// <summary> /// Creates the campaign to forecast. A campaign to forecast lets you try out /// various configuration and keywords to find the best optimization for your /// future campaigns. Once you've found the best campaign configuration, /// create a serving campaign in your Google Ads account with similar values /// and keywords. For more details, see: /// https://support.google.com/google-ads/answer/3022575 /// </summary> private CampaignToForecast CreateCampaignToForecast() { CampaignToForecast campaignToForecast = new CampaignToForecast() { KeywordPlanNetwork = KeywordPlanNetwork.GoogleSearch, BiddingStrategy = new CampaignToForecast.Types.CampaignBiddingStrategy() { ManualCpcBiddingStrategy = new ManualCpcBiddingStrategy() { MaxCpcBidMicros = 1_000_000 } } }; // See https://developers.google.com/google-ads/api/reference/data/geotargets // for the list of geo target IDs. campaignToForecast.GeoModifiers.Add(new CriterionBidModifier() { // Geo target constant 2840 is for USA. GeoTargetConstant = ResourceNames.GeoTargetConstant(2840) }); // See https://developers.google.com/google-ads/api/reference/data/codes-formats#languages // for the list of language criteria IDs. // Language constant 1000 is for English. campaignToForecast.LanguageConstants.Add(ResourceNames.LanguageConstant(1000)); // Create forecast ad group based on themes such as creative relevance, product category, // or cost per click. ForecastAdGroup forecastAdGroup = new ForecastAdGroup(); forecastAdGroup.BiddableKeywords.Add(new BiddableKeyword() { MaxCpcBidMicros = 2_500_000, Keyword = new KeywordInfo() { Text = "mars cruise", MatchType = KeywordMatchType.Broad } }); forecastAdGroup.BiddableKeywords.Add(new BiddableKeyword() { MaxCpcBidMicros = 1_500_000, Keyword = new KeywordInfo() { Text = "cheap cruise", MatchType = KeywordMatchType.Phrase } }); forecastAdGroup.BiddableKeywords.Add(new BiddableKeyword() { MaxCpcBidMicros = 1_990_000, Keyword = new KeywordInfo() { Text = "jupiter cruise", MatchType = KeywordMatchType.Broad } }); forecastAdGroup.NegativeKeywords.Add(new KeywordInfo() { Text = "moon walk", MatchType = KeywordMatchType.Broad }); campaignToForecast.AdGroups.Add(forecastAdGroup); return campaignToForecast; } }
PHP
<?php /** * Copyright 2023 Google LLC * * 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 * * https://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. */ namespace Google\Ads\GoogleAds\Examples\Planning; require __DIR__ . '/../../vendor/autoload.php'; use GetOpt\GetOpt; use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames; use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser; use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder; use Google\Ads\GoogleAds\Lib\V18\GoogleAdsClient; use Google\Ads\GoogleAds\Lib\V18\GoogleAdsClientBuilder; use Google\Ads\GoogleAds\Lib\V18\GoogleAdsException; use Google\Ads\GoogleAds\Util\V18\ResourceNames; use Google\Ads\GoogleAds\V18\Common\DateRange; use Google\Ads\GoogleAds\V18\Common\KeywordInfo; use Google\Ads\GoogleAds\V18\Enums\KeywordMatchTypeEnum\KeywordMatchType; use Google\Ads\GoogleAds\V18\Enums\KeywordPlanNetworkEnum\KeywordPlanNetwork; use Google\Ads\GoogleAds\V18\Errors\GoogleAdsError; use Google\Ads\GoogleAds\V18\Services\BiddableKeyword; use Google\Ads\GoogleAds\V18\Services\CampaignToForecast; use Google\Ads\GoogleAds\V18\Services\CampaignToForecast\CampaignBiddingStrategy; use Google\Ads\GoogleAds\V18\Services\CriterionBidModifier; use Google\Ads\GoogleAds\V18\Services\ForecastAdGroup; use Google\Ads\GoogleAds\V18\Services\GenerateKeywordForecastMetricsRequest; use Google\Ads\GoogleAds\V18\Services\ManualCpcBiddingStrategy; use Google\ApiCore\ApiException; /** * Generates forecast metrics for keyword planning. * * Guide: * https://developers.google.com/google-ads/api/docs/keyword-planning/generate-forecast-metrics */ class GenerateForecastMetrics { private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE'; public static function main() { // Either pass the required parameters for this example on the command line, or insert them // into the constants above. $options = (new ArgumentParser())->parseCommandArguments([ ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT ]); // Generate a refreshable OAuth2 credential for authentication. $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build(); // Construct a Google Ads client configured from a properties file and the // OAuth2 credentials above. $googleAdsClient = (new GoogleAdsClientBuilder())->fromFile() ->withOAuth2Credential($oAuth2Credential) ->build(); try { self::runExample( $googleAdsClient, $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID ); } catch (GoogleAdsException $googleAdsException) { printf( "Request with ID '%s' has failed.%sGoogle Ads failure details:%s", $googleAdsException->getRequestId(), PHP_EOL, PHP_EOL ); foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) { /** @var GoogleAdsError $error */ printf( "\t%s: %s%s", $error->getErrorCode()->getErrorCode(), $error->getMessage(), PHP_EOL ); } exit(1); } catch (ApiException $apiException) { printf( "ApiException was thrown with message '%s'.%s", $apiException->getMessage(), PHP_EOL ); exit(1); } } /** * Runs the example. * * @param GoogleAdsClient $googleAdsClient the Google Ads API client * @param int $customerId the customer ID */ public static function runExample( GoogleAdsClient $googleAdsClient, int $customerId ): void { $campaignToForecast = self::createCampaignToForecast(); $keywordPlanIdeaServiceClient = $googleAdsClient->getKeywordPlanIdeaServiceClient(); // Generates keyword forecast metrics based on the specified parameters. $response = $keywordPlanIdeaServiceClient->generateKeywordForecastMetrics( new GenerateKeywordForecastMetricsRequest([ 'customer_id' => $customerId, 'campaign' => $campaignToForecast, 'forecast_period' => new DateRange([ // Sets the forecast start date to tomorrow. 'start_date' => date('Ymd', strtotime('+1 day')), // Sets the forecast end date to 30 days from today. 'end_date' => date('Ymd', strtotime('+30 days')) ]) ]) ); $metrics = $response->getCampaignForecastMetrics(); printf( "Estimated daily clicks: %s%s", $metrics->hasClicks() ? sprintf("%.2f", $metrics->getClicks()) : "'none'", PHP_EOL ); printf( "Estimated daily impressions: %s%s", $metrics->hasImpressions() ? sprintf("%.2f", $metrics->getImpressions()) : "'none'", PHP_EOL ); printf( "Estimated average CPC (micros): %s%s", $metrics->hasAverageCpcMicros() ? sprintf("%d", $metrics->getAverageCpcMicros()) : "'none'", PHP_EOL ); } /** * Creates the campaign to forecast. A campaign to forecast lets you try out various * configurations and keywords to find the best optimization for your future campaigns. Once * you've found the best campaign configuration, create a serving campaign in your Google Ads * account with similar values and keywords. For more details, see: * * https://support.google.com/google-ads/answer/3022575 * * @return CampaignToForecast the created campaign to forecast */ private static function createCampaignToForecast(): CampaignToForecast { // Creates a campaign to forecast. $campaignToForecast = new CampaignToForecast([ 'keyword_plan_network' => KeywordPlanNetwork::GOOGLE_SEARCH, 'bidding_strategy' => new CampaignBiddingStrategy([ 'manual_cpc_bidding_strategy' => new ManualCpcBiddingStrategy([ 'max_cpc_bid_micros' => 1_000_000 ]) ]), // See https://developers.google.com/google-ads/api/reference/data/geotargets for the // list of geo target IDs. 'geo_modifiers' => [ new CriterionBidModifier([ // Geo target constant 2840 is for USA. 'geo_target_constant' => ResourceNames::forGeoTargetConstant(2840) ]) ], // See // https://developers.google.com/google-ads/api/reference/data/codes-formats#languages // for the list of language criteria IDs. Language constant 1000 is for English. 'language_constants' => [ResourceNames::forLanguageConstant(1000)], ]); // Creates forecast ad group based on themes such as creative relevance, product category, // or cost per click. $forecastAdGroup = new ForecastAdGroup([ 'biddable_keywords' => [ new BiddableKeyword([ 'max_cpc_bid_micros' => 2_500_000, 'keyword' => new KeywordInfo([ 'text' => 'mars cruise', 'match_type' => KeywordMatchType::BROAD ]) ]), new BiddableKeyword([ 'max_cpc_bid_micros' => 1_500_000, 'keyword' => new KeywordInfo([ 'text' => 'cheap cruise', 'match_type' => KeywordMatchType::PHRASE ]) ]), new BiddableKeyword([ 'max_cpc_bid_micros' => 1_990_000, 'keyword' => new KeywordInfo([ 'text' => 'jupiter cruise', 'match_type' => KeywordMatchType::BROAD ]) ]) ], 'negative_keywords' => [ new KeywordInfo([ 'text' => 'moon walk', 'match_type' => KeywordMatchType::BROAD ]) ] ]); $campaignToForecast->setAdGroups([$forecastAdGroup]); return $campaignToForecast; } } GenerateForecastMetrics::main();
Python
#!/usr/bin/env python # Copyright 2023 Google LLC # # 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 # # https://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 generates forecast metrics for keyword planning. For more details see this guide: https://developers.google.com/google-ads/api/docs/keyword-planning/generate-forecast-metrics """ import argparse from datetime import datetime, timedelta import sys from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads.errors import GoogleAdsException def main(client, customer_id): """The main method that creates all necessary entities for the example. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID. """ campaign_to_forecast = create_campaign_to_forecast(client) generate_forecast_metrics(client, customer_id, campaign_to_forecast) def create_campaign_to_forecast(client): """Creates the campaign to forecast. A campaign to forecast lets you try out various configurations and keywords to find the best optimization for your future campaigns. Once you've found the best campaign configuration, create a serving campaign in your Google Ads account with similar values and keywords. For more details, see: https://support.google.com/google-ads/answer/3022575 Args: client: an initialized GoogleAdsClient instance. Returns: An CampaignToForecast instance. """ googleads_service = client.get_service("GoogleAdsService") # Create a campaign to forecast. campaign_to_forecast = client.get_type("CampaignToForecast") campaign_to_forecast.keyword_plan_network = ( client.enums.KeywordPlanNetworkEnum.GOOGLE_SEARCH ) # Set the bidding strategy. campaign_to_forecast.bidding_strategy.manual_cpc_bidding_strategy.max_cpc_bid_micros = ( 1000000 ) # For the list of geo target IDs, see: # https://developers.google.com/google-ads/api/reference/data/geotargets criterion_bid_modifier = client.get_type("CriterionBidModifier") # Geo target constant 2840 is for USA. criterion_bid_modifier.geo_target_constant = ( googleads_service.geo_target_constant_path("2840") ) campaign_to_forecast.geo_modifiers.append(criterion_bid_modifier) # For the list of language criteria IDs, see: # https://developers.google.com/google-ads/api/reference/data/codes-formats#languages # Language criteria 1000 is for English. campaign_to_forecast.language_constants.append( googleads_service.language_constant_path("1000") ) # Create forecast ad groups based on themes such as creative relevance, # product category, or cost per click. forecast_ad_group = client.get_type("ForecastAdGroup") # Create and configure three BiddableKeyword instances. biddable_keyword_1 = client.get_type("BiddableKeyword") biddable_keyword_1.max_cpc_bid_micros = 2500000 biddable_keyword_1.keyword.text = "mars cruise" biddable_keyword_1.keyword.match_type = ( client.enums.KeywordMatchTypeEnum.BROAD ) biddable_keyword_2 = client.get_type("BiddableKeyword") biddable_keyword_2.max_cpc_bid_micros = 1500000 biddable_keyword_2.keyword.text = "cheap cruise" biddable_keyword_2.keyword.match_type = ( client.enums.KeywordMatchTypeEnum.PHRASE ) biddable_keyword_3 = client.get_type("BiddableKeyword") biddable_keyword_3.max_cpc_bid_micros = 1990000 biddable_keyword_3.keyword.text = "cheap cruise" biddable_keyword_3.keyword.match_type = ( client.enums.KeywordMatchTypeEnum.EXACT ) # Add the biddable keywords to the forecast ad group. forecast_ad_group.biddable_keywords.extend( [biddable_keyword_1, biddable_keyword_2, biddable_keyword_3] ) # Create and configure a negative keyword, then add it to the forecast ad # group. negative_keyword = client.get_type("KeywordInfo") negative_keyword.text = "moon walk" negative_keyword.match_type = client.enums.KeywordMatchTypeEnum.BROAD forecast_ad_group.negative_keywords.append(negative_keyword) campaign_to_forecast.ad_groups.append(forecast_ad_group) return campaign_to_forecast def generate_forecast_metrics(client, customer_id, campaign_to_forecast): """Generates forecast metrics and prints the results. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID. campaign_to_forecast: a CampaignToForecast to generate metrics for. """ keyword_plan_idea_service = client.get_service("KeywordPlanIdeaService") request = client.get_type("GenerateKeywordForecastMetricsRequest") request.customer_id = customer_id request.campaign = campaign_to_forecast # Set the forecast range. Repeat forecasts with different horizons to get a # holistic picture. # Set the forecast start date to tomorrow. tomorrow = datetime.now() + timedelta(days=1) request.forecast_period.start_date = tomorrow.strftime("%Y-%m-%d") # Set the forecast end date to 30 days from today. thirty_days_from_now = datetime.now() + timedelta(days=30) request.forecast_period.end_date = thirty_days_from_now.strftime("%Y-%m-%d") response = keyword_plan_idea_service.generate_keyword_forecast_metrics( request=request ) metrics = response.campaign_forecast_metrics print(f"Estimated daily clicks: {metrics.clicks}") print(f"Estimated daily impressions: {metrics.impressions}") print(f"Estimated daily average CPC: {metrics.average_cpc_micros}") if __name__ == "__main__": parser = argparse.ArgumentParser( description="Generates forecast metrics for keyword planning." ) # The following argument(s) should be provided to run the example. parser.add_argument( "-c", "--customer_id", type=str, required=True, help="The Google Ads customer ID.", ) args = parser.parse_args() # GoogleAdsClient will read the google-ads.yaml configuration file in the # home directory if none is specified. googleads_client = GoogleAdsClient.load_from_storage(version="v18") try: main(googleads_client, args.customer_id) except GoogleAdsException as ex: print( f'Request with ID "{ex.request_id}" failed with status ' f'"{ex.error.code().name}" and includes the following errors:' ) for error in ex.failure.errors: print(f'Error with message "{error.message}".') if error.location: for field_path_element in error.location.field_path_elements: print(f"\t\tOn field: {field_path_element.field_name}") sys.exit(1)
Ruby
#!/usr/bin/env ruby # Encoding: utf-8 # # Copyright 2019 Google LLC # # 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 # # https://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 generates forecast metrics for keyword planning. # # For more details see this guide: # https://developers.google.com/google-ads/api/docs/keyword-planning/generate-forecast-metrics require 'optparse' require 'google/ads/google_ads' require 'date' def generate_forecast_metrics(customer_id) # GoogleAdsClient will read a config file from # ENV['HOME']/google_ads_config.rb when called without parameters client = Google::Ads::GoogleAds::GoogleAdsClient.new campaign_to_forecast = create_campaign_to_forecast(client) # Generates forecast metrics and prints the results. keyword_plan_idea_service = client.service.keyword_plan_idea # Set the forecast range. Repeat forecasts with different horizons to get a # holistic picture. forecast_period = client.resource.date_range do |p| tomorrow = Date.today + 1 p.start_date = tomorrow.strftime("%Y-%m-%d") # Set the forecast end date to 30 days from today. thirty_days_from_now = Date.today + 30 p.end_date = thirty_days_from_now.strftime("%Y-%m-%d") end response = keyword_plan_idea_service.generate_keyword_forecast_metrics( customer_id: customer_id, campaign: campaign_to_forecast, forecast_period: forecast_period, ) metrics = response.campaign_forecast_metrics puts "Estimated daily clicks: #{metrics.clicks}" puts "Estimated daily impressions: #{metrics.impressions}" puts "Estimated daily average CPC: #{metrics.average_cpc_micros}" end def create_campaign_to_forecast(client) campaign_to_forecast = client.resource.campaign_to_forecast do |c| c.keyword_plan_network = :GOOGLE_SEARCH c.bidding_strategy = client.resource.campaign_bidding_strategy do |bs| bs.manual_cpc_bidding_strategy = client.resource.manual_cpc_bidding_strategy do |mbs| mbs.max_cpc_bid_micros = 1000000 end end criterion_bid_modifier = client.resource.criterion_bid_modifier # For the list of geo target IDs, see: # https://developers.google.com/google-ads/api/reference/data/geotargets # Geo target constant 2840 is for USA. criterion_bid_modifier.geo_target_constant = client.path.geo_target_constant("2840") c.geo_modifiers << criterion_bid_modifier # For the list of language criteria IDs, see: # https://developers.google.com/google-ads/api/reference/data/codes-formats#languages # Language criteria 1000 is for English. language_constant = client.path.language_constant("1000") # English c.language_constants << language_constant # Create forecast ad groups based on themes such as creative relevance, # product category, or cost per click. forecast_ad_group = client.resource.forecast_ad_group biddable_keyword_1 = client.resource.biddable_keyword do |bk| bk.max_cpc_bid_micros = 1500000 bk.keyword = client.resource.keyword_info do |k| k.text = "mars cruise" k.match_type = :BROAD end end biddable_keyword_2 = client.resource.biddable_keyword do |bk| bk.max_cpc_bid_micros = 2500000 bk.keyword = client.resource.keyword_info do |k| k.text = "cheap cruise" k.match_type = :PHRASE end end biddable_keyword_3 = client.resource.biddable_keyword do |bk| bk.max_cpc_bid_micros = 1990000 bk.keyword = client.resource.keyword_info do |k| k.text = "cheap cruise" k.match_type = :EXACT end end forecast_ad_group.biddable_keywords << biddable_keyword_1 forecast_ad_group.biddable_keywords << biddable_keyword_2 forecast_ad_group.biddable_keywords << biddable_keyword_3 # Create and configure a negative keyword, then add it to the forecast ad # group. negative_keyword = client.resource.keyword_info do |k| k.text = "moon walk" k.match_type = :BROAD end forecast_ad_group.negative_keywords << negative_keyword c.ad_groups << forecast_ad_group end return campaign_to_forecast end if __FILE__ == $0 options = {} # The following parameter(s) should be provided to run the example. You can # either specify these by changing the INSERT_XXX_ID_HERE values below, or on # the command line. # # Parameters passed on the command line will override any parameters set in # code. # # Running the example with -h will print the command line usage. options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE' OptionParser.new do |opts| opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__)) opts.separator '' opts.separator 'Options:' opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v| options[:customer_id] = v end opts.separator '' opts.separator 'Help:' opts.on_tail('-h', '--help', 'Show this message') do puts opts exit end end.parse! begin generate_forecast_metrics(options.fetch(:customer_id).tr("-", "")) rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e e.failure.errors.each do |error| STDERR.printf("Error with message: %s\n", error.message) if error.location error.location.field_path_elements.each do |field_path_element| STDERR.printf("\tOn field: %s\n", field_path_element.field_name) end end error.error_code.to_h.each do |k, v| next if v == :UNSPECIFIED STDERR.printf("\tType: %s\n\tCode: %s\n", k, v) end end raise end end
Perl
#!/usr/bin/perl -w # # Copyright 2023, Google LLC # # 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 generates forecast metrics for keyword planning. # Guide: https://developers.google.com/google-ads/api/docs/keyword-planning/generate-forecast-metrics use strict; use warnings; use utf8; use FindBin qw($Bin); use lib "$Bin/../../lib"; use Google::Ads::GoogleAds::Client; use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; use Google::Ads::GoogleAds::V18::Common::DateRange; use Google::Ads::GoogleAds::V18::Common::KeywordInfo; use Google::Ads::GoogleAds::V18::Services::KeywordPlanIdeaService::BiddableKeyword; use Google::Ads::GoogleAds::V18::Services::KeywordPlanIdeaService::CampaignToForecast; use Google::Ads::GoogleAds::V18::Services::KeywordPlanIdeaService::CriterionBidModifier; use Google::Ads::GoogleAds::V18::Services::KeywordPlanIdeaService::ForecastAdGroup; use Google::Ads::GoogleAds::V18::Services::KeywordPlanIdeaService::ManualCpcBiddingStrategy; use Google::Ads::GoogleAds::V18::Utils::ResourceNames; use Getopt::Long qw(:config auto_help); use Pod::Usage; use Cwd qw(abs_path); use POSIX qw(strftime); sub generate_forecast_metrics { my ($api_client, $customer_id) = @_; my $campaign_to_forecast = create_campaign_to_forecast(); my $keyword_forecast_metrics_response = $api_client->KeywordPlanIdeaService()->generate_keyword_forecast_metrics({ customerId => $customer_id, campaign => $campaign_to_forecast, # Set the forecast range. Repeat forecasts with different horizons # to get a holistic picture. forecastPeriod => Google::Ads::GoogleAds::V18::Common::DateRange->new({ # Set the forecast start date to tomorrow. startDate => strftime("%Y-%m-%d", localtime(time + 60 * 60 * 24)), # Set the forecast end date to 30 days from today. endDate => strftime("%Y-%m-%d", localtime(time + 60 * 60 * 24 * 30))}) }); my $metrics = $keyword_forecast_metrics_response->{campaignForecastMetrics}; printf "Estimated daily clicks: %s.\n", defined $metrics->{clicks} ? $metrics->{clicks} : "undef"; printf "Estimated daily impressions: %s.\n", defined $metrics->{impressions} ? $metrics->{impressions} : "undef"; printf "Estimated average cpc (micros): %s.\n\n", defined $metrics->{averageCpcMicros} ? $metrics->{averageCpcMicros} : "undef"; return 1; } # Creates the campaign to forecast. A campaign to forecast lets you try out # various configuration and keywords to find the best optimization for your # future campaigns. Once you've found the best campaign configuration, # create a serving campaign in your Google Ads account with similar values # and keywords. For more details, see: # https://support.google.com/google-ads/answer/3022575 sub create_campaign_to_forecast { my ($api_client) = @_; # Create a campaign to forecast. my $campaign_to_forecast = Google::Ads::GoogleAds::V18::Services::KeywordPlanIdeaService::CampaignToForecast ->new({keywordPlanNetwork => 'GOOGLE_SEARCH'}); # Set the bidding strategy. $campaign_to_forecast->{biddingStrategy}->{manualCpcBiddingStrategy} = Google::Ads::GoogleAds::V18::Services::KeywordPlanIdeaService::ManualCpcBiddingStrategy ->new({maxCpcBidMicros => 1000000}); # See https://developers.google.com/google-ads/api/reference/data/geotargets # for the list of geo target IDs. $campaign_to_forecast->{geoModifiers} = [ Google::Ads::GoogleAds::V18::Services::KeywordPlanIdeaService::CriterionBidModifier ->new({ # Geo target constant 2840 is for USA. geoTargetConstant => Google::Ads::GoogleAds::V18::Utils::ResourceNames::geo_target_constant( 2840)})]; # See https://developers.google.com/google-ads/api/reference/data/codes-formats#languages # for the list of language criteria IDs. $campaign_to_forecast->{languageConstants} = [ # Language criteria 1000 is for English. Google::Ads::GoogleAds::V18::Utils::ResourceNames::language_constant(1000)]; # Create forecast ad groups based on themes such as creative relevance, # product category, or cost per click. $campaign_to_forecast->{adGroups} = [ Google::Ads::GoogleAds::V18::Services::KeywordPlanIdeaService::ForecastAdGroup ->new({ biddableKeywords => [ Google::Ads::GoogleAds::V18::Services::KeywordPlanIdeaService::BiddableKeyword ->new({ maxCpcBidMicros => 2500000, keyword => Google::Ads::GoogleAds::V18::Common::KeywordInfo->new({ text => "mars cruise", matchType => 'BROAD' })} ), Google::Ads::GoogleAds::V18::Services::KeywordPlanIdeaService::BiddableKeyword ->new({ maxCpcBidMicros => 1500000, keyword => Google::Ads::GoogleAds::V18::Common::KeywordInfo->new({ text => "cheap cruise", matchType => 'PHRASE' })} ), Google::Ads::GoogleAds::V18::Services::KeywordPlanIdeaService::BiddableKeyword ->new({ maxCpcBidMicros => 1990000, keyword => Google::Ads::GoogleAds::V18::Common::KeywordInfo->new({ text => "jupiter cruise", matchType => 'EXACT' })}) ], negativeKeywords => [ Google::Ads::GoogleAds::V18::Common::KeywordInfo->new({ text => "moon walk", matchType => 'BROAD' })]})]; return $campaign_to_forecast; } # Don't run the example if the file is being included. if (abs_path($0) ne abs_path(__FILE__)) { return 1; } # Get Google Ads Client, credentials will be read from ~/googleads.properties. my $api_client = Google::Ads::GoogleAds::Client->new(); # By default examples are set to die on any server returned fault. $api_client->set_die_on_faults(1); my $customer_id = undef; # Parameters passed on the command line will override any parameters set in code. GetOptions("customer_id=s" => \$customer_id); # Print the help message if the parameters are not initialized in the code nor # in the command line. pod2usage(2) if not check_params($customer_id); # Call the example. generate_forecast_metrics($api_client, $customer_id =~ s/-//gr); =pod =head1 NAME generate_forecast_metrics =head1 DESCRIPTION This example generates forecast metrics for a campaign forecast. =head1 SYNOPSIS generate_forecast_metrics.pl [options] -help Show the help message. -customer_id The Google Ads customer ID. =cut