Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

在backtrader中,用cerebro.plot绘出的图横坐标只显示日期,没显示时间

  1. User

    在backtrader中,用cerebro.plot绘出的图横坐标只显示日期,没显示时间

  2. Assistant

    这是由于backtrader默认将x轴刻度格式化为日期格式,因此没有显示时间。

    要在绘图中显示时间,需要自定义x轴格式。可以在策略的__init__()方法中定义一个新的时间格式,例如:

    from backtrader.plot import TimeFormatter
    
    class MyStrategy(bt.Strategy):
    
        def __init__(self):
            self.datefmt = '%Y-%m-%d %H:%M:%S'
            # ...
    
        def next(self):
            # ...
    
    cerebro = bt.Cerebro()
    cerebro.addstrategy(MyStrategy)
    cerebro.plot(style='candle', fmt_x_ticks=TimeFormatter(fmt=self.datefmt))
    

    在这里,我们定义了一个日期和时间的格式字符串'%Y-%m-%d %H:%M:%S',然后将其作为参数传递给TimeFormatter类的构造函数,并将其作为fmt_x_ticks参数传递给cerebro.plot()方法。这将覆盖默认的日期格式,并将x轴刻度格式化为指定的日期和时间格式。

    需要注意的是,在使用自定义时间格式时,需要确保数据源包含了对应的时间信息,否则x轴的时间刻度将会是空白的。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.