Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Newb question on how orders are modelled

Hi all,

please help me build a mental model of howto think of the backtesting engine.
When I make a call to order a security (assuming high enough volume) can I assume the order is filled immediately?
This question only pertains when I run backtesting.

2 responses

First off, very good question. "how to think about the backtesting engine?" It's important to understand the process of how trades are simulated to then understand the limitations (and power) of the Zipline backtester.

The first and foremost concept of the backtester is that it is discrete-event simulator. It 'loops' through it's code every minute. The smallest resolution for Quantopian events (and data) is 1 minute. This resolution is generally referred to in the documentation as a 'tick' or a 'bar'.

The basic steps which occur during each bar of each trading day are:

  • 1. get orders - fetch the list of outstanding orders. These could be new orders or partially filled orders.

  • 2. iterate through the orders and process each one - calculate any buys/sells from existing orders. How much of an order fills, and
    at what price, is based upon the slippage model specified in the
    initialize method (or the default if none specified). Note that the
    data available to calculate fill price is only data which is
    available at the beginning of this bar (ie at the close of the
    previous bar).

  • 3. execute handle_data and any scheduled functions - this is when any user defined logic is executed.

  • 4. record new orders - done here so the timestamps reflect the current bar when entered or modified.

The above sequence is repeated each minute of the trading day.

From the above it can be seen that orders are really not 'filled' until the beginning of the following bar, or later depending upon the slippage model. Sometimes an order will get spread out over multiple bars. So, to answer the question "can I assume the order is filled immediately?", the answer is no. There is a little subtlety... even though the order logic is executed at the beginning of the following bar, the price and volume data used to determine how it is filled is from the previous bar when the order was placed. This sort of simulates an order being filled during that previous bar (sort of).

If one wants to dig into the exact order of things take a look at the class "AlgorithmSimulator" and the method "transform" . That's the main work loop of the backtest engine (https://github.com/quantopian/zipline/blob/master/zipline/gens/tradesimulation.py).

Dan, thank you so much for the detailed answer! Does the same logic apply if I have only daily bars (using quandl wiki data).