For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See:

timeframe parameter for Analyzers and weekly data

  • Hello,

    I am running some backtest with a very simple system using only weekly data (pandas) and I added a few analyzers:

    cerebro.addanalyzer(bt.analyzers.Returns, _name='returns')
    cerebro.addanalyzer(bt.analyzers.DrawDown, _name='drawdown')
    cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='sharpe', riskfreerate=0.0, annualize=True)

    Portfolio results for return didn't look right to me:

    Total Net Profit 1582338.10
    CAGR 58.0894%
    Max Drawdown 22.6135%
    Max Drawdown Len 91
    Sharpe Ratio 0.8554

    I modified the code to add the analyzer adding the timeframe parameter:

    cerebro.addanalyzer(bt.analyzers.Returns, _name='returns', timeframe=bt.TimeFrame.Weeks)
    cerebro.addanalyzer(bt.analyzers.DrawDown, _name='drawdown')
    cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='sharpe', riskfreerate=0.0, annualize=True, timeframe=bt.TimeFrame.Weeks)

    Stats now look right:

    Total Net Profit 1582338.10
    CAGR 9.9116%
    Max Drawdown 22.6135%
    Max Drawdown Len 91
    Sharpe Ratio 0.6601

    In the Analyzers/Reference/Returns documentation I read:

    timeframe (default: None)

    If None the timeframe of the 1st data in the system will be used

    Pass TimeFrame.NoTimeFrame to consider the entire dataset with no time constraints

    It's not a big deal to add a parameter but maybe I am missing something here: my data (pandas) are all with weekly compression, shouldn't backtrader infer the weekly timeframe from the 1st data? Am I misunderstanding the docs?



  • If not specified, the analyzer's timeframe attribute will be initialized with the _timeframe attribute of the first data added in cerebro (exactly as it appears in the documentation)

    Are you sure the correct timeframe param was specified upon data creation? (you didn't show the code for the data initialization).

    There is no "magic" or any other smart code in Backtrader (AFAIK) to automatically infer the correct data timeframe and compression from raw bars.

  • You're right! I was adding all my weekly pandas data without specifying their timeframe because I wrongly assumed backtrader was able to identify it from the data:

    for i, value in enumerate(data.items()):
        s, df = value
        if isinstance(df, DataFrame):
            cerebro.adddata(PandasData(dataname=df, name =, plot=False))
    # ......

    As you said I missed this from the docs: timeframe (default: TimeFrame.Days)

Log in to reply