Hi community members~
I need some help on my codes, which aim to use Implied Volatility v.s. Historical Volatility as indicators to indentify long/short straddle opportunities and create a long/short portfolio rebalanced monthly. The codes did not run through. Would appreciate if anyone could help take a look and diagnose. Cheers!
Duke
Duke He
import pandas as pd from functools import partial from QuantConnect.Securities.Option import OptionPriceModels from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel class DontKnowWhatImDoing(QCAlgorithm): def Initialize(self): self.numberOfLiquidStocks = 20 # Controls the number of stocks in play self.SetWarmUp(timedelta(30)) self.SetStartDate(2020, 10, 1) self.SetEndDate(2020, 12, 31) self.SetCash(100000) self.UniverseSettings.Resolution = Resolution.Hour self.AddUniverse(self.CoarseSelectionFilter) self.UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw # create an empty dictionary to place indicators for future use self.watchList = {} self.SetWarmup(30) self.selected = {} self.portfolios = {} self.SetExecution(ImmediateExecutionModel()) self.next_rebalance = self.Time def CoarseSelectionFilter(self, coarse): if self.Time < self.next_rebalance: return Universe.Unchanged self.sortedByDollarVolume = sorted(coarse, key=lambda c: c.DollarVolume, reverse=True) self.MostLiquid = self.sortedByDollarVolume[:self.numberOfLiquidStocks] return self.MostLiquid def OptionSubscription (self, data): for underlying in self.ActiveSecurities: ## "OR" in self.MostLiquid if underlying.Symbol not in self.watchList: self.watchList[underlying.Symbol] = SymbolData(underlying.Symbol) ## need to create a class "SymbolData" self.watchList[underlying.Symbol].HV = self.STD(underlying.Symbol,30, Resolution.Daily) option = self.AddOption(underlying.Symbol, Resolution.Minute) ## for each stock in universe, pull option chain data option.SetFilter(-1, +1, timedelta(20), timedelta(49)) option.PriceModel = OptionPriceModels.CrankNicolsonFD() # return option # if option.Contracts.Count < 1: # continue atmContract = sorted(option, key = lambda x: abs(x.UnderlyingLastPrice - x.Strike))[0] self.watchList[underlying.Symbol].IV = atmContract.ImpliedVolatility self.watchList[underlying.Symbol].volatility=self.watchList[underlying.Symbol].HV/atmContract.ImpliedVolatility def OnData(self, slice): if self.Time < self.next_rebalance: return sortedByIndicator = dict(sorted(self.watchList.items(),key=lambda x:x[1].volatility,reverse = True)) sorted = pd.DataFrame.from_dict(sortedByIndicator,orient="index") high = sorted[: int(0.1*len(sorted))] low = sorted[-int(0.1*len(sorted)):] self.selected.append(high+low) for i in self.portfolios: if i.Underlying.Symbol not in selected: self.Liquidate(i) high_weight = 1 / len(high) for x in high: callContract = self.atmCall(x[0]) putContract = self.atmPut(x[0]) quantity = self.CalculateOrderQuantity(callContract, -1/2*high_weight/1.2) self.SetHoldings(callContract, -1*quantity) self.SetHoldings(putContract, -1*quantity) low_weight = 1 / len(high) for y in low: callContract = self.atmCall(y[0]) putContract = self.atmPut(y[0]) quantity = self.CalculateOrderQuantity(callContract, 1/2*high_weight/1.2) self.SetHoldings(callContract, 1*quantity) self.SetHoldings(putContract, 1*quantity) self.next_rebalance = Expiry.EndOfMonth(self.Time) def atmCall(self,data): option = self.AddOption(data, Resolution.Minute) option.SetFilter(-1, +1, timedelta(20), timedelta(49)) contracts = self.OptionChainProvider.GetOptionContractList(data, data.Time) calls = [i for i in contracts if i.ID.OptionRight == self.Right.Call and self.DTE - 8 < (i.ID.Date - data.Time).days < self.DTE + 8] atmCall = sorted(calls, key = lambda x: abs(x.UnderlyingLastPrice - x.Strike))[0] return atmCall def atmPut(self,data): option = self.AddOption(data, Resolution.Minute) option.SetFilter(-1, +1, timedelta(20), timedelta(49)) contracts = self.OptionChainProvider.GetOptionContractList(data, data.Time) puts = [i for i in contracts if i.ID.OptionRight == self.Right.Put and self.DTE - 8 < (i.ID.Date - data.Time).days < self.DTE + 8] atmPut = sorted(calls, key = lambda x: abs(x.UnderlyingLastPrice - x.Strike))[0] return atmPut class SymbolData: def __init__(self, symbol): self.symbol = symbol self.HV = None self.IV = None self.volatility = None
Edinson Leandro Medina Alfonzo
I should reccomend you to add more comments to your code, in order to make it easier for other people. Also, try to add more details about what do you think that is the problem.
Regards.
Derek Melchin
Hi Duke,
#1 The `CoarseSelectionFilter` should return a list of symbols, so we should replace
return self.MostLiquid
with
return [c.Symbol for c in self.MostLiquid]
#2 The algorithm declares a variable called `sorted`, but this is a reserved word in Python.
#3 There are several attempts to `append` to a dictionary.
self.selected.append(high+low)
#4 `OptionSubscription` is never called, so `self.watchList` is always empty.
#5 The `atmCall` and `atmPut` methods call `self.AddOption` when `self.OptionChainProvider.GetOptionContractList` will suffice.
For assistance trading options with the securities returned from coarse universe selection, we recommend reviewing this related thread. Additionally, our Introduction to Financial Python tutorial series may be helpful.
Best,
Derek Melchin
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.
Duke He
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!