Backtrader cerebro.plot() 函数在 Spyder 中不返回任何绘图

问题描述 投票:0回答:1

我获取了一些示例代码,用于下载股票数据,并使用 Backtrader 的 cerebro 函数通过交易策略运行它。当我运行 cerebro.plot() 函数时,没有返回图表(无论是内嵌还是作为弹出窗口)。其代码如下:

import backtrader as bt

# Define a simple moving average crossover strategy
class SMACrossOver(bt.Strategy):
    params = (('short_period', 10), ('long_period', 30))

    def __init__(self):
        self.short_ma = bt.indicators.SimpleMovingAverage(
            self.data.close, period=self.params.short_period)
        self.long_ma = bt.indicators.SimpleMovingAverage(
            self.data.close, period=self.params.long_period)

    def next(self):
        if self.short_ma > self.long_ma:
            self.buy()
        elif self.short_ma < self.long_ma:
            self.sell()

# Create a cerebro engine
cerebro = bt.Cerebro()

data = yf.download('AAPL', start='2020-01-01', end='2022-01-01')

# Convert data to backtrader format
data_bt = bt.feeds.PandasData(dataname=data)

cerebro.adddata(data_bt)

# Add strategy
cerebro.addstrategy(SMACrossOver)

# Add a broker with a cash fund for the initial capital
cerebro.broker.set_cash(100000)

# Add commission - This is for illustrative purposes and can be modified as needed
cerebro.broker.setcommission(commission=0.001)

# Add the analyzers
cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='sharpe')
cerebro.addanalyzer(bt.analyzers.DrawDown, _name='drawdown')

# Run the backtest
strategies = cerebro.run()

# Print the results
strat = strategies[0]
print('Sharpe Ratio:', strat.analyzers.sharpe.get_analysis()['sharperatio'])
print('Max Drawdown:', strat.analyzers.drawdown.get_analysis()['max']['drawdown'])

# Plot the results
cerebro.plot()

控制台的唯一输出如下所示:

[*********************100%***********************]  1 of 1 completed
Sharpe Ratio: 1.545255702414604
Max Drawdown: 3.1184551599840895
<IPython.core.display.Javascript object>
<IPython.core.display.HTML object>

[[<Figure size 432x288 with 4 Axes>]]

任何帮助将不胜感激!

尝试过将 iline 设置为 True 和 False 进行绘图,没有区别。无法找到有关此问题的更多信息。

python plot spyder algorithmic-trading backtrader
1个回答
0
投票

配置 IPython 控制台以进行内联显示 Spyder 使用 IPython 控制台,可以将其配置为内联显示绘图:

打开 Spyder,转到“工具”>“首选项”。 导航到 IPython 控制台 > 图形。 在“图形后端”部分中,选择“内联”。 单击“应用”,然后单击“确定”保存更改。 重新启动 Spyder 以确保更改生效

© www.soinside.com 2019 - 2024. All rights reserved.