aggregate_ohlcv_across_pairs#

API documentation for tradingstrategy.utils.aggregate_ohlcv.aggregate_ohlcv_across_pairs Python function.

aggregate_ohlcv_across_pairs(pair_universe, price_df, liquidity_df=None)[source]#

Builds an aggregates dataframe for trading data.

  • Merge all pools e.g. ETH/USDC Uniswap v2, ETH/USDC Uniswap v3 30 BPS and 5 BPS to a single volume data

  • Prices are weighted by volume

  • Currently supports same-chain pairs only

Example:

from tradingstrategy.utils.aggregate_ohlcv import aggregate_ohlcv_across_pairs

client = persistent_test_client
exchange_universe = client.fetch_exchange_universe()
pairs_df = client.fetch_pair_universe().to_pandas()

# Create filtered exchange and pair data
exchange = exchange_universe.get_by_chain_and_slug(ChainId.ethereum, "uniswap-v3")

pair_universe = PandasPairUniverse.create_pair_universe(
        pairs_df,
        [
            (exchange.chain_id, exchange.exchange_slug, "WETH", "USDC", 0.0005),
            (exchange.chain_id, exchange.exchange_slug, "WETH", "USDC", 0.0030),
            (exchange.chain_id, exchange.exchange_slug, "WETH", "USDC", 0.0100)
        ],
    )
pair_ids = {p.pair_id for p in pair_universe.iterate_pairs()}
candles_df = client.fetch_candles_by_pair_ids(
    pair_ids,
    TimeBucket.d7,
    start_time=datetime.datetime(2024, 1, 1),
    end_time=datetime.datetime(2024, 3, 1)
)
candles_df = candles_df.groupby("pair_id")
candles_df = forward_fill(candles_df, "W")

# fetch_all_liquidity_samples() unnecessary heavy here
# TODO: Change to dynamic fetch method in the future
liquidity_df = client.fetch_all_liquidity_samples(TimeBucket.d7).to_pandas()
liquidity_df = liquidity_df.loc[liquidity_df["pair_id"].isin(pair_ids)]
liquidity_df = liquidity_df.set_index("timestamp").groupby("pair_id")
liquidity_df = forward_fill(liquidity_df, "W", columns=("close",))  # Only close liquidity column needd

aggregated_df = aggregate_ohlcv_across_pairs(
    pair_universe,
    candles_df,
    liquidity_df["close"],
)
Parameters:
  • pair_universe (PandasPairUniverse) – Pair metadata

  • price_df (DataFrame) –

    OHLCV dataframe.

    Must be forward filled.

  • liquidity_df (pandas.core.groupby.generic.DataFrameGroupBy | None) –

    Liquidity dataframe.

    Must be forward filled.

    Only “close” column is used.

Returns:

DataFrame with following colmuns

  • aggregate_id

  • base

  • quote

  • open

  • low

  • high

  • close

  • volume

  • liquidity

  • pair_ids (list of ints)

Volume and liquidity are in USD.

Return type:

DataFrame