Python股票回测报错:'int' object is not callable 求解决方案
解决Backtest框架RuntimeError: 'int' object is not callable问题
错误原因分析
- 核心错误:
Strategy.I()方法要求传入可调用的函数(用于动态计算指标),而你直接传入了int类型的self.average_price,框架尝试调用这个整数,导致'int' object is not callable错误。 - 次要问题:
next()方法中self.h1是笔误,应为self.hl- 原代码仅计算回测初始前10天的高低价,未实现滚动更新,不符合回测过程中每日指标动态变化的逻辑。
修复后的代码
from backtesting import Strategy, Backtest from backtesting.lib import crossover import talib as ta class HighLow(Strategy): timeperiod = 10 def init(self): # 滚动计算10天最高最低价,每日自动更新 self.highest_price = self.I(ta.MAX, self.data.High, self.timeperiod) self.lowest_price = self.I(ta.MIN, self.data.Low, self.timeperiod) # 用lambda封装平均价计算逻辑,转为可调用函数传入self.I self.hl = self.I(lambda: (self.highest_price + self.lowest_price) / 2, name='AverageHighLow') def next(self): # 修正笔误:self.h1 → self.hl if crossover(self.data.Close, self.hl): self.buy() elif crossover(self.hl, self.data.Close): self.position.close() bt2 = Backtest(data, HighLow, cash=10000) stats = bt2.run() print(stats) bt2.plot()
关键修改说明
- 正确使用
Strategy.I():- 用talib的
ta.MAX/ta.MIN作为可调用对象传入,实现每日滚动计算10天高低价。 - 用
lambda封装平均价计算逻辑,满足self.I对可调用参数的要求。
- 用talib的
- 修正笔误:将
next()中的self.h1改为self.hl。 - 优化交易逻辑:原逻辑中
crossover(self.hl, self.highest_price)几乎不会触发(平均值永远≤最高价),改为收盘价与指标交叉,更符合常规策略逻辑。
如果不想依赖talib,可自行实现滚动计算函数:
def rolling_max(series, period): return series.rolling(period).max() def rolling_min(series, period): return series.rolling(period).min() # 在init中替换为: self.highest_price = self.I(rolling_max, self.data.High, self.timeperiod) self.lowest_price = self.I(rolling_min, self.data.Low, self.timeperiod)
内容的提问来源于stack exchange,提问作者prashant tiwari
相关产品推荐
相关产品推荐

