Created with Highcharts 12.1.2Equity200020022004200620082010201220142016201820202022202420260250k500k750k1,000k1,250k1,500k1,750k2,000k2,250k2,500k
Overall Statistics
Total Orders
44261
Average Win
0.07%
Average Loss
-0.04%
Compounding Annual Return
12.590%
Drawdown
56.000%
Expectancy
0.379
Start Equity
100000
End Equity
1982464.29
Net Profit
1882.464%
Sharpe Ratio
0.529
Sortino Ratio
0.574
Probabilistic Sharpe Ratio
2.405%
Loss Rate
47%
Win Rate
53%
Profit-Loss Ratio
1.59
Alpha
0.082
Beta
-0.199
Annual Standard Deviation
0.139
Annual Variance
0.019
Information Ratio
0.131
Tracking Error
0.233
Treynor Ratio
-0.369
Total Fees
$2323.55
Estimated Strategy Capacity
$0
Lowest Capacity Asset
RVNC VNVUWH2KQSTH
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"))