Hello,
I try to backtest totally opposite strategies understand why the same signal if it is on a short or long will not have the same execution price (I do not have any fees).
For instance for the same signal in the long backtest the executed price is 1.12234$ and the short backtest will have a 1.12221$ executed price.
For more details, here is my long example script:
from AlgorithmImports import *
class RSIShortAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2020, 1, 1)
self.SetEndDate(2023, 1, 1)
self.SetCash(100000)
self.symbol = self.AddForex("EURUSD", Resolution.Minute).Symbol
self.rsi = self.RSI(self.symbol, 14, MovingAverageType.Wilders, Resolution.Minute)
# No fees
self.SetSecurityInitializer(self.CustomSecurityInitializer)
self.consolidator = QuoteBarConsolidator(timedelta(minutes=15))
self.SubscriptionManager.AddConsolidator(self.symbol, self.consolidator)
self.consolidator.DataConsolidated += self.OnDataConsolidated
self.quantity = 100000
def CustomSecurityInitializer(self, security):
security.SetFeeModel(ConstantFeeModel(0))
security.SetFillModel(ImmediateFillModel())
security.SetSlippageModel(NullSlippageModel())
def OnDataConsolidated(self, sender, bar):
self.rsi.Update(bar.EndTime, bar.Close)
if not self.rsi.IsReady:
return
current_rsi = self.rsi.Current.Value
self.Debug(f"RSI: {current_rsi}, Time: {self.Time}")
if current_rsi < 30:
if not self.Portfolio[self.symbol].Invested:
self.LimitOrder(self.symbol, self.quantity, bar.Close)
self.Debug(f"Shorted {self.quantity} units of {self.symbol} at {self.Time} with limit price {bar.Close}")
elif current_rsi > 70:
if self.Portfolio[self.symbol].Invested:
self.Liquidate(self.symbol)
self.Debug(f"Closed short {self.symbol} at {self.Time}")
class ConstantFeeModel(FeeModel):
def __init__(self, fee):
self.fee = fee
def GetOrderFee(self, parameters):
return OrderFee(CashAmount(self.fee, "USD"))
For the short stratategy the only change is self.quantity = 100000 becoming : self.quantity = 100000
Here is an extract of the short startegy orders: 2020-01-01 19:15:00 EURUSD Sell Market Fill: $1.12157 USD -100000 Filled +2020-01-01 20:15:00 EURUSD Buy Market Fill: $1.12234 USD 100000 Filled Liquidated
Here is an extract of the long startegy orders: 2020-01-01 19:15:00 EURUSD Buy Market Fill: $1.12168 USD 100000 Filled +2020-01-01 20:15:00 EURUSD Sell Market Fill: $1.12221 USD -100000 Filled Liquidated
Do you know why this is different, it is making me crazy.
Mia Alissi
The difference in execution prices between your long and short strategies could be due to the bid-ask spread. In the forex market, there is always a difference between the bid price (the highest price a buyer is willing to pay) and the ask price (the lowest price a seller is willing to accept). When you place a market order to buy (go long), you pay the ask price. When you place a market order to sell (go short), you receive the bid price. The ask price is always higher than the bid price, which could explain why you're seeing different execution prices for your long and short strategies.
In your code, you're using the
ImmediateFillModel()
, which fills orders with the last trade price. However, in the real market, orders are not always filled at the last trade price due to the bid-ask spread and market volatility. If you want to simulate the impact of the bid-ask spread on your order fills, you could use theSpreadFillModel()
instead.Here's how you can set it in your code:
Please note that this will make your backtest results more realistic, but it could also lead to worse performance due to the impact of the bid-ask spread on your order fills.
For more information on fill models in QuantConnect, you can refer to the documentation.
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
Adrien Aubourg
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!