Overall Statistics
Total Trades
147254
Average Win
0.01%
Average Loss
-0.01%
Compounding Annual Return
10.736%
Drawdown
45.200%
Expectancy
0.287
Net Profit
1019.380%
Sharpe Ratio
0.696
Probabilistic Sharpe Ratio
3.032%
Loss Rate
22%
Win Rate
78%
Profit-Loss Ratio
0.65
Alpha
0.042
Beta
0.639
Annual Standard Deviation
0.115
Annual Variance
0.013
Information Ratio
0.259
Tracking Error
0.078
Treynor Ratio
0.125
Total Fees
$2334.46
Estimated Strategy Capacity
$78000.00
Lowest Capacity Asset
UBA RDAO81KKALPH
Portfolio Turnover
1.10%
 
 
# https://quantpedia.com/strategies/low-volatility-factor-effect-in-stocks-long-only-version/
#
# The investment universe consists of global large-cap stocks (or US large-cap stocks). At the end of each month, the investor constructs 
# equally weighted decile portfolios by ranking the stocks on the past three-year volatility of weekly returns. The investor goes long 
# stocks in the top decile (stocks with the lowest volatility).
#
# QC implementation changes:
#   - Top quartile (stocks with the lowest volatility) is selected instead of decile.

#region imports
from AlgorithmImports import *
import numpy as np
from typing import List, Dict
#endregion

class LowVolatilityFactorEffectStocks(QCAlgorithm):

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

        self.symbol:Symbol = self.AddEquity('SPY', Resolution.Daily).Symbol
        
        self.period:int = 12*21
        
        self.coarse_count:int = 3000
        self.quantile:int = 4
        self.leverage:int = 10
        self.data:Dict[Symbol, SymbolData] = {}
        
        self.long:List[Symbol] = []

        self.selection_flag:bool = True
        self.UniverseSettings.Resolution = Resolution.Daily
        self.Settings.MinimumOrderMarginPortfolioPercentage = 0
        self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)
        self.Schedule.On(self.DateRules.MonthEnd(self.symbol), self.TimeRules.AfterMarketOpen(self.symbol), self.Selection)

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

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

        if not self.selection_flag:
            return Universe.Unchanged

        selected:List[Symbol] = [x.Symbol for x in coarse if x.HasFundamentalData and x.Market == 'usa']
        # selected = [x.Symbol
        #     for x in sorted([x for x in coarse if x.HasFundamentalData and x.Market == 'usa'],
        #         key = lambda x: x.DollarVolume, reverse = True)[:self.coarse_count]]
        
        # Warmup price rolling windows.
        for symbol in selected:
            if symbol in self.data:
                continue
            
            self.data[symbol] = SymbolData(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:pd.Series = history.loc[symbol].close
            for time, close in closes.iteritems():
                self.data[symbol].update(close)
        
        return [x for x in selected if self.data[x].is_ready()]

    def FineSelectionFunction(self, fine:List[FineFundamental]) -> List[Symbol]:
        fine:List[Symbol] = [x for x in fine if x.MarketCap != 0]
        
        # market cap sorting
        if len(fine) > self.coarse_count:
            sorted_by_market_cap:List[Symbol] = sorted(fine, key = lambda x: x.MarketCap, reverse=True)
            fine:List[Symbol] = sorted_by_market_cap[:self.coarse_count]
        
        weekly_vol:Dict[Symbol, float] = {x.Symbol : self.data[x.Symbol].volatility() for x in fine}
        
        if len(weekly_vol) >= self.quantile:
            # volatility sorting
            sorted_by_vol:List[Tuple] = sorted(weekly_vol.items(), key = lambda x: x[1], reverse = True)
            quantile:int = int(len(sorted_by_vol) / self.quantile)
            self.long = [x[0] for x in sorted_by_vol[-quantile:]]
        
        return self.long
        
    def OnData(self, data:Slice) -> None:
        if not self.selection_flag:
            return
        self.selection_flag = False

        # Trade execution.
        stocks_invested:List[Symbol] = [x.Key for x in self.Portfolio if x.Value.Invested]
        for symbol in stocks_invested:
            if symbol not in self.long:
                self.Liquidate(symbol)

        for symbol in self.long:
            if symbol in data and data[symbol]:
                self.SetHoldings(symbol, 1 / len(self.long))

        self.long.clear()
        
    def Selection(self) -> None:
        self.selection_flag:bool = True

class SymbolData():
    def __init__(self, period:int) -> None:
        self.price:RollingWindow = RollingWindow[float](period)
    
    def update(self, value:float) -> None:
        self.price.Add(value)
    
    def is_ready(self) -> bool:
        return self.price.IsReady
        
    def volatility(self) -> float:
        closes:List[float] = [x for x in self.price]
        
        # Weekly volatility calc.
        separete_weeks:List[float] = [closes[x:x+5] for x in range(0, len(closes), 5)]
        weekly_returns:List[float] = [(x[0] - x[-1]) / x[-1] for x in separete_weeks]

        return np.std(weekly_returns)   

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