Tracking Tags

Choose a goal


In [1]:
request = "GET https://www.googleapis.com/analytics/v3/management/accounts/78795478/webproperties/\
    UA-78795478-1/profiles/123303369/goals?key={YOUR_API_KEY}"

In [2]:
import json

with open('files/TMRW_goals_checking.json') as file: 
    input_goals = json.load(file)

input_goals = input_goals["items"]

#input_goals

In [3]:
#check how many goals we have loaded

goals_count = len(input_goals)
max_goal_count = 20

goals_count


Out[3]:
3

In [4]:
#there are 3 goals loaded

goal1 = input_goals[0]
goal2 = input_goals[1]
goal3 = input_goals[2]

In [5]:
goal1 = {
    "id" : "goal%s" % goal1['id'],
    "type": goal1["type"], 
    "name": goal1["name"].lower(),
    "active": goal1["active"]
    }

goal2 = {
    "id" : "goal%s" % goal2['id'],
    "type": goal2["type"], 
    "name": goal2["name"].lower(),
    "active": goal2["active"]
    }

goal3 = {
    "id" : "goal%s" % goal3['id'],
    "type": goal3["type"], 
    "name": goal3["name"].lower(),
    "active": goal3["active"]
    }

goals = [goal1, goal2, goal3]

goals


Out[5]:
[{'active': True,
  'id': 'goal1',
  'name': 'contact form submission',
  'type': 'EVENT'},
 {'active': True,
  'id': 'goal2',
  'name': 'stay informed submission',
  'type': 'EVENT'},
 {'active': True, 'id': 'goal3', 'name': 'telephone click', 'type': 'EVENT'}]

In [6]:
#delete goals that are not EVENTS and not ACTIVE

for goal in goals:
    if goal['active'] == False or goal['type'] != "EVENT":
        index_to_delete = goals.index(goal)
        del goals[index_to_delete]
        
goals


Out[6]:
[{'active': True,
  'id': 'goal1',
  'name': 'contact form submission',
  'type': 'EVENT'},
 {'active': True,
  'id': 'goal2',
  'name': 'stay informed submission',
  'type': 'EVENT'},
 {'active': True, 'id': 'goal3', 'name': 'telephone click', 'type': 'EVENT'}]

In [7]:
len(goals)


Out[7]:
3

In [11]:
# set up keywords to define needed goal
useful_words = ["form","contact","get in touch","submit","submission"]

def goal_names(g,w):
    result = {}
    for goal in g:
        #define goals that are EVENTS and ACTIVE
        if goal['active'] == True and goal['type'] == "EVENT":
            result[goal['id']] = 0
            for word in w:
                if goal['name'].count(word)>0:
                    result[goal['id']] += 1
                    
    return result

goal_names_dir = goal_names(goals,useful_words)

In [12]:
if len(goals) == 1:
    goal_to_use_id = goals[0]['id']
    
elif len(goals) == 0:
    print("Error")
    
else:
    
    # check with goal_names function
    
    words_count = []
    for goal in goal_names_dir:
        words_count.append(goal_names_dir[goal])

    max_word_count = max(words_count)
    
    # define goal with biggest number of keywords found
    
    goal_to_use_id = ""

    for goal in goal_names_dir:
        if goal_names_dir[goal] == max_word_count:
            goal_to_use_id = goal
    
goal_to_use_id


Out[12]:
'goal1'

In [171]:
goal_to_use_name = ""

for goal in goals:
    if goal['id'] == goal_to_use_id:
        goal_to_use_name = goal['name']
        
goal_to_use_name


Out[171]:
'contact form submission'

Check number of events


In [193]:
#POST https://analyticsreporting.googleapis.com/v4/reports:batchGet?\fields=reports(columnHeader(dimensions%2CmetricHeader%2FmetricHeaderEntries)%2Cdata%2Frows)&key={YOUR_API_KEY}"
 
request = {
 "reportRequests": [
  {
   "viewId": "123303369",
   "dateRanges": [
    {
     "startDate": "2017-01-01",
     "endDate": "2017-04-30"
    }
   ],
   "metrics": [
    {
     "expression": "ga:totalEvents"
    }
   ],
   "dimensions": [
    {
     "name": "ga:eventCategory"
    },
    {
     "name": "ga:eventAction"
    },
    {
     "name": "ga:eventLabel"
    }
   ]
  }
 ]
}

In [173]:
import json

with open('files/TMRW_events.json') as file: 
    input_events = json.load(file)

input_events


Out[173]:
{'reports': [{'columnHeader': {'dimensions': ['ga:eventCategory',
     'ga:eventAction',
     'ga:eventLabel'],
    'metricHeader': {'metricHeaderEntries': [{'name': 'ga:totalEvents',
       'type': 'INTEGER'}]}},
   'data': {'rows': [{'dimensions': ['Event', 'Form', 'Submitted'],
      'metrics': [{'values': ['199']}]},
     {'dimensions': ['Link', 'Click', 'Clicked'],
      'metrics': [{'values': ['6']}]}]}}]}

In [174]:
# Define dimensions list
input_events_dimensions = input_events['reports'][0]['columnHeader']['dimensions']

input_events_dimensions


Out[174]:
['ga:eventCategory', 'ga:eventAction', 'ga:eventLabel']

In [175]:
# Define metrics list
input_events_metrics = input_events['reports'][0]['columnHeader']['metricHeader']['metricHeaderEntries']

def create_metric_list(raw_data):
    lst = []
    for item in raw_data:
        lst.append(item['name'])
    return lst

input_events_metrics = create_metric_list(input_events_metrics)

input_events_metrics


Out[175]:
['ga:totalEvents']

In [176]:
#checking count of events

input_events_data = input_events['reports'][0]['data']['rows']

events_count = len(input_events_data)

Print


In [185]:
print("Goals - %s goals detected" % goals_count)

print("%s \'%s\' is used as a main conversion" % (goal_to_use_id.title(),goal_to_use_name.title()))

print("Events - %s events detected" % events_count)

if events_count < 5:
    
    print("Set event tags to enable more user analytics features")


Goals - 3 goals detected
Goal1 'Contact Form Submission' is used as a main conversion
Events - 2 events detected
Set event tags to enable more user analytics features

In [ ]:


In [ ]: