How to Copy a Matplotlib Plot to Cerebro
Last Updated :
23 Jul, 2025
Copying a Matplotlib plot to Backtrader's Cerebro
is not directly possible, as Backtrader generates its own plots based on backtesting data. However, you can overlay or integrate your custom Matplotlib plot with Backtrader's chart by leveraging its plot()
method and combining it with matplotlib
.
Cerebro is a core component of the Backtrader library. If you’ve ever wanted to test a trading strategy without risking real money, Backtrader is the tool for you. Cerebro acts as the engine that manages strategies, runs the backtests, and even plots the results. Steps to Combine a Matplotlib Plot with Backtrader's Cerebro:
- Run your backtest using
Cerebro
. - Extract the
matplotlib.figure.Figure
object from cerebro.plot()
. - Overlay your custom Matplotlib plot on this figure.
We use the cerebro.plot()
function to generate the Backtrader plot and then overlay your custom Matplotlib plot (the portfolio value line) onto it.
This article will walk you through the process and highlight why each step is significant. Before diving into the details of how to copy a Matplotlib plot into Cerebro, it’s helpful to understand what Cerebro is and why it’s used.
What is Cerebro and its Practical Implications?
Backtrader is a popular Python library specifically designed for algorithmic trading, quantitative finance, and backtesting. Cerebro is a core component within Backtrader, responsible for running backtests, managing strategies, and handling the execution of trading logic. It allows traders to test their trading strategies on historical data before deploying them live. This is essential in the financial industry, where testing a strategy in a simulated environment is crucial to understanding its effectiveness and risk profile.
Here are a few key practical implications of Cerebro in the industry:
- Backtesting Trading Strategies: Traders can simulate their strategies on historical market data to understand how their algorithm would have performed under different market conditions. This is a vital step in developing profitable trading strategies.
- Risk Management: By backtesting strategies, traders can evaluate the potential risks associated with their algorithm before risking real capital in the markets.
- Optimization: Traders can fine-tune their strategies using optimization techniques, testing different parameters to maximize performance.
- Customizable Visualizations: Cerebro allows users to visualize the results of their strategies, which helps them better understand their performance metrics and make adjustments where needed.
Given its robust capabilities, Cerebro is widely used in the industry by quant developers, algorithmic traders, and financial analysts to develop and refine trading strategies. By integrating Matplotlib plots into Cerebro, traders can further enhance their strategy evaluations, making it a valuable addition to their analysis toolkit.
Steps for copying a Matplotlib plot into Cerebro
To copy a Matplotlib plot into Cerebro, you’ll need to follow several key steps. These steps involve generating the plot in Matplotlib, converting it into a format that Cerebro can display, and then running the Backtrader strategy to visualize both the strategy and the plot together.
1. Run your backtest using Cerebro
In this step, synthetic data is generated to simulate market behavior. Random price movements are created using a random walk, with a starting price of 100. This data is then converted into a format compatible with Backtrader, a popular backtesting framework for financial strategies. The synthetic data includes open, high, low, close (OHLC) prices, and volume, which are essential for running a backtest.
Python
import backtrader as bt
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import datetime
# Step 1: Generate Synthetic Data for Backtrader
np.random.seed(0)
days = 100
start_date = datetime.datetime(2020, 1, 1)
date_range = pd.date_range(start=start_date, periods=days)
price = 100 + np.cumsum(np.random.randn(days) * 2)
data = pd.DataFrame({'datetime': date_range, 'open': price, 'high': price + np.random.rand(days) * 2,
'low': price - np.random.rand(days) * 2, 'close': price, 'volume': np.random.randint(100, 500, days)})
data.set_index('datetime', inplace=True)
data_bt = bt.feeds.PandasData(dataname=data)
2. Extract the matplotlib.figure.Figure
object from cerebro.plot()
A basic trading strategy is defined in this step using Backtrader's Strategy
class. In this example, the strategy logs the closing price of each bar but does not implement any specific trading logic. This serves as a foundation for more complex strategies, where users can define custom buy, sell, or hold conditions based on market data.
Python
# Step 2: Define a Simple Backtrader Strategy
class TestStrategy(bt.Strategy):
def next(self):
self.log(f"Close: {self.data.close[0]}")
def log(self, txt, dt=None):
dt = dt or self.datas[0].datetime.date(0)
print(f"{dt.isoformat()}, {txt}")
3. Overlay your custom Matplotlib plot on this figure
Here, the Backtrader Cerebro
engine is initialized, which is responsible for running the backtest. The strategy defined in Step 2 is added to Cerebro, along with the synthetic data from Step 1. Cerebro handles the execution of the strategy and provides insights into performance metrics such as portfolio value, trade execution, and strategy results.
Python
# Step 3: Initialize Cerebro and Add Strategy/Data
cerebro = bt.Cerebro()
cerebro.addstrategy(TestStrategy)
cerebro.adddata(data_bt)
# Run Backtrader
cerebro.run()
4. Running the Strategy and Displaying the Plot
In this final step, additional custom data (portfolio value) is generated to represent the performance of the strategy over time. This data is then plotted using Matplotlib, overlaying it on the Backtrader-generated chart to visually track the portfolio’s progress. The combined plot helps analyze both the market price movements and the portfolio's financial growth or decline.
Python
# Step 4: Generate Custom Portfolio Value Data for Matplotlib
portfolio_value = 100000 + np.cumsum(np.random.randn(days) * 100 + 50) # Example portfolio value
fig = cerebro.plot(style='candlestick')[0][0]
ax = fig.gca()
ax.plot(date_range, portfolio_value, label='Portfolio Value', color='orange', linewidth=2)
ax.legend(loc='upper left')
fig.savefig('combined_backtrader_plot.png')
plt.show()
Output:
combined_backtrader_plot.png