# Plotting Market Data with Matplotlib

> Use matplotlib to plot prices, indicators, equity curves, drawdowns and return histograms, with clear examples and tips for honest, readable trading charts.

Source: https://learn.tradelabsai.com/programming/matplotlib/  
Track: Programming and Data · Level: Intermediate · Updated: 2026-10-03  
Publisher: TradeLabs AI (https://tradelabsai.com). Education, not financial advice.  
Cite as: TradeLabs Learn, "Plotting Market Data with Matplotlib", https://learn.tradelabsai.com/programming/matplotlib/

Numbers alone hide a lot. An equity curve shows whether returns came steadily or from one lucky month; a drawdown chart shows how painful the losses were; a histogram reveals fat tails that a single average hides. matplotlib is Python's original and most widely used plotting library, and pandas plots use it underneath. You do not need beautiful charts for research, but you do need honest ones, and a handful of chart types covers almost everything a trader needs.

## The charts traders need

| Chart | Answers | Lesson |
|---|---|---|
| Price with indicators | What did the signal see? | [Moving Averages Explained](https://learn.tradelabsai.com/indicators/moving-averages-explained/) |
| Equity curve | How did the account grow? | [Backtesting Methodology](https://learn.tradelabsai.com/research/backtesting-methodology/) |
| Drawdown | How deep and long were losses? | [Maximum Drawdown](https://learn.tradelabsai.com/portfolio/maximum-drawdown/) |
| Return histogram | How are returns distributed? | [Fat Tails](https://learn.tradelabsai.com/math/fat-tails/) |
| Rolling metric | Is performance stable over time? | [Rolling and Expanding Windows](https://learn.tradelabsai.com/math/rolling-and-expanding-windows/) |
| Scatter | How do two assets or a signal and returns relate? | [Covariance and Correlation](https://learn.tradelabsai.com/math/covariance-and-correlation/) |

## Price and moving averages

```python
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(df.index, df["Close"], label="Close", linewidth=1)
ax.plot(df.index, df["Close"].rolling(50).mean(), label="50 day SMA")
ax.plot(df.index, df["Close"].rolling(200).mean(), label="200 day SMA")
ax.set_title("Price and moving averages")
ax.legend()
plt.show()
```

## Equity curve and drawdown together

```python
equity = (1 + df["strategy"].fillna(0)).cumprod()
drawdown = equity / equity.cummax() - 1

fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(10, 6),
                               gridspec_kw={"height_ratios": [3, 1]})
ax1.plot(equity, label="Strategy")
ax1.set_yscale("log")
ax2.fill_between(drawdown.index, drawdown, 0, alpha=0.4)
ax2.set_ylabel("Drawdown")
plt.show()
```

Sharing the x axis lines up each drawdown with the part of the equity curve that caused it.

## Why use a log scale for equity

On a normal scale, a move from $100 to $200 looks small next to a later move from $1,000 to $2,000, even though both doubled the account. A log scale shows equal percentage changes as equal heights, so early and late performance can be compared fairly. Use it for any equity curve or price chart spanning large changes. See [Compounding and Geometric vs Arithmetic Returns](https://learn.tradelabsai.com/math/compounding/).

**Example: Spotting a lucky streak**
A backtest reports a 40% total return over five years. The equity curve on a log scale shows the account flat for four years, then a steep rise in one quarter. A histogram of monthly returns shows one month at +25% and the rest clustered around zero. Removing that single month leaves a total return of about 12%, since 1.40 divided by 1.25 is 1.12. The chart revealed that the result depends on one event, a fragile basis for a strategy. See [Robustness and Stress Testing](https://learn.tradelabsai.com/research/robustness-and-stress-testing/).

## Return histogram

```python
rets = df["strategy"].dropna()
fig, ax = plt.subplots()
ax.hist(rets, bins=60)
ax.axvline(rets.mean(), linestyle="--")
ax.set_title("Daily strategy returns")
plt.show()
```

Compare the shape with a normal distribution: trading returns usually have taller peaks and fatter tails. See [Normal Distribution](https://learn.tradelabsai.com/math/normal-distribution/) and [Skewness and Kurtosis](https://learn.tradelabsai.com/math/skewness-and-kurtosis/).

## Candlestick charts

matplotlib has no built in candlestick function. The mplfinance package adds one, and plotly offers interactive candlesticks that zoom in a browser. For live trading charts, dedicated charting platforms are far easier. See [Charting Platforms Compared](https://learn.tradelabsai.com/industry/charting-platforms-compared/) and [How to Read Candlesticks](https://learn.tradelabsai.com/candlesticks/how-to-read-candlesticks/).

## Rules for honest charts

1. **Label axes and units,** including currency and whether returns are percentages.
2. **Use log scales** for long equity curves.
3. **Show costs included** or state that they are excluded.
4. **Do not crop** the worst period out of the date range.
5. **Plot in and out of sample periods** in different colours. See [In-Sample vs Out-of-Sample Testing](https://learn.tradelabsai.com/research/out-of-sample-testing/).
6. **Save charts with the code and data version** that produced them. See [Backtest Reproducibility](https://learn.tradelabsai.com/research/backtest-reproducibility/).

## Interactive charts

matplotlib produces static images, which are ideal for reports and quick checks. When you want to zoom into a single day or hover to read exact values, plotly and bokeh create interactive charts that open in a browser or notebook. They are especially useful for inspecting individual trades on intraday data, where a static chart of a full year would squeeze thousands of bars into a few pixels. A practical workflow is to use matplotlib for the overview charts saved with each backtest and an interactive library for digging into specific periods, such as the worst drawdown or the trades with the largest slippage. See [MAE and MFE](https://learn.tradelabsai.com/risk/mae-and-mfe/) for charts that show how far each trade moved for and against you.

## Frequently asked questions

### What is matplotlib used for in trading?

Plotting prices, indicators, equity curves, drawdowns, histograms and other charts for research and reporting.

### How do I plot candlesticks in Python?

Use the mplfinance package for static candlestick charts or plotly for interactive ones.

### Should equity curves use a log scale?

Usually yes, because a log scale shows equal percentage gains as equal heights, which makes long periods easier to compare.

Next, compare the main Python backtesting frameworks in [Backtesting Libraries Compared](https://learn.tradelabsai.com/programming/backtesting-libraries-compared/).

## Continue learning

- Next lesson: [Backtesting Libraries Compared](https://learn.tradelabsai.com/programming/backtesting-libraries-compared/)
- Previous lesson: [NumPy and Pandas for Traders](https://learn.tradelabsai.com/programming/numpy-and-pandas-for-traders/)
- Related: [NumPy and Pandas for Traders](https://learn.tradelabsai.com/programming/numpy-and-pandas-for-traders/): Learn the pandas and NumPy operations traders use most: loading price data, returns, rolling windows, resampling bars, joining assets and avoiding common traps.
- Related: [Python for Trading](https://learn.tradelabsai.com/programming/python-for-trading/): Why Python is the most popular language for trading research and bots, which libraries matter, how to set up a project and a first script that tests a simple rule.
- Related: [Maximum Drawdown](https://learn.tradelabsai.com/portfolio/maximum-drawdown/): Maximum drawdown measures the largest fall from a peak to a trough in an account or strategy. Learn how to calculate it, recovery maths, duration and how to use it.
- Related: [Visual Library](https://learn.tradelabsai.com/reference/visual-library/): A visual library of the most useful trading diagrams: candlestick anatomy, support and resistance, trends, option payoffs, drawdowns and the order book.
- Related: [Backtesting Methodology](https://learn.tradelabsai.com/research/backtesting-methodology/): A backtest simulates a strategy on historical data. Learn the steps, the key performance metrics, common biases and a checklist for backtests you can trust.
