I want to introduce those new to algorithmic trading some simplest algorithms to understand how set it up using python using real stock data.
Early on, when the American stock market was first introduced in Philadelphia, the tools used for trading financial assets were the balance sheet of the company, word of mouth and individual opinions. Today predicting the future price of financial assets using mathematical models is used to create an advantage. This advantage is sometimes called alpha, where alpha is how much a given strategy can outperform the benchmark index. We can define the use of mathematical models to create a profitable trading strategy as algorithmic trading. Algorithmic trading is an idea to profit based on predetermined rules or predictions by executing automatic trades.
A simple example of an algorithmic trading strategy would be to execute a trade once the asset price goes above or below the 20-day simple moving average. The formula for the simple moving average is given as:

Where P is asset price, and n is the number of previous days. Building more complex trading signals may use volatility bands that compare a lower and upper time series typically modelled after asset volatility. An example for volatility bands is given as:

where n is the number of previous days and sigma is the standard deviation for the asset. Sigma can be formulated as

To set up some baseline algorithmic trading strategies, we will test a few simple ones. The first one we explore is the 50 day moving average. The following strategy is as follows when the stock price is above the 50-day moving average, we buy, and when it falls below, we sell. The principal of this strategy is to trade a bullish trend for the medium term. The 50-day moving average is given in MA(50), where the look-back is 50 pervious days.
The next following is the 20-day exponential moving average, where we buy when the stock price is above and sell when it below. The idea is to capture a short-term bullish trend.

The last strategy we investigate is the moving average convergence divergence or MACD. Using the exponential moving average over 12 days and the exponential moving average over 26-days, we find when the EMA(12) crosses the EMA(26), and execute a trade based on either a bullish or bearish trend forming. The MACD is calculated by MACD = EMA(12) — EMA(26) where the MACD becomes an oscillating time series crossing the zero axes. When the short-term line EMA(12) crosses above the long-term line EMA(26) we believe the stock price is in a bullish trend and buy at that point. Conversely, when the EMA(12) crosses below the long-term line EMA(26), we believe the stock prices are in a bearish trend, and we short the stock.
Python Implementation
We investigate the trading results for three different algorithms and compare. Understanding the potential profit or loss for simple trading algorithms builds our baseline for what is achievable for the average investor. The proposed algorithms are tested with the adjusted closing prices downloaded from Yahoo Finance: A. O. Smith Corp (AOS). In order to be consistent, the same period was selected for all strategies; 2018–04–01 to 2020- 02–09. In addition, the dates were selected so that both the 50-day and 20-day exponential moving averages start on the same date. The trading position is 1000 shares.
Before we start the implementation of our simple trading algorithms we first need to import our stock data. We import all stocks in the S&P500.
import yahoo_fin.stock_info as si #extract all ticker information in S&P500
import yfinance as yf #import data via Yahoo
sp_list = si.tickers_sp500()
for i in range(len(sp_list)):
sp_list[i] = sp_list[i].replace(".", "-") # Replaces all "." with "" in the string AAL.B - B class shares
today = datetime.today()
# dd/mm/YY
#get last business day
offset = max(1, (today.weekday() + 6) % 7 - 3)
timed = timedelta(offset)
today_business = today - timed
print("d1 =", today_business)
today = today_business.strftime("%Y-%m-%d")
symbols_list = sp_list
start = '2018-01-01'
end = '2021-01-01'
#start = datetime(2019, 1, 1)
#end = today
print('S&P500 Stock download')
r = yf.download(symbols_list, start,end)
df_pivot = r
#replace all nan data with zero
df_pivot = df_pivot.Close
df_pivot[(df_pivot==0).all(1)] = float('NaN') #change all zero row to NaN
df_pivot.dropna(axis=0,how = 'all', inplace = True) #drop row with all NaN valuesWith all our stock data imported we are able to begin our algorthmic trading strategies. We first explore the results for the 50-day moving average crossover.
#50 day moving average
MA50 = np.zeros([len(data)-50])
for i in range(50,len(data)):
MA50[i-50] = np.mean(data[i-50:i])
The trades that are executed for the 50-Day moving average, are done with the following logic. When the stock is above the 50-Day moving average we buy 1000 shares anticipating continued upside. Conversely, when the stock dropsbelow the 50-Day moving average, the position is closed, and 0 shares are held.

The next simplistic strategy is based on capturing a short-term trend using the 20-Day exponential moving average.
#EMA 20 day
alpha = 2/(20 + 1)
EMA20 = np.zeros(len(data)-1)
for i in range(1,len(data)-1):
EMA20[i] = alpha*data[i] + (1 - alpha)*EMA20[i-1]

The last strategy is the MACD crossover. We look to both profit from a bullish and bearish trend by going either long or short the stock.
# MACD - EMA(12) - EMA(26)
alpha_12 = 2/(12 + 1)
alpha_26 = 2/(26+1)
MACD = np.zeros(len(data)-1)
EMA12 = np.zeros(len(data)-1)
EMA26 = np.zeros(len(data)-1)
for i in range(1,len(data)-1):
EMA12[i] = alpha_12*data[i] + (1 - alpha_12)*EMA12[i-1]
EMA26[i] = alpha_26*data[i] + (1 - alpha_26)*EMA26[i-1]
MACD[i] = EMA12[i] - EMA26[i]

For the given period and the stock AOS, the MACD is the worst performing, and the EMA is the best performing where each strategy outperforms the buy and hold approach. Over the period, the long-term trend for the stock AOS is bearish, realized in the buy and hold approach. For a different stock and period, any of the three algorithms perform and outperform the others.
A-little bit about myself
I have recently completed a master's in applied mathematics at Ryerson University in Toronto, Canada. I am part of the financial mathematics group specializing in statistics. I studied volatility modeling and algorithmic trading in-depth.
I previously worked as an engineering professional at Bombardier Aerospace, where I was responsible for modeling the life-cycle costs associated with aircraft maintenance.
I am actively training for triathlon and love fitness.