Making Your First Trading Algorithm with a Stock Broker API

Simple strategies and trade execution

Matthew Tweed
Automation Generation
4 min readDec 7, 2018

--

Photo by Erda Estremera on Unsplash

(This is 12/7 post for Trading API Advent Calendar 2018)

In this post we’ll be looking at creating the trading logic for your first algorithmic strategy, along with some sample code to pull data and process it into your desired signals.

Technical Analysis and Momentum

The moving average cross is a common momentum strategy, and one of the simplest algorithmic strategies to implement. Momentum strategies seek to capitalise on market strength during bull runs and reduce drawdowns by closing positions before the bulk of a market correction.

The moving averages both help to smooth out noise in the wider trend, with the shorter moving average follows price movement more closely than the long moving average. This makes for cleaner trend identification, even when volatility picks up.

Common pairs for the short and long periods are (20,50) or (50,200), although I found that (60,90) also works well.

While shorter time periods do offer a quicker response to market swings, they can produce higher rates of false signals in choppy markets. Meanwhile longer moving averages can smooth out small market fluctuations in favour of the longer term trend, but risk greater losses in a sharp correction.

Fetching and Processing your Market Data

Market data can be easily pulled from Polygon via the Alpaca API’s.

The candlestick data comes formatted as a pandas DataFrame, making access and manipulating much quicker and easier than raw JSON or native python arrays.

From here, its a matter of calculating your moving averages, a process made simple by ta-lib.

Now we can integrate the simple trading logic, from earlier, with the trading API.

The script is designed to be run at the end of the day’s trading and place an order for market open the next day, since it wouldn’t be possible to both see the daily close price and fill a trade before close.

Strategy Proof of Concept

Here I’ve set up a proof of concept back-test of our strategy against simply buying and holding Apple shares. All stock prices are dividend and split adjusted.

Note: The moving average parameters were chosen to help show off the strategy concept, so shouldn’t be relied upon for future data.

As we can see, while the strategy saw slightly lower absolute returns, we managed to reduce the drawdowns during large market corrections, with the buy and hold strategy seeing 60.2% maximum drawdown vs 49.0% for the moving average crosses. This type of drawdown reduction is what the moving average strategy aims to maximise.

Adjustments to Try

The beauty of the moving average cross is in its simplicity, but there are still several ways to adjust it to try to achieve more robust returns:

  • Change the simple moving average to exponential moving average, for reduced response times to market swings
  • Increase or decrease moving average periods, to alter how sensitive the signal is to smaller movements
  • Add a threshold of how far the short moving average has to cross the long average before a signal is formed

There are limitless possibilities to take a simple trading logic and fit your strategy to your preferences.

Technology and services are offered by AlpacaDB, Inc. Brokerage services are provided by Alpaca Securities LLC (alpaca.markets), member FINRA/SIPC. Alpaca Securities LLC is a wholly-owned subsidiary of AlpacaDB, Inc.

You can find us @AlpacaHQ, if you use twitter.

Follow Automation Generation, a Medium’s publication created for developers/makers in trading and fintech.

--

--