---
title: "Data Preparation"
description: "The US Equities dataset provides price data for backtests and live trading."
canonical: https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/us-equity/data-preparation
markdown: https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/us-equity/data-preparation.md
language: python
source: https://github.com/QuantConnect/Documentation/tree/master/03%20Writing%20Algorithms/03%20Securities/99%20Asset%20Classes/01%20US%20Equity/08%20Data%20Preparation
modified: 2026-10-30
index: https://www.quantconnect.com/llms.txt
---

# Data Preparation

[Documentation](https://www.quantconnect.com/docs/v2.md) > [Writing Algorithms](https://www.quantconnect.com/docs/v2/writing-algorithms.md) > Securities > [Asset Classes](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes.md) > [US Equity](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/us-equity.md) > Data Preparation

> Code examples are shown in Python. Append `?lang=csharp` to this URL for the C# version of this page.

## Introduction

The [US Equities](https://www.quantconnect.com/datasets/algoseek-us-equities) dataset provides price data for backtests and live trading.

## Sourcing

The QuantConnect data provider consolidates US Equity market data across all of the exchanges. Over-the-Counter (OTC) trades are excluded. The data is powered by the Securities Information Processor (SIP), so it has 100% market coverage. In contrast, free platforms that display data feeds like the Better Alternative Trading System (BATS) only have [about 6-7% market coverage](https://www.xignite.com/faqs/stocks-and-etfs-data/why-is-the-volume-on-bats-cboe-lower-than-other-exchanges/).

We provide live splits, dividends, and corporate actions for US companies. We deliver them to your algorithm before the trading day starts.

## Bar Building

We aggregate ticks to build bars.

The bar-building process can exclude ticks. If a tick is excluded, its volume is aggregated in the bar but its price is not aggregated in the bar. If no tick in a period sets the price, the period has no bar. Ticks are excluded if any of the following statements are true:

- The tick is suspicious.
- The trade is from the FINRA exchange and FINRA filtering is active for the security. For more information about FINRA filtering, see the paragraph after this list.
- The trade has none of the included `TradeConditionFlags` and at least one of the excluded `TradeConditionFlags` in the following table.
- The bid size and the ask size of the quote are both less than 100 shares.
- The quote has none of the included `QuoteConditionFlags` in the following table.
- The quote has at least one of the excluded `QuoteConditionFlags` in the following table.

FINRA trades include internal crosses from brokers, dealers, and dark pools. At the start of each trading day, FINRA filtering is inactive for every security. FINRA filtering becomes active once both of the following conditions are met:

- The first tick of the day that passes the condition flag rules in the preceding list has a price of at least $5. We check the price only once per day, so if this tick is below $5, FINRA filtering stays inactive for the rest of the day.
- The dollar volume of the trades that pass the condition flag rules reaches $5,000,000. The count starts with the first trade of the day, including pre-market trades.

After FINRA filtering becomes active, FINRA trades don't set the price of the bar for the rest of the day. Their volume is still aggregated in the bar. Before FINRA filtering becomes active, a FINRA trade sets the price of the bar if it passes the condition flag rules.

The following table shows the `TradeConditionFlags` that the bar-building process uses:

| `TradeConditionFlags` | Status | Description |
| --- | --- | --- |
| `REGULAR` | Included | A trade made without stated conditions is deemed the regular way for settlement on the third business day following the transaction date. |
| `FORM_T` | Included | Trading in extended hours enables investors to react quickly to events that typically occur outside regular market hours, such as earnings reports. However, liquidity may be constrained during such Form T trading, resulting in wide bid-ask spreads. |
| `CASH` | Included | A transaction that requires delivery of securities and payment on the same day the trade takes place. |
| `EXTENDED_HOURS` | Included | Identifies a trade that was executed outside of regular primary market hours and is reported as an extended hours trade. |
| `NEXT_DAY` | Included | A transaction that requires the delivery of securities on the first business day following the trade date. |
| `OFFICIAL_CLOSE` | Included | Indicates the "official" closing value determined by a Market Center. This transaction report will contain the market center generated closing price. |
| `OFFICIAL_OPEN` | Included | Indicates the 'Official' open value as determined by a Market Center. This transaction report will contain the market center generated opening price. |
| `CLOSING_PRINTS` | Included | The transaction that constituted the trade-through was a single priced closing transaction by the Market Center. |
| `OPENING_PRINTS` | Included | The trade that constituted the trade-through was a single priced opening transaction by the Market Center. |
| `INTERMARKET_SWEEP` | Excluded | The transaction that constituted the trade-through was the execution of an order identified as an Intermarket Sweep Order. |
| `TRADE_THROUGH_EXEMPT` | Excluded | Denotes whether or not a trade is exempt (Rule 611). |
| `ODD_LOT` | Excluded | Denotes the trade is an odd lot less than a 100 shares. |

The following table shows the included `QuoteConditionFlags`:

| `QuoteConditionFlags` | Description |
| --- | --- |
| `REGULAR` | This condition is used for the majority of quotes to indicate a normal trading environment. |
| `SLOW` | This condition is used to indicate that the quote is a Slow Quote on both the bid and offer sides due to a Set Slow List that includes high price securities. |
| `GAP` | While in this mode, auto-execution is not eligible, the quote is then considered manual and non-firm in the bid and offer, and either or both sides can be traded through as per Regulation NMS. |
| `OPENING_QUOTE` | This condition can be disseminated to indicate that this quote was the opening quote for a security for that Participant. |
| `FAST_TRADING` | For extremely active periods of short duration. While in this mode, the UTP Participant will enter quotations on a best efforts basis. |

The following table shows the excluded `QuoteConditionFlags`:

| `QuoteConditionFlags` | Description |
| --- | --- |
| `CLOSING` | Indicates that this quote was the last quote for a security for that Participant. |
| `NEWS_DISSEMINATION` | Denotes a regulatory trading halt when relevant news influencing the security is being disseminated. Trading is suspended until the primary market determines that an adequate publication or disclosure of information has occurred. |
| `NEWS_PENDING` | Denotes a regulatory Trading Halt due to an expected news announcement, which may influence the security. An Opening Delay or Trading Halt may be continued once the news has been disseminated. |
| `TRADING_RANGE_INDICATION` | Denotes the probable trading range (Bid and Offer prices, no sizes) of a security that is not Opening Delayed or Trading Halted. The Trading Range Indication is used prior to or after the opening of a security. |
| `ORDER_IMBALANCE` | Denotes a non-regulatory halt condition where there is a significant imbalance of buy or sell orders. |
| `RESUME` | Indicates that trading for a Participant is no longer suspended in a security that had been Opening Delayed or Trading Halted. |

In the preceding tables, **Participant** refers to the entities on page 19 of the [Consolidated Tape System Multicast Output Binary Specification](https://www.ctaplan.com/publicdocs/ctaplan/notifications/trader-update/CTS_BINARY_OUTPUT_SPECIFICATION.pdf).

## Suspicious Ticks

Tick price data is raw and unfiltered, so it can contain a lot of noise. If a tick is not tradable, we flag it as suspicious. This process makes the bars a more realistic representation of what you could execute in live trading. If you use tick data, avoid using suspicious ticks in your algorithms as informative data points. We recommend only using tick data if you understand the risks and are able to perform your own tick filtering. Ticks are flagged as suspicious in the following situations:

- The tick occurs below the best bid or above the best ask
  ![A tick occurs above the best ask of a security](https://cdn.quantconnect.com/i/tu/suspicious-ticks-2.png)
  This image shows a tick that occurred above the best ask price of a security. The green line represents the best ask of the security, the blue line represents the best bid of the security, and the red dots represent trade ticks. The ticks between the best bid and ask occur from filling hidden orders. The tick that occurred above the best ask price is flagged as suspicious.
- The tick occurs far from the current market price
  ![A tick occurs far below the market price of a security](https://cdn.quantconnect.com/i/tu/suspicious-ticks-1.png)
  This image shows a tick that occurred far from the price of the security. The red dots represent trade ticks. The tick that occurred far from the market price is flagged as suspicious.
- The tick occurs on a dark pool
- The tick is rolled back
- The tick is reported late

## Market Auction Prices

The opening and closing price of the day is set by very specific opening and closing auction ticks. When a stock like Apple is listed, it’s listed on Nasdaq. The open auction tick on Nasdaq is the price that’s used as the official open of the day. NYSE, BATS, and other exchanges also have opening auctions, but the only official opening price for Apple is the opening auction on the exchange where it was listed.

We set the opening and closing prices of the first and last bars of the day to the official auction prices. This process is used for second, minute, hour, and daily bars for the 9:30 AM and 4:00 PM Eastern Time (ET) prices. In contrast, other platforms might not be using the correct opening and closing prices.

The official auction prices are usually emitted 2-30 seconds after the market open and close. We do our best to use the official opening and closing prices in the bars we build, but the delay can be so large that there isn't enough time to update the opening and closing price of the bar before it's injected into your algorithms. For example, if you subscribe to second resolution data, we wait until the end of the second for the opening price but most second resolution data won’t get the official opening price. If you subscribe to minute resolution data, we wait until the end of the minute for the opening auction price. Most of the time, you’ll get the actual opening auction price with minute resolution data, but there are always exceptions. Nasdaq and NYSE can have delays in publishing the opening auction price, but we don’t have control over those issues and we have to emit the data on time so that you get the bar you are expecting.

## Live and Backtesting Differences

In live trading, bars are built using the exchange timestamps with microsecond accuracy. This microsecond-by-microsecond processing of the ticks can mean that the individual bars between live trading and backtesting can have slightly different ticks. As a result, it's possible for a tick to be counted in different bars between backtesting and live trading, which can lead to bars having slightly different open, high, low, close, and volume values.

## Data Availability

In live trading, live data is available in real-time. In backtests, live data is available at the following pre-market trading session.

## Examples

The following examples demonstrate some common practices related to our US Equity data preparation process.

### Example 1: Trading at the Opening Auction

The following algorithm creates a [Scheduled Event](https://www.quantconnect.com/docs/v2/writing-algorithms/scheduled-events.md) that places a [Market On Open order](https://www.quantconnect.com/docs/v2/writing-algorithms/trading-and-orders/order-types/market-on-open-orders.md) , which fill at the official opening auction price.

```python
class USEquityDataPreparationExampleAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        # Add Equity data.
        self._spy = self.add_equity("SPY", extended_market_hours=True).symbol
        # Create a Scheduled Event that rebalances with market on open orders.
        self.schedule.on(
            self.date_rules.every_day(self._spy),
            self.time_rules.before_market_open(self._spy, 30),
            self._rebalance
        )

    def _rebalance(self):
        quantity = self.calculate_order_quantity(self._spy, 0.1)
        if quantity:
            self.market_on_open_order(self._spy, quantity)
```

### Example 2: Demonstrate Using Tick Flags to Identify Opening Auction Tick

This example demonstrates using the tick flags to identify the official opening price on the security primary exchange. All exchanges have an opening auction to determine the market on open price, but only the primary listed exchange is used as the official open price for the asset. The algorithm subscribes to the raw tick data of QQQ ETF and logs the auction price tick data of the asset.

```python
class USEquityDataPreparationExampleAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2024, 9, 5)
        self.set_end_date(2024, 9, 5)
        # Subscribe to tick data of a security and find the exchange code.
        self._asset = self.add_equity(ticker = "QQQ", resolution = Resolution.TICK, extended_market_hours = True, data_normalization_mode = DataNormalizationMode.RAW)
        # Define flags to help filter opening auctions in the OnData method.
        self.officialOpen = TradeConditionFlags.REGULAR | TradeConditionFlags.OFFICIAL_OPEN
        self.openingPrints = TradeConditionFlags.REGULAR | TradeConditionFlags.OPENING_PRINTS
        # Display exchange code and trade condition flags on the console.
        self.debug(f"Search Codes: Ex:{self._asset.primary_exchange.code} OO: {self.officialOpen} OP: {self.openingPrints}")

    def on_data(self, data):
        # Create a list of opening auction tick data.
        trades = [
            tick for tick in self._asset.cache.get_all[Tick]()
            if  tick.tick_type == TickType.TRADE and
                tick.price > 0 and
                tick.sale_condition and
                (
                    tick.parsed_sale_condition == self.officialOpen or
                    tick.parsed_sale_condition == self.openingPrints
                )
        ]
        # Log the opening auction tick price
        for tick in trades:
            self.log(f"{self.time},{tick.price},{tick.quantity},{tick.parsed_sale_condition},{tick.exchange_code},{tick.exchange}")
```
