Hi everyone!
Here's a simple Credit Put Spread I've put together that tries the following:
Sell the X Delta, buy the strike of the X - 5.
In other words creating an 5 dollar width Credit Put Spread. (If sold at 430, buy 425)
The DTE isn't added yet but preferably be the nearest to 45 DTE
As always it doesn't work as it should. Some help would be tremendously appreciated!
Thank you in advance
Mia Alissi
Based on the information provided in the extracts, it seems like you're trying to implement a credit put spread strategy. While the extracts don't provide a direct example of a credit put spread, they do provide examples of similar strategies such as the bear put spread and the bull put spread.
Here's a general outline of how you might implement this in Python, based on the examples provided:
Initialize
method, set the start date, end date, cash, and Option universe. Here's an example from the bear put spread:OnData
method, call the appropriate OptionStrategies method and then submit the order. Here's an example from the bear put spread:You would need to adjust the
OptionStrategies
method and parameters to match your specific strategy.Please note that this is a general guide and you may need to adjust the code to fit your specific needs. For more detailed information, you can refer to the QuantConnect documentation on Option Strategies.
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.
Soroosh B
Thank you for your answer, familiar with it but the example is for a Bear Put which is the inverse of the Bull Put. Therefor couple parameters should be changed in the provided example!
Mia Alissi
You're correct, the Bear Put Spread is a different strategy from the Bull Put Spread. The Bear Put Spread profits from a decline in the underlying asset price, while the Bull Put Spread profits from a rise in the underlying asset price.
Here's an example of how you might implement a Bull Put Spread in Python, based on the extracts provided:
Initialize
method, set the start date, end date, cash, and Option universe:OnData
method, call theOptionStrategies.BullPutSpread
method and then submit the order:Remember to adjust the
itm_strike
andotm_strike
parameters to match the strike prices you want for your strategy.For more detailed information, you can refer to the QuantConnect documentation on Bull Put Spread.
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.
Soroosh B
Thank you for the answer preferably the strike price have both to be out of the money (OTM) with their respective Delta selection and strike price. In the your last example the strike tempts to be ITM and OTM. Typically we go for a sell OTM and a buy even further down OTM in order to create an spread than results into a credit (because of the 2 different strike selection)
Mia Alissi
I see, you're looking to implement a credit put spread where both options are out-of-the-money (OTM). This strategy involves selling an OTM put option and buying another OTM put option with a lower strike price.
While the extracts provided don't give a direct example of this strategy, you can modify the Bull Put Spread example to suit your needs.
Here's a general outline of how you might implement this in Python:
Initialize
method, set the start date, end date, cash, and Option universe:OnData
method, you would need to select the OTM put options that you want to sell and buy. You would then call theSell
method to sell the higher strike put option and theBuy
method to buy the lower strike put option.Please note that this is a general guide and you may need to adjust the code to fit your specific needs. For more detailed information, you can refer to the QuantConnect documentation on Option Strategies.
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.
Soroosh B
Ok great here's the code I've put together right now from your example by adjusting it for OTM but it seems like it gives me error messages like the following: API Error Message: There are no spare nodes available in your cluster. To launch a new backtest please stop an existing running backtest or add more compute nodes to your organization.
Here's the code can you double check if it's functional and it runs for a backtest. Thank you!!
from AlgorithmImports import *
class BullPutSpreadStrategy(QCAlgorithm):
def Initialize(self) -> None:
self.SetStartDate(2017, 2, 1)
self.SetEndDate(2022, 3, 5)
self.SetCash(500000)
option = self.AddOption("SPY", Resolution.Minute)
self.symbol = option.Symbol
option.SetFilter(self.UniverseFunc)
def UniverseFunc(self, universe: OptionFilterUniverse) -> OptionFilterUniverse:
return universe.IncludeWeeklys().Strikes(-15, 15).Expiration(timedelta(0), timedelta(31))
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
# 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])
otm_strike = put_strikes[0]
otm_strike = put_strikes[-1]
option_strategy = OptionStrategies.BullPutSpread(self.symbol, otm_strike, otm_strike, expiry)
self.Buy(option_strategy, 1)
Mia Alissi
Your code seems to be mostly correct, but there's a small issue with the selection of the out-of-the-money (OTM) put options. You're assigning the
otm_strike
variable twice in a row, which means the second assignment overwrites the first one.Here's the corrected part of your code:
In this corrected code,
lower_otm_strike
is the strike price of the put option you're buying, andhigher_otm_strike
is the strike price of the put option you're selling.As for the error message you're seeing ("API Error Message: There are no spare nodes available in your cluster..."), this is not related to your code. It means that you're trying to run more backtests than your current QuantConnect subscription allows. You can either stop an existing backtest or upgrade your subscription to add more compute nodes.
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.
Soroosh B
Wonderful! It works and I was looking to implement an Stop Loss logic behind it. Like if the floating loss reaches 2.38 times the credit received close the trade an open another one based on the same rules.
Thank you!
Here's the current code I'm looking to add that logic:
from AlgorithmImports import *
class BullPutSpreadStrategy(QCAlgorithm):
def Initialize(self) -> None:
self.SetStartDate(2010, 2, 1)
self.SetEndDate(2023, 3, 5)
self.SetCash(500000)
option = self.AddOption("SPY", Resolution.Minute)
self.symbol = option.Symbol
option.SetFilter(self.UniverseFunc)
def UniverseFunc(self, universe: OptionFilterUniverse) -> OptionFilterUniverse:
return universe.IncludeWeeklys().Strikes(-15, 15).Expiration(timedelta(0), timedelta(31))
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
# 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)
self.Buy(option_strategy, 1)
Soroosh B
Here the version where I added the Stop Loss logic, can you check if there is anything wrong with it?
Thank you!!
from AlgorithmImports import *
class BullPutSpreadStrategy(QCAlgorithm):
def Initialize(self) -> None:
self.SetStartDate(2023, 2, 1)
self.SetEndDate(2023, 7, 17)
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(0), timedelta(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
# 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 <= -2.38 * 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)
Soroosh B
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!