Overall Statistics
Total Orders
39866
Average Win
0.35%
Average Loss
-0.25%
Compounding Annual Return
14.365%
Drawdown
53.100%
Expectancy
0.068
Start Equity
100000
End Equity
2843115.66
Net Profit
2743.116%
Sharpe Ratio
0.484
Sortino Ratio
0.59
Probabilistic Sharpe Ratio
0.379%
Loss Rate
55%
Win Rate
45%
Profit-Loss Ratio
1.38
Alpha
0.087
Beta
0.227
Annual Standard Deviation
0.2
Annual Variance
0.04
Information Ratio
0.228
Tracking Error
0.232
Treynor Ratio
0.426
Total Fees
$420417.11
Estimated Strategy Capacity
$22000000.00
Lowest Capacity Asset
MHP R735QTJ8XC9X
Portfolio Turnover
38.15%
# https://quantpedia.com/strategies/short-term-reversal-in-stocks/
#
# The investment universe consists of the 100 biggest companies by market capitalization.
# The investor goes long on the ten stocks with the lowest performance in the previous week and
# goes short on the ten stocks with the greatest performance of the prior month. The portfolio is rebalanced weekly.
#
# QC implementation changes:

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

class ShortTermReversalEffectinStocks(QCAlgorithm):

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

        market:Symbol = self.AddEquity('SPY', Resolution.Daily).Symbol
        
        self.fundamental_count:int = 100
        self.fundamental_sorting_key = lambda x: x.MarketCap

        self.period:int = 21
        self.week_period:int = 5
        self.stock_selection:int = 10
        self.leverage:int = 5
        self.min_share_price:float = 1.
        
        self.long:List[Symbol] = []
        self.short:List[Symbol] = []
        
        # daily close data
        self.data:Dict[Symbol, SymbolData] = {}
        
        self.day:int = 1
        self.selection_flag:bool = False
        self.UniverseSettings.Resolution = Resolution.Daily
        self.AddUniverse(self.FundamentalSelectionFunction)
        self.Settings.MinimumOrderMarginPortfolioPercentage = 0.						
        self.Schedule.On(self.DateRules.EveryDay(market), self.TimeRules.AfterMarketOpen(market), self.Selection)

        self.settings.daily_precise_end_time = False

    def OnSecuritiesChanged(self, changes: SecurityChanges) -> None:
        for security in changes.AddedSecurities:
            security.SetFeeModel(CustomFeeModel())
            security.SetLeverage(self.leverage)
        
    def FundamentalSelectionFunction(self, fundamental: List[Fundamental]) -> List[Symbol]:
        # update the rolling window every day
        for stock in fundamental:
            symbol:Symbol = stock.Symbol

            # store monthly price
            if symbol in self.data:
                self.data[symbol].update(stock.AdjustedPrice)

        if not self.selection_flag:
            return Universe.Unchanged

        selected:List[Fundamental] = [x for x in fundamental if x.HasFundamentalData and x.Market == 'usa' and \
            x.Price >= self.min_share_price and x.MarketCap != 0]
        if len(selected) > self.fundamental_count:
            selected = [x for x in sorted(selected, key=self.fundamental_sorting_key, reverse=True)[:self.fundamental_count]]

        month_performances:Dict[Symbol, float] = {}
        week_performances:Dict[Symbol, float] = {}

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

            if symbol not in self.data:
                self.data[symbol] = SymbolData(self.period+1)
                history:DataFrame = self.History(symbol, self.period+1, Resolution.Daily)
                if history.empty:
                    self.Log(f"Not enough data for {symbol} yet")
                    continue
                closes:pd.Series = history.loc[symbol]
                for time, row in closes.iterrows():
                    self.data[symbol].update(row['close'])
            
            if self.data[symbol].is_ready():
                month_performances[symbol] = self.data[symbol].performance(self.period)
                week_performances[symbol] = self.data[symbol].performance(self.week_period)

        if len(month_performances) > self.stock_selection * 2:
            sorted_by_week_perf:List[Symbol] = [x[0] for x in sorted(week_performances.items(), key=lambda item: item[1])]
            sorted_by_month_perf:List[Symbol] = [x[0] for x in sorted(month_performances.items(), key=lambda item: item[1], reverse=True)]
            
            self.long = sorted_by_week_perf[:self.stock_selection]
            self.short = sorted_by_month_perf[:self.stock_selection]
        
        return self.long + self.short
    
    def OnData(self, data: Slice) -> None:
        if not self.selection_flag:
            return
        self.selection_flag = False
        
        # order execution
        invested: List[Symbol] = [x.Key for x in self.Portfolio if x.Value.Invested]
        for symbol in invested:
            if symbol not in self.long + self.short:
                self.Liquidate(symbol)

        for i, portfolio in enumerate([self.long, self.short]):
            for symbol in portfolio:
                if symbol in data and data[symbol]:
                    self.SetHoldings(symbol, ((-1) ** i) / len(portfolio))

        self.long.clear()
        self.short.clear()
                
    def Selection(self) -> None:
        if self.day == 5:
            self.selection_flag = True
        
        self.day += 1
        if self.day > 5:
            self.day = 1
            
class SymbolData():
    def __init__(self, period:float) -> None:
        self._daily_close = RollingWindow[float](period)

    def update(self, close:float) -> None:
        self._daily_close.Add(close)

    def is_ready(self) -> bool:
        return self._daily_close.IsReady
    
    def performance(self, period:int) -> float:
        return self._daily_close[0] / self._daily_close[period] - 1

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