You need to enable JavaScript to run this app. Pandas iloc传入时间戳报非整数索引TypeError的修正问询
优惠活动
大模型
产品
解决方案
定价
更多

Pandas iloc传入时间戳报非整数索引TypeError的修正问询

代码报错修正方案:TypeError: Cannot index by location index with a non-integer key

错误核心原因

你先后两次调整代码触发报错,本质是混淆了pandas两种索引的适用规则,两处错误代码分别为:

# 第一次报错:使用loc的版本
exit_price = df.loc[exit_time + dt.timedelta(minutes=1)].Open
# 第二次报错:换成iloc的版本
exitprice = df.iloc[exittime + dt.timedelta(minutes=1)].Open
  • df.iloc[] 是纯位置索引,只接受整数类型的行号作为入参,完全不支持datetime等非整数类型的key。你将原代码里的loc换成iloc后,直接把exittime + dt.timedelta(minutes=1)生成的时间对象传入iloc,自然会触发“非整数key无法用于位置索引”的报错。
  • 最初使用df.loc[]时的报错,不是loc不支持时间索引,而是取数逻辑存在缺陷:直接给信号触发时间戳加1分钟的偏移量,得到的时间值不一定恰好存在于行情索引中——尤其遇到美股盘前盘后、午间休市的时段,时间偏移后很容易匹配不到对应K线,或取错相邻的K线。

具体修正逻辑

所有需要按时间定位的场景,全部转成整数位置索引操作,彻底避免时间戳匹配偏差:

  • 拿到离场信号时间exittime后,先通过df.index.get_loc()方法,把这个时间值转换为它在行情表里对应的整数行号
  • 按照交易逻辑,取信号触发后下一根K线的开盘价,直接在整数行号上+1,不需要手动给时间戳加分钟偏移
  • 增加越界判断:如果信号触发的K线已经是行情表的最后一行,就直接取最后一行的开盘价,避免数组越界报错

修正后的可运行代码

import yfinance as yf
import pandas as pd
import datetime as dt

asset = "TSLA"
intraday = yf.download(asset, start="2021-03-17", end="2021-03-18", interval="1m")

def Intradaytrend(df, entry, exit):
    ret_120min = df.iloc[120].Open/df.iloc[0].Open - 1
    tickret = df.Open.pct_change()
    if ret_120min > entry:
        buyprice = df.iloc[121].Open
        buytime = df.iloc[121].name
        cumulated = (tickret.loc[buytime:] + 1).cumprod() - 1
        exittime = cumulated[(cumulated < -exit) | (cumulated > exit)].first_valid_index()
        if exittime == None:
            exitprice = df.iloc[-1].Open
        else:
            # 核心修正部分:先把时间值转换为对应的整数行号
            exit_row_idx = df.index.get_loc(exittime)
            # 取相邻下一根K线的开盘价,增加越界保护
            next_row_idx = exit_row_idx + 1 if exit_row_idx + 1 < len(df) else exit_row_idx
            exitprice = df.iloc[next_row_idx].Open
        profit = exitprice - buyprice
        profitrel = profit / buyprice
        return profitrel
    else:
        return None

Intradaytrend(intraday, 0.01, 0.01)

修正后的取数逻辑,完全匹配“信号触发后等下一根1分钟K线开盘离场”的策略初衷,不会因为美股交易时段中断、行情索引跳空的问题,出现“时间加1分钟匹配不到K线”的情况,取数可靠性远高于直接给时间戳加偏移量的写法。

内容的提问来源于stack exchange,提问作者FM2020

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.27 16:54:04