Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading