If I Can’t Make Money, My Python Trading Bot Will…

Neal
6 min readJan 24, 2020
Photo by Chris Liverani on Unsplash

disclaimer: if you use this article as financial advice, be prepared to lose a lot of money. I am not an accredited source of financial advice.

FOOL’S GOLD

When I was a student in my first year at University, my classes bore me. I wanted to learn how to make money to get paid to go to the classes I didn’t like.

Like everyone that has seen The Wolf of Wallstreet, I turned to the stock market. I found a commission-free iOS trading platform called Robinhood, loaded a majority of my banked savings, and began reading books about trading (specifically value-trading).

Now, I know what you’re thinking: it was incredibly foolish to utilize my savings in an attempt to make money in the stock market as a naive, 18-year-old trader. I know. Seriously, do not do this. Do not do this.

However, since it was my money, I cared deeply about what happened to it. I spent hours each day dedicated to learning about the market, the ‘who’s who’ of finance, and where to find resources to learn how to become a profitable trader. Eventually, I stumbled upon works by Ray Dalio and Benjamin Graham.

I picked stocks such as $INTC, $AMD, and $NVDA due to enjoying building computers and having an above-average understanding of those companies and their products. But on the other hand, I also picked up $AAPL, $AMZN, and other stereotypical college bro-trader securities.

A few months pass, and I see an approximate 9% return on my initial portfolio. I quickly cashed out and left the market all-together. I considered myself lucky to have profitably learned through experience. Again, I know what you’re thinking, 9%? Really? I attribute most of that return to luck.

Photo by Felicia Buitenwerf on Unsplash

INSPIRATION

Fast forward two years, and I am nearing the end of my formal education. A few weeks ago, I received an email from my father entitled “Must Buy Stocks of 2019.” In traditional Indian father style, he gave no context in the email but the links and the singular word “thoughts?”

What you may not know is that my father loves to send my brother and I a plethora of emails that encourage us to not be a failure… if you’re of Asian or South Asian ancestry, you will understand.

I know enough about the market to know that articles on the internet are not reliable buy/sell indicators, and I told my father this many times; however, he never listened. The emails kept coming. I began to ponder a way to have any email he sent me with a similar subject/body auto-replied to by a Python bot.

While I was looking into how to do that, I had the idea to look into stock trading APIs, and that is when I found Alpaca—a trading platform that allows for both live and paper trading through the use of RESTful APIs. My father’s regular spam emails—especially ones talking about finance—ignited the idea to create an algorithmic trading bot.

Photo by Chris Ried on Unsplash

TOOLS

I started researching all the tools I’d need to use to bring this idea to fruition. Firstly, I’d need to choose a language to develop such a program… Python seemed like a good fit. Next, I needed to find a way to automate this task… I chose the Google Cloud Platform (GCP). I became familiar with the console because of my previous computer vision Raspberry Pi hardware camera project. Lastly, I needed to choose an algorithm that would allow me to build my program around such that the algorithm became a modular piece of the program. In other words, I wanted to plug-and-play different algorithms while keeping the same core trading code functionality.

BUILDING THE TRADING BOT

With the knowledge that I would be using the Alpaca trading platform and their python-based API wrapper, I began looking for packages and APIs that would build-out the database required for the bot.

I do not wish to articulate the process of building this bot in paragraph form… no one wants that. So here it is in a problem/solution format:

Problem: How can I get a list of stock market tickers? How can find information about those tickers?

Solution: Web-scraping eoddata.com with BeautifulSoup4 & passing the resulting stocks into the TD Ameritrade price history endpoint. I chose this solution because it costs $0 to implement, and it provides a large range for information for each security. (However, only 2 calls / second are allowed to the TD Ameritrade API.)

Problem: How do I organize this data? How can I efficiently feed this information into a Python script?

Solution: Using the GCP’s BigQuery Tables. These are essentially schema-strict databases that can be queried with SQL. And as far as efficiently feeding data into a Python script, this is where Pandas comes in handy.

Problem: How do we pick stocks?

Solution: Any algorithm can be translated into Python code; however, some are easier than others. Due to existing modules, such as pyportfolioopt, and articles such as this one by Quant-Investing, choosing and implementing an algorithm has never been easier! Once again, I am not guaranteeing any results nor giving financial advice.

Problem: How do I conduct trades?

Solution: Easy! As I mentioned earlier, the Alpaca platform has a great API; however, there is an even better option: the API Wrapper (linked again)! You can submit trades and even read account or order information through the use of defined objects. Read the documentation for more information.

Photo by Adam Nowakowski on Unsplash

THE FINAL PROGRAM

Once you have all these tools, it becomes easy to fabricate the bot. Think of each part of this program as a physical pipe. The output of one pipe is the input to the next.

[0] DATA_PIPE: this pipe will take all of your BigQuery Table data that you scraped and push it forward down the line.

[1] ALGO_PIPE: the pipe that takes DATA_PIPE’s output (raw scraped data) and processes it. Assigning a ‘score’ that ranks each stock by its algorithmically assigned ‘potential profitability’ metric, the ALGO_PIPE is the core piece of this program. It determines what will be bought and sold.

[2] PROCESSING_PIPE: this pipe takes a score for every single stock in your universe and eliminates “bad apples,” such as penny stocks, and cleans your list of potential buys and sells. This pipe will also take current portfolio data and create a “delta” list, or a list of desired positions given current ones. For example, you might want to increase/decrease a current position, liquidate it all-together, or buy a whole new position.

[3] ORDER_PIPE: this pipe will take a cleaned lists of buys and sells. It will then pass all of this data into the final piece of the puzzle, the API Wrapper for Alpaca. Here, orders will be submitted to your personal account. And that’s it!

AUTOMATION

Now, you might be asking yourself… this is all great, but how do I automate it? That is where the GCP comes into play. This Python script can be executed as a Cloud Function and scheduled using Cloud Tasks. I run my scrape every day at 5:00 PM EST, and I run my daily trades every day at 8:50 AM EST. It is important to remember that the daily scrape will directly effect the algorithm results if it requires running (continuously updated) data.

CONCLUSION

While this was quite the project to tackle, there is much excitement in continuing to develop this bot. Currently, I have implemented only market trades and have not even touched shorting, after-hours, or limit trades. I look forward to learning more throughout this process and bringing together a more holistic project.

Code for this project can be found on my GitHub.

--

--