Back to Community
Do momentum and reversals coexist?

Many in academia have studied the predictability of stock returns along various cross-sections based on past returns. Some of these cross-sectional analyses dissect stock returns along time (returns patterns like momentum over the short and long term), industry (sector returns) among other dimensions.

Jason Wei of the University of Toronto proposes that momentum and reversals coexist. Here, momentum is understood to be the rate of acceleration of a security's price. Reversals are defined as changes in the direction of a price trend. Wei's research, detailed in the paper titled “Do momentum and reversals coexist?”, states that rather than assuming momentum and reversals as separate phenomena, the two occur simultaneously. Further, Wei also studies return predictability along the dimensions of size and volatility. Wei’s research documents that for large-cap/ low-volatility stocks, reversals prevail while large-cap/high-volatility stocks experience momentum.

Quantpedia concludes that this cannot be fully rationalized by either risk-based or behavioral-based explanations, with Wei adding that some behavioral-based models go the furthest in rationalizing the findings.

In order to study Wei’s findings, my notebook recreates the methodology using the Q1500 universe of stocks for a time period ranging from December 1, 2010 to December 1, 2016. When tuning and backtesting the corresponding algorithm, I noted a consistent decline or stagnation in performance from early 2015 to mid 2016. The reason for this is still unknown.

As my first exercise writing a notebook and conducting quantitative research, I’d love to receive feedback from the community. How can I heighten my researching skills? Thank you for reading and for your responses.

Loading notebook preview...
Notebook previews are currently unavailable.
Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

3 responses

Attached is the backtest for the strategy described above.

Clone Algorithm
31
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
"""
*star*
# Pick lowest volatility group and then go long on worst performers
# go short on top performers

1. Momentum aspect (Returns)
2. Lookback window for volatility
3. Can you separate out by lowest volatility per sector
4. Instead of using volatility as a mask, short high vol and long low vol
5. Separate out by long/short
"""

from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import AverageDollarVolume, Returns
from quantopian.pipeline.filters.morningstar import Q500US, Q1500US
from quantopian.pipeline.data import morningstar
from quantopian.pipeline import CustomFactor
import quantopian.experimental.optimize as opt
import quantopian.algorithm as algo
import numpy as np
import pandas as pd


MAX_SHORT_POSITION_SIZE = 0.03
MAX_LONG_POSITION_SIZE = 0.03

MAX_GROSS_LEVERAGE = 1.0

def initialize(context):
    # schedule_function(open_positions, date_rules.every_day(), time_rules.market_open(hours=2))
    schedule_function(my_record_vars, date_rules.every_day(), time_rules.market_close())
    # Create our dynamic stock selector.
    pipe = make_pipeline(Q1500US())
    algo.attach_pipeline(pipe, 'my_pipeline')
    algo.schedule_function(
        open_positions,
        date_rule=algo.date_rules.every_day(),
        time_rule=algo.time_rules.market_open(minutes=10),
        half_days=False
    )
    # set_slippage(slippage.FixedSlippage(spread=0))
    # set_commission(commission.PerShare(cost=0, min_trade_cost=0))


class DelayedReturns(CustomFactor):
    inputs = [USEquityPricing.close]
    def compute(self, today, assets, out, close):
        out[:] = close[-1] / close[0]


class DelayedVolatility(CustomFactor):
    inputs = [USEquityPricing.close]
    def compute(self, today, assets, out, close):
        out[:] = -np.nanstd(close[:-1], axis=0)


class MarketCap(CustomFactor):
    inputs = [morningstar.valuation.shares_outstanding, USEquityPricing.close]
    def compute(self, today, assets, out, shares, close_price):
        out[:] = shares * close_price


def make_pipeline(mask):
    # market_cap = MarketCap(window_length=1, mask=mask)
    # mkt_cap_q = market_cap.quantiles(2)
    # mkt_bot = mkt_cap_q.eq(1)
    
    # mask = mask & mkt_bot
    
    # 30 day vol 90 day lookback - 25.6%
    # 30 day vol 90 day lookback 0 - 20 lowest ret 80 - 100 highest ret - 25.6%
    # -delayed_returns.rank() - 35%
    
    delayed_volatility = DelayedVolatility(window_length=30, mask=mask)
    dv_q = delayed_volatility.quantiles(5)
    dv_bot = dv_q.eq(0)
    
    mask = mask & dv_bot

    delayed_returns = Returns(window_length=90, mask=mask) # DelayedReturns(window_length=90, mask=mask)
    lowest_returns = delayed_returns.percentile_between(0, 20, mask=mask)
    highest_returns = delayed_returns.percentile_between(80, 100, mask=mask)
    
    alpha = -delayed_returns.rank()
    
    pipe = Pipeline(
        screen = mask & (highest_returns | lowest_returns),
        columns = {
            'Delayed Returns' : delayed_returns,
            'lowest_returns' : lowest_returns,
            'highest_returns' : highest_returns,
            'alpha' : alpha
        }
    )
    return pipe


def open_positions(context, data):
    # for stock in context.longs:
    #     if stock not in context.portfolio.positions:
    #         order_target_percent(stock, .5/len(context.longs))

    # for stock in context.shorts:
    #     if stock not in context.portfolio.positions:
    #         order_target_percent(stock, -.5/len(context.shorts))

    # for stock in context.portfolio.positions:
    #     if stock not in context.longs | context.shorts:
    #         order_target_percent(stock, 0)
    universe = context.pipeline_data.index
    
    objective = opt.MaximizeAlpha(context.pipeline_data.alpha)
    
    leverage_constraint = opt.MaxGrossLeverage(MAX_GROSS_LEVERAGE)
    
    position_size_constraint = opt.PositionConcentration.with_equal_bounds(
        -MAX_SHORT_POSITION_SIZE,
        MAX_LONG_POSITION_SIZE
    )
    
    market_neutral_constraint = opt.DollarNeutral()
    
    algo.order_optimal_portfolio(
        objective=objective,
        constraints=[
            leverage_constraint,
            position_size_constraint,
            market_neutral_constraint
        ],
        universe=universe
    )


def before_trading_start(context, data):
    context.pipeline_data = pipeline_output('my_pipeline')

    context.longs = context.pipeline_data[context.pipeline_data['lowest_returns']].index 
    context.shorts = context.pipeline_data[context.pipeline_data['highest_returns']].index
    
    # context.longs = context.pipeline_data[context.pipeline_data['highest_returns']].index
    # context.shorts = context.pipeline_data[context.pipeline_data['lowest_returns']].index


def my_record_vars(context, data):
    record(leverage=context.account.leverage,
           positions=len(context.portfolio.positions))
There was a runtime error.

Two things:

I don't see that the volatility factor uses the window length at all?

And second, it seems obvious that high momentum would cause high volatility, just mathematically. For this study to be useful, high volatility would have to predict high momentum; as such, someone should rerun the study by calculating the volatility for the 30 days prior to the momentum window and test that relationship.

Never mind the first point been away from it for too long.