Skip to content

Instantly share code, notes, and snippets.

# tvladeck/Updated Simulation.RSecret Created Oct 2, 2012

State Intrade prices imply a 98% probability of Obama Winning
 library("hash") # States treated as going democratic with probability 1 DemStates <- hash() .set(DemStates, "WA"=12, "OR"=7, "CA"=55, "NM"=5, "MN"=10, "IL"=20, "MD"=10, "DC"=3, "DE"=3, "NJ"=14, "CT"=7, "RI"=4, "MA"=11, "VT"=3,"ME"=4,"HI"=4, "NY"=29) # States treated as going republican with probability 1 RepStates <- hash() .set(RepStates, "ID"=4, "UT"=6, "WY"=3, "MT"=3, "ND"=3, "SD"=3, "NE"=5, "KS"=6, "OK"=7, "TX"=38, "AR"=6, "LA"=8, "MS"=6, "AL"=9, "GA"=16, "TN"=11, "KY"=8, "WV"=5, "SC"=9, "AK"=3) # Swing States # First entry in each value of the hash is the electoral # college vote # Second entry is the intrade probability of the state # going democratic SwingStates <- hash() .set(SwingStates, "AZ"=c(11, 0.200), "NV"= c(6, 0.812), "IN"=c(11, 0.150), "WI"=c(10, 0.769), "CO"=c(9, 0.762), "MI"=c(16, 0.900), "IA"=c(6, 0.750), "VA"=c(13, 0.741), "MO"=c(10, 0.250), "NC"=c(15, 0.370), "FL"=c(29, 0.678), "PA"=c(20, 0.835), "NH"=c(4, 0.786), "OH"=c(18, 0.744)) # electoral college votes needed to win kCountNeeded <- 538/2 Run.Simulation <- function () { # Returns TRUE if simulation predicts democratic win # ... and FALSE otherwise # treats each state as independent (I know - not true...) # the count of electoral votes that are "safely" democratic dem.count <- sum(values(DemStates)) # runif(1) is a uniform random variable in (0,1) # it has a 75% probability of being less than 0.75 # this is how we simulate the outcomes with the intrade # probabilities listed above for (i in keys(SwingStates)) { result <- runif(1) state <- SwingStates[[i]] if (result < state) { # if runif(1) < intrade price dem.count <- dem.count + state # then the dems get the votes } } if (dem.count > kCountNeeded) { return(T) } else { return(F) } } Run.Simulations <- function(count) { # returns portion of simulations that returned a # democratic win i <- 0 total.results <- c() while (i < count){ single.result <- Run.Simulation() total.results <- append(total.results, single.result) i <- i + 1 } return(sum(total.results)/count) } Run.Simulations(10000) #=> ~ 0.97
to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.