Overall Statistics
Total Orders
42884
Average Win
0.07%
Average Loss
-0.04%
Compounding Annual Return
13.747%
Drawdown
53.200%
Expectancy
0.398
Start Equity
100000
End Equity
2278731.93
Net Profit
2178.732%
Sharpe Ratio
0.588
Sortino Ratio
0.639
Probabilistic Sharpe Ratio
4.621%
Loss Rate
47%
Win Rate
53%
Profit-Loss Ratio
1.61
Alpha
0.091
Beta
-0.203
Annual Standard Deviation
0.141
Annual Variance
0.02
Information Ratio
0.172
Tracking Error
0.236
Treynor Ratio
-0.406
Total Fees
$2577.08
Estimated Strategy Capacity
$0
Lowest Capacity Asset
SOLO WWISH221M2QT
Portfolio Turnover
0.55%
# 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.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"))