microsoft/qlib · error · KeyError

{item} can't be found in {self}

Error message

{item} can't be found in {self}

What it means

Index.get_index(item) (and anything built on it, such as SingleData.fetch) looks the query item up in index_map; when the converted key is absent the lookup raises and qlib re-raises it as KeyError with the offending item and index contents. This is qlib's equivalent of a pandas .loc miss.

Source

Thrown at qlib/utils/index_data.py:170

        Parameters
        ----------
        item :
            The item to query

        Returns
        -------
        int:
            The index of the item

        Raises
        ------
        KeyError:
            If the query item does not exist
        """
        try:
            return self.index_map[self._convert_type(item)]
        except IndexError as index_e:
            raise KeyError(f"{item} can't be found in {self}") from index_e

    def __or__(self, other: "Index"):
        return Index(idx_list=list(set(self.idx_list) | set(other.idx_list)))

    def __eq__(self, other: "Index"):
        # NOTE:  np.nan is not supported in the index
        if self.idx_list.shape != other.idx_list.shape:
            return False
        return (self.idx_list == other.idx_list).all()

    def __len__(self):
        return len(self.idx_list)

    def is_sorted(self):
        return self._is_sorted

    def sort(self) -> Tuple["Index", np.ndarray]:
        """

View on GitHub (pinned to 79633dd950)

Solutions

  1. Verify membership first: `if item in sd.index` (Index implements __contains__ via index_map) before fetching.
  2. For range/alignment work, reindex the SingleData with your target index and fill_value=np.nan instead of fetching missing keys one by one.
  3. If dates mismatch, normalize precision with pd.to_datetime(item).to_datetime64() matching the index dtype.

Example fix

// before
value = sd.fetch(pd.Timestamp('2019-01-01'))  # KeyError if date absent

// after
if pd.Timestamp('2019-01-01') in sd.index:
    value = sd.fetch(pd.Timestamp('2019-01-01'))
else:
    value = np.nan
Defensive patterns

Strategy: type-guard

Validate before calling

item = pd.Timestamp('2019-01-01')
if item not in sd.index:
    sd = sd.reindex(sd.index | Index([item.to_datetime64()]))  # or handle missing explicitly

Type guard

def index_has(sd, item) -> bool:
    return item in sd.index  # uses Index.index_map

Try / catch

try:
    v = sd.fetch(item)
except KeyError:
    v = np.nan  # graceful miss

Prevention

When it happens

Trigger: Calling data.fetch(some_date) or index.get_index(item) where item is not in the index: a date outside the calendar range, an instrument not in the universe, or a value whose type/precision differs from the stored keys after _convert_type.

Common situations: Fetching a trading date that is a holiday or outside the backtest range; querying an instrument removed from the index; datetime precision mismatch (querying datetime64[ns] keys with datetime64[D] values) after _convert_type cannot reconcile them; stale cached index after data update.

Related errors


AI-assisted analysis of microsoft/qlib@79633dd950 (2026-08-15). Data as JSON: /api/errors/cbc89a495cfa2b85. Report an issue: GitHub.