Skip to content

AssertionError while using TrailingStrategy kernc#316 #319

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from

Conversation

zlpatel
Copy link
Contributor

@zlpatel zlpatel commented Apr 27, 2021

I have found the culprit. It's self.__atr[-1].

/usr/local/lib/python3.8/site-packages/backtesting/lib.py(433)set_atr_periods()
-> self.__atr = atr
(Pdb) pp atr[-1]
62.03802490234375

/usr/local/lib/python3.8/site-packages/backtesting/lib.py(440)set_trailing_sl()
-> self.__n_atr = n_atr
(Pdb) pp n_atr
1.5

/usr/local/lib/python3.8/site-packages/backtesting/lib.py(446)next()
-> trade.sl = max(trade.sl or -np.inf,
(Pdb) pp self.data.Close[-1]
22.170000076293945

so per the formula: trade.sl = max(trade.sl or -np.inf, self.data.Close[-1] - self.__atr[-1] * self.__n_atr)

22.17 - (62.04*1.5) = -70.89

the code shouldn't be using atr[-1]. It should be using atr[index] where index = len(self.data)-1

Because, when self.data in init() is different from self.data in next(). self.data in init() has all the data. while the one in next() gets accumulated data over iterations. i.e. 5 iterations -> 5 data. n iteration -> n data. so doing self.data.Close[-1] in next() gets you the last record. but the same is not true for self.__atr, because self.__atr always has full computed set from init(), so you need to use absolute index while accessing atr value from self.__atr.

@zlpatel zlpatel closed this Apr 27, 2021
@zlpatel zlpatel deleted the patch-1 branch April 27, 2021 17:58
@kernc
Copy link
Owner

kernc commented Apr 28, 2021

Continued in #322.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants