In [3]:
request = "POST https://analyticsreporting.googleapis.com/v4/reports:batchGet?fields=reports(columnHeader%2Cdata(rows%2Ctotals))&key={YOUR_API_KEY}"
In [5]:
request={
"reportRequests": [
{
"viewId": "123303369",
"dateRanges": [
{
"startDate": "2017-01-01",
"endDate": "2017-04-30"
}
],
"metrics": [
{
"expression": "ga:sessions"
},
{
"expression": "ga:bounces"
},
{
"expression": "ga:goal1Completions" #instead of "ga:goal1Completions" use "goal_to_use_in_request" variable from tracking-tags code
}
],
"dimensions": [
{
"name": "ga:deviceCategory"
}
]
}
]
}
In [105]:
import json
with open('files/TMRW_mob.json') as file:
input_dev = json.load(file)
input_dev
Out[105]:
In [106]:
# Define dimensions list
input_dev_dimensions = input_dev['reports'][0]['columnHeader']['dimensions']
input_dev_dimensions
Out[106]:
In [107]:
# Define metrics list
input_dev_metrics = input_dev['reports'][0]['columnHeader']['metricHeader']['metricHeaderEntries']
def create_metric_list(raw_data):
lst = []
for item in raw_data:
lst.append(item['name'])
return lst
input_dev_metrics = create_metric_list(input_dev_metrics)
input_dev_metrics
Out[107]:
In [108]:
# Create input_dev_data
input_dev_data = input_dev['reports'][0]['data']['rows']
input_dev_data
Out[108]:
In [109]:
# Define each metric dict
dev_sessions = {}
dev_bounces = {}
dev_conversions = {}
for device in input_dev_data:
device_name = device['dimensions'][0]
sessions_metric = int(device['metrics'][0]['values'][0])
bounces_metric = int(device['metrics'][0]['values'][1])
conv_metric = int(device['metrics'][0]['values'][2])
dev_sessions[device_name] = sessions_metric
dev_bounces[device_name] = bounces_metric
dev_conversions[device_name] = conv_metric
print(dev_sessions)
print(dev_bounces)
print(dev_conversions)
new_data = [dev_sessions, dev_bounces, dev_conversions]
new_data
Out[109]:
In [110]:
# Create dev_data
dev_data = {}
for metric_list in new_data:
#print(metric_list)
for device in metric_list:
#print (device)
dev_data[device] = {'sessions':0,
'bounces':0,
'conversions':0}
dev_data[device]['sessions'] = dev_sessions[device]
dev_data[device]['bounces'] = dev_bounces[device]
dev_data[device]['conversions'] = dev_conversions[device]
dev_data
Out[110]:
In [111]:
# Group MOBILE and TABLET into MOBILE DEVICES
dev_data['mobile devices'] = {}
for device in dev_data:
if device == 'mobile' or device == 'tablet':
metrics = dev_data[device]
for metric in metrics:
dev_data['mobile devices'][metric] = 0
dev_data['mobile devices'][metric] += dev_data['mobile'][metric]+dev_data['tablet'][metric]
del dev_data['mobile']
del dev_data['tablet']
dev_data
Out[111]:
In [112]:
# Calculate CONVERSION RATE
for device in dev_data:
dev_data[device]['conversion rate'] = 0
dev_data[device]['conversion rate'] = dev_data[device]['conversions']/dev_data[device]['sessions']
dev_data
Out[112]:
In [113]:
# Calculate how conversions can increase in the next 4 monthes
conv_increase = int(dev_data['mobile devices']['sessions'] * dev_data['desktop']['conversion rate']\
- dev_data['mobile devices']['conversions'])
mobile_CR = float(dev_data['mobile devices']['conversion rate'])
mobile_CR = "{0:.2f}%".format(mobile_CR * 100)
desktop_CR = float(dev_data['desktop']['conversion rate'])
desktop_CR = "{0:.2f}%".format(desktop_CR * 100)
mobile_session_share = dev_data['mobile devices']['sessions'] / (dev_data['mobile devices']['sessions']\
+ dev_data['desktop']['sessions'])
mobile_session_share = "{0:.0f}%".format(mobile_session_share * 100)
mobile_session_share
Out[113]:
In [114]:
print ("Have %s more conversions per month by optmising mobile UX" % conv_increase)
print ("Only %s of all mobile visits end up completing a conversion" % mobile_CR)
In [115]:
print("Optimize Mobile UX to get additional %s conversions per months from mobile devices. Mobile traffic is %s of total however conversion rate is just %s comparing to %s of desktop." % (conv_increase, mobile_session_share, mobile_CR, desktop_CR))
In [98]:
import plotly
In [99]:
import plotly.plotly as py
import plotly.figure_factory as ff
from plotly import graph_objs as go
from __future__ import division
py.sign_in('m-nudha', 'NlSXxWgqIy6tgiVQIi6e')
In [100]:
mob_metrics = []
for metric in dev_data['mobile devices']:
if metric == "sessions" or metric == "bounces" or metric == "conversions":
mob_metrics.append(dev_data['mobile devices'][metric])
mob_metrics
Out[100]:
In [101]:
# chart stages data
values = mob_metrics
phases = ['All users', 'Engaged users', 'Converted users']
# color of each funnel section
colors = ['rgb(32,155,160)', 'rgb(253,93,124)', 'rgb(182,231,235)']
In [102]:
n_phase = len(phases)
plot_width = 400
# height of a section and difference between sections
section_h = 100
section_d = 10
# multiplication factor to calculate the width of other sections
unit_width = plot_width / max(values)
# width of each funnel section relative to the plot width
phase_w = [int(value * unit_width) for value in values]
# plot height based on the number of sections and the gap in between them
height = section_h * n_phase + section_d * (n_phase - 1)
In [103]:
# list containing all the plot shapes
shapes = []
# list containing the Y-axis location for each section's name and value text
label_y = []
for i in range(n_phase):
if (i == n_phase-1):
points = [phase_w[i] / 2, height, phase_w[i] / 2, height - section_h]
else:
points = [phase_w[i] / 2, height, phase_w[i+1] / 2, height - section_h]
path = 'M {0} {1} L {2} {3} L -{2} {3} L -{0} {1} Z'.format(*points)
shape = {
'type': 'path',
'path': path,
'fillcolor': colors[i],
'line': {
'width': 1,
'color': colors[i]
}
}
shapes.append(shape)
# Y-axis location for this section's details (text)
label_y.append(height - (section_h / 2))
height = height - (section_h + section_d)
In [104]:
# For phase names
label_trace = go.Scatter(
x=[-350]*n_phase,
y=label_y,
mode='text',
text=phases,
textfont=dict(
color='rgb(200,200,200)',
size=15
)
)
# For phase values
value_trace = go.Scatter(
x=[350]*n_phase,
y=label_y,
mode='text',
text=values,
textfont=dict(
color='rgb(200,200,200)',
size=15
)
)
data = [label_trace, value_trace]
layout = go.Layout(
title="<b>Funnel Chart</b>",
titlefont=dict(
size=20,
color='rgb(203,203,203)'
),
shapes=shapes,
height=560,
width=800,
showlegend=False,
paper_bgcolor='rgba(44,58,71,1)',
plot_bgcolor='rgba(44,58,71,1)',
xaxis=dict(
showticklabels=False,
zeroline=False,
),
yaxis=dict(
showticklabels=False,
zeroline=False
)
)
fig = go.Figure(data=data, layout=layout)
py.iplot(fig)
Out[104]:
In [ ]:
In [ ]: