每月构建等权重十分位组合,通过全球(或美国)大盘股的三年波动率排名。做多排名前十分位的股票。

策略概述

在由全球或美国大盘股组成的股票池中,每月构建等权重的十分位组合。根据股票的三年周收益波动率进行排名,做多波动率最低的前十分位股票。

策略合理性

杠杆在最大化低风险股票的回报中至关重要,但杠杆的有限使用导致了未套利的机会。波动率效应可能源于分散投资和行为偏差,投资者可能会为高风险股票支付过高的价格,类似于购买“彩票”性质的股票。研究表明,低波动率股票的异常回报可能源于市场定价错误或对更高系统性风险的补偿,挑战了传统的资产定价理论。尽管进行了调整,但波动率效应仍然显著,与动量效应和规模效应等经典效应相当。专注于三年的历史波动率可以减少组合的换手率,增强长期效率。

论文来源

The Volatility Effect: Lower Risk Without Lower Return [点击浏览原文]

<摘要>

我们提供了实证证据,表明低波动率股票能获得较高的风险调整回报。在1986年至2006年期间,全球低波动率和高波动率股票组合的年度超额收益率(alpha spread)为12%。我们还在美国、欧洲和日本市场中分别观察到了这一波动率效应。此外,我们发现波动率效应无法通过其他众所周知的效应(如价值效应和规模效应)来解释。我们的结果表明,股权投资者为高风险股票支付了过高的价格。对此现象的可能解释包括:(i)杠杆限制,(ii)无效的两步投资流程,(iii)私人投资者的行为偏差。为在实践中利用波动率效应,我们建议投资者应在战略资产配置阶段将低风险股票作为单独的资产类别。

回测表现

年化收益率11.3%
波动率10.1%
Beta0.66
夏普比率0.52
索提诺比率0.51
最大回撤45.9%
胜率78%

完整python代码

from AlgoLib import *
import numpy as np
from typing import List, Dict

class LowVolatilityFactorEffectStocks(XXX):
    """
    A class designed to implement a low volatility factor effect trading strategy.
    It selects stocks based on their volatility and constructs a portfolio that is rebalanced monthly.
    """
    
    def Initialize(self) -> None:
        """
        Initializes the strategy by setting starting cash, adding the target equity (SPY),
        setting parameters for the strategy, and scheduling function calls.
        """
        self.SetStartDate(2000, 1, 1)  # Set the start date for the backtest
        self.SetCash(100000)  # Set the initial cash for the backtest
        self.symbol: Symbol = self.AddEquity('SPY', Resolution.Daily).Symbol  # Add SPY as the equity to trade
        self.period: int = 12 * 21  # Define the period for rolling window calculations
        self.fundamental_count: int = 3000  # Number of fundamental data points to consider
        self.quantile: int = 4  # Division of data into quantiles
        self.leverage: int = 10  # Set the leverage for the strategy
        self.data: Dict[Symbol, SymbolData] = {}  # Initialize a dictionary to store symbol data
        self.long: List[Symbol] = []  # List to keep track of symbols to go long on
        self.selection_flag: bool = True  # Flag to control the selection process
        self.UniverseSettings.Resolution = Resolution.Daily  # Set universe resolution to daily
        self.Settings.MinimumOrderMarginPortfolioPercentage = 0.  # Set minimum margin percentage
        self.AddUniverse(self.FundamentalSelectionFunction)  # Define the universe based on a custom selection function
        self.Schedule.On(self.DateRules.MonthEnd(self.symbol), self.TimeRules.AfterMarketOpen(self.symbol), self.Selection)  # Schedule the selection function

    def OnSecuritiesChanged(self, changes: SecurityChanges) -> None:
        """
        Updates securities settings on changes in the investment universe, like setting a custom fee model and leverage.
        """
        for security in changes.AddedSecurities:
            security.SetFeeModel(CustomFeeModel())  # Set a custom fee model for added securities
            security.SetLeverage(self.leverage)  # Set the leverage for the securities
            
    def FundamentalSelectionFunction(self, fundamental: List[Fundamental]) -> List[Symbol]:
        """
        Selects symbols based on fundamental data, targeting low volatility stocks within the top market capitalization.
        """
        for stock in fundamental:
            symbol: Symbol = stock.Symbol
            if symbol in self.data:
                self.data[symbol].update(stock.AdjustedPrice)
        if not self.selection_flag:
            return Universe.Unchanged
        fundamental: List[Fundamental] = [x for x in fundamental if x.HasFundamentalData and x.Market == 'usa' and x.MarketCap != 0]
        if len(fundamental) > self.fundamental_count:
            fundamental = sorted(fundamental, key=lambda x: x.MarketCap, reverse=True)[:self.fundamental_count]
        weekly_vol: Dict[Symbol, float] = {}
        for stock in fundamental:
            symbol: Symbol = stock.Symbol
            if symbol not in self.data:
                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)         
            if self.data[symbol].is_ready():
                weekly_vol[symbol] = self.data[symbol].volatility()
        if len(weekly_vol) >= self.quantile:
            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:
        """
        Executes the trading logic at each data point, adjusting the portfolio based on the selection of low volatility stocks.
        """
        if not self.selection_flag:
            return
        self.selection_flag = False
        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.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:
        """
        Sets a flag to true to trigger the selection process at the next opportunity.
        """
        self.selection_flag = True

class SymbolData():
    """
    A helper class for storing and updating price data for symbols, and calculating their volatility.
    """
    def __init__(self, period: int) -> None:
        self.price: RollingWindow = RollingWindow[float](period)  # Initialize a rolling window for prices
    
    def update(self, value: float) -> None:
        """
        Updates the rolling window with the latest price.
        """
        self.price.Add(value)
    
    def is_ready(self) -> bool:
        """
        Checks if the rolling window has enough data.
        """
        return self.price.IsReady
        
    def volatility(self) -> float:
        """
        Calculates the volatility of the symbol based on price data in the rolling window.
        """
        closes: List[float] = [x for x in self.price]
        separate_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 separate_weeks]
        return np.std(weekly_returns)   

class CustomFeeModel(FeeModel):
    """
    A custom fee model that calculates trading fees based on the transaction volume.
    """
    def GetOrderFee(self, parameters: OrderFeeParameters) -> OrderFee:
        fee: float = parameters.Security.Price * parameters.Order.AbsoluteQuantity * 0.00005
        return OrderFee(CashAmount(fee, "USD"))

Leave a Reply

Discover more from Quant Buffet

Subscribe now to keep reading and get access to the full archive.

Continue reading