Skip to content

Trades opened at a price even above highs  #538

@wolfcuring

Description

@wolfcuring

When the SmaCross strategy is fed by E-mini S&P 500 1 minute data, the trades are all "opened in the air", even higher than the high price of the bar. (Actually, all my other strategies are experiencing this, the trades are opened at right conditions, but executed at a wrong price.)

The data looks like this:

2019-03-03 07:30:00 2825.50 | 2827.88 | 2825.50 | 2827.25 | 0
2019-03-03 07:31:00 2827.25 | 2827.38 | 2826.25 | 2826.50 | 0
2019-03-03 07:32:00 2826.50 | 2826.88 | 2825.75 | 2826.00 | 0
2019-03-03 07:33:00 2826.00 | 2826.50 | 2825.50 | 2825.75 | 0
2019-03-03 07:34:00 2825.75 | 2826.00 | 2825.00 | 2825.50 | 0

import pandas as pd
from backtesting import Strategy
from backtesting.lib import crossover
from backtesting import Backtest

class SmaCross(Strategy):
    # Define the two MA lags as *class variables*
    # for later optimization
    n1 = 10
    n2 = 20
    
    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):
        # If sma1 crosses above sma2, close any existing
        # short trades, and buy the asset
        if crossover(self.sma1, self.sma2):
            self.position.close()
            self.buy()
             
bt = Backtest(es, SmaCross, cash=10_000, commission=.002)
stats = bt.run()

Screenshot from 2021-11-21 10-44-57

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionNot a bug, but a FAQ entry

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions