How can I use Pyfolio with backtrader?



  • So, as the document mentioned that the API of pyfolio changed.

    I would like to know how can I integrate pyfolio with backtrader.

    Can someone give me an example to explain the procedure of integrating pyfolio with backtrader?

    Thanks!



  • Hi Michael,
    I see that nobody answered your question. So I think the following lines of coding
    could be a starting point for you:

        # Add a strategy
        cerebro.addstrategy(TestStrategy,df_alloc)
        # Analyzer
        cerebro.addanalyzer(btanalyzers.SharpeRatio, _name='mysharpe')
        cerebro.addanalyzer(bt.analyzers.PyFolio, _name='pyfolio')
          # Set our desired cash start
        cerebro.broker.setcash(initcash)
        cerebro.broker.setcommission(commission=0.0)
    
        # Print out the starting conditions
        print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
    
        # Run over everything
        strat = cerebro.run()
        #cerebro.plot(numfigs = 1,grid = True,iplot=True)
        # Print out the final result
        print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
        print('Sharpe Ratio:', strat[0].analyzers.mysharpe.get_analysis())
        strat[0].analyzers.mysharpe.pprint()
        pyfoliozer = strat[0].analyzers.getbyname('pyfolio')
        returns, positions, transactions, gross_lev = pyfoliozer.get_pf_items()
        import pyfolio as pf
        pf.create_full_tear_sheet(
            returns,
            positions=positions,
            transactions=transactions,
            #gross_lev=gross_lev,
            live_start_date='2008-01-01',  # This date is sample specific
            round_trips=True)
    
        pf.create_simple_tear_sheet(returns)
        pf.create_returns_tear_sheet(returns)
    
    

    Of course you will have to install pyfolio! The instruction are here: https://quantopian.github.io/pyfolio/

    Pyfolio will give you lots of information (not all of unquestionable utility). I think it is more important to
    get first a good synthetic view, and for this I like (and strongly suggest) the one contributed by Richard O' Regan:
    https://community.backtrader.com/topic/670/it-s-here-a-beta-you-can-use-right-now-essential-trade-statistics-all-in-one-place
    Only after screening with this tool I would adventure into the fine tuning of a strategy with pyfolio.
    Good luck...


Log in to reply
 

Looks like your connection to Backtrader Community was lost, please wait while we try to reconnect.