The Trump Bot

Earlier this year, I found myself checking Trump's approval rating several times a week. I realised that if someone had made a Twitter account that posted updates, then I could turn on push notifications and be alerted when things changed.

It turned out to be true: @potusapproval does just that. I turned on these notifications. For the record, his approval so far is about 35% and decreasing at about 1% per month.

Not long later, I found out that betting odds were suggesting that Trump may not make it to the end of his four year term, and that the chances of this happening were as low as 50%. This gave me something else to check, and I couldn't find a bot for this one.

Betfair Exchange

I like watching betting markets for a fairly neutral view of what is likely to happen, especially when there is a wide range of opinions in the media. You can figure out the effective probability of something happening from betting odds, but there's a slight catch - since the bookie always takes a cut, the odds are slightly changed. If you sum the probabilities of each event happening, you will get to slightly less than one.

Betfair Exchange is a little different: it's a platform allowing people to bet against each other. They claim that this leads to the best odds, and that's true, in a way, but only because they're making money in a different way. If you win, they take a cut from the winnings afterwards, typically 5%. Anyway, since people are betting both ways on the same thing it's possible to take the average of the two sets of odds and get an unbiased estimate for the likelihood of something happening.

How it works

I previously wrote a simple bot to post the opening times for the Oxford University Parks. It worked by using BeautifulSoup to scrape the relevant information from a webpage, then Tweepy to post the times once a week. This wasn't too hard to do once the authentication was set up.

I refactored this slightly to add room for a second bot, this time tweeting about Trump. Here, though, it got a little bit more complicated. Since Betfair uses a dynamic webpage updated by javascript, you can't just download the HTML and parse it to find the information you want. The static HTML doesn't contain what you need.

Fortunately, people have had this problem before. Selenium is a project that allows you to harness a real web browser from your application. You can get it to launch your local Firefox, load the page, extract the data, and close it again. In the case that you don't have a desktop open (you really want to run this on a server), there's a project called PhantomJS that makes a headless version of Chrome you can use.

Deployment

You might have a virtual private server you can use, but in practice we've all got a Raspberry Pi lying around that could use a project. I wrote a shell script to set up virtualenv and add a cron job to run it every hour.

You can find everything at Github, and the bot is on Twitter here.