Zipline

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(self).

An optional scheduled event can be defined to behave like before_trading_start(). OnData() is also optional but is treated especially if defined.

QuantopianQuantConnect
initialize(context)Initialize(self)
Required function called once at the start of a backtest.
before_trading_start(context, data)self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.AfterMarketOpen(symbol, 10), self.before_trading_start)
Optional function called prior to market open on every trading day.
handle_data(context, data)OnData(self, slice)
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().

In QuantConnect/Lean, the portfolio state and the positions are class attributes of QCAlgorithm, available via self keyword. The scheduled function is parameterless and can algorithms can self.CurrentSlice.

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

The features from the BarData methods are found in the Slice object (current data), History method (past data) and class attribute Securities.

QuantopianQuantConnect
quantopian.algorithm.interface.BarData.currentSlice[symbol]
Returns the "current" value of the given fields for the given assets at the current simulation time.
quantopian.algorithm.interface.BarData.historyself.History(symbols, bar_count)
Returns a trailing window of length bar_count containing data for the given assets, fields, and frequency.
quantopian.algorithm.interface.BarData.can_tradeself.Securities[symbol].IsTradable
For the given asset or iterable of assets, returns True if all of the following are true:
quantopian.algorithm.interface.BarData.is_stalenot Slice[symbol].IsFillForward
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 Universe selection. For more information on the Universe Selection API, see the Univeres API Reference.

QuantopianQuantConnect
quantopian.algorithm.attach_pipeline(...)universe = self.AddUniverse(...)
name = universe.Configuration.Symbol
Register a pipeline to be computed at the start of each day.
quantopian.algorithm.pipeline_output(name)self.UniverseManager[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.

QuantopianQuantConnect
quantopian.algorithm.schedule_function(func)self.Schedule.On(IDateRule, ITimeRule, 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().

QuantopianQuantConnect
quantopian.algorithm.date_rules.every_day()self.DateRules.EveryDay(symbol)
Create a rule that triggers every day.
quantopian.algorithm.date_rules.month_start([...])self.DateRules.MonthStart(symbol, daysOffset)
Create a rule that triggers a fixed number of trading days after the start of each month.
quantopian.algorithm.date_rules.month_end([...])self.DateRules.MonthEnd(symbol, daysOffset)
Create a rule that triggers a fixed number of trading days before the end of each month.
quantopian.algorithm.date_rules.week_start([...])self.DateRules.WeekStart(symbol, daysOffset)
Create a rule that triggers a fixed number of trading days after the start of each week.
quantopian.algorithm.date_rules.week_end([...])self.DateRules.WeekEnd(symbol, daysOffset)
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().

QuantopianQuantConnect
quantopian.algorithm.time_rules.market_open([...])self.TimeRules.AfterMarketOpen(symbol, minutes_after_open = 0)
Create a rule that triggers at a fixed offset from market open.
quantopian.algorithm.time_rules.market_close([...])self.TimeRules.BeforeMarketClose(symbol, minutes_before_close = 0)
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 SetHoldings method which correctly accounts the porfolio buying power model and fees. At the moment, there is no equivalent for order_optimal_portfolio(). However a similar behavior can be replicated with a Portfolio Construction Model.

Algorithms that require explicit manual control of their orders can use the lower-level ordering functions.

Placing Orders

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

Controlling Order Execution

QuantopianQuantConnect
zipline.finance.execution.ExecutionStyleFillModel
Base class for order execution styles.
zipline.finance.execution.MarketOrder([exchange])self.MarketOrder(symbol, quantity)
Execution style for orders to be filled at current market price.
zipline.finance.execution.LimitOrder(limit_price)self.LimitOrder(symbol, quantity, 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)self.StopMarketOrder(symbol, quantity, stop_price)
Execution style representing a market order to be placed if market price reaches a threshold.
zipline.finance.execution.StopLimitOrder(...)self.StopLimitOrder(symbol, quantity, stop_price, limit_price)
Execution style representing a limit order to be placed if market price reaches a threshold.

Managing Existing Orders

QuantopianQuantConnect
quantopian.algorithm.get_order(order_id)self.Transactions.GetOrderById(order_id)
Lookup an order based on the order Id returned from one of the order functions.
quantopian.algorithm.get_open_orders([asset])self.Transactions.GetOpenOrders(symbol)
Retrieve all of the current open orders.
quantopian.algorithm.cancel_order(order_param)self.Transactions.CancelOpenOrders(symbol)
Cancel an open order.

Customizing the Simulation

Slippage

Algorithms can customize the simulation of order fills by calling SetSlippageModel() with a ISlippageModel which is any class that implements GetSlippageApproximation method. Unlike Quantopian, the slippage model is a security attribute, not a global attribute. Different securities can have different slippage models.

The default slippage model on QuantConnect is a constant slippage model with zero slippage percent (no slippage).

QuantopianQuantConnect
quantopian.algorithm.set_slippage([...])self.Securities[symbol].SetSlippageModel(ISlippageModel)
Set the slippage models for the simulation.
zipline.finance.slippage.SlippageModel()N/A (class must implement GetSlippageApproximation method)
Abstract base class for slippage models.
zipline.finance.slippage.FixedBasisPointsSlippage([...])ConstantSlippageModel(slippage_percent)
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()NullSlippageModel.Instance
A slippage model where all orders fill immediately and completely at the current close price.
zipline.finance.slippage.FixedSlippage([spread])N/A
Simple model assuming a fixed-size spread for all assets.
zipline.finance.slippage.VolumeShareSlippage([...])N/A
Model slippage as a quadratic function of percentage of historical volume.

Commissions

Algorithms can customize the simulation of order fees by calling SetFeeModel() with a IFeeModel which is any class that implements GetOrderFee method. Unlike Quantopian, the fee model is a security attribute, not a global attribute. Different securities can have different fee models.

The default fee model on QuantConnect depends on the security type and the brokerage. For instance, the default fee model for equity is the Interactive Brokers fee model.

QuantopianQuantConnect
quantopian.algorithm.set_commission([...])self.Securities[symbol].SetFeeModel(IFeeModel)
Sets the commission models for the simulation.
zipline.finance.commission.CommissionModelN/A (class must implement GetOrderFee method)
Abstract base class for commission models.
zipline.finance.commission.PerShare([cost, ...])N/A
Calculates a commission for a transaction based on a per share cost with an optional minimum cost per trade.
zipline.finance.commission.PerTrade([cost])N/A
Calculates a commission for a transaction based on a per trade cost.
zipline.finance.commission.PerDollar([cost])N/A
Model commissions by applying a fixed cost per dollar transacted.
zipline.finance.commission.NoCommissionFeeModel()
Model commissions as free.

Benchmark

The default benchmark is SPY.

QuantopianQuantConnect
quantopian.algorithm.set_benchmark(benchmark)self.SetBenchmark(benchmark)
Set the benchmark asset.

You can also see our Videos. You can also get in touch with us via Discord.

Did you find this page helpful?

Contribute to the documentation: