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


Out[2]:
[{'accountId': '78795478',
  'active': True,
  'created': '2017-01-26T16:41:38.797Z',
  'eventDetails': {'eventConditions': [{'expression': 'Event',
     'matchType': 'EXACT',
     'type': 'CATEGORY'},
    {'expression': 'Form', 'matchType': 'EXACT', 'type': 'ACTION'},
    {'expression': 'Submitted', 'matchType': 'EXACT', 'type': 'LABEL'}],
   'useEventValue': True},
  'id': '1',
  'internalWebPropertyId': '117885953',
  'kind': 'analytics#goal',
  'name': 'Contact form submission',
  'parentLink': {'href': 'https://www.googleapis.com/analytics/v3/management/accounts/78795478/webproperties/UA-78795478-1/profiles/123303369',
   'type': 'analytics#profile'},
  'profileId': '123303369',
  'selfLink': 'https://www.googleapis.com/analytics/v3/management/accounts/78795478/webproperties/UA-78795478-1/profiles/123303369/goals/1',
  'type': 'EVENT',
  'updated': '2017-01-29T19:24:58.853Z',
  'value': 0.0,
  'webPropertyId': 'UA-78795478-1'},
 {'accountId': '78795478',
  'active': True,
  'created': '2017-01-26T16:42:15.852Z',
  'eventDetails': {'eventConditions': [{'expression': 'Form',
     'matchType': 'EXACT',
     'type': 'CATEGORY'},
    {'expression': 'Submitted', 'matchType': 'EXACT', 'type': 'ACTION'},
    {'expression': 'Stay Informed Form',
     'matchType': 'EXACT',
     'type': 'LABEL'}],
   'useEventValue': True},
  'id': '2',
  'internalWebPropertyId': '117885953',
  'kind': 'analytics#goal',
  'name': 'Stay informed submission',
  'parentLink': {'href': 'https://www.googleapis.com/analytics/v3/management/accounts/78795478/webproperties/UA-78795478-1/profiles/123303369',
   'type': 'analytics#profile'},
  'profileId': '123303369',
  'selfLink': 'https://www.googleapis.com/analytics/v3/management/accounts/78795478/webproperties/UA-78795478-1/profiles/123303369/goals/2',
  'type': 'EVENT',
  'updated': '2017-01-26T16:42:15.852Z',
  'value': 0.0,
  'webPropertyId': 'UA-78795478-1'},
 {'accountId': '78795478',
  'active': True,
  'created': '2017-01-26T16:42:51.939Z',
  'eventDetails': {'eventConditions': [{'expression': 'Link',
     'matchType': 'EXACT',
     'type': 'CATEGORY'},
    {'expression': 'Click', 'matchType': 'EXACT', 'type': 'ACTION'},
    {'expression': 'Clicked', 'matchType': 'EXACT', 'type': 'LABEL'}],
   'useEventValue': True},
  'id': '3',
  'internalWebPropertyId': '117885953',
  'kind': 'analytics#goal',
  'name': 'Telephone click',
  'parentLink': {'href': 'https://www.googleapis.com/analytics/v3/management/accounts/78795478/webproperties/UA-78795478-1/profiles/123303369',
   'type': 'analytics#profile'},
  'profileId': '123303369',
  'selfLink': 'https://www.googleapis.com/analytics/v3/management/accounts/78795478/webproperties/UA-78795478-1/profiles/123303369/goals/3',
  'type': 'EVENT',
  'updated': '2017-01-29T19:29:12.187Z',
  'value': 0.0,
  'webPropertyId': 'UA-78795478-1'}]

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]:
#create a list of goals according to number of goals loaded

goal_list = []
goals = {}


for i in range(goals_count):
    goal_names = "goal%s" % str(i+1)
    goal_list.append(goal_names)

    
    
    for goal in goal_list:
        goals[goal] = {
            'id' : "",
            'name' : "",
            'type' : "",
            'active' : ""
        }
        for p in goals[goal]:

            goals[goal][p] = str(input_goals[goal_list.index(goal)][p]).lower()
            
            
#print(goal_list)       
goals


Out[4]:
{'goal1': {'active': 'true',
  'id': '1',
  'name': 'contact form submission',
  'type': 'event'},
 'goal2': {'active': 'true',
  'id': '2',
  'name': 'stay informed submission',
  'type': 'event'},
 'goal3': {'active': 'true',
  'id': '3',
  'name': 'telephone click',
  'type': 'event'}}

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

goals_to_delete = []

for goal in goals:
    
    if goals[goal]['active'] == "false" or goals[goal]['type'] != "event":
        goals_to_delete.append(goal)
        

goals_to_delete


Out[5]:
[]

In [6]:
for g in goals_to_delete:
    del goals[g]
    
goals


Out[6]:
{'goal1': {'active': 'true',
  'id': '1',
  'name': 'contact form submission',
  'type': 'event'},
 'goal2': {'active': 'true',
  'id': '2',
  'name': 'stay informed submission',
  'type': 'event'},
 'goal3': {'active': 'true',
  'id': '3',
  'name': 'telephone click',
  'type': 'event'}}

In [7]:
len(goals)


Out[7]:
3

In [8]:
useful_words = ["form","contact","get in touch","submit","submission"]

def goal_names(g,w):
    result = {}
    for goal in g:        
        result[goal] = 0
        for word in w:
            if g[goal]['name'].count(word) > 0:
                result[goal] += 1              
    return result

goal_names_dir = goal_names(goals,useful_words)

In [9]:
if len(goals) == 1:
    for goal in goals:
        goal_to_use_id = goal
    
elif len(goals) == 0:
    print("Error")
    
else:
    
    # check with goal_names function
    
    words_count = []
    for goal in goal_names_dir:
        
        #print (goals[goal])
        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[9]:
'goal1'

In [10]:
goal_to_use_name = ""

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


Out[10]:
'contact form submission'

In [18]:
#name of metric to use in user_flow and mobile_analytics, user_groups methods
goal_to_use_in_request = 'ga:%sCompletions' % (goal_to_use_id)
goal_to_use_in_request


Out[18]:
'ga:goal1Completions'

Check number of events


In [12]:
#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 [13]:
import json

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

input_events


Out[13]:
{'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 [14]:
# Define dimensions list
input_events_dimensions = input_events['reports'][0]['columnHeader']['dimensions']

input_events_dimensions


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

In [15]:
# 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[15]:
['ga:totalEvents']

In [16]:
#checking count of events

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

events_count = len(input_events_data)

Print


In [17]:
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 [ ]: