Overall Statistics
Total Orders
16374
Average Win
0.10%
Average Loss
-0.06%
Compounding Annual Return
1.096%
Drawdown
41.000%
Expectancy
0.131
Start Equity
100000
End Equity
130997.36
Net Profit
30.997%
Sharpe Ratio
-0.137
Sortino Ratio
-0.156
Probabilistic Sharpe Ratio
0.000%
Loss Rate
56%
Win Rate
44%
Profit-Loss Ratio
1.58
Alpha
-0.007
Beta
-0.107
Annual Standard Deviation
0.081
Annual Variance
0.007
Information Ratio
-0.28
Tracking Error
0.193
Treynor Ratio
0.104
Total Fees
$247.41
Estimated Strategy Capacity
$8000.00
Lowest Capacity Asset
IVCB XVQ0TDUA32AT
Portfolio Turnover
0.39%
# https://quantpedia.com/strategies/small-capitalization-stocks-premium-anomaly/
#
# The investment universe contains all NYSE, AMEX, and NASDAQ stocks. Decile portfolios are formed based on the market capitalization
# of stocks. To capture “size” effect, SMB portfolio goes long small stocks (lowest decile) and short big stocks (highest decile).
#
# QC implementation changes:
#   - The investment universe contains 3000 largest stocks traded on NYSE, AMEX, and NASDAQ with price >= 2$.

from AlgorithmImports import *
from typing import List

class SizeFactorSmallCapitalizationStocksPremium(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.fundamentals_count: int = 3_000
        self.min_share_price: float = 2.
        
        self.quantile: int = 10
        self.rebalancing_month: int = 12
        self.selection_flag: bool = True

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

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

        filtered: List[Fundamental] = [
            f for f in fundamental if f.HasFundamentalData 
            and f.SecurityReference.ExchangeId in self.exchange_codes
            and f.price >= self.min_share_price
        ]

        sorted_by_market_cap: List[Fundamental] = sorted(
            filtered, 
            key = lambda x: x.MarketCap, 
            reverse=True)[:self.fundamentals_count]

        if len(sorted_by_market_cap) >= self.quantile:
            quintile: int = int(len(sorted_by_market_cap) / self.quantile)
            self.long_symbols = [i.Symbol for i in sorted_by_market_cap[-quintile:]]
            self.short_symbols = [i.Symbol for i in sorted_by_market_cap[:quintile]]

        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"))