This repository has been archived by the owner on Jun 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 53
/
mixpanel_experiment.py
162 lines (131 loc) · 4.54 KB
/
mixpanel_experiment.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#! /usr/bin/env python
#
# Mixpanel, Inc. -- http://mixpanel.com/
#
# Python API client library to consume mixpanel.com analytics data.
#
# Modified by Chris Mueller at Thumbtack for A/B tests
import hashlib
import urllib
import time
import datetime
import sys
import webbrowser
try:
import json
except ImportError:
import simplejson as json
API_KEY = 'xxxxxxxxxxxx'
API_SECRET = 'xxxxxxxxxxxx'
class Mixpanel(object):
ENDPOINT = 'http://mixpanel.com/api'
VERSION = '2.0'
def __init__(self, api_key, api_secret):
self.api_key = api_key
self.api_secret = api_secret
def request(self, methods, params, format='json'):
"""
methods - List of methods to be joined, e.g. ['events', 'properties', 'values']
will give us http://mixpanel.com/api/2.0/events/properties/values/
params - Extra parameters associated with method
"""
params['api_key'] = self.api_key
params['expire'] = int(time.time()) + 600 # Grant this request 10 minutes.
params['format'] = format
if 'sig' in params: del params['sig']
params['sig'] = self.hash_args(params)
request_url = '/'.join([self.ENDPOINT, str(self.VERSION)] + methods) + '/?' + self.unicode_urlencode(params)
request = urllib.urlopen(request_url)
data = request.read()
return json.loads(data)
def unicode_urlencode(self, params):
"""
Convert lists to JSON encoded strings, and correctly handle any
unicode URL parameters.
"""
if isinstance(params, dict):
params = params.items()
for i, param in enumerate(params):
if isinstance(param[1], list):
params[i] = (param[0], json.dumps(param[1]),)
return urllib.urlencode(
[(k, isinstance(v, unicode) and v.encode('utf-8') or v) for k, v in params]
)
def hash_args(self, args, secret=None):
"""
Hashes arguments by joining key=value pairs, appending a secret, and
then taking the MD5 hex digest.
"""
for a in args:
if isinstance(args[a], list): args[a] = json.dumps(args[a])
args_joined = ''
for a in sorted(args.keys()):
if isinstance(a, unicode):
args_joined += a.encode('utf-8')
else:
args_joined += str(a)
args_joined += '='
if isinstance(args[a], unicode):
args_joined += args[a].encode('utf-8')
else:
args_joined += str(args[a])
hash = hashlib.md5(args_joined)
if secret:
hash.update(secret)
elif self.api_secret:
hash.update(self.api_secret)
return hash.hexdigest()
def get_api():
return Mixpanel(
api_key = API_KEY,
api_secret = API_SECRET
)
def experiment(funnel, exp, days=None):
"""
funnel: a Mixpanel funnel ID
exp: experiment key (a Mixpanel property)
days: number of days back (defaults to 1 day)
"""
api = get_api()
if days is None:
days = 0
today = datetime.datetime.now()
past = today - datetime.timedelta(days=int(days))
result = api.request(['funnels'], {
'funnel_id': int(funnel),
'from_date': past.strftime('%Y-%m-%d'),
'to_date': today.strftime('%Y-%m-%d'),
'on': 'properties["%s"]' % exp,
})
data = result['data']
final = {}
for day, buckets in data.iteritems():
for bucket_key, events in buckets.iteritems():
if not final.has_key(bucket_key):
final[bucket_key] = []
for i in xrange(0, len(events)):
if len(final[bucket_key]) < (i + 1):
final[bucket_key].append(0)
final[bucket_key][i] += events[i]['count']
abba = []
for key, events in final.iteritems():
events.reverse()
query = "%s=%s" % (key, ",".join([str(event) for event in events]))
if key == "baseline":
abba.insert(0, query)
else:
abba.append(query)
abba_url = "http://www.thumbtack.com/labs/abba/#" + "&".join(abba)
print abba_url
webbrowser.open_new_tab(abba_url)
if __name__ == '__main__':
if len(sys.argv) < 3:
print "Usage: %s <funnel> <experiment> [days]" % sys.argv[0]
sys.exit()
funnel = sys.argv[1]
exp = sys.argv[2]
if len(sys.argv) > 3:
days = sys.argv[3]
experiment(funnel, exp, days)
else:
experiment(funnel, exp)