Sling Academy
Home/Python/Comparing Multiple Assets in One Figure with mplfinance

Comparing Multiple Assets in One Figure with mplfinance

Last updated: December 22, 2024

Visualizing financial data is critical in the analysis and comparison of multiple assets over time. mplfinance, a powerful Python library, helps in plotting financial data with ease, especially when it comes to overlays, moving averages, and volume bars. In this article, we're going to explore how to compare multiple financial assets in a single figure using mplfinance.

Why Choose mplfinance?

mplfinance provides a straightforward and flexible way to plot various financial data types, making it ideal for asset comparison. It builds on matplotlib, a widely-used plotting library, offering unique capabilities tailored for financial data, like candlestick, OHLC (Open-High-Low-Close), and Renko charts. If you need to display multiple assets in one chart for better visual analysis and decision-making, this library can do just that with relatively simple code.

Getting Started

Before moving forward with the comparison, ensure you have mplfinance installed. You can do this via pip:

pip install mplfinance

Once installed, we need some stock data. For this example, we'll use the yfinance library to pull historical financial data. Install it if you haven't already:

pip install yfinance

Fetching Data

For demonstration, we'll fetch data for two popular assets: Apple (AAPL) and Microsoft (MSFT). The following code demonstrates how to use yfinance to get historical data:

import yfinance as yf
import pandas as pd

symbols = ['AAPL', 'MSFT']
data = {symbol: yf.download(symbol, start='2022-01-01', end='2023-01-01') for symbol in symbols}
dataframes = {symbol: data[symbol].rename(columns={
    'Open': symbol+'_Open', 
    'High': symbol+'_High', 
    'Low': symbol+'_Low', 
    'Close': symbol+'_Close'}) 
    for symbol in symbols}

The data dictionary now holds DataFrames for each asset, each renamed to include the ticker symbol. These will serve as our datasets for comparison.

Preparing for Comparison

We'll start by merging these datasets into a single DataFrame while focusing on the closing prices:

df = pd.concat([df[[col for col in df.columns if 'Close' in col]] for _, df in dataframes.items()], axis=1)

The df variable now contains only the closing prices of AAPL and MSFT, aligned for comparability.

Plotting with mplfinance

Our next step is to visualize the data. We use mplfinance to overlay these assets:

import mplfinance as mpf

mpf.plot(df, type='line', title='AAPL and MSFT Comparison', ylabel='Price')

This simple plot gives a side-by-side look at how the stock prices evolved over the given time frame. mplfinance supports stylized and ornamented charts with ease, allowing for complex graphical presentations.

Advanced Visualization

If you want to include more information on your chart, mplfinance offers customization:

styles = mpf.make_mpf_style(base_mpf_style='charles', rc={'font.size': 10})
additional_args = mpf.make_addplot((df['MSFT_Close']/df['AAPL_Close'])*100, title='MSFT/AAPL Closing Ratio')

mpf.plot(df, type='candle', addplot=additional_args, style=styles, title='Advanced Comparison', ylabel='Price', volume=True)

This code snippet introduces a new ratio line plot that contrasts MSFT against AAPL, providing an insight into their relative performance. The code also applies a unique style to enhance presentation clarity.

Conclusion

Comparing multiple assets using mplfinance in a single chart can significantly aid in analyzing how stocks or other financial assets move in relation to each other. The capabilities of this library, combined with readily available data sources like yfinance, make it an invaluable tool for analysts and traders seeking comprehensive visual insights. Try experimenting further with different styles and data to see what insights you can uncover with your market analyses.

Next Article: Annotating Charts and Adding Labels in mplfinance

Previous Article: Overlaying Technical Indicators on mplfinance Charts

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