microsoft/qlib · error · TypeError

All elements in idx_list must be of the same type

Error message

All elements in idx_list must be of the same type

What it means

The Index class in qlib/utils/index_data.py builds a numpy array and a lookup dict from idx_list, and requires every element to share one Python type. Mixing types (e.g. strings with ints, or Timestamps with datetime64) would produce an object-dtype array and break hashing/equality downstream, so the constructor rejects it early with TypeError.

Source

Thrown at qlib/utils/index_data.py:113

    NOTE: the indexing has following flaws
    - duplicated index value is not well supported (only the first appearance will be considered)
    - The order of the index is not considered!!!! So the slicing will not behave like pandas when indexings are ordered
    """

    def __init__(self, idx_list: Union[List, pd.Index, "Index", int]):
        self.idx_list: np.ndarray = None  # using array type for index list will make things easier
        if isinstance(idx_list, Index):
            # Fast read-only copy
            self.idx_list = idx_list.idx_list
            self.index_map = idx_list.index_map
            self._is_sorted = idx_list._is_sorted
        elif isinstance(idx_list, int):
            self.index_map = self.idx_list = np.arange(idx_list)
            self._is_sorted = True
        else:
            # Check if all elements in idx_list are of the same type
            if not all(isinstance(x, type(idx_list[0])) for x in idx_list):
                raise TypeError("All elements in idx_list must be of the same type")
            # Check if all elements in idx_list are of the same datetime64 precision
            if isinstance(idx_list[0], np.datetime64) and not all(x.dtype == idx_list[0].dtype for x in idx_list):
                raise TypeError("All elements in idx_list must be of the same datetime64 precision")
            self.idx_list = np.array(idx_list)
            # NOTE: only the first appearance is indexed
            self.index_map = dict(zip(self.idx_list, range(len(self))))
            self._is_sorted = False

    def __getitem__(self, i: int):
        return self.idx_list[i]

    def _convert_type(self, item):
        """

        After user creates indices with Type A, user may query data with other types with the same info.
            This method try to make type conversion and make query sane rather than raising KeyError strictly

        Parameters

View on GitHub (pinned to 79633dd950)

Solutions

  1. Normalize every element to one type before constructing, e.g. list(pd.to_datetime(raw_dates)) or [str(x) for x in items].
  2. If the data comes from a file, parse the date/instrument column explicitly (pd.to_datetime / astype) instead of relying on mixed raw values.
  3. Check for accidental None/NaN entries in the list, which commonly cause the first mixed-type element.

Example fix

// before
idx = Index(['2020-01-01', pd.Timestamp('2020-01-02')])  # TypeError

// after
idx = Index(list(pd.to_datetime(['2020-01-01', '2020-01-02'])))
Defensive patterns

Strategy: validation

Validate before calling

def homogeneous(items) -> bool:
    items = list(items)
    return len(items) == 0 or all(type(x) is type(items[0]) for x in items)

assert homogeneous(raw_index), 'mixed types in index'

Type guard

def is_homogeneous_index(items: list) -> bool:
    items = list(items)
    return not items or all(isinstance(x, type(items[0])) for x in items)

Try / catch

try:
    idx = Index(raw)
except TypeError as e:
    raw = [str(x) for x in raw]  # or normalize to timestamps
    idx = Index(raw)

Prevention

When it happens

Trigger: Constructing Index(['2020-01-01', pd.Timestamp('2020-01-02')]), Index([1, '2']), or SingleData/MultiData whose index/columns argument is a mixed-type list; also passing an empty-then-heterogeneous iterable from user data files.

Common situations: Loading calendars or instrument lists from CSV where dates are sometimes ISO strings and sometimes parsed Timestamps; concatenating hand-written test fixtures with literals of inconsistent types; migrating code from pandas Index (which tolerates object dtype) to qlib's Index.

Related errors


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