Your First Trading Algorithm

Matthew Tweed
Automation Generation
2 min readDec 23, 2019

The moving average cross is one of the simplest and oldest algorithmic trading signals. It relies on two rolling averages of price movement over your desired look-back period. This example strategy aims to help capture the majority of any bullish moves, while also adding some downside protection by closing out a trade as the market begins to reverse.

Here’s an example of our simple moving average cross strategy.

The last 50 days of candlestick data are pulled from the IEX API for each stock. Using TA-Lib it’s possible to quickly calculate a 20 and 50 day moving average, which is added to the Pandas DataFrame.

Next, check if there is any existing open position and what signal indicates — buy, sell or hold. Last, execute the order to either bring the position to the target number of shares, or close it.

To run the code:

python3 <file location>--key-id <your key id>--secret-key <your secret key> 

Then, just let the algorithm run!

To change default settings, run the following command for details on the command-line options:

python3 <file location> -h

Happy coding, and happy trading!

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.

--

--