Skip to content

AssertionError while using TrailingStrategy #322

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

Merged
merged 14 commits into from
Apr 29, 2021
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions backtesting/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -441,13 +441,21 @@ def set_trailing_sl(self, n_atr: float = 6):

def next(self):
super().next()
"""
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 fully computed set from init(),
so we need to use absolute index while accessing atr value from self.__atr.
"""
index = len(self.data)-1
for trade in self.trades:
if trade.is_long:
trade.sl = max(trade.sl or -np.inf,
self.data.Close[-1] - self.__atr[-1] * self.__n_atr)
self.data.Close[index] - self.__atr[index] * self.__n_atr)
else:
trade.sl = min(trade.sl or np.inf,
self.data.Close[-1] + self.__atr[-1] * self.__n_atr)
self.data.Close[index] + self.__atr[index] * self.__n_atr)


# Prevent pdoc3 documenting __init__ signature of Strategy subclasses
Expand Down
1 change: 0 additions & 1 deletion backtesting/test/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ def _read_file(filename):
EURUSD = _read_file('EURUSD.csv')
"""DataFrame of hourly EUR/USD forex data from April 2017 to February 2018."""


def SMA(arr: pd.Series, n: int) -> pd.Series:
"""
Returns `n`-period simple moving average of array `arr`.
Expand Down
4 changes: 1 addition & 3 deletions backtesting/test/_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -858,10 +858,8 @@ def next(self):
super().next()
if not self.position and self.data.Close > self.sma:
self.buy()

stats = Backtest(GOOG, S).run()
self.assertEqual(stats['# Trades'], 51)

self.assertEqual(stats['# Trades'], 57)

class TestUtil(TestCase):
def test_as_str(self):
Expand Down