Created
November 6, 2020 07:30
-
-
Save nanaze/9a420453305e5fda7965376103da1777 to your computer and use it in GitHub Desktop.
Calculate x intercept for Pennsylvania ballot counting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# Calculates expected time that Biden will overtake Trump in Pennsylvania | |
# base on time series data: margin over time. | |
# | |
# Example usage: | |
# $ curl "https://raw.githubusercontent.com/alex/nyt-2020-election-scraper/master/battleground-state-changes.csv" | ./calculate_margin_intercept.py | |
import csv | |
import datetime | |
import sys | |
import numpy as np | |
def _YieldRecords(): | |
reader = csv.DictReader(sys.stdin) | |
yield from reader | |
def _FilteredRecords(): | |
for record in _YieldRecords(): | |
if 'Pennsylvania' in record['state']: | |
yield record | |
def _YieldDataPoints(): | |
# Ignore times before noon wed | |
cutoff = datetime.datetime.fromisoformat( | |
'2020-11-05 12:00:00-05:00') | |
for record in _FilteredRecords(): | |
margin = int(record['vote_differential']) | |
# source data is UTC | |
timestamp = datetime.datetime.fromisoformat( | |
record['timestamp']).replace(tzinfo=datetime.timezone.utc) | |
if timestamp >= cutoff: | |
unix_timestamp = datetime.datetime.timestamp(timestamp) | |
yield unix_timestamp, margin | |
def main(): | |
points = list(_YieldDataPoints()) | |
x = [d[0] for d in points] | |
y = [d[1] for d in points] | |
model = np.polyfit(x, y, 1) | |
a , b = model | |
# y = a * x + b | |
# y - b = a * x | |
# 0 - b = a * x | |
# x = (0 - b) / a | |
intersection = b / -a | |
print('Intersection timestamp:', intersection) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment