Whether you are a huge business or a marketing agency, the chances are that you may have plenty of Google Ads accounts to monitor and optimize. Manually managing numerous or even a single Google Ads accounts time-consuming and often sub-optimal. 

It is necessary to implement automated monitoring strategies to utilize all your Google Ads accounts to the fullest to have access to endless benefits!

This informative article focuses on implementing a highly convenient automated monitoring application that can manage and maintain your Google Ads account by utilizing R and the Google AdWords API to check the data. 

What You Need:

What is ‘R’?!

Let’s start with the basics– what exactly is the R that we speak of?

R is a popular statistical programming language that virtually supports the same Machine Learning (ML) strategies that Python does. There have been endless debates regarding the competition between R and Python. However, since both abide by pretty much the same principles, it is a matter of preference. Which one do you think resonates with you!?

In this particular example, Machine Learning is unnecessary. However, more advanced solutions do require the use of ML. This is why we chose to go with R!

An IDE of R that makes it easier to use is ‘Rstudio.’ A quote from their website reads, 

“RStudio is an integrated development environment (IDE) for R. It includes a console, syntax-highlighting editor that supports direct code execution, as well as tools for plotting, history, debugging, and workspace management.”

RStudio can run on the desktop or even in a browser that connects to a Rstudio Server. It is not only available in open source but commercial editions as well. 

Cool, right?!

If you do not have RStudio yet, do not deprive yourself any longer! Install it right now from RStudio downloads.

Done? Great!

After you have set up your RStudio, we can begin the scripting process. 

An R script

To store the Google Ads Customer IDS of your clients, you can use MariaDB as it will allow you to retrieve them for various other automation and integration purposes conveniently. 

If, for instance, you are using some other database server, you will have to modify the DB part of this code to cater to your needs. R can support numerous databases, maybe even all of them. It will suffice to say that if it has anything to do with data, R can read it!

In case you are not using any database, you can skip the DB part. 

Furthermore, if you need to read the Customer IDs directly from AdWords API, you can access the Managed Customer Service via a newer R package known as adwordsR.

Okay, Now Let’s Get to the Script!

Ther are specific steps you need to take to begin the script:


Create a new R file in your RStudio with the following content, set up your DB user and pass, and save the file as db_credentials.R in /YOUR_R_USER_ROOT_DIR/auth/. 

This is your DB auth file.


Create another file, including the following code, and save the file as connect_db.R in /YOUR_R_USER_ROOT_DIR/. 

This is your DB connector.


And finally, the actual Ads R script, include the following code and save it as google-ads-zero-cost-monitor.R in /YOUR_R_USER_ROOT_DIR/.

The code should be the following

# Init the DB connection


# Check if the required packages are installed, install if not

if(!require(RAdwords)) install.packages(“RAdwords”)

# Load packages


# Define the file path where your AdWords API OAuth RData file should be stored to, we’ll need this next

google_ads_auth_file <- “~/auth/google_ads_auth.RData”

# Check if the google_auth RData file already exists, create if not

if(!file.exists(google_ads_auth_file)) {

  # Auth steps:

  •   # 1) You’ll need Google API Client ID, Client Secret and AdWords Developer Token here for authenticating, see https://github.com/jburkhardt/RAdwords for details
  •   # 2) Once you’ve provided those in your R console when R requests them, you’ll get redirected to OAuth screen in your browser
  •   # 3) Authenticate with your Google Account (the same that has access to your AdWords account)
  •   # 4) You’ll be redirected to a OAuth success screen that provides a final token code and asks you to copy/paste it to your application (to your R console in this case)

  google_auth <- doAuth(save = FALSE)

  # Save the auth credentials, to be used the auth from a file from now on

  save(google_auth, file = google_ads_auth_file)


# Load Google auth credentials

load(file = google_ads_auth_file)

# Init date vars

dayBeforeYesterday <- Sys.Date() – 2

yesterday <- Sys.Date() – 1

# Fetch Google Ads Customer IDs from your DB

ads_accounts <- dbGetQuery(con, “SELECT ads_customer_id FROM ads_accounts”)

# Create a list of the IDs for later looping

account_list <- ads_accounts$ads_customer_id

# Alternatively, if you want to skip the DB stuff, you can define your Google Ads Customer IDs manually by uncommenting the following line and listing the IDs here:

# account_list <- c(“123-123-1234”, “234-234-2345”)

# Init AdWords API request

# We’re checking the cost data from two previous days

body <- statement(select = c(‘Cost’),

                  report = “ACCOUNT_PERFORMANCE_REPORT”,

                  start  = dayBeforeYesterday,

                  end    = yesterday)

# Init a data frame for collecting the data and an index variable for keeping track of progress during the for loop

adsdata <- data.frame()

progressIndex <- 0

# Get the Ads to cost data

for (account in account_list) {

  # Get cost data

  ads_api_response <- getData(clientCustomerId = account,

                              google_auth      = google_auth,

                              statement        = body)

  # Proceed only if the API doesn’t return an error (happens when there’s no data to return or when the API fails), this is for dropping off false zero cost alerts

  if(!is.null(dim(ads_api_response))) {

    # Init empty data frame

    adsdata_temp <- setNames(data.frame(matrix(ncol = 2, nrow = 1)), c(“Cost”, “Account”))

    # Include account id

    adsdata_temp$Account <- account

    # Include cost data

    # If there’s no data, the result is doubled for some reason

    # Fix this by always reading the 1st value only with [1]

    adsdata_temp$Cost <- ads_api_response$Cost[1]

    # If cost is zero, NA is returned, replace it with zero

    if(is.na(adsdata_temp$Cost)) adsdata_temp$Cost <- 0

    # Collect during each iteration

    adsdata <- rbind(adsdata, adsdata_temp, stringsAsFactors = FALSE)


  # Print progress to R console

  progressIndex <- progressIndex + 1

  cat(paste(“Query “, progressIndex, ” of “, NROW(account_list), ” done\r\n”, sep = “”)


# Keep accounts with zero cost only

ads_accounts_with_zero_cost <- subset(adsdata, Cost == 0)

# Count nbr of alerted accounts

nbr_of_accounts_with_alerts <- nrow(ads_accounts_with_zero_cost)

# Save all alerts to DB, if there was any

# This assumes you have DB table named “alerts” existing with fields: 

# ads_customer_id VARCHAR

# category VARCHAR

# status_id INT

# created_at DATETIME

# updated_at DATETIME

if(nbr_of_accounts_with_alerts > 0) {

  for (i in 1:nrow(ads_accounts_with_zero_cost)) {

    row <- ads_accounts_with_zero_cost[i, ]

    ads_customer_id <- row$ads_customer_id

    category <- “ALERT_ZERO_COST” # For categorizing different types of alerts

    status_id <- 0 # To be set to eg. 1 when the alert is handled via a custom UI

    # Save each item to db

    query <- paste(“INSERT INTO alerts (






                   VALUES (“,

                    “‘”, ads_customer_id, “‘, “,

                    “‘”, category, “‘, “,

                    status_id, “, “,

                    “now(), “,


                   sep = “”


    dbExecute(con, query)


# If you want to check/debug what was stored, uncomment and run these lines

# db_alerts <- dbGetQuery(con, “SELECT * FROM alerts”)

# View(db_alerts)


Okay, phew! You now have your Ads zero cost monitor script ready for action!

Do test it in RStudio and ensure that it is working smoothly. 

The next step is to move your script to production by scheduling it via cron.

Time for the Cron Job

Open crontab in your Linux shell for editing:

crontab -e

Add the cron job that caters to your requirements. 

Here’s an example syntax with a scheduler that runs the R monitoring script daily at 10 AM.

# Daily at 10 AM

0 10 * * * Rscript /home/YOUR_USERNAME/google-ads-zero-cost-monitor.R

Voila! You are now ready for smooth, automated monitoring for your Google Ads accounts. 


With this technique, you will create a robust pipeline to monitor your Google Ads– a channel that has boundless opportunities for extension. 

It will also enable you to detect anomalies, track high spending, strategize campaigns, automate ads placement, and other opportunities to optimize your Google Ads. 

There is no denying that automating such tasks is essential in the current marketing landscape. It can save your company from intense manual labor and supercharge your profits. 

If you have any suggestions, concerns, or questions, please feel free to contact us!