DEV Community

Cover image for Algorithmic Trading: backtesting your algorithm
An Rodriguez
An Rodriguez

Posted on • Updated on • Originally published at Medium

Algorithmic Trading: backtesting your algorithm

As I wrote in my previous article, Algorithmic Trading: algorithms to beat the market, if you are into writing code to buy and sell stocks, options, forex or whatnot, it's very important to consider backtesting your code.

What is Backtesting?

Backtesting a trading algorithm means to run the algorithm against historical data and study its performance.

From Investopedia:

Backtesting is the general method for seeing how well a strategy or model would have done ex-post. Backtesting assesses the viability of a trading strategy by discovering how it would play out using historical data. If backtesting works, traders and analysts may have the confidence to employ it going forward.

As an example, I’m going to share some lines of code on how to download minute data from 2016.

Next, we’ll do a simple custom backtest script.

Open an Alpaca Account

First, we’ll need an Alpaca paper account. Head to Alpaca and open a free account.

Next, log in to your Alpaca account and find or generate your API keys.

I like to create a file just to save this information.

So create a file alpaca_conf_paper.py to save our Alpaca API Keys for the paper account.

Installing Python dependencies

Let’s install Alpaca’s Python SDK and other dependencies:

  • alpaca-trade-api is Alpaca’s Python SDK

  • tqdm is a very nice library that will show a progress bar.

  • pandas a great “library providing high-performance, easy-to-use data structures, and data analysis tools for Python

In your console, run:

pip3 install alpaca-trade-api tqdm pandas
Enter fullscreen mode Exit fullscreen mode

Downloading data

It’s very easy to download data from Alpaca.

Let’s say we want data for a day, grouped by minutes. We can do this with a very simple script. I tried to make it very explicit.

Create a file named download_data.py and paste this code:

If you run the code as-is, running python3 download_data.py will download OHLC minute data for AAPL for all 252 trading days of 2016 to your ../historical-market-data/ directory, in CSV format.

It looks like this in my WSL (Linux) console:

$ ls ../historical-market-data/*AAPL*2016*
AAPL-2016-01-04.csv  AAPL-2016-02-12.csv  AAPL-2016-03-24.csv  ...

$ ls ../historical-market-data/*AAPL*2016* | wc
    252     252    5040
Enter fullscreen mode Exit fullscreen mode

Our first backtesting script

To backtest an algorithm we first need to have an algorithm. Since we don’t have one yet we just going to assume a “buy and hold” strategy.

Let’s start by seeing how well a buy & hold strategy looked for AAPL in 2016: buying the first day of the year and selling the last day.

To test a “buy and hold” strategy, we need to calculate the ratio of the last price of the year (when we would have sold) and the first price of the year (when we would have bought).

That is,

profit_pc = price_last_day)/price_first_day
Enter fullscreen mode Exit fullscreen mode

Below is a script that does just that.

If you want to run it, create a file named backtest_buy_and_hold.py with this content:

If we run the script, we get:

$ python3 backtest-buy-and-hold.py
AAPL's 2016's Buy-n-Hold strategy return profit is: 1.099
Enter fullscreen mode Exit fullscreen mode

Which means that during 2016, AAPL grew 9.9%. This checks out:

AAPL grew 9.9% during 2016AAPL grew 9.9% during 2016

So, great! We did our first backtesting script for a trivial strategy.

Fancier strategies

As mentioned in my previous article, there are many strategies:

  • Buy and Hold
  • Mean reversion
  • Scalping
  • Fading
  • Daily pivots
  • Momentum
  • Many, many other

In my next article I’ll post some code that uses all we’ve built here, and extend the backtesting script to test a simple scalping algorithm.

See you next time!

Top comments (1)

Collapse
 
x777 profile image
YD

Hi, I started using backtrader library and tried to test with Alpaca, but without funding account their parther not allow use data API (I mean polygon).
Maybe you know similiar services how to test strategy for live data, but with paper account? Thx!