INNER CODE UNIT · Python
SelectContractByDelta
ldt9/PyOptionTrader · research/backtesting/QuantConnect.py:95
def SelectContractByDelta(self, symbolArg, strikeDeltaArg, expiryDTE, optionRightArg=OptionRight.Call):
canonicalSymbol = self.AddOption(symbolArg)
# canonicalSymbol = self.AddIndexOption(symbolArg)
theOptionChain = self.CurrentSlice.OptionChains[canonicalSymbol.Symbol]
theExpiryDate = self.Time + timedelta(days=expiryDTE)
## Filter the Call/Put options contracts
filteredContracts = [x for x in theOptionChain if x.Right == optionRightArg]
## Sort the contracts according to their closeness to our desired expiry
contractsSortedByExpiration = sorted(filteredContracts, key=lambda p: abs(p.Expiry - theExpiryDate),
reverse=False)
closestExpirationDate = contractsSortedByExpiration[0].Expiry
## Get all contracts for selected expiration
contractsMatchingExpiryDTE = [contract for contract in contractsSortedByExpiration if
contract.Expiry == closestExpirationDate]