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.