Overall Statistics
Total Orders
63276
Average Win
0.09%
Average Loss
-0.11%
Compounding Annual Return
-3.636%
Drawdown
87.200%
Expectancy
-0.029
Start Equity
100000
End Equity
39830.69
Net Profit
-60.169%
Sharpe Ratio
-0.121
Sortino Ratio
-0.119
Probabilistic Sharpe Ratio
0.000%
Loss Rate
47%
Win Rate
53%
Profit-Loss Ratio
0.82
Alpha
0
Beta
0
Annual Standard Deviation
0.21
Annual Variance
0.044
Information Ratio
-0.016
Tracking Error
0.21
Treynor Ratio
0
Total Fees
$937.40
Estimated Strategy Capacity
$5100000.00
Lowest Capacity Asset
DUO X95P0920YMW5
Portfolio Turnover
4.56%
# https://quantpedia.com/strategies/momentum-factor-effect-in-stocks/
#
# The investment universe consists of NYSE, AMEX, and NASDAQ stocks. We define momentum as the past 12-month return, skipping the most 
# recent month’s return (to avoid microstructure and liquidity biases). To capture “momentum”, UMD portfolio goes long stocks that have 
# high relative past one-year returns and short stocks that have low relative past one-year returns.
#
# QC implementation changes:
#   - Instead of all listed stock, we select top 500 stocks by market cap from QC stock universe.

# region imports
from AlgorithmImports import *
from typing import List, Dict
from pandas.core.frame import DataFrame
# endregion

class MomentumFactorEffectinStocks(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2000, 1, 1)
        self.set_cash(100_000)

        self.set_brokerage_model(BrokerageName.INTERACTIVE_BROKERS_BROKERAGE, AccountType.MARGIN)

        self.add_equity('SPY', Resolution.DAILY).symbol
        
        self.weight: Dict[Symbol, float] = {}
        self.data: Dict[Symbol, RollingWindow] = {}
        self.period: int = 12 * 21
        self.quantile: int = 5
        self.leverage: int = 5
        self.exchange_codes: List[str] = ['NYS', 'NAS', 'ASE']
        
        self.fundamental_count: int = 500
        self.fundamental_sorting_key = lambda x: x.dollar_volume

        self.selection_flag: bool = False
        self.universe_settings.resolution = Resolution.DAILY
        self.add_universe(self.fundamental_selection_function)
        
        self.settings.daily_precise_end_time = False
        self.settings.minimum_order_margin_portfolio_percentage = 0.
        self._recent_month: int = -1

    def on_securities_changed(self, changes: SecurityChanges) -> None:
        for security in changes.added_securities:
            security.set_fee_model(CustomFeeModel())
            security.set_leverage(self.leverage)
        
    def fundamental_selection_function(self, fundamental: List[Fundamental]) -> List[Symbol]:
        # update the rolling window every day
        [self.data[stock.symbol].add(stock.adjusted_price) for stock in fundamental if stock.symbol in self.data]

        if self._recent_month == self.time.month:
            return Universe.UNCHANGED
        
        self._recent_month = self.time.month
        self.selection_flag = True

        selected: List[Fundamental] = [
            x for x in fundamental if x.has_fundamental_data and x.market_cap != 0 and x.market == 'usa' and \
            x.security_reference.exchange_id in self.exchange_codes
        ]
        if len(selected) > self.fundamental_count:
            selected = [x for x in sorted(selected, key=self.fundamental_sorting_key, reverse=True)[:self.fundamental_count]]

        # warmup price rolling windows
        for stock in selected:
            symbol: Symbol = stock.symbol

            if symbol not in self.data:
                self.data[symbol] = RollingWindow[float](self.period)
                history: DataFrame = self.history(symbol, self.period, Resolution.DAILY)

                if history.empty:
                    self.log(f"Not enough data for {symbol} yet")
                    continue
                closes: Series = history.loc[symbol].close
                for time, close in closes.items():
                    self.data[symbol].add(close)
            
        perf: Dict[Symbol, float] = {
            stock.symbol : self.data[stock.symbol][0] / self.data[stock.symbol][self.period - 1] - 1 for stock in selected if self.data[stock.symbol].is_ready
        }

        if len(perf) >= self.quantile:
            sorted_by_perf: List = sorted(perf, key=perf.get)
            quantile: int = int(len(sorted_by_perf) / self.quantile)
            long: List[Symbol] = sorted_by_perf[-quantile:]
            short: List[Symbol] = sorted_by_perf[:quantile]

            # calculate weights
            for i, portfolio in enumerate([long, short]):
                for symbol in portfolio:
                    self.weight[symbol] = ((-1) ** i) / len(portfolio)
        
        return list(self.weight.keys())
        
    def on_data(self, slice: Slice) -> None:
        if not self.selection_flag:
            return
        self.selection_flag = False

        # trade execution
        portfolio: List[PortfolioTarget] = [
            PortfolioTarget(symbol, w) for symbol, w in self.weight.items() if slice.contains_key(symbol)
        ]
        self.set_holdings(portfolio, True)

        self.weight.clear()

# Custom fee model.
class CustomFeeModel(FeeModel):
    def get_order_fee(self, parameters):
        fee = parameters.security.price * parameters.order.absolute_quantity * 0.00005
        return OrderFee(CashAmount(fee, "USD"))