How to Build your Personal Automated Stock Trading Agent using Deep Learning Forecasts in Python

Predicto
8 min readDec 8, 2020

--

Photo by Christopher Burns on Unsplash

After you are done reading this article you will be in a position to setup your own auto stock trader based on Deep Learning forecasting. You are going to achieve this by retrieving the latest stock forecasts from Predicto API and submitting them daily to Alpaca using your own test account. You can be up and running in a couple of hours!

Introduction

A large part of stock trading is done by automated systems these days. More and more quantitative hedge funds start to appear. A search online will convince you. Hedge Funds and banks, realizing the potential of big data and latest advances in Deep Learning, are growing their Data Science and Infrastructure teams or start building them if they are already left behind in this game.

If you have been following Predicto, you should have a good idea by now on how we use Deep Learning to generate short-term forecasts for the stocks we follow. You should also have a good understanding on how we deal with uncertainty and how we use our explainability framework to understand what our models “see” in order to identify what factors and which time periods influence their predictions.

We’ll analyze step by step how we can connect the dots and trade those forecasts! We will go through detailed code using Predicto Python library and Alpaca Python package to submit our orders and hedge them.

We have been experimenting for quite some time with the paper (test environment) version of Alpaca API and it’s been very accurate, trustworthy, and it provides all the tools we need to construct a fully automated trader based on our forecasts.

At the end of this article, you will find links to Predicto Python library on GitHub, a detailed Jupyter Notebook and a link to a python script that you can use to get started straight away.

Context

Before jumping into the code, for those that are not familiar with Predicto we provide some links to previous medium articles to help you better understand what we do.

Terminology

Forecast: when we refer to a forecast we mean a 15-day prediction by Predicto’s models (this means a price for each one of the next 15 days).

Trade Pick: a trade pick contains information derived from our latest forecast for a stock. It contains uncertainty level, entry price, target price, stop-loss price, expiration date, trade action (BUY/SELL), model’s historical ROI and more.

From Forecasting to Trading. Automated end to end.

Examples of forecasts and trade picks will be given below as we go on.

Let’s prepare our setup and explore

To setup your first Automated Trader based on Deep Learning forecasts, you are going to need 3 things:

  1. A Predicto account to retrieve latest forecasts and Trade Picks programmatically
  2. An Alpaca account to submit stock market orders programmatically
  3. The Predicto Python library available on GitHub that contains everything we need to start interacting with both Predicto and Alpaca.

Once we have those, we can go ahead and initialize PredictoApiWrapper and AlpacaApiWrapper. You’ll have to replace the xxxxxxx parts with your own keys to get access to your Predicto and Alpaca account. Make sure you use the Alpaca API paper (test environment) endpoint while testing.

Initialization of API wrappers

OK, now let’s see if our wrappers work as expected.

Script
Output

Seems we are good to go. We are able to query Predicto API and Alpaca API successfully!

As an example, we are going to retrieve the latest Forecast and Trade Pick from Predicto for a random stock. Let’s go with Visa Inc. stock (V):

Script
Output

Predicto gives a forecast for the next 15 days along with uncertainty percentage for each prediction. It also gives a Trade Pick based on this forecast which contains an action (BUY) with entry price, target price, stop loss price and expiration date. We can use this Trade Pick prediction to submit it to Alpaca and hedge it — or you can calculate your own entry/target/stop-loss prices based on your own logic, it’s up to you.

Be careful, some Trade Picks might return a SELL action which means that our models predict a down trend. If you decide to use those predictions, Alpaca API will open a short position. Make sure you understand the risks of shorting before using those trade orders. Otherwise you can choose to only use BUY orders.

When it comes to placing our order with Alpaca API, we can do this either by submitting a bracket order (market order, take-profit and stop-loss order in one go), or by submitting a market order to open the position and later hedge it with an OCO (take-profit and stop-loss) order. We prefer the second as we usually want to let our position open for at least one day and add the exit orders the next day to avoid opening and closing positions on the same day (for more details on those type of orders, check Alpaca orders documentation). But for our Automated Trader example we are going to use bracket orders, all in one go.

Let’s Trade!

We are finally ready to use our Automated Trader!

Complete auto trading Python script

We did it — We have successfully submitted 3 orders based on latest Predicto Forecasts!

You can experiment with different parameter values for submit_latest_trade_picks(…) method to match your personal preferences.

Keep in mind that if the stock price changed since Predicto generated those forecasts (very possible due to pre-market and after-hours activity) then target price and stop loss prices will be re-adjusted, and order will only be submitted if it makes sense: e.g. if action is BUY and new price is more than target price then we’ll cancel, if action is BUY and new price is less than target price we’ll go through with re-adjusted stop-loss, etc. (more details on this logic in AlpacaApiWrapper.validate_latest_price_and_stoploss method)

We can check the Alpaca Web UI orders section to verify that we submitted our orders successfully:

Indeed we can see 3 open orders for EXPE, LYFT, NFLX. Two BUY orders and one SELL(short), just like we saw in the output of our trading script.

Also in our order history in Alpaca’s Dashboard page, we can see the Held orders that are hedging our position and will be triggered once stock price moves beyond those points.

You can use the above Python code daily, as a scheduled job at 9.31am E.T., and use latest Forecasts from Predicto to auto trade. We generate Forecasts and Trade Picks daily.

Another important thing to know is the Pattern Day Trader (PDT) Protection at Alpaca. Below explanation comes from Alpaca Documentation:

Pattern Day Trader (PDT) Protection at Alpaca

In order to prevent Alpaca Brokerage Account customers from unintentionally being designated as a Pattern Day Trader (PDT), the Alpaca Trading platform checks the PDT rule condition every time an order is submitted from a customer. If the order could potentially result in the account being flagged as a PDT, the order is rejected, and API returns error with HTTP status code 403 (Forbidden).

An account is designated as a Pattern Day Trader if it makes four (4) day trades within five (5) business days. Day trades less than this criteria will not flag the account for PDT.

So make sure you take this into account in your Automated Trader by adding some logic to remember how many trades you execute and how many are considered day trades.

Use your paper account to experiment, but before switching to real money make sure you understand all the risks — Please read Disclaimer section below.

As a final note, the Trade Picks returned by submit_latest_trade_picks(…) method are generated daily around 10pm E.T. and are also available in our website.

Daily Trade Picks with links to forecast details, explainability graphs and more

There you can find more details about each Trade Pick such as forecasting details, explainability graphs, model performance per stock and more.

Making your trade algorithm robust and reliable

For robust systems, it’s very important to handle all errors and always verify occasionally that there are no orphan orders or positions, for example pending orders that never filled. Ideally you want to put in place some kind of automated supervisor that makes sure you are completely aware of the current state of your auto trading. Also you might want to scan and exit positions that have been active beyond a Trade Pick expiration date and haven’t hit your take-profit or stop-loss price, so that you can start fresh with this stock.

As mentioned above, it is a good idea to add some logic to avoid Pattern Day Trader (PDT) flag on your Alpaca account. There is chance that your take-profit or stop-loss order is executed on the same trading day that the position was opened because of increased intra-day market volatility.

We’ll come back to this topic in more detail with a dedicated post in the near future. But for now, keep in mind that reliability of an automated stock trading system is key.

Disclaimer

Note that our forecasts will NOT always be on the right direction. To understand more on how our forecasts are generated and how we are able to provide an explainability framework, please read our previous posts on medium at Predicto.

Please also read our full disclaimer here.

In our first ever medium post, Investing + Deep Learning — an introduction, we mentioned:

When it comes to investing, what Deep Learning can offer is identifying complex patterns that are not visible to the human eye. Whether the patterns found are useful depends on the data we feed our models, so our job is to feed quality data.

Deep Learning for investing can’t predict the future, can’t predict unpredictable events, but it might be able to identify complex patterns.

With a certain level of uncertainty.

Identifying and evaluating those opportunities is our goal.

Make sure you understand all the risks involved before using real money in Automated Trading!

Thank you

If you made it this far, good job! We really hope you enjoyed this as much as we did!

Let us know about any questions in the comments section or contact us directly with suggestions and/or feedback.

See you soon!

Web https://predic.to — Twitter @ThePredicto — GitHub ThePredicto

Links to APIs, Documentation & Notebooks

  1. https://github.com/thepredicto/predicto_api — Predicto Python Library
  2. https://github.com/thepredicto/predicto_api/blob/main/Notebooks/predicto_autotrader_example.ipynb — This posts’s code in a Jupyter Notebook
  3. https://github.com/thepredicto/predicto_api/blob/main/samples/autotrader_daily.py — Daily Automated Trader python script
  4. https://predic.to/ — Create your free trial account to get access to latest forecasts and trade picks generated daily using explainable Deep Learning models
  5. https://alpaca.markets/ — Alpaca website to create your free paper test account
  6. https://github.com/alpacahq/alpaca-trade-api-python/ — Documentation for alpaca python trade api
  7. https://alpaca.markets/docs/trading-on-alpaca/orders/ — Alpaca documentation to understand order types

--

--

Predicto

Stock & Cryptocurrency Forecasting AI. Based on Options Data. Powered by Intelligible Deep Learning models. https://predic.to