Available languages: [Python](https://databento.com/docs/examples/equities/equities-premarket-movers.python.md) · [C++](https://databento.com/docs/examples/equities/equities-premarket-movers.cpp.md) · [Rust](https://databento.com/docs/examples/equities/equities-premarket-movers.rust.md) · [HTTP](https://databento.com/docs/examples/equities/equities-premarket-movers.http.md) · [Raw](https://databento.com/docs/examples/equities/equities-premarket-movers.raw.md)

Source: https://databento.com/docs/examples/equities/equities-premarket-movers


# Top pre-market movers

## Overview

This example demonstrates how to use the [Historical client](https://databento.com/docs/api-historical/client.md) to
retrieve OHLCV-1m bar aggregate data to analyze the largest movers in the Nasdaq pre-market.
Equities which are trading in the early pre-market may be reacting to recent events or news announcements,
relevant to a single stock, an industry, or an entire sector. This notable pre-market activity
usually manifests in large price changes and volume, which significantly exceed the normal range,
and may be indicative of subsequent moves after the session open.

For our purposes we'll define the pre-market as 4:00 AM to 9:30 AM in the 'US/Eastern' time zone,
which accounts for changes for daylight savings.

You can find more information on Nasdaq trading hours [here](https://www.nasdaq.com/stock-market-trading-hours-for-nasdaq).

## Nasdaq dataset

For this example, we'll use the [Nasdaq TotalView-ITCH]($PLATFORM_HOSTNAME/datasets/XNAS.ITCH)
dataset, whose dataset ID is `XNAS.ITCH`. You'll need to pass this in as the `dataset`
parameter of any API or client method.

## OHLCV-1m schema

The data we need will come from the [OHLCV-1m schema](https://databento.com/docs/schemas/ohlcv.md).
The OHLCV family of schemas contain the opening, high, low, and closing prices, as well
as the aggregated volume of trades occurring within each time interval. Since we are interested in
a specific market session, we'll use an interval of one minute, which is specified by the
suffix `-1m`.

## Example

```python
import databento as db
import pandas as pd

# Create a historical client
client = db.Historical(key="$YOUR_API_KEY")

# Next, request OHLCV-1m bars for the time range we're interested in
data = client.timeseries.get_range(
    dataset="XNAS.ITCH",
    schema="ohlcv-1m",
    symbols="ALL_SYMBOLS",
    start=pd.Timestamp("2023-06-06T04:00", tz="US/Eastern"),
    end=pd.Timestamp("2023-06-06T09:30", tz="US/Eastern"),
)

# We need to obtain the symbology mappings for 'ALL_SYMBOLS'
symbology = data.request_symbology(client)

# This allows us to populate the 'symbol' column when we convert to a DataFrame
data.insert_symbology_json(symbology)

# Convert to dataframe with timestamps in the US/Eastern timezone
df = data.to_df(tz="US/Eastern")

# Combine the first open, last close and volume sum into a DataFrame
df_moves = df.groupby("symbol").agg({"open": "first", "close": "last", "volume": "sum"})

# Calculate the change from start to end of pre-market
df_moves["change"] = (df_moves["close"] - df_moves["open"]) / df_moves["open"]
df_moves = df_moves.sort_values(by="change", ascending=False)

# Display the top 10 largest movers
print(df_moves.head(10))
```
## Result

```plaintext
           open    close   volume    change
symbol
CRGOW    0.1564   0.3200     1977  1.046036
ZVZZT   13.0200  25.0000      369  0.920123
MLECW    0.0974   0.1798     3394  0.845996
HOTH     2.0300   3.5400  1600550  0.743842
BOAC+    0.0458   0.0782      700  0.707424
RCRT     0.1918   0.2953   575273  0.539625
ATMCR    0.1489   0.2237      400  0.502351
SBFMW    0.5938   0.8915      305  0.501347
RCRTW    0.0229   0.0302      300  0.318777
TCBPW    0.0436   0.0573      300  0.314220
```
> **See also**
>
> [End-of-day pricing and portfolio valuation](https://databento.com/docs/examples/basics-historical/eod.md) and
> [Benchmark portfolio performance](https://databento.com/docs/examples/basics-historical/benchmarks.md).


# Top pre-market movers

## Overview

This example demonstrates how to use the [Historical client](https://databento.com/docs/api-historical/client.md) to retrieve OHLCV-1m bar aggregate data to analyze the largest movers in the Nasdaq pre-market.
Equities which are trading in the early pre-market may be reacting to recent events or news announcements,
relevant to a single stock, an industry, or an entire sector.
This notable pre-market activity usually manifests in large price changes and volume,
which significantly exceed the normal range, and may be indicative of subsequent moves after the session open.

For our purposes we'll define the pre-market as 4:00 AM to 9:30 AM in the US Eastern time zone,
which accounts for daylight savings.

You can find more information on Nasdaq trading hours [here](https://www.nasdaq.com/stock-market-trading-hours-for-nasdaq).

## Nasdaq dataset

For this example, we'll use the [Nasdaq TotalView-ITCH]($PLATFORM_HOSTNAME/datasets/XNAS.ITCH)
dataset, whose dataset ID is `XNAS.ITCH`.
We'll use the `Dataset` enum to pass this as the `dataset` parameter.

## OHLCV-1m schema

The data we need will come from the [OHLCV-1m schema](https://databento.com/docs/schemas/ohlcv.md).
The OHLCV family of schemas contain the opening, high, low, and closing prices,
 as well as the aggregated volume of trades occurring within each time interval.
Since we are interested in a specific market session, we'll use an interval of one minute, which is specified by the suffix `1M`.

## Example

```rust
use std::collections::HashMap;

use databento::{
    HistoricalClient, Symbols,
    dbn::{Dataset, OhlcvMsg, Schema, pretty::Px},
    historical::{symbology::ResolveParams, timeseries::GetRangeParams},
};
use time::macros::datetime;
use time_tz::{PrimitiveDateTimeExt, timezones};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let mut client = HistoricalClient::builder().key_from_env()?.build()?;
    let tz = timezones::db::us::EASTERN;
    // First, request the OHLCV-1m bars for the time range we're interested in
    let params = GetRangeParams::builder()
        .dataset(Dataset::XnasItch)
        .date_time_range(
            datetime!(2023 - 06 - 06 04:00).assume_timezone(tz).unwrap()
                ..datetime!(2023 - 06 - 06 09:30).assume_timezone(tz).unwrap(),
        )
        .symbols(Symbols::All)
        .schema(Schema::Ohlcv1M)
        .build();
    let mut decoder = client.timeseries().get_range(&params).await?;
    // We need to obtain symbology mappings for all symbols requests separately
    let symbol_map = client
        .symbology()
        .resolve(&ResolveParams::from(params))
        .await?
        .symbol_map()?;

    // Aggregate the results into a single bar for the pre-open period
    let mut aggregated_bars = HashMap::new();
    while let Some(bar) = decoder.decode_record::<OhlcvMsg>().await? {
        aggregated_bars
            .entry(bar.hd.instrument_id)
            .and_modify(|agg_bar: &mut OhlcvMsg| {
                agg_bar.volume += bar.volume;
                agg_bar.close = bar.close;
            })
            .or_insert(bar.clone());
    }
    // Calculate the percent change
    let mut bars_with_change = aggregated_bars
        .into_values()
        .map(|bar| {
            let change = (bar.close_f64() - bar.open_f64()) / bar.open_f64();
            let symbol = symbol_map[&bar].clone();
            (symbol, bar, change)
        })
        .collect::<Vec<_>>();
    // Find and print the top 10 largest movers
    bars_with_change.sort_by(|(_, _, a), (_, _, b)| a.partial_cmp(b).unwrap().reverse());
    println!(
        "{:<6}{:>9}{:>9}{:>9}{:>10}",
        "symbol", "open", "close", "volume", "change"
    );
    for (symbol, bar, change) in bars_with_change.iter().take(10) {
        println!(
            "{symbol:<6}{:>9.4}{:>9.4}{:>9}{change:>10.6}",
            Px(bar.open),
            Px(bar.close),
            bar.volume
        );
    }
    Ok(())
}
```
## Result

```plaintext
symbol     open    close   volume    change
CRGOW    0.1564   0.3200     1977  1.046036
ZVZZT   13.0200  25.0000      369  0.920123
MLECW    0.0974   0.1798     3394  0.845996
HOTH     2.0300   3.5400  1600550  0.743842
BOAC+    0.0458   0.0782      700  0.707424
RCRT     0.1918   0.2953   575273  0.539625
ATMCR    0.1489   0.2237      400  0.502351
SBFMW    0.5938   0.8915      305  0.501347
RCRTW    0.0229   0.0302      300  0.318777
TCBPW    0.0436   0.0573      300  0.314220
```
> **See also**
>
> [End-of-day pricing and portfolio valuation](https://databento.com/docs/examples/basics-historical/eod.md) and
> [Benchmark portfolio performance](https://databento.com/docs/examples/basics-historical/benchmarks.md).
