How I programmed my first trading algorithm based on technical indicators

Marko Laesseriger, PhD
4 min readJan 7, 2023

--

As I sat at my computer, my hands shaking with excitement and nerves, I couldn’t believe that I was about to embark on my very first coding project for a trading algorithm. I had spent countless hours studying the Moving Average Convergence Divergence (MACD) and was eager to put my knowledge to the test.

I began typing out the code, my fingers flying across the keyboard as I worked to bring my vision to life. I knew that the MACD was a powerful tool for identifying trend changes and measuring the strength of a trend, and I was determined to create an algorithm that could make the most of it.

As I hit “enter” and the code began to run, I held my breath, waiting to see if all of my hard work had paid off. It was a moment that I would never forget — the moment I took my first steps towards success in the world of algorithmic trading.

The Moving Average Convergence Divergence (MACD)

The Moving Average Convergence Divergence (MACD) is a technical indicator that is used to identify trend changes and to measure the strength of a trend. The MACD is calculated by subtracting a 26-period exponential moving average (EMA) from a 12-period EMA. In addition to the MACD line, which represents the difference between the two EMAs, the MACD also includes a 9-period EMA of the MACD line, known as the “signal line.”

There are several ways in which traders and investors may use the MACD with periods of 6 and 18 to make gains in the stock market:

  1. Identifying trend changes: The MACD can be used to identify changes in the trend of a security. A bullish crossover, which occurs when the MACD line crosses above the signal line, may indicate that a security is about to enter an uptrend. A bearish crossover, which occurs when the MACD line crosses below the signal line, may indicate that a security is about to enter a downtrend.
  2. Measuring trend strength: The MACD can also be used to measure the strength of a trend. A rising MACD line may indicate that a trend is gaining strength, while a falling MACD line may indicate that a trend is losing strength.
  3. Setting trade triggers: Some traders may use the MACD with periods of 6 and 18 to set trade triggers. For example, a trader may enter a long position when the MACD line crosses above the signal line, and exit the position when the MACD line crosses back below the signal line.

My first code for a long position for a bullish crossover (MACD)

This following algorithm first calculates the 12-period and 26-period exponential moving averages of the close price, and then uses these values to calculate the MACD line. It then calculates the 9-period exponential moving average of the MACD line, which is used as the signal line. When the MACD line crosses above the signal line, the algorithm enters a long position by setting the trade size to be equal to the initial capital divided by the close price. Finally, it calculates the final portfolio value by multiplying the trade size by the close price for each period.

# import necessary libraries
import pandas as pd
import numpy as np

# load data into a Pandas dataframe
df = pd.read_csv('stock_data.csv')

# calculate the 12-period and 26-period exponential moving averages
df['ema_12'] = df['close'].ewm(span=12, adjust=False).mean()
df['ema_26'] = df['close'].ewm(span=26, adjust=False).mean()

# calculate the MACD line
df['macd'] = df['ema_12'] - df['ema_26']

# calculate the 9-period exponential moving average of the MACD line
df['signal_line'] = df['macd'].ewm(span=9, adjust=False).mean()

# create a column to store the trading signals
df['signal'] = 0

# set the signal to 1 when the MACD line crosses above the signal line
df.loc[df['macd'] > df['signal_line'], 'signal'] = 1

# set the initial capital
initial_capital = 10000

# create a column to store the size of each trade
df['trade_size'] = 0

# set the trade size to be equal to the capital divided by the close price
df.loc[df['signal'] == 1, 'trade_size'] = initial_capital / df['close']

# calculate the final portfolio value
df['portfolio_value'] = df['trade_size'] * df['close']

# print the final portfolio value
print(df['portfolio_value'].iloc[-1])

Where/on which platforms can I apply a trading algorithm?

There are several platforms that can be used to test and apply a trading algorithm such as the Moving Average Convergence Divergence (MACD) algorithm that I provided. Some popular platforms include:

  1. MetaTrader: MetaTrader is a widely used platform for trading Forex, CFDs, and futures. It allows you to test and apply trading algorithms using the built-in Strategy Tester, and also provides a wide range of technical indicators and other tools to help you analyze the markets.
  2. TradeStation: TradeStation is a platform that is popular among algorithmic traders. It provides a wide range of tools and resources for testing, optimizing, and automating trading strategies.
  3. NinjaTrader: NinjaTrader is another platform that is popular among algorithmic traders. It offers a range of tools and resources for developing, testing, and executing automated trading strategies, including a strategy development environment and a backtesting tool.
  4. Thinkorswim: Thinkorswim is a platform offered by TD Ameritrade that is popular among traders and investors. It provides a range of tools and resources for developing and testing trading strategies, including a strategy backtesting tool.

It is important to note that these platforms may have different fees and requirements for using algorithmic trading strategies, and may not be available in all countries. It is recommended that you research and compare the features and fees of these platforms before deciding which one is right for you.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Marko Laesseriger, PhD
Marko Laesseriger, PhD

Written by Marko Laesseriger, PhD

Entrepreneur and tech enthusiast. Finance background and PhD in Social Science. Work experience Big4, M&A, IT consulting.

No responses yet

Write a response