Hello,
I am getting a result I wasn't expecting. What I intend for my code to do is take a universe of equities, make sure the equities have an option chain, then create strangles based on the rules I set in my code. However, the result is the code telling me that an option contract is not an equity.
Can someone assist me with this?
Here is a print out of my full code:
# region imports
from AlgorithmImports import *
from datetime import timedelta
# endregion
class VolatilityStrangleStrategy(QCAlgorithm):
def initialize(self):
self.set_start_date(2014, 6, 17)
self.set_cash(1_000_000)
self.add_universe(self.select_volatile_stocks)
self.universe_settings.resolution = Resolution.DAILY
self.universe_settings.data_normalization_mode = DataNormalizationMode.RAW
self.volatile_stocks = []
self.option_trades = {}
def select_volatile_stocks(self, coarse):
# Define volatility selection logic here
sorted_by_volatility = sorted(coarse, key=lambda x: x.Volume, reverse=True)
self.volatile_stocks = [x.Symbol for x in sorted_by_volatility[:5]]
return self.volatile_stocks
def on_securities_changed(self, changes):
for added in changes.added_securities:
if added.Symbol.SecurityType == SecurityType.EQUITY:
option_contracts = self.option_chain_provider.get_option_contract_list(added.Symbol, self.time)
if len(option_contracts) > 0:
option = self.add_option(added.Symbol)
option.set_filter(-5, 5, timedelta(30), timedelta(60))
self.option_trades[added.Symbol] = None
else:
self.debug(f"No option contracts available for {added.Symbol}")
else:
self.debug(f"Security type for {added.Symbol} is not EQUITY")
def on_data(self, slice):
for symbol, trade in self.option_trades.items():
if trade is None and self.time <= self.end_date - timedelta(days=45):
self.place_strangle(symbol, slice)
elif trade and self.time >= trade["expiration"] - timedelta(days=21):
self.manage_trade(symbol, trade)
def place_strangle(self, symbol, slice):
chain = slice.option_chains.get(symbol)
if not chain:
return
# Identify strikes for the strangle
underlying_price = self.securities[symbol].price
put_contract = min(chain, key=lambda x: abs(x.strike - 0.8 * underlying_price))
call_contract = min(chain, key=lambda x: abs(x.strike - 1.2 * underlying_price))
if put_contract and call_contract:
self.sell(put_contract.Symbol, 1)
self.sell(call_contract.Symbol, 1)
self.option_trades[symbol] = {"put": put_contract.Symbol, "call": call_contract.Symbol, "expiration": put_contract.Expiry}
def manage_trade(self, symbol, trade):
# Logic for decision-making at 21 DTE
put_symbol = trade["put"]
call_symbol = trade["call"]
put_contract = self.portfolio[put_symbol]
call_contract = self.portfolio[call_symbol]
if put_contract.unrealized_profit + call_contract.unrealized_profit >= 0.5 * put_contract.price:
self.liquidate(put_symbol)
self.liquidate(call_symbol)
else:
# Will implement the rolling or other adjustments later
pass
Mia Alissi
Here's the corrected version of your code:
This version includes a correction to convert the
option_contracts
to a list so that its length can be checked.Sources: Long Strangle - QuantConnect.com, Volatility Risk Premium Effect, Short Strangle - QuantConnect.com, Basic Template Option Strategy Algorithm, Handling Data - 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.
Thomas Zaborenko
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!