AuthorJing Wu2018-08-30


The short-term reversal strategy buys stocks which are past losers and sells stocks which are past winners. It is commonly used in the Equity market. This algorithm will explore the reversal effect in the Futures market. Research also suggests that trading volume contains information about Future market movements. The algorithm will be constructed with both the volume and return reversal effect.


The investment universe consists of 8 CME continuous Futures: 4 currencies, 4 financial Indices. The continuous contracts are mapped based on open interest, while data is subscribed in daily resolution.

The algorithm uses a weekly time frame (Wednesday-Wednesday interval). We constructed a SymbolData class to hold weekly consolidators for volume, open interest and price that consolidate every Wednesday 00:00. To compare the weekly change of volume and open interest, we create a RateOfChange indicator that uses consolidated data to update for each feature, and set up flag variables to indicate if they are up-to-date in which are handled by Updated handler. Other information like Mapped contract and update methods are also held within the class object.

def Initialize(self):
    self.tickers = [Futures.Currencies.CHF, 
    self.length = len(self.tickers)

    self.symbol_data = {}

    for ticker in self.tickers:
        future = self.AddFuture(ticker,
                resolution = Resolution.Daily,
                extendedMarketHours = True,
                dataNormalizationMode = DataNormalizationMode.BackwardsRatio,
                dataMappingMode = DataMappingMode.OpenInterest,
                contractDepthOffset = 0
        self.symbol_data[future.Symbol] = SymbolData(self, future)

class SymbolData:
    def __init__(self, algorithm, future):
        self._future = future
        self.Symbol = future.Symbol
        self._is_volume_ready = False
        self._is_oi_ready = False
        self._is_return_ready = False

        # create ROC(1) indicator to get the volume and open interest return, and handler to update state
        self._volume_roc = RateOfChange(1)
        self._oi_roc = RateOfChange(1)
        self._return = RateOfChange(1)
        self._volume_roc.Updated += self.OnVolumeRocUpdated
        self._oi_roc.Updated += self.OnOiRocUpdated
        self._return.Updated += self.OnReturnUpdated

        # Create the consolidator with the consolidation period method, and handler to update ROC indicators
        self.consolidator = TradeBarConsolidator(self.consolidation_period)
        self.oi_consolidator = OpenInterestConsolidator(self.consolidation_period)
        self.consolidator.DataConsolidated += self.OnTradeBarConsolidated
        self.oi_consolidator.DataConsolidated += lambda sender, oi: self._oi_roc.Update(oi.Time, oi.Value)

        # warm up
        history = algorithm.History[TradeBar](future.Symbol, 14, Resolution.Daily)
        oi_history = algorithm.History[OpenInterest](future.Symbol, 14, Resolution.Daily)
        for bar, oi in zip(history, oi_history):

    def IsReady(self):
        return self._volume_roc.IsReady and self._oi_roc.IsReady \
            and self._is_volume_ready and self._is_oi_ready and self._is_return_ready

    def Mapped(self):
        return self._future.Mapped

    def VolumeReturn(self):
        return self._volume_roc.Current.Value

    def OpenInterestReturn(self):
        return self._oi_roc.Current.Value

    def Return(self):
        return self._return.Current.Value

    def Update(self, slice):
        if slice.Bars.ContainsKey(self.Symbol):

            oi = OpenInterest(slice.Time, self.Symbol, self._future.OpenInterest)

    def OnVolumeRocUpdated(self, sender, updated):
        self._is_volume_ready = True

    def OnOiRocUpdated(self, sender, updated):
        self._is_oi_ready = True

    def OnReturnUpdated(self, sender, updated):
        self._is_return_ready = True

    def OnTradeBarConsolidated(self, sender, bar):
        self._volume_roc.Update(bar.EndTime, bar.Volume)
        self._return.Update(bar.EndTime, bar.Close)

    # Define a consolidation period method
    def consolidation_period(self, dt):
        period = timedelta(7)

        dt = dt.replace(hour=0, minute=0, second=0, microsecond=0)
        weekday = dt.weekday()
        if weekday > 2:
            delta = weekday - 2
        elif weekday < 2:
            delta = weekday + 5
            delta = 0
        start = dt - timedelta(delta)

        return CalendarInfo(start, period)

We'll update each consolidators of SymbolData with Slice data in the OnData event handler, as well as rolling over behavior of mapped continuous future contracts.

def OnData(self, slice):
    for symbol, symbol_data in self.symbol_data.items():
        # Update SymbolData

        # Rollover
        if slice.SymbolChangedEvents.ContainsKey(symbol):
            changed_event = slice.SymbolChangedEvents[symbol]
            old_symbol = changed_event.OldSymbol
            new_symbol = changed_event.NewSymbol
            tag = f"Rollover - Symbol changed at {self.Time}: {old_symbol} -> {new_symbol}"
            quantity = self.Portfolio[old_symbol].Quantity

            # Rolling over: to liquidate any position of the old mapped contract and switch to the newly mapped contract
            self.Liquidate(old_symbol, tag = tag)
            self.MarketOrder(new_symbol, quantity // self.Securities[new_symbol].SymbolProperties.ContractMultiplier, tag = tag)

Then, all contracts are also assigned to either high-open interest (top 50% of changes in open interest) or low-open interest groups (bottom 50% of changes in open interest) based on lagged changes in open interest between the period from to and the period from to .

We take the intersection of the top volume group and bottom open interest group. The trading candidates are selected from this group. Next, the Futures in the intersection are sorted based on the return in the previous week. The algorithm goes long on Futures from the high-volume, low-open interest group with the lowest return and shorts the contract with the highest return.

# Select stocks with most weekly extreme return out of lowest volume change and highest OI change
trade_group = set(sorted(self.symbol_data.values(), key=lambda x: x.VolumeReturn)[:int(self.length*0.5)] +
    sorted(self.symbol_data.values(), key=lambda x: x.OpenInterestReturn)[-int(self.length*0.5):])
sorted_by_returns = sorted(trade_group, key=lambda x: x.Return)
short_symbol = sorted_by_returns[-1].Mapped
long_symbol = sorted_by_returns[0].Mapped

for symbol in self.Portfolio.Keys:
    if self.Portfolio[symbol].Invested and symbol not in [short_symbol, long_symbol]:

# Adjust for contract mulitplier for order size
qty = self.CalculateOrderQuantity(short_symbol, -0.3)
multiplier = self.Securities[short_symbol].SymbolProperties.ContractMultiplier
self.MarketOrder(short_symbol, qty // multiplier)

qty = self.CalculateOrderQuantity(long_symbol, 0.3)
multiplier = self.Securities[long_symbol].SymbolProperties.ContractMultiplier
self.MarketOrder(long_symbol, qty // multiplier)


Previous: Pre-holiday Effect Next: Combining Momentum Effect with Volume