Skip to Content

Building and Deploying a Stock Trading Bot in Python: Simple Moving Average (SMA)

Building and Deploying a Stock Trading Bot in Python: Simple Moving Average (SMA)

Algorithmic trading is becoming increasingly popular among retail investors, thanks to the advancements in technology and accessible trading platform APIs. In this tutorial, we will walk through the process of building a trading algorithm in Python using the simple moving average (SMA) as an indicator. We will use Apple Inc. (AAPL) stock for our example, buying shares when the stock price is above its 50-day SMA. However, you can test this strategy on whatever ticker you would like. We will also cover backtesting our strategy and deploying it live on paper money by connecting to Alpaca, a trading API-based brokerage platform. This guide will help you create an algorithmic trading bot from scratch, even if you're a beginner to Python and have minimal coding experience. Note: No machine learning is necessary for this tutorial.

This article will focus on the application of algorithmic trading in the realm of stocks and ETFs. Note: You can also adapt the strategy below to look into cryptocurrencies like Bitcoin and Ethereum with platforms such as Binance.

1. Setting up the environment:

To begin, we need to install the necessary Python libraries. We will use the following:

  • pandas: For data manipulation using dataframes

  • numpy: For numerical computations

  • matplotlib: For plotting

  • yfinance: For historical stock market data

  • alpaca-trade-api: For connecting to the Alpaca brokerage platform

  • time: to wait x time period between each trading period

pip install pandas numpy matplotlib yfinance alpaca-trade-api

I’d also recommend using version control in a github repo to ensure you can track any changes you make to your trading bot over time.

2. Importing the libraries and fetching historical data:

Next, we will import the necessary libraries and fetch historical stock data using the yfinance library.

import numpy as np import pandas as pd import yfinance as yf import matplotlib.pyplot as plt

# Fetch historical data symbol = 'AAPL' start_date = '2015-01-01' end_date = '2022-12-31' data = yf.download(symbol, start=start_date, end=end_date)

3. Calculating the 50-day SMA:

We will now calculate the 50-day SMA and add it as a new column in our DataFrame.

data['SMA_50'] = data['Close'].rolling(window=50).mean()

4. Implementing the trading strategy:

Our trading strategy is simple: buy AAPL when its price is above the 50-day SMA. We will create a new DataFrame column called 'Signal' that indicates whether we should buy (1) or hold (0) the stock.

data['Signal'] = np.where(data['Close'] > data['SMA_50'], 1, 0)

5. Backtesting the strategy and comparing it with SPY:

Now that we have our signals, we can backtest our strategy. For this, we will calculate the daily returns and the cumulative returns for our strategy.

data['Daily_Return'] = data['Close'].pct_change() data['Strategy_Return'] = data['Daily_Return'] * data['Signal'].shift(1) data['Cumulative_Return'] = (1 + data['Strategy_Return']).cumprod()

6. Plotting the results:

Let's visualize our strategy's performance by plotting the cumulative returns. Ensure that your strategy isn't overfit (you can find more information on overfitting here).

# Fetch historical data for SPY spy_data = yf.download('SPY', start=start_date, end=end_date)

# Calculate daily returns and cumulative returns for SPY spy_data['Daily_Return'] = spy_data['Close'].pct_change() spy_data['Cumulative_Return'] = (1 + spy_data['Daily_Return']).cumprod()

# Plot both cumulative returns on the same chart plt.figure(figsize=(12, 6)) plt.plot(data.index, data['Cumulative_Return'], label='SMA Strategy') plt.plot(spy_data.index, spy_data['Cumulative_Return'], label='SPY') plt.xlabel('Date') plt.ylabel('Cumulative Returns') plt.legend() plt.show()

7. Connecting to Alpaca:

To deploy our trading algorithm live with real money, we will connect to the Alpaca brokerage platform. Alpaca provides live real-time data for execution. First, sign up for an account on Alpaca, then generate your API key and secret. Replace "YOUR_API_KEY" and "YOUR_SECRET_KEY" with your actual credentials. Please ensure you keep them in safely in a .env file and do not share them with anyone.

from alpaca_trade_api import REST

api_key = 'YOUR_API_KEY' api_secret = 'YOUR_SECRET_KEY' base_url = 'https://paper-api.alpaca.markets' # Use the paper trading URL for testing

api = REST(api_key, api_secret, base_url)

8. Implementing the trading algorithm for live trading:

To deploy our trading algorithm live, we will create a function that checks the current AAPL price against the 50-day SMA and places an order if the condition is met. We will also need a function to check our existing positions. Using both the live trading algorithm and the backtests, you can optimize your strategy by adjust the metrics/timeframe.

import time

def check_positions(symbol): positions = api.list_positions() for position in positions: if position.symbol == symbol: return int(position.qty) return 0

def trade(symbol, qty): current_price = api.get_latest_trade(symbol).price historical_data = yf.download(symbol, start=start_date, end=end_date, interval='1d') historical_data['SMA_50'] = historical_data['Close'].rolling(window=50).mean() if current_price > historical_data['SMA_50'][-1]: if check_positions(symbol) == 0: api.submit_order( symbol=symbol, qty=qty, side='buy', type='market', time_in_force='gtc' ) print("Buy order placed for", symbol) else: print("Holding", symbol)

9. Running the algorithm:

Now that we have our functions in place, we can run the algorithm by calling the 'trade()' function in a loop. We will use a time delay of one day (86400 seconds) to simulate daily trading. If you want to switch the algorithm from day trading to weekly trading etc, you can adjust the time.sleep(...) function.

symbol = 'AAPL' qty = 10 while True: trade(symbol, qty) time.sleep(86400)

This will run the algorithm indefinitely, checking the AAPL price against the 50-day SMA every day and placing a buy order if the condition is met.

In this article, we demonstrated how to build a simple moving average trading algorithm in Python and deploy it for live trading using the Alpaca brokerage platform. While this example showcases a basic trading strategy, there's a whole world of possibilities when it comes to algorithmic trading and technical analysis. You can also try the strategy above with other technical indicators.

Disclaimer: Please note that the above example is for educational purposes only and should not be considered as financial advice. Always do thorough research and testing before deploying a trading algorithm with real money.

What other brokerage APIs and platforms can I create this with?

While this tutorial focused on the Alpaca API, there are many ways to create your trading bot. Other alternatives include:

  • Interactive brokers API, TD Ameritrade API, Binance API (crypto only)

  • If you're looking for options with less or no coding, check out the following:

    • Composer: Composer is a no-code trading platform (with an AI ChatGPT4 copilot). It offers an intuitive drag-and-drop interface that allows you to build, test, and deploy sophisticated trading strategies with ease. With a comprehensive library of pre-built indicators, professional grade data, and trading actions, Composer empowers you to create a wide range of strategies without writing a single line of code.

    • EquBot AI Watson: EquBot uses IBM Watson’s AI to make trading decisions, including analysis of news articles and social media. If you're looking for an AI trading bot that uses alternative data this could be a platform to consider.

    • Tickeron: Tickeron is a subsidiary of SAS Global Corp. with customizable AI bots, providing dynamic price alerts for trade timing for stock, exchange-traded fund (ETF), forex and crypto pattern recognition. Tickeron’s AI pattern recognition surfaces daily top-ranked stock price patterns and provides a confidence level for trading ideas. It also has robust trend forecasting tools that can help provide predictions for future price levels.

You may also like:

Important Disclosures

Investing in securities involves risks, including the risk of loss, including principal. Composer Securities LLC is a broker-dealer registered with the SEC and member of FINRA / SIPC. The SEC has not approved this message.

Certain information contained in here has been obtained from third-party sources. While taken from sources believed to be reliable, Composer has not independently verified such information and makes no representations about the accuracy of the information or its appropriateness for a given situation. In addition, this content may include third-party advertisements; Composer has not reviewed such advertisements and does not endorse any advertising content contained therein.

This content is provided for informational purposes only, as it was prepared without regard to any specific objectives, or financial circumstances, and should not be relied upon as legal, business, investment, or tax advice. You should consult your own advisers as to those matters. References to any securities or digital assets are for illustrative purposes only and do not constitute an investment recommendation or offer to provide investment advisory services. Furthermore, this content is not intended as a recommendation to purchase or sell any security and performance of certain hypothetical scenarios described herein is not necessarily indicative of actual results. Any investments referred to, or described are not representative of all investments in strategies managed by Composer, and there can be no assurance that the investments will be profitable or that other investments made in the future will have similar characteristics or results.

Charts and graphs provided within are for informational purposes solely and should not be relied upon when making any investment decision. Past performance is not indicative of future results. The content speaks only as of the date indicated. Any projections, estimates, forecasts, targets, prospects, and/or opinions expressed in these materials are subject to change without notice and may differ or be contrary to opinions expressed by others. Please see Composer's Legal Page for additional important information.