This is probably my favorite side project I’ve done. I’ve always been interested in algorithmic trading, and it’s exciting to code something that can potentially repay you in the form of cold, hard cash.
The bot is written in Python and relies on two core libraries for the majority of its functionality: robin-stocks and ta. robin-stocks is a library that interacts with the Robinhood API and allows one to execute buy and sell orders, get real time ticker information, and more. ta is a technical analysis library that also incorporates the Python Pandas library to generate indicators from stock data.
Okay, that’s nice to know, but what does the bot actually do?
As of now, it implements the golden cross strategy, so if a stock’s 50-day moving average crosses above its 200-day moving average, we purchase it. Likewise, we own a stock and its 50-day moving average crosses below its 200-day moving average (AKA a death cross), we sell it. A really simple and well-known strategy. The nice thing about the code is that it’s really simple to write and plug in new strategies, which I’ll likely be adding in the near future.
For Robinhood, the stocks we hold are listed in the portfolio section of the app, and the stocks we want to buy are listed in our watchlist. So every time you run the script, it will scan your portfolio for stocks that meet the selling requirement, and scan your watchlist for stocks that meet the buying requirement, and potentially execute the orders.
The bot can also keep track of your trades, writing the initial buying price of the stock, the date it was bought and sold, the total gain from the trade, and more as JSON data to a text file.
So how do I run it?
Install Python on your machine if you haven’t already (I use Python 3), and use pip to install robin-stocks, ta, numpy, pandas, and matplotlib.
Once you’ve downloaded the repo, edit line 10 of main.py to include the email address and password you use to login to Robinhood. If you want to see which stocks have had golden/death crosses, but don’t want to actually execute the orders, comment out lines 236–238 (preventing sell orders) and 244–245 (prevents buy orders). Then simply run main.py.
Whenever the script sells a stock, it considers itself to have completed a trade and writes data about the trade to a text file. To print out information from the file, call read_trade_history(“tradehistory.txt”). tradehistory.txt is the default file that I’ve included in the repo to store this information.
Here’s a sample run of the script:
Since I’m using the 50-day and 200-day moving averages as my indicators, I only have to run the script once a day to keep the bot running up to speed with the market. To run the script with a single click, you can create a batch file.
Thanks for reading, and feel free to edit the repo however you want and implement your own strategies. If you want a bit more insight on the code, keep scrolling.
Some notes on the code
Here’s the snippet of code in main.py that fetches the symbols for each stock in our portfolio and watchlist and returns them as 2 lists of strings.
Now that we have a list of the stock tickers in our portfolio and watchlist, we can feed them into the strategy.
Here is all the code that pertains to our strategy.
In the last method, golden_cross(), we get the stock’s historical data from the last year and extract the closing prices and corresponding dates on lines 80–85, putting them into two lists. We convert those lists into pandas series so they can be used as input for the ta library function, bollinger_mavg(), which generates simple moving averages for the stock. We concatenate the pandas series that contain the price, indicators, and dates into a single dataframe on lines 91–92, and finally call get_last_crossing(), which returns 1 if there was a golden cross, 0 if nothing happened, and -1 for a death cross.
If you want to use a golden cross strategy with indicators other than the simple moving average, this documentation for the ta library provides many options. You would simply replace lines 89–90 with your indicators of choice.
The function five_year_check() is something I added to the strategy, I’m making sure that a stock has IPO’d or risen overall within the last 5 years before buying it, since stocks that don’t meet this requirement are either:
- Fundamentally on the decline (Most stocks should be expected to gain over a period of several years, since the average annual market return is 7–10%)
- Related to commodities and range-bound, so the golden cross strategy is not very suited for trading them.
You can comment out lines 94–95 to see the price and indicators charted out using matplotlib.
Here is the remaining code in main.py:
scan_stocks() is the method that actually iterates through the stock symbols from your portfolio and watchlist, checks for a golden/death cross, and calls sell_holdings() to execute sell orders, buy_holdings to execute buy orders, and update_trade_history() to write trade information to the text file.
We call our golden cross strategy on lines 59 and 67. You can edit their arguments to change the periods of the moving averages, defined by the arguments n1 and n2, and the number of days you want to look back in order to find a cross, defined by the argument days.
Currently, sell_holdings() will always sell all of your holdings of a stock, and buy_holdings() will try to buy an amount of shares that will spread your holdings roughly evenly and try to use up some extra buying power if you have a lot lying around. You could edit these methods to change the bot’s behavior.