Overall Statistics
Total Orders
42384
Average Win
0.07%
Average Loss
-0.04%
Compounding Annual Return
13.073%
Drawdown
54.900%
Expectancy
0.387
Start Equity
100000
End Equity
2119227.04
Net Profit
2019.227%
Sharpe Ratio
0.555
Sortino Ratio
0.602
Probabilistic Sharpe Ratio
3.281%
Loss Rate
46%
Win Rate
54%
Profit-Loss Ratio
1.59
Alpha
0.086
Beta
-0.203
Annual Standard Deviation
0.139
Annual Variance
0.019
Information Ratio
0.147
Tracking Error
0.234
Treynor Ratio
-0.379
Total Fees
$2403.89
Estimated Strategy Capacity
$0
Lowest Capacity Asset
BGL R735QTJ8XC9X
Portfolio Turnover
0.53%
# https://quantpedia.com/strategies/value-book-to-market-factor/
#
# The investment universe contains all NYSE, AMEX, and NASDAQ stocks. To represent “value” investing, HML portfolio goes long high book-to-price stocks and short,
# low book-to-price stocks. In this strategy, we show the results for regular HML which is simply the average of the portfolio returns of HML small (which goes long 
# cheap and short expensive only among small stocks) and HML large (which goes long cheap and short expensive only among large caps). The portfolio is equal-weighted
# and rebalanced monthly.
#
# QC implementation changes:
#   - Quintile selection is done.

from AlgorithmImports import *
import numpy as np
from typing import List

class ValueBooktoMarketFactor(QCAlgorithm):

    def Initialize(self) -> None:
        self.SetStartDate(2000, 1, 1)
        self.SetCash(100_000)

        self.UniverseSettings.Leverage = 5
        self.UniverseSettings.Resolution = Resolution.Daily
        self.AddUniverse(self.FundamentalFunction)
        self.Settings.MinimumOrderMarginPortfolioPercentage = 0.0
        self.settings.daily_precise_end_time = False
        
        self.long_symbols: List[Symbol] = []
        self.short_symbols: List[Symbol] = []

        # Fundamental Filter Parameters
        self.exchange_codes: List[str] = ['NYS', 'NAS', 'ASE']        
        self.quantile: int = 5

        self.rebalancing_month: int = 12
        self.selection_flag: bool = True

        self.exchange: Symbol = self.AddEquity('SPY', Resolution.Daily).Symbol
        self.Schedule.On(self.DateRules.MonthEnd(self.exchange), 
                        self.TimeRules.AfterMarketOpen(self.exchange), 
                        self.Selection)

    def FundamentalFunction(self, fundamental: List[Fundamental]) -> List[Symbol]:
        if not self.selection_flag:
            return Universe.Unchanged

        selected: List[Fundamental] = [f for f in fundamental if f.HasFundamentalData 
                                                    and f.SecurityReference.ExchangeId in self.exchange_codes
                                                    and not np.isnan(f.ValuationRatios.PBRatio) 
                                                    and f.ValuationRatios.PBRatio != 0]
        
        if len(selected) >= self.quantile:
            sorted_by_pb: List[Fundamental] = sorted(selected, 
                                                    key = lambda x:(x.ValuationRatios.PBRatio), 
                                                    reverse=False)
            quantile: int = int(len(sorted_by_pb) / self.quantile)
            self.long_symbols = [i.Symbol for i in sorted_by_pb[:quantile]]
            self.short_symbols = [i.Symbol for i in sorted_by_pb[-quantile:]]

        return self.long_symbols + self.short_symbols
    
    def OnData(self, slice: Slice) -> None:
        if not self.selection_flag:
            return
        self.selection_flag = False
        
        # Trade execution - Leveraged portfolio - 100% long, 100% short
        targets: List[PortfolioTarget] = []
        for i, portfolio in enumerate([self.long_symbols, self.short_symbols]):
            for symbol in portfolio:
                if slice.ContainsKey(symbol) and slice[symbol] is not None:
                    targets.append(PortfolioTarget(symbol, ((-1) ** i) / len(portfolio)))

        self.SetHoldings(targets, True)

        self.long_symbols.clear()
        self.short_symbols.clear()
    
    def Selection(self) -> None:
        if self.Time.month == self.rebalancing_month:
            self.selection_flag = True

    def OnSecuritiesChanged(self, changes: SecurityChanges) -> None:
        for security in changes.AddedSecurities:
            security.SetFeeModel(CustomFeeModel())

# Custom fee model
class CustomFeeModel(FeeModel):
    def GetOrderFee(self, parameters: OrderFeeParameters) -> OrderFee:
        fee: float = parameters.Security.Price * parameters.Order.AbsoluteQuantity * 0.00005
        return OrderFee(CashAmount(fee, "USD"))