AuthorAlethea Lin2019-09-26

Abstract

In this tutorial we implement a trend following strategy on commodities futures based on a 2014 paper "Two Centuries Of Trend Following" by Y. Lempérière, C. Deremble, P. Seager, M. Potters, and J. P. Bouchaud.

Introduction

The paper highlights the existence of trends as an anomaly that contradicts the efficient market hypothesis. If financial markets are completely efficient as the hypothesis suggests, then asset price changes should be totally unpredictable. In other words, no systematic excess return based on public information should exist since asset prices ought to reflect all public information available. However observationally, trend existence in the market do exist. They make it possible to use the simple trend following strategy which states, buy when prices goes up and sell when prices goes down. Numerous academic studies have demonstrated that trend following strategies generate persistent returns over long periods of time.

The paper extends the backtest period of trend following strategies to two centuries and demonstrates statistically significant systematic excess returns on four asset classes (commodities, currencies, stock indices, and bonds). It implements a risk managed strategy that buys or sells a quantity of of the underlying contract depending on the sign of .

The signal at the beginning of month is:

where is last month's exponential moving average of past prices with a decay rate equal to months, is the price of last month, and is last month's volatility, estimated as the exponential moving average of the absolute monthly price changes, with a decay rate equal to months. The decay rate was set to 5 months.

Below, we will implement the above monthly-rebalanced trend following strategy on commodities futures.

Method

Step 1: Subscribe to continuous futures data

The paper selected a well-balanced commodities pool to include 7 representative contracts: Crude oil, Henry Hub Natural Gas, Corn, Wheat, Super, Live Cattle and Copper. We will add continuous futures data of these contracts in daily resolution.

from QuantConnect.Python import PythonQuandl

class ImprovedCommodityMomentumTrading(QCAlgorithm):
    def Initialize(self):
        tickers = [Futures.Grains.Wheat,
                   Futures.Grains.Corn,
                   Futures.Meats.LiveCattle,
                   Futures.Energies.CrudeOilWTI,
                   Futures.Energies.NaturalGas,
                   Futures.Softs.Sugar11,
                   Futures.Metals.Copper]
        for ticker in tickers:
            # subscribe to continuous future data and set desired leverage
            future = self.AddFuture(ticker,
                resolution = Resolution.Daily,
                extendedMarketHours = True,
                dataNormalizationMode = DataNormalizationMode.BackwardsRatio,
                dataMappingMode = DataMappingMode.OpenInterest,
                contractDepthOffset = 0
            )
            future.SetLeverage(3) 

Step 2: Create a SymbolData class to store and update the number of contracts to trade for each security

In Initialize, we create a dictionary to store the SymbolData object for each security. The strategy is designed to trade monthly, so we will create a monthly consolidator for each security as well. When a new monthly data becomes available, the consolidator calls the consolidator event handler CalendarHandler. Within this event handler, we will update the SymbolData object with the freshly received monthly data.

def Initialize(self):                   
    # Container to store the SymbolData object for each security
    self.Data = {}

    for ticker in tickers:
        # subscribe to continuous future data and set desired leverage
            future = self.AddFuture(ticker,
                resolution = Resolution.Daily,
                extendedMarketHours = True,
                dataNormalizationMode = DataNormalizationMode.BackwardsRatio,
                dataMappingMode = DataMappingMode.OpenInterest,
                contractDepthOffset = 0
            )
            future.SetLeverage(3) 

        # Create a monthly consolidator for each security
        self.Consolidate(future.Symbol, CalendarType.Monthly, self.CalendarHandler)

        # Create a SymbolData object for each security to store relevant indicators 
        # and calculate quantity of contracts to Buy/Sell
        self.Data[future.Symbol] = SymbolData(future)

def CalendarHandler(self, bar):
    '''
    Event Handler that updates the SymbolData object for each security when a new monthly bar becomes available
    '''
    self.Data[bar.Symbol].Update(bar)

The SymbolData class is designed to contain everything we need for calculating how many contracts to buy/sell at the beginning of each month. LEAN provides helpful indicators to get the exponential moving average and momentum. We also hold the pointer of mapped contract and contract multiplier as properties of the object for later ordering use. The Introduction section above detailed the formula for calculating the number of contracts to buy/sell. We implement the formula in the Update function.

class SymbolData:
    '''
    Contains the relevant indicators used to calculate number of contracts to Buy/Sell
    '''
    def __init__(self, future):
        self.future = future
        self.ema = ExponentialMovingAverage("MonthEMA", 5)

        # Volatility estimation is defined as the EMA of absolute monthly price changes
        # Use Momentum indicator to get absolute monthly price changes
        # Then use the IndicatorExtensions.EMA and pass the momentum indicator values to get the volatility
        self.mom = Momentum("MonthMOM", 1)
        # Note: self.vol will automatically be updated with self.mom
        self.vol = IndicatorExtensions.EMA(self.mom, 5)

        self.Quantity = 0

    @property
    def Mapped(self):
        return self.future.Mapped

    @property
    def ContractMultiplier(self):
        return self.future.SymbolProperties.ContractMultiplier

    def Update(self, bar):
        self.ema.Update(bar.Time, bar.Value)
        self.mom.Update(bar.Time, bar.Value)

        if self.ema.IsReady and self.vol.IsReady:
            # Equation 1 in [1]
            signal = (bar.Value - self.ema.Current.Value) / self.vol.Current.Value
            # Equation 2 in [1], assuming price change is the same next step
            self.Quantity = np.sign(signal) * self.mom.Current.Value / abs(self.vol.Current.Value)

        return self.Quantity != 0

Step 3: Buy and Sell at the beginning of each month

Now we’ll place orders based on the quantity of contracts calculated from previous month stored in the SymbolData object. Note that we warm up the algorithm with 150 days of data to allow the algorithm to execute trades on the start date.

def OnData(self, data):
    '''
    Buy/Sell security every month
    '''
    if self.IsWarmingUp:
        return

    for symbol, symbolData in self.Data.items():
        if not data.Bars.ContainsKey(symbol) or self.Time < self.nextRebalance[symbol]:
            continue

        if symbolData.Quantity != 0:
            # divided by the contract multiplier
            self.MarketOrder(symbolData.Mapped, self.leverage * symbolData.Quantity // symbolData.ContractMultiplier)

        self.nextRebalance[symbol] = Expiry.EndOfMonth(self.Time)

Summary

For the backtest period (January 2010 to January 2020), the trend following strategy produced a Sharpe ratio of -0.131, compared to SPY’s Sharpe ratio of 0.805, while information ratio is -0.767 and alpha is 0.003. The performance of suggests that the trend information no longer provide extra information for alpha profit generation, unlike the period of the paper tested on.

Trend following was considered one of the best information source of excess return, especially via Futures assets, in the 60s-70s. However, by the technological progression particularly from the last decade, this simple information is absorbed in miliseconds by the more efficient market.

Algorithm



Reference

  1. Y. Lempérière, C. Deremble, P. Seager, M. Potters, J. P. Bouchaud (2014). Two centuries of trend following. Online Copy

Previous: Residual Momentum Next: Price and Earnings Momentum