Skip to content

Instantly share code, notes, and snippets.

@jszym
Last active November 5, 2024 20:28
Show Gist options
  • Save jszym/89a1542baff2c035c052b483fba5372f to your computer and use it in GitHub Desktop.
Save jszym/89a1542baff2c035c052b483fba5372f to your computer and use it in GitHub Desktop.
2024 Election Forecast Ensemble
from random import random
state_codes = ['al','ak','az','ar','ca','co','ct','de','dc','fl','ga','hi','id','il','in','ia','ks','ky','la','me','me1','me2','md','ma','mi','mn','ms','mo','mt','ne','ne1','ne2','ne3','nv','nh','nj','nm','ny','nc','nd','oh','ok','or','pa','ri','sc','sd','tn','tx','ut','vt','va','wa','wv','wi','wy']
# Probabilities from an average of the following state-level forecasts:
# - Nate Silver Bulletin
# - FiveThirtyEight
# - 338Canada
# - The Economist
# - RaceToTheWH
# - The Hill
state_probs = [0.03,7.30,32.88,0.07,100.00,97.75,99.45,99.15,100.00,8.20,39.85,99.43,1.18,98.82,0.02,16.00,0.53,0.02,0.12,93.55,99.88,12.74,100.00,99.97,60.97,89.90,0.83,0.85,0.48,0.03,2.44,91.78,0.02,47.95,84.48,99.05,89.52,99.97,39.10,0.15,6.48,0.00,98.37,49.95,99.20,1.22,0.13,0.00,7.22,0.15,99.97,90.95,99.95,0.05,57.00,0.02]
state_evs = [9,3,11,6,54,10,7,3,3,30,16,4,4,19,11,6,6,8,8,2,1,1,10,11,15,10,6,10,4,2,1,1,1,6,4,14,5,28,16,3,17,7,8,19,4,9,3,11,40,6,3,13,12,4,10,3]
dem_wins = 0
# Number of simulations to run
sims = 1_000_000
# update these with the two-letter state codes of the states that are called for either Harris or Trump.
called_states_for_harris = []
called_states_for_trump = []
for _ in range(sims):
dem_evs = 0
for state_code, state_prob, state_ev in zip(state_codes, state_probs, state_evs):
p = state_prob / 100
x = random()
if (x <= p or state_code in called_states_for_harris) and state_code not in called_states_for_trump:
dem_evs += state_ev
if dem_evs >= 270:
dem_wins += 1
print(f"Harris wins {dem_wins} of {sims} simulation ({dem_wins/sims:.3}%)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment