Skip to content

Instantly share code, notes, and snippets.

@mmaelzer
Last active October 18, 2016 04:07
Show Gist options
  • Save mmaelzer/e65521bb1453097ea1c9433ceaf7477c to your computer and use it in GitHub Desktop.
Save mmaelzer/e65521bb1453097ea1c9433ceaf7477c to your computer and use it in GitHub Desktop.
Bash script to fetch latest polls-only forecast from fivethirtyeight.com. Defaults to US but allows an optional state argument.
#!/bin/bash
# Fetches data from http://projects.fivethirtyeight.com/2016-election-forecast/summary.json,
# parses the results using python, and prints the polls-only forecast results in the format:
# "{STATE} D {PROBABILITY} R {PROBABILITY}"
#
# The script takes an optional argument that specifies an individual two letter abbreviation (case insensitive)
# of a U.S. state. By default, the state is US which returns the national results.
#
# Examples:
# $ ./538.sh ca
# CA D 50.00% R 50.00%
#
# $ ./538.sh
# US D 50.00% R 50.00%
STATE=${1:-US}
URL="http://projects.fivethirtyeight.com/2016-election-forecast/summary.json"
curl -sH "Accept:application/json" -H "Accept-encoding:gzip" $URL | \
gunzip - | \
python -c "\
import sys, json; \
results = json.load(sys.stdin); \
state = next((r for r in results if r['state'] == '$STATE'.upper()), None); \
getprob = lambda party: state['latest'][party]['models']['polls']['winprob']; \
print '{} D {}% R {}%'.format('$STATE'.upper(), getprob('D'), getprob('R'))"
#!/bin/bash
# Fetches data from http://projects.fivethirtyeight.com/2016-election-forecast/summary.json,
# parses the results using python, and prints the polls-only forecast results in the format:
# "{STATE} D {PROBABILITY} R {PROBABILITY}"
#
# Lists all states, sorted by party. Default: D
# To sort by R, use:
# ./538-ls R
PARTY=${1:-D}
URL="http://projects.fivethirtyeight.com/2016-election-forecast/summary.json"
curl -sH "Accept:application/json" -H "Accept-encoding:gzip" $URL | \
gunzip - | \
python -c "\
from __future__ import print_function; \
import sys, json; \
results = json.load(sys.stdin); \
get_prob = lambda d, party: d['latest'][party]['models']['polls']['winprob']; \
probs = [{'state': d['state'], 'D': get_prob(d, 'D'), 'R': get_prob(d, 'R')} for d in results]; \
probs.sort(key=lambda p: p['$PARTY'], reverse=True); \
[print('{}\tD {:>5.2f}%\tR {:>5.2f}%'.format(p['state'], p['D'], p['R'])) for p in probs]"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment