Run your first trading algorithm!

Code or pick an algorithm, backtest it, and run it using a paper or money account in Alpaca.

Felipe Cunha
Towards Data Science

--

Photo by Phillip Glickman on Unsplash

Disclaimer: The content of this article does not constitute financial advice. This is a mere tutorial on how to set up the infrastructure for a trading bot.

The motivation

Well, a picture is worth a thousand words. See below the performance comparison of the S&P500 index and some of the mutual funds that compose the ML 401k portfolio, and make your own conclusions.

(Source: https:/finance.yahoo.com)

S&P500 vs FSELX
S&P500 vs RYSIX
S&P500 vs S&P500?

As you can tell, the performance of these mutual funds isn’t that great when compared to S&P500. Besides that, obtaining performance/risk metrics for those funds isn’t straightforward. Sharpe ratio, max drawdown, alpha, beta — good luck trying to find that.

We shouldn't blindly rely on corporations to manage our finances. By the end of the day, it’s our future and we’re the most interested in it.

But who has time to manage a portfolio? Well, this is why we need to automate it.

Let’s see how we can deploy our first trading algorithm.

The architecture

You’ll need:

  • Quantopian code. Write your own or search in the community. There’s a lot of good stuff out there, but I’d recommend a market neutral strategy (small market correlation, small Beta) due to the current COVID-19 market volatility.
  • PythonAnywhere account (you’ll need the 5 dollar/month plan): https://www.pythonanywhere.com/
  • Alpaca account (it’s free!)
    https://alpaca.markets
I should’ve been an artist.

Setting up the infrastructure

  1. Alpaca

Once you’ve created and verified your Alpaca account, click on ‘Go to Paper Account’ and hit the button ‘View’ in the ‘Your API Keys’. Take note of the key_id, secret_key and base_url.

2. PythonAnywhere

Creating a virtual environment

Time Magazine’s 2015 virtual reality cover spawned a classic meme. Pic: @PellyNV

Let’s start by creating a virtual environment with python 3.6 and install pylivetrader.

Pylivetrader is the package that will allow Alpaca to understand Quantopian algos. This package allows you to harvest the power of the backtesting capabilities of Quantopian and Alpaca’s algorithmic order execution, all glued together with PythonAnywhere while running uninterrupted in the cloud.

Upon creating and upgrading your account (to the cheapest plan), you’ll need to create a virtual environment with Python 3.6 and install pylivetrader.

Open a bash on PythonAnywhere and type the following commands:

$ python3.6 -m venv venv
$ source venv/bin/activate
(venv)$ pip install pylivetrader

Note that pylivetrader will only work with Python 3.6.

All the packages installed inside the virtual environment will only be accessible inside the same, here called ‘venv’. The Python version inside ‘venv’ will also be restricted to 3.6 (in this particular case); however, you can still use other python versions outside of the ‘venv’. In order to do so, simply type deactivate.

(venv)$ deactivate

You can jump right back into the virtual environment by typing:

$ source venv/bin/activate

Uploading a Quantopian algo

Close the bash and go to ‘Files’, create a new empty file called algo.py, and paste the following code:

from pylivetrader.api import order_target, symbol

def initialize(context):
context.i = 0
context.asset = symbol('AAPL')

def handle_data(context, data):
# Compute averages
# data.history() has to be called with the same params
# from above and returns a pandas dataframe.
short_mavg = data.history(context.asset, 'price', bar_count=100, frequency="1m").mean()
long_mavg = data.history(context.asset, 'price', bar_count=300, frequency="1m").mean()

# Trading logic
if short_mavg > long_mavg:
# order_target orders as many shares as needed to
# achieve the desired number of shares.
order_target(context.asset, 100)
elif short_mavg < long_mavg:
order_target(context.asset, 0)

Save it and close it. We’ll need a configuration file to get access to Alpaca; remember the api_key and secret? We’ll need them now.

Create a new file called config.yaml and add the following definitions:

key_id: 'your key_id'
secret: 'your secret'
base_url: https://paper-api.alpaca.markets

Save it and close it. We’re almost done: the last thing to do is to schedule a task that will run in the cloud uninterrupted.

Go to tasks, scroll all the way down to ‘Always-on tasks’, and type the following command:

source venv/bin/activate && pylivetrader run -f algo.py --backend-config config.yaml

After a little bit, the task will start to run:

Finally, go to your Alpaca paper account and check if the orders are going through.

Once you’re ready to start with real money, get the api key and secret for your money account and update the config.yaml file.

Conclusion

In this article, we went through the steps to run a Quantopian algorithm using PythonAnywhere and Alpaca.

Depending on your algorithm you may need to include more imports to make it work. You can find here a list of what packages need to be imported for each case here:

https://alpaca.markets/docs/alpaca-works-with/zipline-to-pylivetrader/

Finally, if you decide to run your Alpaca money account, I strongly advise to use a market neutral algo (shorts and longs positions in equal proportions). My Apple stock Bollinger bands trading algo has been working very well with all the volatility caused by the Corona virus crisis. You can check it out here: https://towardsdatascience.com/backtesting-bollinger-bands-on-apple-stock-using-quantopian-6be2e4824f43

I hope you have enjoyed this article! Please don’t hesitate to comment or share your results.

Thanks

Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.

--

--