Python GAQL Script for Negative Keywords: Prune Broad Tails

Learn how to build a Python GAQL script to extract search terms, detect wasteful 4-word broad match tails, and automatically exclude negative keywords.

By AdTurbo Team · 2026-10-11

Broad match keyword expansion in Google Ads relies heavily on Smart Bidding to locate incremental query volume. However, modern broad match frequently captures multi-word informational tails, irrelevant location qualifiers, job searches, and peripheral user intent that burn budget long before Smart Bidding registers enough statistical signal to adjust downward. Manually running Search Query Reports (SQRs) every Friday inside the Google Ads web UI quickly becomes unsustainable across multiple campaigns or client accounts.

Building an automated programmatic pipeline allows you to query the Google Ads API using Google Ads Query Language (GAQL), analyze query string tokens using an n-gram tokenizer, calculate statistical non-conversion thresholds, and upload account-level or campaign-level negative keywords without manual UI interaction.

This technical guide breaks down the full workflow to construct a production-ready Python GAQL script that identifies non-converting 4-word broad match tails and auto-excludes them.

---

Understanding the Broad Match Query Tail Problem in GAQL

When you target broad match keywords, the Google Ads matching engine evaluates user queries against semantic signals rather than exact syntactic matches. While this captures high-converting novel queries, it routinely captures long, four-to-six-word phrase fragments that dilute relevance.

The Anatomy of Wasteful 4-Word Tails

Consider an enterprise SaaS company selling accounting software bidding on the broad keyword enterprise accounting software. The query matching engine might match:

• enterprise accounting software for college student projects

• how to build enterprise accounting software from scratch

• enterprise accounting software open source github free

• enterprise accounting software salary requirements reddit

Every one of these search queries contains a 4-word tail (for college student projects, from scratch, open source github free, salary requirements reddit) that signals non-commercial intent. Because broad match spreads spend across thousands of distinct individual queries, each specific tail might only accrue 1–3 clicks per month. If you evaluate queries strictly on a standalone exact-match basis in the UI, none of them individually cross your threshold for manual exclusion.

The N-Gram Aggregation Solution

By aggregating your search terms into distinct token sequences (specifically 4-grams and 3-grams) via Python, you can aggregate the clicks, impressions, and cost across every query containing those specific phrases. That single aggregate view reveals that while salary requirements reddit only spent $8, all combinations containing salary or reddit accumulated $850 with zero conversions.

Reviewing our search terms report guide highlights why manual spot-checking fails: statistical fragmentation conceals aggregate budget waste.

---

Setting Up the Google Ads Python SDK and Authentication

To interact programmatically with your Google Ads account, you need access to the Google Ads API and a working authentication profile configured in Python.

Prerequisites

1. Google Cloud Platform Project: Create a project in the GCP Console and enable the Google Ads API.

2. OAuth 2.0 Credentials: Generate an OAuth Client ID and Client Secret configured as a Desktop App.

3. Developer Token: Obtain a basic or standard access developer token from your Google Ads Manager Account (MCC).

4. Refresh Token: Run the official Google Ads Python authorization script (authenticateindesktopapplication.py) to generate a persistent refresh token.

Configuration File: google-ads.yaml

Store your credentials in a standard YAML configuration file. Place this file in your root project directory or home folder (~/google-ads.yaml):

yaml

developertoken: "INSERTDEVELOPERTOKENHERE"

clientid: "INSERTCLIENTID.apps.googleusercontent.com"

clientsecret: "INSERTCLIENTSECRET"

refreshtoken: "INSERTREFRESHTOKEN"

useprotoplus: true

logincustomerid: "INSERTMCCACCOUNTIDWITHOUTHYPHENS"

Environment Initialization

Install the required Python packages in your virtual environment:

bash

pip install google-ads pandas nltk

Initialize the client in your script:

python

import sys

from google.ads.googleads.client import GoogleAdsClient

from google.ads.googleads.errors import GoogleAdsException

def initgoogleadsclient(configpath="google-ads.yaml") - GoogleAdsClient:

try:

return GoogleAdsClient.loadfromstorage(configpath)

except Exception as exc:

sys.exit(f"Failed to initialize Google Ads Client: {exc}")

---

Extracting Search Terms with GAQL (searchtermview)

Google Ads Query Language (GAQL) is SQL-like syntax used to query the Google Ads API. To extract raw search queries alongside core performance metrics and the triggering positive keyword, we query the searchtermview resource joined with segments and metrics.

Constructing the GAQL Extraction Query

sql

SELECT

searchtermview.searchterm,

searchtermview.status,

campaign.id,

campaign.name,

adgroup.id,

adgroup.name,

adgroupcriterion.keyword.text.value,

adgroupcriterion.keyword.matchtype,

metrics.impressions,

metrics.clicks,

metrics.costmicros,

metrics.conversions,

metrics.conversionsvalue

FROM searchtermview

WHERE

segments.date DURING LAST30DAYS

AND metrics.clicks 0

AND adgroupcriterion.keyword.matchtype = 'BROAD'

ORDER BY metrics.costmicros DESC

Executing the Query in Python

Let's write a dedicated extractor function using the GoogleAdsService to load the results into a clean Pandas DataFrame:

python

import pandas as pd

def fetchbroadsearchterms(client: GoogleAdsClient, customerid: str) - pd.DataFrame:

gaservice = client.getservice("GoogleAdsService")

query = """

SELECT

searchtermview.searchterm,

campaign.id,

campaign.name,

adgroup.id,

adgroupcriterion.keyword.text.value,

metrics.impressions,

metrics.clicks,

metrics.costmicros,

metrics.conversions

FROM searchtermview

WHERE

segments.date DURING LAST30DAYS

AND metrics.clicks 0

AND adgroupcriterion.keyword.matchtype = 'BROAD'

"""

searchrequest = client.gettype("SearchGoogleAdsStreamRequest")

searchrequest.customerid = customerid

searchrequest.query = query

stream = gaservice.searchstream(searchrequest)

records = []

for batch in stream:

for row in batch.results:

records.append({

"campaignid": row.campaign.id,

"campaignname": row.campaign.name,

"adgroupid": row.adgroup.id,

"triggeringkeyword": row.adgroupcriterion.keyword.text.value,

"searchterm": row.searchtermview.searchterm.lower().strip(),

"impressions": row.metrics.impressions,

"clicks": row.metrics.clicks,

"cost": row.metrics.costmicros / 1000000.0,

"conversions": row.metrics.conversions

})

df = pd.DataFrame(records)

return df

Notice that costmicros is divided by 1,000,000 to convert the micro-currency integer into standard currency units (e.g., USD or EUR). If your account suffers from broader structural cost issues, read our breakdown on why Google Ads is so expensive to balance keyword hygiene against bid structure.

---

Algorithmic Detection: Mining Non-Converting 4-Word Tails

Once raw search terms are stored in a Pandas DataFrame, the next stage is n-gram tokenization. An n-gram is a contiguous sequence of n items from a given sample of text. A 4-gram captures recurring 4-word phrasing across distinct search terms.

The N-Gram Parsing Pipeline

We break down queries that contain 4 or more words into rolling windows of four consecutive words, map their collective performance metrics, and surface tails that consistently fail to convert.

python

import re

from collections import defaultdict

def generatengrams(text: str, n: int = 4):

Strip extraneous punctuation and tokenize by whitespace

cleanedtext = re.sub(r'[^a-zA-Z0-9\s]', '', text)

tokens = cleanedtext.split()

if len(tokens) < n:

return []

return [" ".join(tokens[i:i+n]) for i in range(len(tokens) - n + 1)]

def analyzengramtails(df: pd.DataFrame, n: int = 4, minclicks: int = 8, maxconversions: float = 0.0) - pd.DataFrame:

ngramstats = defaultdict(lambda: {"impressions": 0, "clicks": 0, "cost": 0.0, "conversions": 0.0, "occurrences": 0})

for , row in df.iterrows():

query = row["searchterm"]

grams = generatengrams(query, n=n)

for gram in grams:

ngramstats[gram],["impressions"] += row["impressions"]

ngramstats[gram],["clicks"] += row["clicks"]

ngramstats[gram],["cost"] += row["cost"]

ngramstats[gram],["conversions"] += row["conversions"]

ngramstats[gram],["occurrences"] += 1

parsedrows = []

for gram, metrics in ngramstats.items():

parsedrows.append({

"ngram": gram,

"occurrences": metrics["occurrences"],

"impressions": metrics["impressions"],

"clicks": metrics["clicks"],

"cost": metrics["cost"],

"conversions": metrics["conversions"],

"cpa": metrics["cost"] / metrics["conversions"] if metrics["conversions"] 0 else None

})

ngramdf = pd.DataFrame(parsedrows)

Filter down to the bleeding tails

wastedtails = ngramdf[

(ngramdf["clicks"] = minclicks) &

(ngramdf["conversions"] <= maxconversions)

].sortvalues(by="cost", ascending=False)

return wastedtails

Establishing Threshold Cutoffs

Setting these thresholds too aggressively risks excluding high-intent queries that simply have not yet gathered statistical confidence. Here are practical benchmark filters depending on your target CPA:

| Aggressiveness Level | Minimum Clicks | Max Conversions | Target Cost Threshold | Recommended Use Case |

| :--- | :--- | :--- | :--- | :--- |

| Conservative | 20 clicks | 0 conversions | 1.5x Target CPA | High-volume accounts with large budgets |

| Balanced | 10 clicks | 0 conversions | 1.0x Target CPA | Standard B2B SaaS or E-commerce accounts |

| Aggressive | 5 clicks | 0 conversions | 0.5x Target CPA | Tight daily budgets with zero tolerance for waste |

For more industry criteria on identifying bleeders, see our detailed walkthrough on how to find negative keywords.

---

Auto-Exclusion Implementation via Google Ads API

Once your Python script extracts the underperforming 4-word tails, you can automatically add them as phrase match negative keywords. You have three structural options for adding negative keywords in Google Ads:

1. Ad Group Level (AdGroupCriterionOperation): Restricts the tail within that ad group only.

2. Campaign Level (CampaignCriterionOperation): Restricts the tail across the specific campaign.

3. Account-Level Shared Sets (SharedCriterionOperation): Blocks the phrase everywhere.

For 4-word non-converting tails, Campaign Level or Negative Keyword Shared Lists are typically best. Adding them as Phrase Match ensures that any future query containing those exact four words in sequence is suppressed.

Code: Appending Campaign-Level Negative Keywords

python

def addcampaignnegativekeywords(client: GoogleAdsClient, customerid: str, campaignid: str, negativetexts: list[str]):

campaigncriterionservice = client.getservice("CampaignCriterionService")

operations = []

for text in negativetexts:

operation = client.gettype("CampaignCriterionOperation")

criterion = operation.create

criterion.campaign = client.getservice("CampaignService").campaignpath(customerid, campaignid)

criterion.negative = True

Use PHRASE match to isolate the specific 4-word sequence

criterion.keyword.text = text

criterion.keyword.matchtype = client.enums.KeywordMatchTypeEnum.PHRASE

operations.append(operation)

try:

response = campaigncriterionservice.mutatecampaigncriteria(

customerid=customerid,

operations=operations

)

print(f"Successfully added {len(response.results)} negative criteria to Campaign {campaignid}.")

except GoogleAdsException as ex:

print(f"Request failed with status {ex.error.code().name} and includes {len(ex.failure.errors)} errors:")

for error in ex.failure.errors:

print(f"\tError: {error.message}")

Alternative: Adding to a Shared Negative Keyword List

To prevent the same tail from spending money in secondary campaigns, append it to a Shared Negative Keyword Set using SharedCriterionService:

python

def addtosharednegativeset(client: GoogleAdsClient, customerid: str, sharedsetid: str, negativetexts: list[str]):

sharedcriterionservice = client.getservice("SharedCriterionService")

operations = []

for text in negativetexts:

operation = client.gettype("SharedCriterionOperation")

criterion = operation.create

criterion.sharedset = client.getservice("SharedSetService").sharedsetpath(customerid, sharedsetid)

criterion.keyword.text = text

criterion.keyword.matchtype = client.enums.KeywordMatchTypeEnum.PHRASE

operations.append(operation)

response = sharedcriterionservice.mutatesharedcriteria(

customerid=customerid,

operations=operations

)

print(f"Appended {len(response.results)} negatives to shared list {sharedsetid}.")

If you prefer comprehensive manual lists before automating execution, reference our curated library of 100+ negative keyword examples.

---

Safeguards, Edge Cases, and Smart Bidding Alignment

Automating keyword exclusions without safeguards can accidentally suppress high-converting traffic. When building automated search query cleaning pipelines, implement the following guardrails.

1. Protect Brand and High-Intent Core Tokens

Never allow an automated algorithm to negate terms containing your brand name, core product nouns, or conversion qualifiers (e.g., pricing, demo, enterprise, buy). Maintain a programmatic whitelist:

python

BRANDANDCOREWHITELIST = {"acme", "pricing", "quote", "software", "platform", "demo"}

def passeswhitelist(ngramphrase: str) - bool:

phrasetokens = set(ngramphrase.lower().split())

If any whitelist token exists in the phrase, reject it from auto-exclusion

return len(phrasetokens.intersection(BRANDANDCOREWHITELIST)) == 0

2. Match Type Safety: Phrase vs. Exact vs. Broad Negatives

When excluding n-gram tails, always use Phrase Match negatives.

• If you exclude open source github free as an Exact Match negative, it only excludes that exact phrase when searched alone. Queries like best enterprise accounting open source github free will still trigger your ads.

• If you exclude it as a Broad Match negative, Google might negate permutations of those words in any order, blocking legitimate queries.

• Phrase Match negative precisely neutralizes the consecutive sequence of those 4 words while preserving the rest of your auction eligibility.

3. Playing Nice with Smart Bidding

Google Ads practitioners sometimes worry that adding negative keywords confuses Smart Bidding algorithms (tCPA or Max Conversions). In reality, automated bidding evaluates real-time intent signals, but it can take weeks to adjust down for obscure search tails with low query frequency. Systematically removing definitively irrelevant 4-word tails cuts wasted spend faster, letting Smart Bidding allocate budget to viable auctions.

For teams managing complex accounts that want machine-learning-driven optimization without managing internal Python scripts, tools like AdTurbo provide automated query parsing, anomaly detection, and bid adjustments within a pre-built platform.

---

Complete End-to-End Automation Pipeline Script

Here is the consolidated script assembling the data extraction, n-gram analysis, safeguard validation, and API execution into an executable pipeline.

python

"""

Automated 4-Word Broad Match Negative Tail Excluder

Author: AdTurbo PPC Engineering

"""

import re

from collections import defaultdict

import pandas as pd

from google.ads.googleads.client import GoogleAdsClient

from google.ads.googleads.errors import GoogleAdsException

CUSTOMERID = "1234567890" Replace with target Account ID (no hyphens)

WHITELIST = {"acme", "pricing", "quote", "software", "platform", "demo"}

CLICKTHRESHOLD = 8

MAXCONVERSIONS = 0.0

def extractsearchterms(client: GoogleAdsClient, customerid: str) - pd.DataFrame:

gaservice = client.getservice("GoogleAdsService")

query = """

SELECT

searchtermview.searchterm,

campaign.id,

metrics.clicks,

metrics.costmicros,

metrics.conversions

FROM searchtermview

WHERE

segments.date DURING LAST30DAYS

AND metrics.clicks 0

AND adgroupcriterion.keyword.matchtype = 'BROAD'

"""

stream = gaservice.searchstream(customerid=customerid, query=query)

rows = []

for batch in stream:

for row in batch.results:

rows.append({

"campaignid": str(row.campaign.id),

"searchterm": row.searchtermview.searchterm.lower().strip(),

"clicks": row.metrics.clicks,

"cost": row.metrics.costmicros / 1000000.0,

"conversions": row.metrics.conversions

})

return pd.DataFrame(rows)

def findwasted4gramtails(df: pd.DataFrame) - pd.DataFrame:

ngramstats = defaultdict(lambda: {"clicks": 0, "cost": 0.0, "conversions": 0.0, "campaignids": set()})

for , row in df.iterrows():

words = re.sub(r'[^a-zA-Z0-9\s]', '', row["searchterm"]).split()

if len(words) = 4:

for i in range(len(words) - 3):

gram = " ".join(words[i:i+4])

ngramstats[gram],["clicks"] += row["clicks"]

ngramstats[gram],["cost"] += row["cost"]

ngramstats[gram],["conversions"] += row["conversions"]

ngramstats[gram],["campaignids"].add(row["campaignid"])

taildata = []

for gram, stats in ngramstats.items():

Safeguard: Skip phrases containing whitelisted terms

if any(token in WHITELIST for token in gram.split()):

continue

if stats["clicks"] = CLICKTHRESHOLD and stats["conversions"] <= MAXCONVERSIONS:

taildata.append({

"tail": gram,

"clicks": stats["clicks"],

"cost": stats["cost"],

"conversions": stats["conversions"],

"campaignids": list(stats["campaignids"])

})

return pd.DataFrame(taildata)

def executecampaignnegatives(client: GoogleAdsClient, customerid: str, tailsdf: pd.DataFrame, dryrun: bool = True):

if tailsdf.empty:

print("No non-converting tails exceeded the threshold.")

return

campaigncriterionservice = client.getservice("CampaignCriterionService")

operations = []

for , row in tailsdf.iterrows():

tailtext = row["tail"]

for campid in row["campaignids"]:

if dryrun:

print(f"[DRY RUN] Would add negative '{tailtext}' to campaign {campid} (Spent ${row['cost']:.2f} across {row['clicks']} clicks)")

continue

operation = client.gettype("CampaignCriterionOperation")

criterion = operation.create

criterion.campaign = client.getservice("CampaignService").campaignpath(customerid, campid)

criterion.negative = True

criterion.keyword.text = tailtext

criterion.keyword.matchtype = client.enums.KeywordMatchTypeEnum.PHRASE

operations.append(operation)

if not dryrun and operations:

response = campaigncriterionservice.mutatecampaigncriteria(

customerid=customerid,

operations=operations

)

print(f"Successfully deployed {len(response.results)} campaign negative keywords.")

def main():

client = GoogleAdsClient.loadfromstorage("google-ads.yaml")

print("Extracting search terms via GAQL...")

dfterms = extractsearchterms(client, CUSTOMERID)

print(f"Retrieved {len(dfterms)} search term records.")

wastedtails = findwasted4gramtails(dfterms)

print(f"Identified {len(wastedtails)} wasteful 4-word broad match tails.")

Run in dryrun mode first to review changes before committing

executecampaignnegatives(client, CUSTOMERID, wastedtails, dryrun=True)

if name == "main":

main()

Run this script on a weekly schedule using cron or GitHub Actions. Once you have validated the output via dryrun=True, set dryrun=False to execute updates automatically through the Google Ads API.

For a broader audit checklist of components to monitor in parallel, check our PPC audit checklist and weekly Google Ads optimization checklist.

---

Real-World Auditing Pitfalls to Avoid

Deploying automated scripts comes with subtle edge cases. Keep these common audit pitfalls in mind:

1. Truncating Search Terms Manually

Engineers often attempt to tokenize strings with rigid string splits without considering connector prepositions (in, for, with, and). A 4-word tail like software for mac os loses context if stripped down to software mac. Always parse natural contiguous n-grams rather than arbitrary token bags.

2. Excluding Actively Targeted Geographic Locations

One common error occurs when broad match expands to queries containing city or regional qualifiers (e.g., commercial plumbing austin texas). If you are running localized campaigns, naively excluding austin texas as a negative phrase keyword will block your core local prospects. Ensure your whitelists account for target geolocations before applying exclusions.

3. Exceeding List and Account Limits

Google Ads enforces strict limits on negative keywords:

• Campaign-level negative keywords: 10,000 per campaign.

• Negative keyword lists (shared sets): 20 lists per account, up to 5,000 keywords per list.

If your script adds hundreds of 4-word tails every week without pruning or de-duplicating, you will eventually hit these limits. Program your script to prioritize the highest-spend waste and consolidate phrases where possible.

---

When to Build vs. Buy PPC Automation

Maintaining custom Python scripts with the Google Ads API offers complete control over your optimization logic, but it also carries development overhead:

• API Version Deprecations: Google Ads API versions sunset regularly, requiring manual updates to dependencies and client libraries.

• Authentication Expirations: OAuth tokens can desync or expire, causing silent job failures.

• Infrastructure Hosting: You must manage serverless tasks, secrets, error notifications, and logging.

If your marketing team lacks dedicated engineering resources to maintain custom API code, purpose-built PPC management software can provide identical benefits without maintenance overhead. Solutions like AdTurbo ($149/mo, 7-day trial) continuously analyze query performance, identify waste, and adjust bids within an automated platform.

---

Related Guides

• How to Use the Google Ads Search Terms Report to Cut Wasted Spend

• How to Find Negative Keywords in Google Ads (Step by Step)

• PPC Audit Checklist: 12 Steps to Fix a Leaking Google Ads Account

---

Frequently Asked Questions

Why focus on 4-word tails instead of 1-word or 2-word n-grams?

Single words often lack sufficient context, making single-word negative exclusions risky (e.g., negating "free" might inadvertently block "free shipping" or "free trial" queries). Four-word tails capture specific, nuanced user intent without accidentally negating broad commercial queries, making them safer for automated exclusions.

How often should this Python script be executed?

Running the script once a week or bi-weekly over a rolling 30-day lookback window is usually ideal. Running it daily often evaluates small sample sizes with insufficient click volume, leading to premature keyword negations that hurt overall volume.

Can this script run across multiple accounts in an MCC?

Yes. You can query the customerclient resource to fetch all active child account IDs under your Manager Account (MCC). Then, loop through each customerid sequentially or asynchronously using Python's concurrent.futures module.

What negative match type should the script apply to 4-word tails?

Phrase match (KeywordMatchTypeEnum.PHRASE) is recommended for 4-word tails. Phrase match ensures the exact 4-word sequence is suppressed wherever it appears in a search term, without over-blocking other keyword combinations.