{"record":{"id":"cbc89a495cfa2b85","repo":"microsoft/qlib","slug":"item-can-t-be-found-in-self","errorCode":null,"errorMessage":"{item} can't be found in {self}","messagePattern":"(.+?) can't be found in (.+?)","errorType":"exception","errorClass":"KeyError","httpStatus":null,"severity":"error","filePath":"qlib/utils/index_data.py","lineNumber":170,"sourceCode":"        Parameters\n        ----------\n        item :\n            The item to query\n\n        Returns\n        -------\n        int:\n            The index of the item\n\n        Raises\n        ------\n        KeyError:\n            If the query item does not exist\n        \"\"\"\n        try:\n            return self.index_map[self._convert_type(item)]\n        except IndexError as index_e:\n            raise KeyError(f\"{item} can't be found in {self}\") from index_e\n\n    def __or__(self, other: \"Index\"):\n        return Index(idx_list=list(set(self.idx_list) | set(other.idx_list)))\n\n    def __eq__(self, other: \"Index\"):\n        # NOTE:  np.nan is not supported in the index\n        if self.idx_list.shape != other.idx_list.shape:\n            return False\n        return (self.idx_list == other.idx_list).all()\n\n    def __len__(self):\n        return len(self.idx_list)\n\n    def is_sorted(self):\n        return self._is_sorted\n\n    def sort(self) -> Tuple[\"Index\", np.ndarray]:\n        \"\"\"","sourceCodeStart":152,"sourceCodeEnd":188,"githubUrl":"https://github.com/microsoft/qlib/blob/79633dd9506ea689e5400dea0197717b5b3d74b7/qlib/utils/index_data.py#L152-L188","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Verify membership first: `if item in sd.index` (Index implements __contains__ via index_map) before fetching.","For range/alignment work, reindex the SingleData with your target index and fill_value=np.nan instead of fetching missing keys one by one.","If dates mismatch, normalize precision with pd.to_datetime(item).to_datetime64() matching the index dtype."],"exampleFix":"// before\nvalue = sd.fetch(pd.Timestamp('2019-01-01'))  # KeyError if date absent\n\n// after\nif pd.Timestamp('2019-01-01') in sd.index:\n    value = sd.fetch(pd.Timestamp('2019-01-01'))\nelse:\n    value = np.nan","handlingStrategy":"type-guard","validationCode":"item = pd.Timestamp('2019-01-01')\nif item not in sd.index:\n    sd = sd.reindex(sd.index | Index([item.to_datetime64()]))  # or handle missing explicitly","typeGuard":"def index_has(sd, item) -> bool:\n    return item in sd.index  # uses Index.index_map","tryCatchPattern":"try:\n    v = sd.fetch(item)\nexcept KeyError:\n    v = np.nan  # graceful miss","preventionTips":["Membership-check (`item in sd.index`) before every fetch of user-supplied keys.","For bulk alignment, prefer reindex with fill_value over per-key fetch loops.","Match datetime precision between stored index and query keys."],"tags":["qlib","index-data","keyerror","lookup","datetime"],"backgroundTag":null,"analyzedSha":"79633dd9506ea689e5400dea0197717b5b3d74b7","analyzedAt":"2026-08-15T07:01:27.511Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}