Building a Market-Making Trading Strategy using Python

Janelle Turing
4 min readNov 8, 2023

--

Market-making is a common trading strategy used by financial institutions to provide liquidity to the market. Market makers continuously quote both bid and ask prices for a particular asset, thereby creating a market for buyers and sellers. In return for their services, market makers earn the spread between the bid and ask prices.

Photo by Nicholas Cappello on Unsplash

In this tutorial, we will explore how to build a market-making trading strategy using Python. We will leverage the power of object-oriented programming and various Python libraries to implement a comprehensive and functional trading system. We will also use the yfinance library to download financial data for real assets and visualize our trading strategy using creative and informative plots.

To get started, make sure you have the necessary libraries installed. Open your terminal and run the following command:

pip install yfinance numpy matplotlib mplfinance plotly

Now that we have all the required libraries, let’s dive into building our market-making trading strategy.

Step 1: Importing the Required Libraries

First, let’s import the necessary libraries for our project. We will be using the following libraries:

  • yfinance for downloading financial data
  • numpy for numerical operations
  • matplotlib for creating plots
  • mplfinance for advanced financial plotting
  • plotly for interactive and dynamic plots
import yfinance as yf
import numpy as np
import matplotlib.pyplot as plt
import mplfinance as mpf
import plotly.graph_objects as go

Step 2: Downloading Financial Data

To build our market-making trading strategy, we need historical price data for a specific asset. We will use the yfinance library to download the data. Let's download the data for JPMorgan Chase (JPM) from January 1, 2020, to November 30, 2023.

ticker = "JPM"
start_date = "2020-01-01"
end_date = "2023-11-30"

data = yf.download(ticker, start=start_date, end=end_date)

Now that we have the data, let’s explore it and visualize it using a candlestick plot.

mpf.plot(data, type='candle')
Cover Image
Figure 1: Candlestick plot of JPM stock prices from January 1, 2020, to November 30, 2023.

The candlestick plot provides a visual representation of the stock prices over time. Each candlestick represents a specific time period and displays the opening, closing, highest and lowest prices for that period.

Step 3: Preprocessing the Data

Before we can implement our market-making trading strategy, we need to preprocess the data and calculate some additional metrics. Let’s calculate the daily returns and the 20-day moving average.

data['Returns'] = data['Close'].pct_change()
data['MA_20'] = data['Close'].rolling(window=20).mean()

Now that we have the necessary metrics, let’s visualize them using a line plot.

plt.plot(data.index, data['Returns'], label='Returns')
plt.plot(data.index, data['MA_20'], label='20-day Moving Average')
plt.legend()
plt.xlabel('Date')
plt.ylabel('Value')
plt.title('Daily Returns and 20-day Moving Average')
Plot 2
Figure 2: Line plot of daily returns and 20-day moving average of JPM stock prices. Created by Author

The line plot provides insights into the daily returns of the stock and the trend indicated by the 20-day moving average.

Step 4: Implementing the Market-Making Strategy

Now that we have preprocessed the data, let’s implement our market-making trading strategy. In this strategy, we will place bid and ask orders based on certain conditions. For simplicity, let’s assume that we will place bid orders when the stock price is below the 20-day moving average and ask orders when the stock price is above the 20-day moving average.

data['Bid'] = np.where(data['Close'] < data['MA_20'], data['Close'], np.nan)
data['Ask'] = np.where(data['Close'] > data['MA_20'], data['Close'], np.nan)

Now that we have the bid and ask prices, let’s visualize them using a scatter plot.

plt.scatter(data.index, data['Bid'], color='green', label='Bid')
plt.scatter(data.index, data['Ask'], color='red', label='Ask')
plt.plot(data.index, data['Close'], color='blue', label='Close')
plt.legend()
plt.xlabel('Date')
plt.ylabel('Price')
plt.title('Market-Making Strategy')
Plot 3
Figure 3: Scatter plot of bid and ask prices along with the closing price. Created by Author

The scatter plot shows the bid and ask prices as green and red dots, respectively, along with the closing price represented by the blue line.

Step 5: Backtesting the Strategy

To evaluate the performance of our market-making trading strategy, we need to backtest it using historical data. Let’s calculate the profit/loss for each trade based on the bid and ask prices.

data['Profit/Loss'] = np.where(data['Bid'].shift(1) > 0, data['Ask'] - data['Bid'].shift(1), 0)
data['Cumulative Profit/Loss'] = data['Profit/Loss'].cumsum()

Now that we have the profit/loss for each trade and the cumulative profit/loss, let’s visualize them using a line plot.

plt.plot(data.index, data['Cumulative Profit/Loss'])
plt.xlabel('Date')
plt.ylabel('Profit/Loss')
plt.title('Cumulative Profit/Loss')
Plot 4
Figure 4: Line plot of cumulative profit/loss of the market-making trading strategy. Created by Author

The line plot shows the cumulative profit/loss over time, indicating the performance of our market-making strategy.

Conclusion

In this tutorial, we have learned how to build a market-making trading strategy using Python. We leveraged the power of object-oriented programming and various Python libraries to implement a comprehensive and functional trading system. We also used the yfinance library to download financial data for real assets and visualized our trading strategy using creative and informative plots.

By following this tutorial, you now have the knowledge and tools to develop your own market-making trading strategies and explore the exciting world of algorithmic trading.

Remember to experiment with different parameters and asset classes to further enhance your trading strategies.

--

--

Janelle Turing
Janelle Turing

Written by Janelle Turing

Your AI & Python guide on Medium. 🚀📈 | Discover the Power of AI, ML, and Deep Learning | Check out my articles for a fun tech journey – see you there! 🚀🔍😄