In [1]:
%pylab inline
import os, sys, glob
import time
import numpy as np
import pickle
import json

import matplotlib as mpl
import matplotlib.pyplot as plt


Populating the interactive namespace from numpy and matplotlib

In [2]:
# Load credential data 
from untappd_credentials import *

USER_NAME = 'ovarol'
#CLIENT_ID = "XXXXXXXXXXXXXX"
#CLIENT_SECRET = "XXXXXXXXXXXXXX"
#print 'Id:\t{}\nSecret:\t{}\n'.format(CLIENT_ID, CLIENT_SECRET)

In [3]:
# Using API from https://github.com/marshall91/pythonUntappd
import untappd_api as pythonUntappd

api = pythonUntappd.api(CLIENT_ID,CLIENT_SECRET)
userData = api.user_info(USER_NAME)['response']
#print json.dumps(userData, indent=4)

In [4]:
uniqueBeers = list()
userData = api.user_info(USER_NAME)['response']

count, keepCollect = 0, True
scanCount = 0
while keepCollect:
    resp = api.user_distinct_beers(USER_NAME, offset=count)['response']
    count += resp['beers']['count']
    uniqueBeers.extend(resp['beers']['items'])
    print('Unique beers collected: {}'.format(len(uniqueBeers)))
    scanCount += 1
    if resp['beers']['count'] != 0:
        time.sleep(1)
    else:
        break
        
with open('docs/data/{}_untappd_data.json'.format(USER_NAME),'w') as fl:
    fl.write(json.dumps({'user_data':userData, 'beer_data':uniqueBeers}))


Unique beers collected: 25
Unique beers collected: 50
Unique beers collected: 75
Unique beers collected: 100
Unique beers collected: 125
Unique beers collected: 150
Unique beers collected: 175
Unique beers collected: 200
Unique beers collected: 225
Unique beers collected: 250
Unique beers collected: 275
Unique beers collected: 300
Unique beers collected: 325
Unique beers collected: 350
Unique beers collected: 375
Unique beers collected: 400
Unique beers collected: 425
Unique beers collected: 450
Unique beers collected: 450

In [5]:
#print json.dumps(uniqueBeers, indent=4, sort_keys=True)
print(json.dumps(uniqueBeers[-1], indent=4, sort_keys=True))


{
    "beer": {
        "beer_abv": 4.2,
        "beer_description": "Swirling clouds tumble as the storm begins to calm. Settle. Breathe in the moment, then break through the smooth, light head to the bittersweet reward.\r\n\r\nUnmistakeably GUINNESS, from the first velvet sip to the last, lingering drop. And every deep-dark satisfying mouthful in between.\r\n\r\nPure beauty. Pure GUINNESS.\r\n\r\nGuinness Draught is sold in kegs, widget cans, and bottles. The ABV varies from 4.1 to 4.3%.\r\n\r\nGuinness Extra Cold is the exact same beer only served through a super cooler at 3.5 \u00b0C",
        "beer_ibu": 45,
        "beer_label": "https://untappd.akamaized.net/site/beer_logos/beer-_4473_8122008947804818c90640a06d83.jpeg",
        "beer_name": "Guinness Draught",
        "beer_slug": "guinness-guinness-draught",
        "beer_style": "Stout - Irish Dry",
        "bid": 4473,
        "created_at": "Sat, 21 Aug 2010 09:26:35 +0000",
        "rating_count": 493582,
        "rating_score": 3.8044
    },
    "brewery": {
        "brewery_active": 1,
        "brewery_id": 49,
        "brewery_label": "https://untappd.akamaized.net/site/brewery_logos/brewery-49_a03fc.jpeg",
        "brewery_name": "Guinness",
        "brewery_slug": "guinness",
        "contact": {
            "facebook": "https://www.facebook.com/guinness",
            "instagram": "guinness",
            "twitter": "GuinnessIreland",
            "url": "http://www.guinness.com"
        },
        "country_name": "Ireland",
        "location": {
            "brewery_city": "St. James's Gate",
            "brewery_state": "Dublin",
            "lat": 53.3437,
            "lng": -6.28879
        }
    },
    "count": 2,
    "first_checkin_id": 258368559,
    "first_created_at": "Wed, 23 Dec 2015 12:12:58 -0500",
    "first_had": "Wed, 23 Dec 2015 12:12:58 -0500",
    "rating_score": 4,
    "recent_checkin_id": 354587643,
    "recent_created_at": "Mon, 29 Aug 2016 21:37:33 -0500",
    "recent_created_at_timezone": "-5"
}

In [5]:
# Check style counts
styleCounts = dict()
styleCountSimple = dict()
for b in uniqueBeers:
    if b['beer']['beer_style'] not in styleCounts:
        styleCounts[b['beer']['beer_style']] = 0
    styleCounts[b['beer']['beer_style']] += 1

    sstyle = b['beer']['beer_style'].split('-')[0].split('/')[0]
    if sstyle not in styleCountSimple:
        styleCountSimple[sstyle] = 0
    styleCountSimple[sstyle] += 1
    
for s in sorted(styleCountSimple, key=styleCountSimple.get, reverse=True):
    print(s, styleCountSimple[s])


Stout  131
IPA  48
Porter  41
Lager  24
Brown Ale  21
Pale Ale  17
Red Ale  12
Sour  10
Bock  9
Scotch Ale  8
Belgian Quad 7
Belgian Tripel 7
Barleywine  7
Pumpkin  7
Belgian Strong Dark Ale 6
Belgian Strong Golden Ale 5
Saison  5
Pilsner  5
Pale Wheat Ale  5
Cream Ale 4
Strong Ale  4
Hefeweizen 4
Dunkelweizen 4
Fruit Beer 4
Blonde Ale 3
Belgian Dubbel 3
Cider  3
Altbier 3
Shandy  3
Smoked Beer 3
Dark Ale 3
Märzen 3
Kölsch 3
Rye Beer 3
Gluten 2
Blonde Ale  2
Scottish Ale 2
Kristallweizen 2
English Mild Ale 2
Kellerbier  2
Spiced  2
American Wild Ale 1
Other 1
Scottish Export Ale 1
Specialty Grain 1
Old Ale 1
Roggenbier 1
English Bitter 1
Gruit  1
Golden Ale 1
Schwarzbier 1
Witbier 1

In [6]:
# Most preferred brewery
breweryCount = dict()
for b in uniqueBeers:
    if b['brewery']['brewery_name'] not in breweryCount:
        breweryCount[b['brewery']['brewery_name']] = 0
    breweryCount[b['brewery']['brewery_name']] += 1

for s in sorted(breweryCount, key=breweryCount.get, reverse=True):
    print(s, breweryCount[s])


New Holland Brewing  19
Boston Beer Company 16
South Bend Brew Werks 15
Bell's Brewery 13
Upland Brewing Company 12
Stone Brewing 8
Founders Brewing Co. 8
Bare Hands Brewery 8
Evil Czech Brewery 8
Great Lakes Brewing Company 7
Dogfish Head Craft Brewery 6
Samuel Smith's Old Brewery 6
Evil Twin Brewing 6
Left Hand Brewing Company 6
Silver Harbor Brewing 6
Goshen Brewing Company 6
Alltech Lexington Brewing & Distilling Co. 5
North Pier Brewing Company 5
Gordon Biersch Brewery Restaurant 5
Market Garden Brewery 5
Crooked Ewe Brewery 5
Ballast Point Brewing Company 4
Unibroue 4
Southern Tier Brewing Company 4
Weyerbacher Brewing Company 4
Boulevard Brewing Co. 4
Jackalope Brewing Company 4
The Tap Brewery 4
Anadolu Efes 4
Brasserie Dieu du Ciel! 3
Harpoon Brewery 3
Brewery Ommegang 3
North Coast Brewing Company 3
Baxter Brewing Co. 3
Allagash Brewing Company 3
Angry Orchard Cider Company 3
Jaws Brewery 3
Short's Brewing Company 3
Sierra Nevada Brewing Co. 3
Forest & Main Brewing Company 3
Greenbush Brewing Company 3
Saugatuck Brewing Company 3
Quaff ON! Brewing Company 3
Rogue Ales 3
Breckenridge Brewery 3
Eagle Brewery (formerly Charles Wells) 3
Lagunitas Brewing Company 3
Goose Island Beer Co. 3
Brauerei Beck 3
Deschutes Brewery 2
Anderson Valley Brewing Company 2
Night Shift Brewing 2
Firestone Walker Brewing Company 2
Berkshire Brewing Company (B.B.C.) 2
Somerville Brewing Company (Slumbrew) 2
21st Amendment Brewery 2
Cisco Brewers Inc. 2
Long Trail Brewing Company 2
The Shed Brewery 2
Magic Hat Brewing Company 2
Barrel House Z 2
Smuttynose Brewing Co. 2
Triumph Brewing Company 2
Tröegs Independent Brewing 2
Victory Brewing Company 2
Epic Brewing Co. (Utah, Colorado) 2
Oskar Blues Brewery 2
Guinness 2
Traveler Beer Co. 2
Tallgrass Brewing Company 2
Great Divide Brewing Company 2
Brooklyn Brewery 2
Flying Dog Brewery 2
Yards Brewing Co. 2
Gordon Biersch Brewing Company 2
Yazoo Brewing Company 2
Fountain Square Brewing Company 2
Arrogant Consortia 2
Round Barn Brewery 2
Kona Brewing Company 2
Two Brothers Brewing Company 2
Flat12 Bierwerks 2
Jacob Leinenkugel Brewing Company 2
Erdinger Weissbräu 2
Kulmbacher Brauerei 2
Brasserie de Silly 1
Beau's All Natural Brewing Company  1
Scuttlebutt Brewing Company 1
Crooked Stave Artisan Beer Project 1
Mast Landing Brewing Co. 1
Wicked Weed Brewing 1
Lord Hobo Brewing Co. 1
Yard House 1
Brouwerij Van Steenberge 1
Banded Brewing Co. 1
Off Color Brewing 1
Brouwerij Van Honsebrouck 1
Bernard Family Brewery/ Rodinný pivovar Bernard a.s. 1
Element Brewing Company 1
Mighty Squirrel Brewing Co. 1
Revolution Brewing Company 1
Wormtown Brewery 1
Collective Arts Brewing 1
Ipswich Ale Brewery 1
Otter Creek Brewing 1
Asahi Breweries 1
Spencer Brewery 1
Barrier Brewing Company 1
Brouwerij Bosteels 1
Greenport Harbor Brewing Company 1
Interboro Spirits & Ales 1
The Bronx Brewery 1
Brouwerij Verhaeghe 1
Birra Moretti 1
Neshaminy Creek Brewing Company  1
Demented Brewing Company 1
Fegley's Brew Works 1
Castle Island Brewing Company 1
Two Roads Brewing Company 1
Duvel Moortgat 1
Atlantic Brewing Company 1
Innis & Gunn 1
Desnoes & Geddes 1
Heineken Ireland 1
Notch Brewing 1
Portico Brewing Company 1
Brouwerij De Brabandere 1
Foolproof Brewing Company 1
Kiuchi Brewery 1
Abbaye de Leffe 1
Base Camp Brewing Company 1
Kirin Brewery Company 1
Sun King Brewing Company 1
United Breweries 1
4 Hands Brewing Co. 1
James Page Brewing 1
Baltika Breweries (Балтика) 1
Traquair House Brewery 1
Mad Anthony Brewing Company 1
St. Peter’s Brewery Co. 1
Wild Onion Brewery 1
Brouwerij de Molen 1
Buxton Brewery 1
Ale Asylum 1
Heineken 1
Anheuser-Busch 1
Mayflower Brewing Company 1
Cambridge Brewing Company 1
Aeronaut Brewing Company 1
Heavy Seas Beer 1
Bayerische Staatsbrauerei Weihenstephan 1
Lost Forty Brewing 1
New Belgium Brewing Company 1
Central Waters Brewing Company 1
Blue Moon Brewing Company 1
DuClaw Brewing Company 1
Coney Island Brewery 1
Coors Brewing Company 1
Thirsty Dog Brewing Company 1
Hacker-Pschorr 1
Fish Brewing Company 1
Huyghe Brewery 1
Atwater Brewery 1
Ozark Beer Company 1
Orkney Brewery 1
Anchor Brewing Company 1
Lost Coast Brewery 1
Triton Brewing Company 1
Boulder Beer Company 1
Rhinelander Brewing Company 1
Georgetown Trading Co 1
Small Town Brewery 1
Fat Head's Brewery 1
Mother's Brewing Company 1
3 Floyds Brewing Company 1
Belhaven Brewery 1
Yuengling Brewery 1
Boddington's Brewery 1
Einstök Ölgerð 1
Omission Beer 1
Carlsberg Group 1
Arcadia Brewing Company 1
Resignation Brewery 1
Goodwood Brewing 1
Radeberger Gruppe 1
Tyskie Browary Książęce 1
Velké Březno 1
Cölner Hofbräu Früh 1
Tyranena Brewing 1
Dark Horse Brewing Co. 1
Ayinger Privatbrauerei 1
Brouwerij Rodenbach 1
Abita Brewing Company 1
Uerige Obergärige Hausbrauerei 1
Adnams 1
Schlafly - The Saint Louis Brewery 1

In [7]:
for b in sorted(uniqueBeers, key=lambda x: x['rating_score'], reverse=True)[:30]:
    print(b['brewery']['brewery_name'], b['beer']['beer_name'], b['rating_score'])


Southern Tier Brewing Company Cherry Cordial 4.75
Revolution Brewing Company Deth's Tar 4.75
Weyerbacher Brewing Company Sunday Morning Stout 4.75
Southern Tier Brewing Company Crème Brûlée 4.75
Bell's Brewery Black Note Stout (2016) 4.75
Dogfish Head Craft Brewery Raison D'Extra 4.75
Alltech Lexington Brewing & Distilling Co. Kentucky Bourbon Barrel Barleywine 4.75
New Holland Brewing  Pure Brews Porter 4.75
New Holland Brewing  Dragon's Milk: Basil 4.75
New Holland Brewing  Dragon's Milk Reserve: Raspberry Lemon 4.75
Crooked Ewe Brewery Bourbon Barrel-Aged Wendigo 4.75
Adnams Tally-Ho Reserve 2012 4.75
Upland Brewing Company Teddy Bear Kisses 4.75
New Holland Brewing  Dragon's Milk 4.75
Brasserie de Silly Scotch Silly 4.5
Beau's All Natural Brewing Company  Tom Green Cherry Milk Stout 4.5
Brasserie Dieu du Ciel! Péché Mortel 4.5
Anderson Valley Brewing Company Wild Turkey Bourbon Barrel Stout 4.5
Stone Brewing Drew Curtis / Wil Wheaton / Greg Koch Stone Farking Wheaton W00tstout (2018) 4.5
Mast Landing Brewing Co. Gunner's Daughter 4.5
Wicked Weed Brewing El Paraiso Imperial Coffee Stout 4.5
Brewery Ommegang Double Barrel Dubbel 4.5
Founders Brewing Co. Dankwood 4.5
New Holland Brewing  Dragon's Milk Reserve: Cherry Chocolate 4.5
New Holland Brewing  Dragon's Milk Reserve: Salted Caramel 4.5
Somerville Brewing Company (Slumbrew) Trekker Trippel 4.5
Barrel House Z Adeline Stout 4.5
The Bronx Brewery O.P.P. 4.5
Weyerbacher Brewing Company Blithering Idiot 4.5
Neshaminy Creek Brewing Company  Punkless Dunkel 4.5

In [8]:
ibuList, abvList = list(), list()
for b in uniqueBeers:
    ibuList.append(b['beer']['beer_ibu'])
    abvList.append(b['beer']['beer_abv'])
    
print('Avg. IBU: {}'.format(np.mean(ibuList)))
print('Avg. ABV: {}'.format(np.mean(abvList)))

fig, axarr = plt.subplots(1, 2, figsize=(7,3))
axarr[0].hist(ibuList, bins=20, alpha=0.5, linewidth=0)
axarr[0].set_xlabel('IBU (International Bitterness Units)', fontsize=12)
axarr[0].tick_params(axis='both', which='major', labelsize=12)

axarr[1].hist(abvList, bins=20, alpha=0.5, linewidth=0)
axarr[1].set_xlabel('ABV (Alcohol By Volume)', fontsize=12)
axarr[1].tick_params(axis='both', which='major', labelsize=12)
plt.tight_layout()


Avg. IBU: 28.702222222222222
Avg. ABV: 7.034466666666667

In [9]:
# Beer ABV vs IBU
beerMeasures = list()
for b in uniqueBeers:
    beerMeasures.append((b['beer']['beer_abv'],b['beer']['beer_ibu']))
beerMeasures = np.array(beerMeasures)
print(beerMeasures.shape)

fig = plt.figure(figsize=(4,4))
plt.scatter(beerMeasures[:,0], beerMeasures[:,1], alpha=0.5)
plt.xlim(xmin=0)
plt.ylim(ymin=0)
plt.xlabel('ABV (Alcohol By Volume)', fontsize=12)
plt.ylabel('IBU (International Bitterness Units)', fontsize=12)
plt.tick_params(axis='both', which='major', labelsize=14)


(450, 2)

In [10]:
# Scatter plot of avg. ratings vs. my ratings
scatterData = list()
for b in uniqueBeers:
    if b['beer']['rating_score'] == 0:
        continue
    scatterData.append((b['beer']['rating_score'], b['rating_score']))
scatterData = np.array(scatterData)    

fig = plt.figure(figsize=(4,4))
plt.plot([0,5],[0,5],'r--', linewidth=2)
plt.scatter(scatterData[:,0], scatterData[:,1], alpha=0.5)

minV, maxV = np.min(scatterData), np.max(scatterData)
print(minV, maxV)
plt.xlim((minV-0.2, maxV+0.2))
plt.ylim((minV-0.2, maxV+0.2))
plt.xlabel('Avg. rating', fontsize=14)
plt.ylabel('My rating', fontsize=14)
plt.tick_params(axis='both', which='major', labelsize=12)


2.0 4.75

In [11]:
# What kind of beers I like more than avg. people
scatterData = list()
for b in uniqueBeers:
    if b['beer']['rating_score'] == 0:
        continue
    scatterData.append((b['rating_score'] - b['beer']['rating_score'], 
                        b['beer']['beer_abv'],
                        b['beer']['beer_ibu']))
scatterData = np.array(scatterData)    
print(scatterData.shape)

fig, axarr = plt.subplots(1, 2, figsize=(7,3), sharey=True)
axarr[0].scatter(scatterData[:,2], scatterData[:,0], alpha=0.5)
axarr[0].axhline(y=0, c='k', linewidth=2, linestyle='--')
fit = np.polyfit(scatterData[:,2], scatterData[:,0], 1)
fit_fn = np.poly1d(fit) 
axarr[0].plot(scatterData[:,2], fit_fn(scatterData[:,2]), 'r--', linewidth=2)
axarr[0].set_xlim(xmin=-5, xmax=105)
axarr[0].set_xlabel('IBU (International Bitterness Units)', fontsize=12)
axarr[0].set_ylabel('Rating difference', fontsize=12)
axarr[0].tick_params(axis='both', which='major', labelsize=12)

axarr[1].scatter(scatterData[:,1], scatterData[:,0], alpha=0.5)
axarr[1].axhline(y=0, c='k', linewidth=2, linestyle='--')
fit = np.polyfit(scatterData[:,1], scatterData[:,0], 1)
fit_fn = np.poly1d(fit) 
axarr[1].plot(scatterData[:,1], fit_fn(scatterData[:,1]), 'r--', linewidth=2)
axarr[1].set_xlim(xmin=-1, xmax=max(scatterData[:,1])+1)
axarr[1].set_xlabel('ABV (Alcohol By Volume)', fontsize=12)
axarr[1].tick_params(axis='both', which='major', labelsize=12)
plt.tight_layout()


(446, 3)

In [12]:
# Cumulative beer discoveries
dTimes = list()
for b in uniqueBeers:
    dTimes.append(datetime.datetime.strptime(b['first_created_at'].split(' -')[0],
                                             '%a, %d %b %Y %H:%M:%S'))
dTimes.sort()
    
fig = plt.figure(figsize=(7,3))
plt.plot(dTimes, range(len(dTimes)), linewidth=2)
plt.ylabel('Unique beer count', fontsize=14)
plt.xticks(rotation=30)
plt.tick_params(axis='both', which='major', labelsize=12)



In [ ]: