"""This algorithm demonstrates the concept of long-short equity. It uses a
technical factor to rank equities in our universe. It then longs the top of
the ranking and shorts the bottom.
For information on long-short equity strategies, please see the corresponding
lecture on our lectures page:
WARNING: These factors were selected because they worked in the past over the
specific time period we choose. We do not anticipate them working in the
future. In practice finding your own factors is the hardest part of developing
any long-short equity strategy. This algorithm is meant to serve as a
framework for testing your own ranking factors.
This algorithm was developed as part of
Quantopian's Lecture Series. Please direct any
questions, feedback, or corrections to [email protected]
from quantopian.algorithm import attach_pipeline, pipeline_output, order_optimal_portfolio
from quantopian.pipeline import Pipeline
from quantopian.pipeline.factors import CustomFactor, SimpleMovingAverage, AverageDollarVolume, RollingLinearRegressionOfReturns
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.data import morningstar
from quantopian.pipeline.filters.morningstar import IsPrimaryShare
from quantopian.pipeline.classifiers.morningstar import Sector
import numpy as np
import pandas as pd
from quantopian.pipeline.filters import Q1500US
import quantopian.experimental.optimize as opt
# Constraint Parameters
MAX_GROSS_LEVERAGE = 1.0
NUM_LONG_POSITIONS = 300
NUM_SHORT_POSITIONS = 300
# Here we define the maximum position size that can be held for any
# given stock.
MAX_SHORT_POSITION_SIZE = 2*1.0/(NUM_LONG_POSITIONS + NUM_SHORT_POSITIONS)
MAX_LONG_POSITION_SIZE = 2*1.0/(NUM_LONG_POSITIONS + NUM_SHORT_POSITIONS)
# Risk Exposures
MAX_SECTOR_EXPOSURE = 0.10
MAX_BETA_EXPOSURE = 0.20
Here we define a basic mean reversion factor using a CustomFactor. We
take a ratio of the last close price to the average price over the
last 60 days. A high ratio indicates a high price relative to the mean
and a low ratio indicates a low price relative to the mean.
inputs = [USEquityPricing.close]
window_length = 60
def compute(self, today, assets, out, prices):
out[:] = -prices[-1] / np.mean(prices, axis=0)
Create and return our pipeline.
We break this piece of logic out into its own function to make it easier to
test and modify in isolation.
# Create our mean reversion factor by taking the negative of a momentum factor
reversion = Reversion()
# Classify all securities by sector so that we can enforce sector neutrality later
sector = Sector()
# Screen out non-desirable securities by defining our universe.
universe = Q1500US()
# By applying a mask to the rank computations, we remove any stocks that failed
# to meet our initial criteria **before** computing ranks. This means that the
# stock with rank 10.0 is the 10th-lowest stock that was included in the Q1500US.
factor_rank = reversion.rank(mask=universe).zscore()
# Build Filters representing the top and bottom 150 stocks by our ranking system.
# We'll use these as our tradeable universe each day.
longs = factor_rank.top(NUM_LONG_POSITIONS)
shorts = factor_rank.bottom(NUM_SHORT_POSITIONS)
# The final output of our pipeline should only include
# the top/bottom 300 stocks by our criteria
long_short_screen = (longs | shorts)
# Define any risk factors that we will want to neutralize
# We are chiefly interested in market beta as a risk factor so we define it using
# Bloomberg's beta calculation
# Ref: https://www.lib.uwo.ca/business/betasbydatabasebloombergdefinitionofbeta.html
beta = 0.66 * RollingLinearRegressionOfReturns(
).beta + 0.33*1.0
# Create pipeline
pipe = Pipeline(
# Here we set our slippage and commisions. Set slippage
# and commission to zero to evaulate the signal-generating
# ability of the algorithm independent of these additional
context.spy = sid(8554)
# Schedule my rebalance function
# record my portfolio variables at the end of day
def before_trading_start(context, data):
# Call pipeline_output to get the output
# Note: this is a dataframe where the index is the SIDs for all
# securities to pass my screen and the columns are the factors
# added to the pipeline object above
context.pipeline_data = pipeline_output('long_short_equity_template')
def recording_statements(context, data):
# Plot the number of positions over time.
# Called at the start of every month in order to rebalance
# the longs and shorts lists
def rebalance(context, data):
# Optimize API
pipeline_data = context.pipeline_data
todays_universe = pipeline_data.index
# Extract from pipeline any specific risk factors you want
# to neutralize that you have already calculated
risk_factor_exposures = pd.DataFrame(
# We fill in any missing factor values with a market beta of 1.0.
# We do this rather than simply dropping the values because we have
# want to err on the side of caution. We don't want to exclude
# a security just because it's missing a calculated market beta,
# so we assume any missing values have full exposure to the market.
# Here we define our objective for the Optimize API. We have
# selected MaximizeAlpha because we believe our combined factor
# ranking to be proportional to expected returns. This routine
# will optimize the expected return of our algorithm, going
# long on the highest expected return and short on the lowest.
objective = opt.MaximizeAlpha(pipeline_data.factor_rank)
# Define the list of constraints
constraints = 
# Constrain our maximum gross leverage
# Require our algorithm to remain dollar neutral
# Add a sector neutrality constraint using the sector
# classifier that we included in pipeline and the
# MAX_SECTOR_EXPOSURE set at the the top of the algorithm
# Take the risk factors that you extracted above and
# list your desired max/min exposures to them - the
# MAX_BETA_EXPOSURE was set at the top of the algorithm
neutralize_risk_factors = opt.WeightedExposure(
# With this constraint we enforce that no position can make up
# greater than MAX_SHORT_POSITION_SIZE on the short side and
# no greater than MAX_LONG_POSITION_SIZE on the long side. This
# ensures that we do not overly concentrate our portfolio in
# one security or a small subset of securities.
# Put together all the pieces we defined above by passing
# them into the order_optimal_portfolio function. This handles
# all of our ordering logic, assigning appropriate weights
# to the securities in our universe to maximize our alpha with
# respect to the given constraints.