Applying Research

Key Concepts

Introduction

The ultimate goal of research is to produce a strategy that you can backtest and eventually trade live. Once you've developed a hypothesis that you're confident in, you can start working towards exporting your research into backtesting. To export the code, you need to replace QuantBook() with self and replace the QuantBook methods with their QCAlgorithm counterparts.

Workflow

Imagine that you've developed the following hypothesis: stocks that are below 1 standard deviation of their 30-day mean are due to revert and increase in value. The following Research Environment code picks out such stocks from a preselected basket of stocks:

import numpy as np
qb = QuantBook()

symbols = {}
assets = ["SHY", "TLT", "SHV", "TLH", "EDV", "BIL",
"SPTL", "TBT", "TMF", "TMV", "TBF", "VGSH", "VGIT",
"VGLT", "SCHO", "SCHR", "SPTS", "GOVT"]

for i in range(len(assets)):

# Fetch history on our universe
df = qb.History(qb.Securities.Keys, 30, Resolution.Daily)

# Make all of them into a single time index.
df = df.close.unstack(level=0)

# Calculate the truth value of the most recent price being less than 1 std away from the mean
classifier = df.le(df.mean().subtract(df.std())).tail(1)

# Get indexes of the True values
classifier_indexes = np.where(classifier)[1]

# Get the Symbols for the True values
classifier = classifier.transpose().iloc[classifier_indexes].index.values

# Get the std values for the True values (used for magnitude)
magnitude = df.std().transpose()[classifier_indexes].values

# Zip together to iterate over later
selected = zip(classifier, magnitude)


Once you are confident in your hypothesis, you can export this code into the backtesting environment. The algorithm will ultimately go long on the stocks that pass the classifier logic. One way to accommodate this model into a backtest is to create a Scheduled Event that uses the model to pick stocks and place orders.

def Initialize(self) -> None:
self.SetStartDate(2014, 1, 1)
self.SetCash(1000000)
self.SetBenchmark("SPY")

self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel())
self.SetExecution(ImmediateExecutionModel())

self.assets = ["IEF", "SHY", "TLT", "IEI", "SHV", "TLH", "EDV", "BIL",
"SPTL", "TBT", "TMF", "TMV", "TBF", "VGSH", "VGIT",
"VGLT", "SCHO", "SCHR", "SPTS", "GOVT"]

self.symbols = {}

for i in range(len(self.assets)):

# Set the Scheduled Event method
self.Schedule.On(self.DateRules.Every(DayOfWeek.Monday), self.TimeRules.AfterMarketOpen("IEF", 1), self.EveryDayAfterMarketOpen)


Now that the Initialize method of the algorithm is set, export the model into the Scheduled Event method. You just need to switch qb with self and replace QuantBook methods with their QCAlgorithm counterparts. In this example, you don't need to switch any methods because the model only uses methods that exist in QCAlgorithm.

def EveryDayAfterMarketOpen(self):
qb = self
# Fetch history on our universe
df = qb.History(qb.Securities.Keys, 5, Resolution.Daily)

# Make all of them into a single time index.
df = df.close.unstack(level=0)

# Calculate the truth value of the most recent price being less than 1 std away from the mean
classifier = df.le(df.mean().subtract(df.std())).tail(1)

# Get indexes of the True values
classifier_indexes = np.where(classifier)[1]

# Get the Symbols for the True values
classifier = classifier.transpose().iloc[classifier_indexes].index.values

# Get the std values for the True values (used for magnitude)
magnitude = df.std().transpose()[classifier_indexes].values

# Zip together to iterate over later
selected = zip(classifier, magnitude)

# ==============================

insights = []

for symbol, magnitude in selected:
insights.append(Insight.Price(symbol, timedelta(days=5), InsightDirection.Up, magnitude))

self.EmitInsights(insights)


With the Research Environment model now in the backtesting environment, you can further analyze its performance with its backtesting metrics. If you are confident in the backtest, you can eventually live trade this strategy.

To view full examples of this Research to Production workflow, see the examples in the menu.

Contribute Tutorials

If you contribute Research to Production tutorials, you'll get the following benefits:

• A QCC reward
• You'll learn the Research to Production methodology to improve your own strategy research and development
• Your contribution will be featured in the community forum

To view the topics the community wants Research to Production tutorials for, see the issues with the WishList tag in the Research GitHub repository. If you find a topic you want to create a tutorial for, make a pull request to the repository with your tutorial and we will review it.