Overall Statistics
Total Trades
6089
Average Win
0.02%
Average Loss
-0.03%
Compounding Annual Return
10.540%
Drawdown
25.500%
Expectancy
0.323
Net Profit
37.916%
Sharpe Ratio
0.665
Loss Rate
25%
Win Rate
75%
Profit-Loss Ratio
0.77
Alpha
0.217
Beta
-9.147
Annual Standard Deviation
0.123
Annual Variance
0.015
Information Ratio
0.544
Tracking Error
0.123
Treynor Ratio
-0.009
Total Fees
$8096.92
# https://quantpedia.com/Screener/Details/26
from QuantConnect.Data.UniverseSelection import *
import math
import numpy as np
import pandas as pd
import scipy as sp

# ----------------------------------------------------------------
# To do
# ----------------------------------------------------------------
# x Rebalance Monthly
# x Change weighting of positions to equal weights
# x Plot development of Breakpoints over time
# - Narrow down to single asset (for testing purposes) 
# - Add calculation of target price

# - Overlay covered call strategy linking strikes with breakpoints
# - Overlay LT & ST replication (short put & long call)
# - Extend to multiple tickers
# - Extend to short leg 

# ----------------------------------------------------------------
# Some Notes
# ----------------------------------------------------------------
# self.lowercase variables are variables defined by oneself
# self.Uperrcase variables reference QC API



class BooktoMarketAnomaly(QCAlgorithm):

    def Initialize(self):
        self.Log('Initializing Backtest')
        self.Log('_____________________________________________________________________________________________________________________________________')

        self.SetStartDate(2016, 1, 1)   
        self.SetEndDate(2019, 3, 15)         
        self.SetCash(1000000) 
        
        self.sorted_by_bm = None
        self.monthly_rebalance = False
        
        # Universe + Settings
        self.UniverseSettings.Resolution = Resolution.Daily
        self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)
        
        # Benchmark
        self.SetBenchmark("SPY")
        self.AddEquity("SPY", Resolution.Daily)
        
        # Schedule functions
        # Trigger an event every day a specific symbol is trading --> here monthly
        self.Schedule.On(self.DateRules.MonthStart("SPY"), self.TimeRules.AfterMarketOpen("SPY"), Action(self.rebalance))
        
        # Plotting
        # Chart - Master Container for the Chart:
        breakpPlot = Chart('Fundamentals')
        breakpPlot.AddSeries(Series('Breakpoint-Min', SeriesType.Line))
        breakpPlot.AddSeries(Series('Breakpoint-Max', SeriesType.Line))
        self.AddChart(breakpPlot)

        
    def CoarseSelectionFunction(self, coarse):
        if self.monthly_rebalance:
            # drop stocks which have no fundamental data or have low price
            self.filtered_coarse = [x.Symbol for x in coarse if (x.HasFundamentalData and x.AdjustedPrice > 5)]
        else: 
            self.filtered_coarse = []
        return self.filtered_coarse    

    def FineSelectionFunction(self, fine):
        # To calculate the overall breakpoints of a systematic strategy, we need multiple shares (# defined by some cutoff, e.g. top 20% Mcap)
        # For testing & replication narrow down to < 5
        if self.monthly_rebalance:
            # Filter stocks with positive PB Ratio
            fine = [x for x in fine if (x.ValuationRatios.PBRatio > 0)] 
            
            # Calculate the market cap and add the "MarketCap" property to fine universe object
            for i in fine:
                i.MarketCap = float(i.EarningReports.BasicAverageShares.ThreeMonths * (i.EarningReports.BasicEPS.TwelveMonths*i.ValuationRatios.PERatio))
                
            # Syntax : sorted(iterable, key, reverse) --> reverse means from highest (expensive) to lowest (cheap)
            top_market_cap = sorted(fine, key = lambda x: x.MarketCap, reverse=True)[:int(len(fine)*0.2)]
            
            # sorted stocks in the top market-cap list by book-to-market ratio -> cheap first
            # lowest B/M Ratio has lowest 1/(P/B) -> but REVERSE here (!)
            top_bm = sorted(top_market_cap, key = lambda x: 1 / x.ValuationRatios.PBRatio, reverse=True)[:int(len(top_market_cap)*0.2)]
            self.sorted_by_bm = [i.Symbol for i in top_bm] 
            
            top_bm_tickers = [i.SecurityReference.SecuritySymbol for i in top_bm] 
            top_bm_ratios = [i.ValuationRatios.PBRatio for i in top_bm] 
            current_universe = dict(zip(top_bm_tickers, top_bm_ratios))

            current_min = min(current_universe.items(), key=lambda x: x[1]) 
            current_max = max(current_universe.items(), key=lambda x: x[1]) 
            
            # Save cut-off breakpoint for plot
            self.breakpoint_max = current_max[1]
            self.breakpoint_min = current_min[1]
            
            # calculate the weight with the market cap
            total_market_cap = np.sum([i.MarketCap for i in top_bm])
            self.weights = {}
            for i in top_bm:
                self.weights[str(i.Symbol)] = 1/len(self.sorted_by_bm) 
                
            # Logging
            self.Log('Current Universe: ')
            self.Log('# of stocks: ' + str(len(top_bm)))
            self.Log('Max PB Ratio ' + str(current_max))
            self.Log('Min PB Ratio ' + str(current_min))
        else:
            self.sorted_by_bm = []
        return self.sorted_by_bm
            
    def rebalance(self):
        # form yearly to monthly rebalance
        self.monthly_rebalance = True
        self.Log('Rebalancing on ' + str(self.Time))

    def OnData(self, data):
        if not self.monthly_rebalance: return 
        
        if self.sorted_by_bm:
            stocks_invested = [x.Key for x in self.Portfolio if x.Value.Invested]
            # liquidate stocks not in the trading list 
            for i in stocks_invested:
                if i not in self.sorted_by_bm:
                    self.Liquidate(i)   
                    
            # goes long stocks with the highest book-to-market ratio   
            for i in self.sorted_by_bm:
                # Changed this to simple weight +1 for single asset
                self.SetHoldings(i, self.weights[str(i)])
            
            # Later in your OnData(self, data):
            self.Plot('Fundamentals', 'Breakpoint Min', self.breakpoint_min)
            self.Plot('Fundamentals', 'Breakpoint Max', self.breakpoint_max)
            
            self.monthly_rebalance = False