Backtesting Tutorial Using Alpaca and JavaScript

Kendel Chopp
2 min readOct 15, 2020

--

Welcome to part three of my tutorials on using JavaScript and Node.js with Alpaca to do algorithmic trading. If you have not read part one or part two yet be sure to check those out. By the end of this, you should be able to backtest your Alpaca trading algorithm using my new backtesting package. For the full code of this part of the tutorial, check out this branch on my GitHub repository. This tutorial will assume that you already have some sort of algorithm using Node.js and Alpaca which you want to backtest. If you would prefer a video version of the tutorial you can also check that out on YouTube here.

Background on Backtesting

If you are not familiar with backtesting, Investopedia has another great article on what it is. At a high level, backtesting is running a trading algorithm using data from the past. This allows you to see how your algorithm would have performed in the past, and if we generally believe that the market will behave similarly in the future, we can make some predictions about how the trading algorithm will perform going forward.

Install Backtesting Package

I created a new package to allow you to backtest an algorithm that uses Node.js and Alpaca. You can see the source code on GitHub here as well as the npm package. In order to install it, you just need to run this command in the directory of your package’s code:

npm install — save @kendelchopp/alpaca-js-backtesting

O`nce you have installed this package, it is time to hop back into the code.

Create the Backtest Object

Next, we will create an instance of the Backtest class. To do that, all that is required is an Alpaca object and start/end dates. Here is an example:

const alpaca = new Alpaca({  keyId: ‘someKey’,});const backtest = new Backtest({  alpaca,  startDate: new Date(2020, 1, 1, 0, 0),  endDate: new Date(2020, 10, 11, 0, 0)});

Connect to the Backtest Websocket

Next, instead of using the Alpaca websocket, we will use the mocked one created for the backtest. For example:

// const client = alpaca.data_ws;const client = backtest.data_ws;

Print the Stats After Disconnecting

Lastly, when we disconnect from the Backtest mock websocket we can print out the stats:

client.onDisconnect(() => {  console.log(backtest.getStats());});

Run Your Algorithm

Now, you run your algorithm as you normally would, replacing any calls to alpaca with calls to backtest. This includes things like creating orders:

// alpaca.createOrder({ /* Some Order Info */ });backtest.createOrder({ /* Some Order Info */ });

Contribute to the Module

If you are interested in contributing to the Alpaca JS Backtesting Node module check out the GitHub repository. There is lots of room for improvement, and if you run any into any issues please reach out to me as I would be happy to help! Happy backtesting!

--

--

Kendel Chopp

Software Engineer trying my hand at writing things down