I'm trying to create an strategy that buy when on Monday at the close price but I need to compare the close price of the Monday against the lowest close price of the last two days. If the close price of Monday is lower or equal to the lowest close price of the last two days, I need to buy. I'm working with the SPY ETF.
The sell conditions are based on two conditions. The first one is to sell when the close price is higher than the maximum value of yesterday. When this happen I will sell at the end of day. The second condition is to sell when the first condition doesn't be accomplish during 10 days so after 10 days I will sell at the close price of the 10th day.
The problem is that my strategy run but when I checked the backtest it doesn't show trades, results, anything.
Here is the code:
from AlgorithmImports import *
class ScheduleBuyOnCloseSellOpen(QCAlgorithm):
def Initialize(self):
# set start and end date for backtest
self.SetStartDate(2023, 6, 1)
self.SetEndDate(2023, 8, 4)
# initialize cash balance
self.SetCash(1000000)
# add an equity
self.security = self.AddEquity("SPY", Resolution.Minute)
self.SetWarmUp(10) # Warm up the algorithm for the last 10 days
self.last_two_days_lowest_close = None
self.max_close_yesterday = None
self.days_since_max_close = 0
# use Interactive Brokers model for fees
self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin)
# benchmark against S&P 500
self.SetBenchmark("SPY")
def OnData(self, slice):
for tradeBar in slice.Values:
symbol = tradeBar.Symbol
# Check if the symbol is "SPY"
if symbol != "SPY":
continue
# Get the close price of the tradeBar
close_price = tradeBar.Close
# Check if it's Monday (Weekday == 0) and we have data for the last two days
if self.Time.weekday == 0 and self.last_two_days_lowest_close is not None:
# Compare Monday's close price with the lowest close price of the last two days
if close_price <= self.last_two_days_lowest_close:
self.Debug(f"Monday's close ({close_price}) is lower or equal to the lowest close in the last two days ({self.last_two_days_lowest_close}). Placing a buy order.")
# Place a buy order for SPY
self.SetHoldings("SPY", 1.0)
# At the end of the trading day, check the sell conditions
if self.max_close_yesterday is not None:
# Check if today's close price is higher than the maximum close price of yesterday
if close_price > self.max_close_yesterday:
self.Debug(f"Today's close ({close_price}) is higher than the maximum close of yesterday ({self.max_close_yesterday}). Selling at the end of the day.")
# Place a sell order at the end of the day
self.Liquidate("SPY")
self.max_close_yesterday = None
self.days_since_max_close = 0
else:
self.days_since_max_close += 1
# Check the second sell condition
if self.days_since_max_close >= 10:
self.Debug(f"Second sell condition met after {self.days_since_max_close} days. Selling at the close price of the 10th day.")
# Place a sell order at the end of the day
self.Liquidate("SPY")
self.max_close_yesterday = None
self.days_since_max_close = 0
def OnEndOfDay(self, symbol):
if symbol == "SPY":
# Calculate the lowest close price of the last two days
history = self.History("SPY", 2, Resolution.Daily)
history_spy = [x for x in history if x.Symbol == "SPY"]
if history_spy:
self.last_two_days_lowest_close = min(history_spy, key=lambda x: x.Close).Close
# Calculate the maximum close price of yesterday
history_yesterday = self.History("SPY", 2, Resolution.Daily)
history_spy_yesterday = [x for x in history_yesterday if x.Symbol == "SPY"]
if history_spy_yesterday:
self.max_close_yesterday = max(history_spy_yesterday, key=lambda x: x.Close).Close
What is happening with my code? Thank you in advance
Mia Alissi
Based on the provided code and the information from the extracts, there are a few potential issues that might be causing your strategy not to execute trades.
Time.weekday: In Python,
datetime.weekday()
returns the day of the week as an integer where Monday is 0 and Sunday is 6. In your code, you're usingself.Time.weekday
which is incorrect. It should beself.Time.weekday()
. This might be the reason why your buy condition is not being met.History Request: In your
OnEndOfDay
method, you're making two history requests for the same symbol and the same period. This is redundant and might slow down your algorithm. You can make a single history request and use it to calculate both the lowest close price of the last two days and the maximum close price of yesterday.Resolution: You're using minute resolution for your SPY data but you're making decisions based on daily data. This might cause your algorithm to miss some trades. Consider changing the resolution to daily.
Here's how you can modify your code:
Please note that this is just a suggestion based on the provided extracts and the code you shared. You might need to adjust it according to your specific needs.
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.
Octavio del Sueldo
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!