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

How to create pyfolio round trip tearsheet?



  • Hi, I'm trying to create round_trip_tearsheet using pyfolio because it has trade stats like profit factor, average winning trade, average losing trade, percent profitable, etc. I found two ways to do it. One is by adding round_trips= True in pf.create_full_tearsheet and another is using pf.create_round_trip_tear_sheet but I failed in both.

    upon running the first one, I get some stats and charts but not the stats I want with RuntimeError: Selected KDE bandwidth is 0. Cannot estiamte density.

    Second alternative with create_round_trip_tear_sheet gives KeyError: ('block_dir', 'block_time')

    Please shed some light here on how I can get those trade stats. Thank you in advance. @ab_trader Below is my full code.

    %matplotlib inline
    from datetime import datetime
    import backtrader as bt
    import pandas as pd
    import math
    import pyfolio as pf
    import backtrader.analyzers as btanalyzers
    class SmaCross(bt.Strategy):
        params = dict(pslow=20,order_percentage= 0.99,ticker = 'NEPSE')
        
        def log(self, txt, dt=None):
                dt = dt or self.datas[0].datetime.date(0)
                print('%s, %s' % (dt.isoformat(), txt))
                
        def __init__(self):
            sma = bt.talib.SMA(self.data.close,timeperiod=self.p.pslow)
            self.crossover = bt.ind.CrossOver(self.data.close, sma, plot = True)  
        
        def next(self):
            if not self.position:  
                if self.crossover > 0: 
                    
                    amount_to_invest = (self.p.order_percentage*self.broker.cash)
                    self.size = math.floor(amount_to_invest/self.data.close)
                    self.buy(size=self.size)           
    #                 self.log('%s,Buy, %d,%d 0,%.0f' % (self.params.ticker,self.size,self.data.close[0],cerebro.broker.getvalue()))
            elif self.crossover < 0: 
                    self.close() 
    #                 self.log('%s,Sell, %d,%d 0,%.0f' % (self.params.ticker,self.size,self.data.close[0],cerebro.broker.getvalue()))
        
    cerebro = bt.Cerebro()  
    feed = pd.read_csv('test.csv',index_col = 'Date',parse_dates = True)
    data = bt.feeds.PandasData(dataname = feed)
    cerebro.adddata(data) 
    cerebro.addstrategy(SmaCross)  
    print('Starting Portfolio Value: %.0f' % cerebro.broker.getvalue())
    # strat = cerebro.run()
    print('Final Portfolio Value: %.0f' % cerebro.broker.getvalue())
    cerebro.addanalyzer(bt.analyzers.PyFolio, _name='pyfolio')
    results = cerebro.run()
    strat = results[0]
    pyfoliozer = strat.analyzers.getbyname('pyfolio')
    returns, positions, transactions, gross_lev = pyfoliozer.get_pf_items()
    pf.create_round_trip_tear_sheet(returns, positions, transactions)
    # pf.create_full_tear_sheet(
    #     returns,
    #     positions=positions,
    #     transactions=transactions,
    #     round_trips=True)
    
    


  • @Arun-Lama said in How to create pyfolio round trip tearsheet?:

    profit factor, average winning trade, average losing trade, percent profitable, etc.

    These items can be found in the trade analyzer.

    If you want a decent tear sheet you can use QuantStats. Just create an indicator that will give you the value of the portfolio and you can send that into QuantStats to get a tearsheet. I use the following analyzer:

    class CashMarket(bt.analyzers.Analyzer):
        """
        Analyzer returning cash and market values
        """
    
        def start(self):
            super(CashMarket, self).start()
    
        def create_analysis(self):
            self.rets = {}
            self.vals = 0.0
    
        def notify_cashvalue(self, cash, value):
            self.vals = (cash, value)
            self.rets[self.strategy.datetime.datetime()] = self.vals
    
        def get_analysis(self):
            return self.rets
    

Log in to reply
 

});