Sling Academy
Home/Python/Building Multi-Panel Charts for Volume and Indicators in mplfinance

Building Multi-Panel Charts for Volume and Indicators in mplfinance

Last updated: December 22, 2024

When it comes to financial data analysis and visualization, being able to create detailed and insightful multi-panel charts is essential. These charts not only plot asset price movement but are also enriched with various volume bars and technical indicators. mplfinance is a versatile library designed explicitly for making such financial plots in Python. This article will walk you through the step-by-step process of building multi-panel charts utilizing mplfinance.

1. Setting Up the Environment

Before diving in, install the necessary library:

pip install mplfinance

This command installs the mplfinance package and its dependencies. Now, import the required modules in your Python environment:

import mplfinance as mpf
import pandas as pd
import yfinance as yf

2. Fetching Financial Data

For demonstration, let us use Yahoo Finance to download some stock data. You can quickly achieve this using the yfinance library:

# Define the stock ticker and time period
stock_ticker = "AAPL"
start_date = "2023-01-01"
end_date = "2023-10-01"
data = yf.download(stock_ticker, start=start_date, end=end_date)

The above code fetches Apple Inc.'s stock data from January to October 2023.

3. Creating a Basic Candlestick Chart

With your data in place, start by creating a fundamental candlestick chart:

mpf.plot(data, type='candle', title='Apple Inc.', ylabel='Price (USD)')

This command plots Apple’s stock price into a simple candlestick chart for the specified timeframe.

4. Adding Volumes to the Chart

Next, enhance your chart by adding volume data:

mpf.plot(data, type='candle', volume=True, title='Apple Inc. with Volume', ylabel='Price (USD)')

Including the volume=True parameter subsequently creates an additional subplot that provides insights regarding the trading volume.

5. Using Subplots for Technical Indicators

Now, it's time to add some technical indicators like Moving Average or RSI to your chart:

First, compute the Moving Average and RSI:

# Calculating 20-day Simple Moving Average
data['SMA20'] = data['Close'].rolling(window=20).mean()

# Calculating Relative Strength Index (RSI)
delta = data['Close'].diff()
gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
rs = gain/loss
data['RSI'] = 100 - (100/(1 + rs))

Integrate these indicators into separate panels in your multi-panel chart:

apd = [
    mpf.make_addplot(data['SMA20'], color='g'),
    mpf.make_addplot(data['RSI'], panel=1, ylabel='RSI')
]

mpf.plot(data, type='candle', addplot=apd, volume=True, ylabel='Price (USD)',
         title='Apple Inc. with SMA20 and RSI', style='yahoo')

In this example, a simple moving average line is added to the price chart, and a separate panel is created for the RSI indicator.

6. Customizing the Layout and Style

You can customize the appearance of your charts further by tweaking style settings:

mpf.plot(data, type='candle', addplot=apd, volume=True, ylabel='Price (USD)',
         title='Apple Inc. with SMA20 and RSI', style='mike', figratio=(12,8), figscale=1.1)

Adjusting the arguments figratio and figscale can improve appearance, particularly in cases with many panels or lengthy data visualizations.

Conclusion

Building comprehensive multi-panel charts with mplfinance allows financial analysts and developers to conduct intricate analyses visually. With the steps outlined above, you should be able to create personalized and insightful charts that consolidate multiple facets of financial data, such as price, volume, and technical indicators. Such capabilities endow stakeholders with the tools needed to visualize and act on crucial data insights.

Next Article: Debugging Common mplfinance Errors and Warnings

Previous Article: Generating Interactive Charts with mplfinance in Jupyter Notebooks

Series: Algorithmic trading with Python

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots