Algorithm API Reference

The Algorithm API provides tools with which you can build trading algorithms. The Algorithm API is only available in the IDE, not in Research.

Quick Reference

User-Implemented Functions

The following table describes functions that are treated specially when defined in the IDE.

Algorithms are required to implement one method: initialize().

Two other methods, before_trading_start() and handle_data() are optional, but are treated specially if defined.

initialize(context) Required function called once at the start of a backtest.
before_trading_start(context, data) Optional function called prior to market open on every trading day.
handle_data(context, data) Optional function called at the end of each market minute.

Interface Classes

The following table describes classes that are passed to initialize(), handle_data(), before_trading_start() and any scheduled with schedule_function().

quantopian.algorithm.interface.AlgorithmContext Shared object for storing custom state.
quantopian.algorithm.interface.BarData Provides methods for accessing minutely and daily price/volume data from Algorithm API functions.
quantopian.algorithm.interface.Portfolio Object providing read-only access to current portfolio state.
quantopian.algorithm.interface.Positions A dict-like object containing the algorithm's current positions.

BarData Methods

quantopian.algorithm.interface.BarData.current Returns the "current" value of the given fields for the given assets at the current simulation time.
quantopian.algorithm.interface.BarData.history Returns a trailing window of length bar_count containing data for the given assets, fields, and frequency.
quantopian.algorithm.interface.BarData.can_trade For the given asset or iterable of assets, returns True if all of the following are true:
quantopian.algorithm.interface.BarData.is_stale For the given asset or iterable of assets, returns True if the asset is alive and there is no trade data for the current simulation time.

Pipeline

The following table describes functions used to schedule and retrieve results of Pipeline computations. For more information on the Pipeline API, see the Pipeline API Reference.

quantopian.algorithm.attach_pipeline(...) Register a pipeline to be computed at the start of each day.
quantopian.algorithm.pipeline_output(name) Get results of the pipeline attached by with name.

Scheduling Functions

The following tables describes functions that can be used to schedule functions to run periodically during your algorithm.

quantopian.algorithm.schedule_function(func) Schedule a function to be called repeatedly in the future.

Date Rules

The following table contains functions that can be used with the date_rule parameter of schedule_function().

quantopian.algorithm.date_rules.every_day() Create a rule that triggers every day.
quantopian.algorithm.date_rules.month_start([...]) Create a rule that triggers a fixed number of trading days after the start of each month.
quantopian.algorithm.date_rules.month_end([...]) Create a rule that triggers a fixed number of trading days before the end of each month.
quantopian.algorithm.date_rules.week_start([...]) Create a rule that triggers a fixed number of trading days after the start of each week.
quantopian.algorithm.date_rules.week_end([...]) Create a rule that triggers a fixed number of trading days before the end of each week.

Time Rules

The following table contains functions that can be used with the time_rule parameter of schedule_function().

quantopian.algorithm.time_rules.market_open([...]) Create a rule that triggers at a fixed offset from market open.
quantopian.algorithm.time_rules.market_close([...]) Create a rule that triggers at a fixed offset from market close.

Ordering

There are several ways to place orders from an algorithm. For most use-cases, we recommend using order_optimal_portfolio(), which correctly accounts for existing open orders and allows for an easy transition to sophisticated portfolio optimization techniques.

Algorithms that require explicit manual control of their orders can use the lower-level ordering functions, but should note that the family of order_target_* functions only consider the status of filled orders, not open orders, when making their calculations to the target position.

Note

Note: Manual ordering is not allowed in the Quantopian Contest. Contest and allocation-eligible algorithms must place all orders with order_optimal_portfolio(). This restriction exists because the Optimize API is required by Quantopian's internal live trading infrastructure.

Placing Orders

quantopian.algorithm.order_optimal_portfolio(...) Calculate an optimal portfolio and place orders toward that portfolio.
quantopian.algorithm.order(asset, amount[, ...]) Place an order for a fixed number of shares.
quantopian.algorithm.order_value(asset, value) Place an order for a fixed amount of money.
quantopian.algorithm.order_percent(asset, ...) Place an order in the specified asset corresponding to the given percent of the current portfolio value.
quantopian.algorithm.order_target(asset, target) Place an order to adjust a position to a target number of shares.
quantopian.algorithm.order_target_value(...) Place an order to adjust a position to a target value.
quantopian.algorithm.order_target_percent(...) Place an order to adjust a position to a target percent of the current portfolio value.

Controlling Order Execution

Note

Limit and stop orders are not supported when using order_optimal_portfolio().

zipline.finance.execution.ExecutionStyle Base class for order execution styles.
zipline.finance.execution.MarketOrder([exchange]) Execution style for orders to be filled at current market price.
zipline.finance.execution.LimitOrder(limit_price) Execution style for orders to be filled at a price equal to or better than a specified limit price.
zipline.finance.execution.StopOrder(stop_price) Execution style representing a market order to be placed if market price reaches a threshold.
zipline.finance.execution.StopLimitOrder(...) Execution style representing a limit order to be placed if market price reaches a threshold.

Managing Existing Orders

quantopian.algorithm.get_order(order_id) Lookup an order based on the order id returned from one of the order functions.
quantopian.algorithm.get_open_orders([asset]) Retrieve all of the current open orders.
quantopian.algorithm.cancel_order(order_param) Cancel an open order.

Customizing the Simulation

Slippage

Algorithms can customize the simulation of order fills by calling quantopian.algorithm.set_slippage() with a zipline.finance.slippage.SlippageModel. set_slippage() can only be called during initialize().

The default slippage model for equities on Quantopian is SlippageModel.

Note

Custom slippage models are ignored for algorithms entered in the Quantopian Contest.

quantopian.algorithm.set_slippage([...]) Set the slippage models for the simulation.
zipline.finance.slippage.SlippageModel() Abstract base class for slippage models.
zipline.finance.slippage.FixedBasisPointsSlippage([...]) Model slippage as a fixed percentage difference from historical minutely close price, limiting the size of fills to a fixed percentage of historical minutely volume.
zipline.finance.slippage.NoSlippage() A slippage model where all orders fill immediately and completely at the current close price.
zipline.finance.slippage.FixedSlippage([spread]) Simple model assuming a fixed-size spread for all assets.
zipline.finance.slippage.VolumeShareSlippage([...]) Model slippage as a quadratic function of percentage of historical volume.

Commissions

Algorithms can customize the simulation of commissions by calling quantopian.algorithm.set_commission() with a zipline.finance.commission.CommissionModel. set_commission() can only be called during initialize().

Note

Custom commission models are ignored for algorithms entered in the Quantopian Contest.

quantopian.algorithm.set_commission([...]) Sets the commission models for the simulation.
zipline.finance.commission.CommissionModel Abstract base class for commission models.
zipline.finance.commission.PerShare([cost, ...]) Calculates a commission for a transaction based on a per share cost with an optional minimum cost per trade.
zipline.finance.commission.PerTrade([cost]) Calculates a commission for a transaction based on a per trade cost.
zipline.finance.commission.PerDollar([cost]) Model commissions by applying a fixed cost per dollar transacted.
zipline.finance.commission.NoCommission Model commissions as free.

Benchmark

quantopian.algorithm.set_benchmark(benchmark) Set the benchmark asset.

Asset Lookup

The following table contains functions that can be used to create Asset inside an algorithm.

quantopian.algorithm.sid(sid) Lookup an Asset by its unique asset identifier.
quantopian.algorithm.symbol(symbol_str[, ...]) Lookup an Equity by its ticker symbol.
quantopian.algorithm.symbols(*args, **kwargs) Lookup multuple Equities as a list.
quantopian.algorithm.set_symbol_lookup_date(dt) Set the date for which symbols will be resolved to their assets (symbols may map to different firms or underlying assets at different times)

Futures

quantopian.algorithm.continuous_future(...) Create a specifier for a continuous contract.
quantopian.algorithm.future_symbol(symbol) Lookup a futures contract with a given symbol.

Miscellaneous

quantopian.algorithm.get_datetime([tz]) Returns the current simulation datetime.
quantopian.algorithm.record(*args, **kwargs) Record numeric values for display or later analysis.
quantopian.algorithm.get_environment([field]) Query the execution environment.

Detailed Reference

User-Implemented Functions

quantopian.algorithm.interface.initialize(context)

Required function called once at the start of a backtest.

Parameters:context (quantopian.algorithm.interface.AlgorithmContext) -- Context object that can be used to store algorithm-specific state. This object will be passed to other top-level functions you define.

Notes

Common operations performed in initialize() include:

quantopian.algorithm.interface.before_trading_start(context, data)

Optional function called prior to market open on every trading day.

Parameters:

Notes

The primary purpose of this method is to execute expensive daily computations that are difficult or impossible to express via the Pipeline API.

Algorithms cannot place orders from this function.

quantopian.algorithm.interface.handle_data(context, data)

Optional function called at the end of each market minute.

Note

WARNING: Defining this function will slow down your algorithm. Only define a handle_data function if your algorithm needs to perform an action on every market minute. If not, consider using schedule_function() instead.

Parameters:

Interface Classes

class quantopian.algorithm.interface.AlgorithmContext

Shared object for storing custom state.

The primary purpose of this object is to serve as a standard place for algorithms to store algorithm-specific information. This object is passed as the context argument to initialize(), handle_data(), before_trading_start(), and any functions scheduled with schedule_function(). If you want to share state between these functions, you can do so by storing the state as an attribute of context.

This object also has a portfolio attribute, which provides information about the algorithm's current holdings.

portfolio

The algorithm's current portfolio.

Returns:portfolio
Return type:quantopian.algorithm.interface.Portfolio
class quantopian.algorithm.interface.BarData

Provides methods for accessing minutely and daily price/volume data from Algorithm API functions.

Also provides utility methods to determine if an asset is alive, and if it has recent trade data.

An instance of this object is passed as data to handle_data() and before_trading_start().

Parameters:
  • data_portal (DataPortal) -- Provider for bar pricing data.
  • simulation_dt_func (callable) -- Function which returns the current simulation time. This is usually bound to a method of TradingSimulation.
  • data_frequency ({'minute', 'daily'}) -- The frequency of the bar data; i.e. whether the data is daily or minute bars
  • restrictions (zipline.finance.asset_restrictions.Restrictions) -- Object that combines and returns restricted list information from multiple sources
  • universe_func (callable, optional) -- Function which returns the current 'universe'. This is for backwards compatibility with older API concepts.
current(assets, fields)

Returns the "current" value of the given fields for the given assets at the current simulation time.

Parameters:
  • assets (zipline.assets.Asset or iterable of zipline.assets.Asset) -- The asset(s) for which data is requested.
  • fields (str or iterable[str]) -- Requested data field(s). Valid field names are: "price", "last_traded", "open", "high", "low", "close", and "volume".
Returns:

current_value -- See notes below.

Return type:

Scalar, pandas Series, or pandas DataFrame.

Notes

The return type of this function depends on the types of its inputs:

  • If a single asset and a single field are requested, the returned value is a scalar (either a float or a pd.Timestamp depending on the field).
  • If a single asset and a list of fields are requested, the returned value is a pd.Series whose indices are the requested fields.
  • If a list of assets and a single field are requested, the returned value is a pd.Series whose indices are the assets.
  • If a list of assets and a list of fields are requested, the returned value is a pd.DataFrame. The columns of the returned frame will be the requested fields, and the index of the frame will be the requested assets.

The values produced for fields are as follows:

  • Requesting "price" produces the last known close price for the asset, forward-filled from an earlier minute if there is no trade this minute. If there is no last known value (either because the asset has never traded, or because it has delisted) NaN is returned. If a value is found, and we had to cross an adjustment boundary (split, dividend, etc) to get it, the value is adjusted to the current simulation time before being returned.
  • Requesting "open", "high", "low", or "close" produces the open, high, low, or close for the current minute. If no trades occurred this minute, NaN is returned.
  • Requesting "volume" produces the trade volume for the current minute. If no trades occurred this minute, 0 is returned.
  • Requesting "last_traded" produces the datetime of the last minute in which the asset traded, even if the asset has stopped trading. If there is no last known value, pd.NaT is returned.

If the current simulation time is not a valid market time for an asset, we use the most recent market close instead.

history(assets, fields, bar_count, frequency)

Returns a trailing window of length bar_count containing data for the given assets, fields, and frequency.

Returned data is adjusted for splits, dividends, and mergers as of the current simulation time.

The semantics for missing data are identical to the ones described in the notes for current().

Parameters:
  • assets (zipline.assets.Asset or iterable of zipline.assets.Asset) -- The asset(s) for which data is requested.
  • fields (string or iterable of string.) -- Requested data field(s). Valid field names are: "price", "last_traded", "open", "high", "low", "close", and "volume".
  • bar_count (int) -- Number of data observations requested.
  • frequency (str) -- String indicating whether to load daily or minutely data observations. Pass '1m' for minutely data, '1d' for daily data.
Returns:

history -- See notes below.

Return type:

pd.Series or pd.DataFrame or pd.Panel

Notes

The return type of this function depends on the types of assets and fields:

  • If a single asset and a single field are requested, the returned value is a pd.Series of length bar_count whose index is pd.DatetimeIndex.
  • If a single asset and multiple fields are requested, the returned value is a pd.DataFrame with shape (bar_count, len(fields)). The frame's index will be a pd.DatetimeIndex, and its columns will be fields.
  • If multiple assets and a single field are requested, the returned value is a pd.DataFrame with shape (bar_count, len(assets)). The frame's index will be a pd.DatetimeIndex, and its columns will be assets.
  • If multiple assets and multiple fields are requested, the returned value is a pd.Panel with shape (len(fields), bar_count, len(assets)). The axes of the returned panel will be:
    • panel.items : fields
    • panel.major_axis : pd.DatetimeIndex of length bar_count
    • panel.minor_axis : assets

If the current simulation time is not a valid market time, we use the last market close instead.

can_trade(assets)

For the given asset or iterable of assets, returns True if all of the following are true:

  1. The asset is alive for the session of the current simulation time (if current simulation time is not a market minute, we use the next session).
  2. The asset's exchange is open at the current simulation time or at the simulation calendar's next market minute.
  3. There is a known last price for the asset.
Parameters:assets (zipline.assets.Asset or iterable of zipline.assets.Asset) -- Asset(s) for which tradability should be determined.

Notes

The second condition above warrants some further explanation:

  • If the asset's exchange calendar is identical to the simulation calendar, then this condition always returns True.
  • If there are market minutes in the simulation calendar outside of this asset's exchange's trading hours (for example, if the simulation is running on the CMES calendar but the asset is MSFT, which trades on the NYSE), during those minutes, this condition will return False (for example, 3:15 am Eastern on a weekday, during which the CMES is open but the NYSE is closed).
Returns:can_trade -- Bool or series of bools indicating whether the requested asset(s) can be traded in the current minute.
Return type:bool or pd.Series[bool]
is_stale(assets)

For the given asset or iterable of assets, returns True if the asset is alive and there is no trade data for the current simulation time.

If the asset has never traded, returns False.

If the current simulation time is not a valid market time, we use the current time to check if the asset is alive, but we use the last market minute/day for the trade data check.

Parameters:assets (zipline.assets.Asset or iterable of zipline.assets.Asset) -- Asset(s) for which staleness should be determined.
Returns:is_stale -- Bool or series of bools indicating whether the requested asset(s) are stale.
Return type:bool or pd.Series[bool]
class quantopian.algorithm.interface.Portfolio

Object providing read-only access to current portfolio state.

Parameters:
  • start_date (pd.Timestamp) -- The start date for the period being recorded.
  • capital_base (float) -- The starting value for the portfolio. This will be used as the starting cash, current cash, and portfolio value.
positions

Dict-like object containing information about currently-held positions.

Type:zipline.protocol.Positions
cash

Amount of cash currently held in portfolio.

Type:float
portfolio_value

Current liquidation value of the portfolio's holdings. This is equal to cash + sum(shares * price)

Type:float
starting_cash

Amount of cash in the portfolio at the start of the backtest.

Type:float
class quantopian.algorithm.interface.Positions

A dict-like object containing the algorithm's current positions.

Pipeline

quantopian.algorithm.attach_pipeline(pipeline, name)

Register a pipeline to be computed at the start of each day.

Parameters:
  • pipeline (Pipeline) -- The pipeline to have computed.
  • name (str) -- The name of the pipeline.
Returns:

pipeline -- Returns the pipeline that was attached unchanged.

Return type:

Pipeline

Examples

from quantopian.algorithm import attach_pipeline, pipeline_output from quantopian.pipeline import Pipeline from quantopian.pipeline.data import EquityPricing

def initialize(context):
pipe = Pipeline({'close': EquityPricing.close.latest}) attach_pipeline(pipe, 'my_pipeline')
def before_trading_start(context, data):
todays_pipeline_results = pipeline_output('my_pipeline')

Notes

It is possible, though usually not necessary, to attach multiple pipelines to an algorithm. Attaching multiple pipelines is generally slower than attaching a single pipeline; if multiple expressions require the same input data, the expressions can share work if they're in the same pipeline, but they cannot share work if the expressions are computed in separate pipelines. Despite potential performance costs, attaching multiple pipelines can be convenient for grouping related expressions.

quantopian.algorithm.pipeline_output(name)

Get results of the pipeline attached by with name.

Parameters:name (str) -- Name of the pipeline from which to fetch results.
Returns:results -- DataFrame containing the results of the requested pipeline for the current simulation date.
Return type:pd.DataFrame

Examples

from quantopian.algorithm import attach_pipeline, pipeline_output from quantopian.pipeline import Pipeline from quantopian.pipeline.data import EquityPricing

def initialize(context):
pipe = Pipeline({'close': EquityPricing.close.latest}) attach_pipeline(pipe, 'my_pipeline')
def before_trading_start(context, data):
todays_pipeline_results = pipeline_output('my_pipeline')

Scheduling Functions

quantopian.algorithm.schedule_function(func, date_rule=None, time_rule=None, half_days=True, calendar=None)

Schedule a function to be called repeatedly in the future.

Parameters:
  • func (callable) -- The function to execute when the rule is triggered. func should have the same signature as handle_data.
  • date_rule (zipline.utils.events.EventRule, optional) -- Rule for the dates on which to execute func. If not passed, the function will run every trading day.
  • time_rule (zipline.utils.events.EventRule, optional) -- Rule for the time at which to execute func. If not passed, the function will execute at the end of the first market minute of the day.
  • half_days (bool, optional) -- Should this rule fire on half days? Default is True.
  • calendar (Sentinel, optional) -- Calendar used to compute rules that depend on the trading calendar.
class quantopian.algorithm.date_rules

Factories for date-based schedule_function() rules.

static every_day()

Create a rule that triggers every day.

Returns:rule
Return type:zipline.utils.events.EventRule
static month_end(days_offset=0)

Create a rule that triggers a fixed number of trading days before the end of each month.

Parameters:days_offset (int, optional) -- Number of trading days prior to month end to trigger. Default is 0, i.e., trigger on the last day of the month.
Returns:rule
Return type:zipline.utils.events.EventRule
static month_start(days_offset=0)

Create a rule that triggers a fixed number of trading days after the start of each month.

Parameters:days_offset (int, optional) -- Number of trading days to wait before triggering each month. Default is 0, i.e., trigger on the first trading day of the month.
Returns:rule
Return type:zipline.utils.events.EventRule
static week_end(days_offset=0)

Create a rule that triggers a fixed number of trading days before the end of each week.

Parameters:days_offset (int, optional) -- Number of trading days prior to week end to trigger. Default is 0, i.e., trigger on the last trading day of the week.
static week_start(days_offset=0)

Create a rule that triggers a fixed number of trading days after the start of each week.

Parameters:days_offset (int, optional) -- Number of trading days to wait before triggering each week. Default is 0, i.e., trigger on the first trading day of the week.
class quantopian.algorithm.time_rules

Factories for time-based schedule_function() rules.

static market_close(offset=None, hours=None, minutes=None)

Create a rule that triggers at a fixed offset from market close.

The offset can be specified either as a datetime.timedelta, or as a number of hours and minutes.

Parameters:
  • offset (datetime.timedelta, optional) -- If passed, the offset from market close at which to trigger. Must be at least 1 minute.
  • hours (int, optional) -- If passed, number of hours to wait before market close.
  • minutes (int, optional) -- If passed, number of minutes to wait before market close.
Returns:

rule

Return type:

zipline.utils.events.EventRule

Notes

If no arguments are passed, the default offset is one minute before market close.

If offset is passed, hours and minutes must not be passed. Conversely, if either hours or minutes are passed, offset must not be passed.

static market_open(offset=None, hours=None, minutes=None)

Create a rule that triggers at a fixed offset from market open.

The offset can be specified either as a datetime.timedelta, or as a number of hours and minutes.

Parameters:
  • offset (datetime.timedelta, optional) -- If passed, the offset from market open at which to trigger. Must be at least 1 minute.
  • hours (int, optional) -- If passed, number of hours to wait after market open.
  • minutes (int, optional) -- If passed, number of minutes to wait after market open.
Returns:

rule

Return type:

zipline.utils.events.EventRule

Notes

If no arguments are passed, the default offset is one minute after market open.

If offset is passed, hours and minutes must not be passed. Conversely, if either hours or minutes are passed, offset must not be passed.

class zipline.utils.events.EventRule

A rule defining when a scheduled function should execute.

Ordering

Placing Orders

quantopian.algorithm.order_optimal_portfolio(objective, constraints, universe=None)

Calculate an optimal portfolio and place orders toward that portfolio.

Parameters:
Raises:
  • InfeasibleConstraints -- Raised when there is no possible portfolio that satisfies the received constraints.
  • UnboundedObjective -- Raised when the received constraints are not sufficient to put an upper (or lower) bound on the calculated portfolio weights.
Returns:

order_ids -- The unique identifiers for the orders that were placed.

Return type:

pd.Series[zipline.assets.Asset, str]

Notes

This is the only method of ordering allowed in the Quantopian Contest.

quantopian.algorithm.order(asset, amount, limit_price=None, stop_price=None, style=None)

Place an order for a fixed number of shares.

Parameters:
  • asset (Asset) -- The asset to be ordered.
  • amount (int) -- The amount of shares to order. If amount is positive, this is the number of shares to buy or cover. If amount is negative, this is the number of shares to sell or short.
  • limit_price (float, optional) -- The limit price for the order.
  • stop_price (float, optional) -- The stop price for the order.
  • style (ExecutionStyle, optional) -- The execution style for the order.
Returns:

order_id -- The unique identifier for this order, or None if no order was placed.

Return type:

str or None

Notes

The limit_price and stop_price arguments provide shorthands for passing common execution styles. Passing limit_price=N is equivalent to style=LimitOrder(N). Similarly, passing stop_price=M is equivalent to style=StopOrder(M), and passing limit_price=N and stop_price=M is equivalent to style=StopLimitOrder(N, M). It is an error to pass both a style and limit_price or stop_price.

quantopian.algorithm.order_value(asset, value, limit_price=None, stop_price=None, style=None)

Place an order for a fixed amount of money.

Equivalent to order(asset, value / data.current(asset, 'price')).

Parameters:
  • asset (Asset) -- The asset to be ordered.
  • value (float) -- Amount of value of asset to be transacted. The number of shares bought or sold will be equal to value / current_price.
  • limit_price (float, optional) -- Limit price for the order.
  • stop_price (float, optional) -- Stop price for the order.
  • style (ExecutionStyle) -- The execution style for the order.
Returns:

order_id -- The unique identifier for this order.

Return type:

str

Notes

See zipline.api.order() for more information about limit_price, stop_price, and style

quantopian.algorithm.order_percent(asset, percent, limit_price=None, stop_price=None, style=None)

Place an order in the specified asset corresponding to the given percent of the current portfolio value.

Parameters:
  • asset (Asset) -- The asset that this order is for.
  • percent (float) -- The percentage of the portfolio value to allocate to asset. This is specified as a decimal, for example: 0.50 means 50%.
  • limit_price (float, optional) -- The limit price for the order.
  • stop_price (float, optional) -- The stop price for the order.
  • style (ExecutionStyle) -- The execution style for the order.
Returns:

order_id -- The unique identifier for this order.

Return type:

str

Notes

See zipline.api.order() for more information about limit_price, stop_price, and style

quantopian.algorithm.order_target(asset, target, limit_price=None, stop_price=None, style=None)

Place an order to adjust a position to a target number of shares. If the position doesn't already exist, this is equivalent to placing a new order. If the position does exist, this is equivalent to placing an order for the difference between the target number of shares and the current number of shares.

Parameters:
  • asset (Asset) -- The asset that this order is for.
  • target (int) -- The desired number of shares of asset.
  • limit_price (float, optional) -- The limit price for the order.
  • stop_price (float, optional) -- The stop price for the order.
  • style (ExecutionStyle) -- The execution style for the order.
Returns:

order_id -- The unique identifier for this order.

Return type:

str

Notes

order_target does not take into account any open orders. For example:

order_target(sid(0), 10)
order_target(sid(0), 10)

This code will result in 20 shares of sid(0) because the first call to order_target will not have been filled when the second order_target call is made.

See zipline.api.order() for more information about limit_price, stop_price, and style

quantopian.algorithm.order_target_value(asset, target, limit_price=None, stop_price=None, style=None)

Place an order to adjust a position to a target value. If the position doesn't already exist, this is equivalent to placing a new order. If the position does exist, this is equivalent to placing an order for the difference between the target value and the current value. If the Asset being ordered is a Future, the 'target value' calculated is actually the target exposure, as Futures have no 'value'.

Parameters:
  • asset (Asset) -- The asset that this order is for.
  • target (float) -- The desired total value of asset.
  • limit_price (float, optional) -- The limit price for the order.
  • stop_price (float, optional) -- The stop price for the order.
  • style (ExecutionStyle) -- The execution style for the order.
Returns:

order_id -- The unique identifier for this order.

Return type:

str

Notes

order_target_value does not take into account any open orders. For example:

order_target_value(sid(0), 10)
order_target_value(sid(0), 10)

This code will result in 20 dollars of sid(0) because the first call to order_target_value will not have been filled when the second order_target_value call is made.

See zipline.api.order() for more information about limit_price, stop_price, and style

quantopian.algorithm.order_target_percent(asset, target, limit_price=None, stop_price=None, style=None)

Place an order to adjust a position to a target percent of the current portfolio value. If the position doesn't already exist, this is equivalent to placing a new order. If the position does exist, this is equivalent to placing an order for the difference between the target percent and the current percent.

Parameters:
  • asset (Asset) -- The asset that this order is for.
  • target (float) -- The desired percentage of the portfolio value to allocate to asset. This is specified as a decimal, for example: 0.50 means 50%.
  • limit_price (float, optional) -- The limit price for the order.
  • stop_price (float, optional) -- The stop price for the order.
  • style (ExecutionStyle) -- The execution style for the order.
Returns:

order_id -- The unique identifier for this order.

Return type:

str

Notes

order_target_value does not take into account any open orders. For example:

order_target_percent(sid(0), 10)
order_target_percent(sid(0), 10)

This code will result in 20% of the portfolio being allocated to sid(0) because the first call to order_target_percent will not have been filled when the second order_target_percent call is made.

See zipline.api.order() for more information about limit_price, stop_price, and style

Controlling Order Execution

Note

Stop and limit orders are not supported when using order_optimal_portfolio().

class zipline.finance.execution.ExecutionStyle

Base class for order execution styles.

class zipline.finance.execution.MarketOrder(exchange=None)

Execution style for orders to be filled at current market price.

This is the default for orders placed with order().

class zipline.finance.execution.LimitOrder(limit_price, asset=None, exchange=None)

Execution style for orders to be filled at a price equal to or better than a specified limit price.

Parameters:limit_price (float) -- Maximum price for buys, or minimum price for sells, at which the order should be filled.
class zipline.finance.execution.StopOrder(stop_price, asset=None, exchange=None)

Execution style representing a market order to be placed if market price reaches a threshold.

Parameters:stop_price (float) -- Price threshold at which the order should be placed. For sells, the order will be placed if market price falls below this value. For buys, the order will be placed if market price rises above this value.
class zipline.finance.execution.StopLimitOrder(limit_price, stop_price, asset=None, exchange=None)

Execution style representing a limit order to be placed if market price reaches a threshold.

Parameters:
  • limit_price (float) -- Maximum price for buys, or minimum price for sells, at which the order should be filled, if placed.
  • stop_price (float) -- Price threshold at which the order should be placed. For sells, the order will be placed if market price falls below this value. For buys, the order will be placed if market price rises above this value.

Managing Existing Orders

quantopian.algorithm.get_order(order_id)

Lookup an order based on the order id returned from one of the order functions.

Parameters:order_id (str) -- The unique identifier for the order.
Returns:order -- The order object.
Return type:Order
quantopian.algorithm.get_open_orders(asset=None)

Retrieve all of the current open orders.

Parameters:asset (Asset) -- If passed and not None, return only the open orders for the given asset instead of all open orders.
Returns:open_orders -- If no asset is passed this will return a dict mapping Assets to a list containing all the open orders for the asset. If an asset is passed then this will return a list of the open orders for this asset.
Return type:dict[list[Order]] or list[Order]
quantopian.algorithm.cancel_order(order_param)

Cancel an open order.

Parameters:order_param (str or Order) -- The order_id or order object to cancel.

Customizing the Simulation

Slippage

quantopian.algorithm.set_slippage(us_equities=None, us_futures=None)

Set the slippage models for the simulation.

Parameters:
  • us_equities (EquitySlippageModel) -- The slippage model to use for trading US equities.
  • us_futures (FutureSlippageModel) -- The slippage model to use for trading US futures.

Notes

This function can only be called during initialize().

class zipline.finance.slippage.SlippageModel

Abstract base class for slippage models.

Slippage models are responsible for the rates and prices at which orders fill during a simulation.

To implement a new slippage model, create a subclass of SlippageModel and implement process_order().

process_order(data, order)
volume_for_bar

Number of shares that have already been filled for the currently-filling asset in the current minute. This attribute is maintained automatically by the base class. It can be used by subclasses to keep track of the total amount filled if there are multiple open orders for a single asset.

Type:int

Notes

Subclasses that define their own constructors should call super(<subclass name>, self).__init__() before performing other initialization.

process_order(data, order)

Compute the number of shares and price to fill for order in the current minute.

Parameters:
  • data (zipline.protocol.BarData) -- The data for the given bar.
  • order (zipline.finance.order.Order) -- The order to simulate.
Returns:

  • execution_price (float) -- The price of the fill.
  • execution_volume (int) -- The number of shares that should be filled. Must be between 0 and order.amount - order.filled. If the amount filled is less than the amount remaining, order will remain open and will be passed again to this method in the next minute.

Raises:

zipline.finance.slippage.LiquidityExceeded -- May be raised if no more orders should be processed for the current asset during the current bar.

Notes

Before this method is called, volume_for_bar will be set to the number of shares that have already been filled for order.asset in the current minute.

process_order() is not called by the base class on bars for which there was no historical volume.

class zipline.finance.slippage.FixedBasisPointsSlippage(basis_points=5.0, volume_limit=0.1)

Model slippage as a fixed percentage difference from historical minutely close price, limiting the size of fills to a fixed percentage of historical minutely volume.

Orders to buy are filled at:

historical_price * (1 + (basis_points * 0.0001))

Orders to sell are filled at:

historical_price * (1 - (basis_points * 0.0001))

Fill sizes are capped at:

historical_volume * volume_limit
Parameters:
  • basis_points (float, optional) -- Number of basis points of slippage to apply for each fill. Default is 5 basis points.
  • volume_limit (float, optional) -- Fraction of trading volume that can be filled each minute. Default is 10% of trading volume.

Notes

  • A basis point is one one-hundredth of a percent.
  • This class, default-constructed, is zipline's default slippage model for equities.
class zipline.finance.slippage.NoSlippage

A slippage model where all orders fill immediately and completely at the current close price.

Notes

This is primarily used for testing.

class zipline.finance.slippage.FixedSlippage(spread=0.0)

Simple model assuming a fixed-size spread for all assets.

Parameters:spread (float, optional) -- Size of the assumed spread for all assets. Orders to buy will be filled at close + (spread / 2). Orders to sell will be filled at close - (spread / 2).

Notes

This model does not impose limits on the size of fills. An order for an asset will always be filled as soon as any trading activity occurs in the order's asset, even if the size of the order is greater than the historical volume.

class zipline.finance.slippage.VolumeShareSlippage(volume_limit=0.025, price_impact=0.1)

Model slippage as a quadratic function of percentage of historical volume.

Orders to buy will be filled at:

price * (1 + price_impact * (volume_share ** 2))

Orders to sell will be filled at:

price * (1 - price_impact * (volume_share ** 2))

where price is the close price for the bar, and volume_share is the percentage of minutely volume filled, up to a max of volume_limit.

Parameters:
  • volume_limit (float, optional) -- Maximum percent of historical volume that can fill in each bar. 0.5 means 50% of historical volume. 1.0 means 100%. Default is 0.025 (i.e., 2.5%).
  • price_impact (float, optional) -- Scaling coefficient for price impact. Larger values will result in more simulated price impact. Smaller values will result in less simulated price impact. Default is 0.1.

Commissions

quantopian.algorithm.set_commission(us_equities=None, us_futures=None)

Sets the commission models for the simulation.

Parameters:
  • us_equities (EquityCommissionModel) -- The commission model to use for trading US equities.
  • us_futures (FutureCommissionModel) -- The commission model to use for trading US futures.

Notes

This function can only be called during initialize().

class zipline.finance.commission.CommissionModel

Abstract base class for commission models.

Commission models are responsible for accepting order/transaction pairs and calculating how much commission should be charged to an algorithm's account on each transaction.

To implement a new commission model, create a subclass of CommissionModel and implement calculate().

calculate(order, transaction)

Calculate the amount of commission to charge on order as a result of transaction.

Parameters:
  • order (zipline.finance.order.Order) --

    The order being processed.

    The commission field of order is a float indicating the amount of commission already charged on this order.

  • transaction (zipline.finance.transaction.Transaction) -- The transaction being processed. A single order may generate multiple transactions if there isn't enough volume in a given bar to fill the full amount requested in the order.
Returns:

amount_charged -- The additional commission, in dollars, that we should attribute to this order.

Return type:

float

class zipline.finance.commission.PerShare(cost=0.001, min_trade_cost=0.0)

Calculates a commission for a transaction based on a per share cost with an optional minimum cost per trade.

Parameters:
  • cost (float, optional) -- The amount of commissions paid per share traded. Default is one tenth of a cent per share.
  • min_trade_cost (float, optional) -- The minimum amount of commissions paid per trade. Default is no minimum.

Notes

This is zipline's default commission model for equities.

class zipline.finance.commission.PerTrade(cost=0.0)

Calculates a commission for a transaction based on a per trade cost.

For orders that require multiple fills, the full commission is charged to the first fill.

Parameters:cost (float, optional) -- The flat amount of commissions paid per equity trade.
class zipline.finance.commission.PerDollar(cost=0.0015)

Model commissions by applying a fixed cost per dollar transacted.

Parameters:cost (float, optional) -- The flat amount of commissions paid per dollar of equities traded. Default is a commission of $0.0015 per dollar transacted.
class zipline.finance.commission.NoCommission

Model commissions as free.

Notes

This is primarily used for testing.

Benchmark

quantopian.algorithm.set_benchmark(benchmark)

Set the benchmark asset.

Parameters:benchmark (zipline.assets.Asset) -- The asset to set as the new benchmark.

Notes

Any dividends payed out for that new benchmark asset will be automatically reinvested.

Asset Lookup

quantopian.algorithm.sid(sid)

Lookup an Asset by its unique asset identifier.

Parameters:sid (int) -- The unique integer that identifies an asset.
Returns:asset -- The asset with the given sid.
Return type:zipline.assets.Asset
Raises:SidsNotFound -- When a requested sid does not map to any asset.
quantopian.algorithm.symbol(symbol_str, country_code=None)

Lookup an Equity by its ticker symbol.

Parameters:
  • symbol_str (str) -- The ticker symbol for the equity to lookup.
  • country_code (str or None, optional) -- A country to limit symbol searches to.
Returns:

equity -- The equity that held the ticker symbol on the current symbol lookup date.

Return type:

zipline.assets.Equity

Raises:

SymbolNotFound -- Raised when the symbols was not held on the current lookup date.

quantopian.algorithm.symbols(*args, **kwargs)

Lookup multuple Equities as a list.

Parameters:
  • *args (iterable[str]) -- The ticker symbols to lookup.
  • country_code (str or None, optional) -- A country to limit symbol searches to.
Returns:

equities -- The equities that held the given ticker symbols on the current symbol lookup date.

Return type:

list[zipline.assets.Equity]

Raises:

SymbolNotFound -- Raised when one of the symbols was not held on the current lookup date.

quantopian.algorithm.set_symbol_lookup_date(dt)

Set the date for which symbols will be resolved to their assets (symbols may map to different firms or underlying assets at different times)

Parameters:dt (datetime) -- The new symbol lookup date.
quantopian.algorithm.continuous_future(root_symbol_str, offset=0, roll='volume', adjustment='mul')

Create a specifier for a continuous contract.

Parameters:
  • root_symbol_str (str) -- The root symbol for the future chain.
  • offset (int, optional) -- The distance from the primary contract. Default is 0.
  • roll_style (str, optional) -- How rolls are determined. Default is 'volume'.
  • adjustment (str, optional) -- Method for adjusting lookback prices between rolls. Options are 'mul', 'add', and None. Default is 'mul'.
Returns:

continuous_future -- The continuous future specifier.

Return type:

zipline.assets.ContinuousFuture

quantopian.algorithm.future_symbol(symbol)

Lookup a futures contract with a given symbol.

Parameters:symbol (str) -- The symbol of the desired contract.
Returns:future -- The future that trades with the name symbol.
Return type:zipline.assets.Future
Raises:SymbolNotFound -- Raised when no contract named 'symbol' is found.

Miscellaneous

quantopian.algorithm.get_datetime(tz=None)

Returns the current simulation datetime.

Parameters:tz (tzinfo or str, optional) -- The timezone to return the datetime in. This defaults to utc.
Returns:dt -- The current simulation datetime converted to tz.
Return type:datetime
quantopian.algorithm.record(*args, **kwargs)

Record numeric values for display or later analysis.

Parameters:**kwargs -- Named numerical values to be recorded.

Notes

If the same key is recorded multiple times in a simulation day, only the last recorded for each day will be kept.

Recorded variables are displayed in the UI of the IDE. Recorded variables can also be retrieved in Research notebooks via recorded_vars.

quantopian.algorithm.get_environment(field='platform')

Query the execution environment.

Parameters:field ({'platform', 'arena', 'data_frequency',) --

'start', 'end', 'capital_base', 'platform', '*'} The field to query. The options have the following meanings:

arena : str
The arena from the simulation parameters. This will normally be 'backtest' but some systems may use this distinguish live trading from backtesting.
data_frequency : {'daily', 'minute'}
data_frequency tells the algorithm if it is running with daily data or minute data.
start : datetime
The start date for the simulation.
end : datetime
The end date for the simulation.
capital_base : float
The starting capital for the simulation.
platform : str
The platform that the code is running on. By default this will be the string 'zipline'. This can allow algorithms to know if they are running on the Quantopian platform instead.
  • : dict[str -> any]
    Returns all of the fields in a dictionary.
Returns:val -- The value for the field queried. See above for more information.
Return type:any
Raises:ValueError -- Raised when field is not a valid option.