Ok, so to build a ‘proper’ stock trading bot you really need to use a API enabled stock broker which was beyond what I wanted to do (for the time being at least). So this is more just about having a bit of fun and utilising a Python web scraper to get real-time stock information from a website, in our case Yahoo finance. There are a couple of different web scrapper libraries but I went with one called Beautiful Soup, you can use it to pull data out of HTML and XML files.
I found this tutorial on YouTube really helpful..
I then wrote the prices to a csv file - I programmed my bot so that it could pull in up to 100 stock prices, however the program takes a couple of seconds to scrap each price, which doesn’t sound like a lot but I found myself opting to limit it to five stocks, so that it would pull in the prices for all of them every 15ish seconds, any longer then 15 - 20 seconds just feels like too long for ‘real time’.
Then I had to choose a trading algorithm to decide when to buy/sell stocks. Because I was just pulling in the price (I could have pulled in more indicators such as PE ratio and trading volumes but I’m trying to keep the program simple at this stage in time) the list of possible trading algo’s is nice and small and I decided on moving averages. If this was a real trading bot it seems that a legit buy/sell indicator could be when the 5hr moving average crossed the 20hr moving average. I used this idea but because this isn’t real life I went with when the 2 minute moving average crossed the 10 minute moving average to get fasted results then having to wait 20+ hours.
Again this bot is useless in real life, it was just a mini project to learn some new Python technologies, so what did I learn?
- Web scraping using the Beautiful Soup library
- Moving Averages in Python using lists
- Scheduled tasks using the Schedule library
At some point in the future I’m planning on re-visiting this project and trying to make a bot for ‘real life’ stock trading (although not using real money).