Overall Statistics
import pandas as pd
import random as rand

class HorizontalResistanceInterceptor(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2018, 10, 30)  # Set Start Date
        self.SetEndDate(2020, 5, 1)  # Set Start Date
        self.SetCash(100000)  # Set Strategy Cash
        self.AddEquity("SPY", Resolution.Hour)

        self.orders = pd.DataFrame()
        self.daily_tracker = pd.DataFrame()

    def OnData(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
            Arguments:
                data: Slice object keyed by symbol containing the stock data
        '''
        # Check if the market is open
        market_open = self.Securities["SPY"].Exchange.Hours.IsOpen(self.Time, False)
        if not market_open:
            return
        
        # Generate random trades
        r = rand.random()
        ticket = None
        if r < 0.03:
            ticket = self.MarketOrder("SPY", 1)
        elif r > 0.97:
            ticket = self.MarketOrder("SPY", -1)
        
        # Report trades
        if ticket is not None:
            value = ticket.QuantityFilled * ticket.AverageFillPrice
            order = pd.DataFrame({"value" : [value]}, index=[self.Time])
            self.orders = self.orders.append(order)
        
    
    def OnEndOfDay(self):
        # Determine cumulative daily buys/sells
        buys = 0
        sells = 0
        if self.orders.shape[0] > 0:
            buys = self.orders[self.orders.value > 0].sum().value
            sells = -self.orders[self.orders.value < 0].sum().value
        self.orders = pd.DataFrame()
        
        # Track NAV
        nav = self.Portfolio.TotalPortfolioValue
        
        # Add new row to our daily_tracker
        row = pd.DataFrame({"buys" : [buys], "sells" : [sells], "NAV": [nav]}, index=[self.Time])
        self.daily_tracker = self.daily_tracker.append(row)
        
    def OnEndOfAlgorithm(self):
        # Shrink daily_tracker to be just the latest 12 months
        self.daily_tracker = self.daily_tracker[self.daily_tracker.index>= self.Time - timedelta(days=365)]
        
        # Calculate portfolio turnover
        buys = self.daily_tracker['buys'].sum()
        sells = self.daily_tracker['sells'].sum()
        turnover = min(buys, sells) / self.daily_tracker['NAV'].mean()
        self.Debug(f"\n12 Month Portfolio Turnover: {turnover}")