How to Build your Personal Automated Stock Trading Agent using Deep Learning Forecasts in Python
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!
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.
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.
- Investing + Deep Learning — an introduction
- Studying volatility, uncertainty and news
- Studying news momentum and narratives
- Explaining Financial Deep Learning Forecasts
- Understanding Deep Learning Forecasts over Time
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 (
SELL), model’s historical ROI and more.
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:
- A Predicto account to retrieve latest forecasts and Trade Picks programmatically
- An Alpaca account to submit stock market orders programmatically
- 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
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.
OK, now let’s see if our wrappers work as expected.
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):
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
SELLaction 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
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.
We are finally ready to use our Automated Trader!
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
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.
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.
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!
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!
Links to APIs, Documentation & Notebooks
- https://github.com/thepredicto/predicto_api — Predicto Python Library
- https://github.com/thepredicto/predicto_api/blob/main/Notebooks/predicto_autotrader_example.ipynb — This posts’s code in a Jupyter Notebook
- https://github.com/thepredicto/predicto_api/blob/main/samples/autotrader_daily.py — Daily Automated Trader python script
- https://predic.to/ — Create your free trial account to get access to latest forecasts and trade picks generated daily using explainable Deep Learning models
- https://alpaca.markets/ — Alpaca website to create your free paper test account
- https://github.com/alpacahq/alpaca-trade-api-python/ — Documentation for alpaca python trade api
- https://alpaca.markets/docs/trading-on-alpaca/orders/ — Alpaca documentation to understand order types