pythonnameerrorback-testing

Backtesting.py function resample_apply not defined


To learn how to use the Backtesting.py library I followed this YouTube video: https://youtu.be/9m987swadQU?si=6UN7ARnrYrN6u7nf

But when I wrote my Strategy class:

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.postion.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()

and try to run that code:

bt = Backtest(df_min, MomentumStrategy, cash = 10_000_000, commission = 0.002)

bt.run()

it had thrown a NameError for the resample_apply function:

NameError: name 'resample_apply' is not defined

Can someone help?


Solution

  • You need to import resample_apply into your script. Add the following line to the beginning of your code:

    from backtesting.lib import resample_apply