Can you help me code for weekly bull put spreads on SPY. Where a trade is only made when the stock is above the 200 period moving average.
Then can the option spread sell the top leg at the strike that has the closest delta to .35. And then buy the strike right below the sold strike.
Then as edit my code so that the stop loss is triggered when, the trade is down by 150% of the profit (credit) received for the strategy.
from AlgorithmImports import *
class BullPutSpreadStrategy(QCAlgorithm):
def Initialize(self) -> None:
self.SetStartDate(2023, 1, 1)
self.SetEndDate(2023, 12, 1)
self.SetCash(50000)
option = self.AddOption("SPY", Resolution.Minute)
self.symbol = option.Symbol
option.SetFilter(self.UniverseFunc)
# Initialize variables for Stop Loss logic
self.credit_received = 0.0
self.current_option_strategy = None
def UniverseFunc(self, universe: OptionFilterUniverse) -> OptionFilterUniverse:
# return universe.IncludeWeeklys().Strikes(-15, 15).Expiration(timedelta(days=1), timedelta(days=7))
return universe.IncludeWeeklys().Strikes(-1, 1).Expiration(timedelta(days=1), timedelta(days=7))
def OnData(self, slice: Slice) -> None:
if self.Portfolio.Invested: return
# Get the OptionChain
chain = slice.OptionChains.get(self.symbol, None)
if not chain: return
# Get the furthest expiration date of the contracts
# expiry = sorted(chain, key=lambda x: x.Expiry, reverse=True)[0].Expiry
# expiry = [option for option in chain if option.Expiry <= Expiry.EndOfWeek(self.Time)]
expiry = [option for option in chain if option.Expiry <= Expiry.EndOfWeek(self.Time)]
# Select the put Option contracts with the furthest expiry
puts = [i for i in chain if i.Expiry == expiry and i.Right == OptionRight.Put]
if len(puts) == 0: return
# Select the ITM and OTM contract strikes from the remaining contracts
put_strikes = sorted([x.Strike for x in puts])
lower_otm_strike = put_strikes[0]
higher_otm_strike = put_strikes[-1]
option_strategy = OptionStrategies.BullPutSpread(self.symbol, higher_otm_strike, lower_otm_strike, expiry)
# Check if a new trade is entered and update credit received and option strategy
if self.current_option_strategy is None:
self.credit_received = self.Securities[self.symbol].Holdings.UnrealizedProfit
self.current_option_strategy = option_strategy
self.Buy(option_strategy, 1)
else:
# Check the Stop Loss condition and take necessary actions
self.CheckStopLoss()
def CheckStopLoss(self):
# Calculate the current floating loss
current_float_loss = self.Securities[self.symbol].Holdings.UnrealizedProfit - self.credit_received
# Check if the floating loss exceeds 2.38 times the credit received
if current_float_loss <= -1.5 * self.credit_received:
# Close the current option strategy trade
self.Liquidate(self.current_option_strategy)
# Reset the credit received
self.credit_received = 0.0
# Re-enter the trade based on the same rules
# (Add the logic here to set 'self.current_option_strategy' similar to the existing code)
self.Buy(self.current_option_strategy, 1)
Mia Alissi
Sources: Index Option Bull Put Spread Algorithm, Index Option Bear Put Spread Algorithm, Bull Put Spread - QuantConnect.com, Index Option Bull Call Spread Algorithm, Bear Put Spread - QuantConnect.com
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.
Warren chapman
Can you now please help me edit the strategy so it will take multiple trades. As in the back test it only shows that 1 trade is taken.
Warren chapman
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!