Skip to content

Instantly share code, notes, and snippets.

@elrasguno
Forked from mmaelzer/538.sh
Created October 17, 2016 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elrasguno/6aa803fd7708ba435cd89514de5de0c8 to your computer and use it in GitHub Desktop.
Save elrasguno/6aa803fd7708ba435cd89514de5de0c8 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 R:50
#
# $ ./538.sh
# US D:50 R:50
STATE=${1:-US}
curl -sH "Accept:application/json" -H "Accept-encoding:gzip" http://projects.fivethirtyeight.com/2016-election-forecast/summary.json | \
gunzip - | \
python -c "\
import sys, json; \
results = json.load(sys.stdin); \
us = next((r for r in results if r['state'] == '$STATE'.upper()), None); \
getprob = lambda party: us['latest'][party]['models']['polls']['winprob']; \
print '{} D {}% R {}%'.format('$STATE'.upper(), getprob('D'), getprob('R'))"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment