Skip to content

Commit

Permalink
Fix MultiIndex issues with forward fill for liquidity
Browse files Browse the repository at this point in the history
  • Loading branch information
miohtama committed Sep 23, 2024
1 parent 5ddece6 commit 0e3b61d
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions tradingstrategy/liquidity.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"""

from dataclasses import dataclass
from typing import List, Optional, Tuple, Dict
from typing import List, Optional, Tuple, Dict, cast

import pandas as pd
import pyarrow as pa
Expand Down Expand Up @@ -323,17 +323,29 @@ def get_liquidity_with_tolerance(

samples_per_kind = candles_per_pair[kind]

# The indexes we can have are
# - MultiIndex (pair id, timestamp) - if multiple trading pairs present
# - DatetimeIndex - if single trading pair present

if isinstance(candles_per_pair.index, pd.MultiIndex):
timestamp_index = cast(pd.DatetimeIndex, candles_per_pair.index.get_level_values(1))
elif isinstance(candles_per_pair.index, pd.DatetimeIndex):
timestamp_index = candles_per_pair.index
else:
raise NotImplementedError(f"Does not know how to handle index {candles_per_pair.index}")

# https://pandas.pydata.org/docs/reference/api/pandas.Index.get_indexer.html
# https://stackoverflow.com/questions/71027193/datetimeindex-get-loc-is-deprecated
indexer = candles_per_pair.index.get_indexer([when], method="pad")
indexer = timestamp_index.get_indexer([when], method="pad")

if indexer[0] != -1:
discrete_ts_idx = indexer[0]
else:
first_sample = candles_per_pair.index[0]
raise LiquidityDataUnavailable(f"Pair {pair_id} does not have data older data than {first_sample}. Tried to look up {when}.")

sample_timestamp = candles_per_pair.index[discrete_ts_idx]

sample_timestamp = timestamp_index[discrete_ts_idx]

latest_value = candles_per_pair.iloc[discrete_ts_idx][kind]

Expand Down

0 comments on commit 0e3b61d

Please sign in to comment.