Introduction
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.
Method
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,
Futures.Currencies.GBP,
Futures.Currencies.CAD,
Futures.Currencies.EUR,
Futures.Indices.NASDAQ100EMini,
Futures.Indices.Russell2000EMini,
Futures.Indices.SP500EMini,
Futures.Indices.Dow30EMini]
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
)
future.SetLeverage(1)
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):
self.consolidator.Update(bar)
self.oi_consolidator.Update(oi)
@property
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
@property
def Mapped(self):
return self._future.Mapped
@property
def VolumeReturn(self):
return self._volume_roc.Current.Value
@property
def OpenInterestReturn(self):
return self._oi_roc.Current.Value
@property
def Return(self):
return self._return.Current.Value
def Update(self, slice):
if slice.Bars.ContainsKey(self.Symbol):
self.consolidator.Update(slice.Bars[self.Symbol])
oi = OpenInterest(slice.Time, self.Symbol, self._future.OpenInterest)
self.oi_consolidator.Update(oi)
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
else:
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
symbol_data.Update(slice)
# 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 \(t-1\) to \(t\) and the period from \(t-2\) to \(t-1\).
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]:
self.Liquidate(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)
Jing Wu
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 QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect 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. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!