Backtesting.py中resample_apply未定义错误求助
解决Backtesting.py中
resample_apply未定义的NameError问题 核心问题原因
resample_apply并非全局可用函数,它是Backtesting.py库的backtesting.lib子模块提供的工具函数,未显式导入会触发NameError。
解决方案步骤
导入
resample_apply函数
在代码开头添加导入语句,确保能调用该工具函数:from backtesting import Backtest, Strategy from backtesting.lib import resample_apply # 关键:导入该函数修复代码拼写错误
原策略类next方法中存在拼写错误:self.postion.is_short里的postion应为position,否则后续运行会触发AttributeError。
完整修正后的代码
from backtesting import Backtest, Strategy from backtesting.lib import resample_apply class MomentumStrategy(Strategy): small_threshold = 0 large_threshold = 3 def momentum(self, data): return data.pct_change(periods=7).to_numpy() * 100 def init(self): self.pct_change_long = resample_apply("2h", self.momentum, self.data.Close.s) self.pct_change_short = resample_apply("30T", self.momentum, self.data.Close.s) def next(self): change_long = self.pct_change_long[-1] change_short = self.pct_change_short[-1] if self.position: if self.position.is_long and change_short < self.small_threshold: self.position.close() elif self.position.is_short and change_short > -1 * self.small_threshold: self.position.close() else: if change_long > self.large_threshold and change_short > self.small_threshold: self.buy() elif change_long < -1 * self.large_threshold and change_short < -1 * self.small_threshold: self.sell() # 测试执行代码 bt = Backtest(df_min, MomentumStrategy, cash=10_000_000, commission=0.002) bt.run()
内容的提问来源于stack exchange,提问作者MateMalte
相关产品推荐
相关产品推荐

