kernc / backtesting.py

:mag_right: :chart_with_upwards_trend: :snake: :moneybag: Backtest trading strategies in Python.
https://kernc.github.io/backtesting.py/
GNU Affero General Public License v3.0
5.04k stars 987 forks source link

number of days in trade mistmached #1099

Open sandeepbhutani304 opened 6 months ago

sandeepbhutani304 commented 6 months ago

Expected Behavior

Number of days in _trades should be just 1 or 2 but are 389 or anything

Actual Behavior

if records count is 300 then difference is coming out as 389

Steps to Reproduce

I am simply buying at records number 10 and selling at record number 11... using a ii counter code:

    # Define the two MA lags as *class variables*
    # for later optimization
    n1 = 10
    n2 = 20

    ii = 0

    boughtonce=False

    def init(self):
        # Precompute the two moving averages
        self.sma1 = self.I(SMA, self.data.Close, self.n1)
        self.sma2 = self.I(SMA, self.data.Close, self.n2)

    def next(self):
        # print(self.data.Close)
        global ggg

        self.ii += 1
        # if ggg == False:
        if self.ii == 10:
            self.buy()
            ggg = True

        if self.ii == 11:
            self.sell()

        return
GOOG = GOOG[:300]
print(GOOG)
bt = Backtest(GOOG, SmaCross, cash=1000, commission=0)
stats = bt.run()
print(stats, "\n", stats._trades)
`

Output:

`dtype: object
    Size  EntryBar  ExitBar  EntryPrice  ExitPrice      PnL  ReturnPct  EntryTime   ExitTime Duration
0     7        30      299       130.8     345.78  1504.86   1.643578 2004-10-01 2005-10-25 389 days

Additional info