I've seen people ask for this a few times, so I'm sharing a simple implementation with comments that should help explain the logic.
The sample SPY strategy in the attached backtest will sell a 30 delta put, expiring in 10 days. After expiration, it will sell another, and so on.
The two core methods (functions) of note are
- InitOptionsAndGreeks: This method initializes options securities settings, chain filters, pricing models, etc
- SelectContractByDelta: This is a convenience method to get an option contracts using delta & expiration
You can reuse SelectContractByDelta anywhere you need to retrieve a contract using delta --eg: you might want to trade SPY covered calls: buying a 60 Delta 180 DTE call contract and then selling 30 Delta 5 DTE calls against it.
The speed / performance of this example can likely be improved, but this should be a useful start for many
Spacetime
Hello, I appreciate that you have shared this simple algorithm.
How do I access the current putContract.Symbol position's expiry date?
I would like to add a logic were the current position is closed 2 days prior to contract's expiry date as I do not want the contracts to get exercised.
Louis Szeto
Hi Spacetime
You can archieve it by the following code in OnData method
If you wish to access it in SellAnOTMPut method in the above algo, you can simply call Strike attribute.
Hope this helps :D!
Cheers
Louis
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.
.ekz.
Slight correction, Louis Szeto: I think you meant the expiry attribute. putContract.Strike will give you the strike price, but he's looking for expiration date.
Louis Szeto
oops sorry, typo. thanks ekz
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.
Spacetime
Thank You!
Carlos Herraiz
I tried to backtest this algorithm but it spended too much time (more than one hour and I stopped it). Do you spend the same time backtesting? Thanks
Varad Kabade
Hi Carlos Herraiz,
In the above algorithm, the data is subscribed at Minute resolution and has a large range of strike prices. This increases the option contract subscription. To speed up the run-time, we can make the option filter more restrictive. For example, only subscribing to contracts within 5/10 strikes instead of 100 or contracts that expire within 30 days instead of 40. Alternatively, we can also use OptionChainProvider to subscribe to contracts that strictly follow our constraints refer to this algorithm on using OptionChainProvider. Refer to the attached backtest.Best,
Varad Kabade
Doug Walton
Thanks for posting this very interesting algorithm, I am new to QC, It has been very instructional to study test it. But, I am having a problem I can't seem to figure out though which happens like this:
1- algo runs and sells the put
2- A the expiration, the put is exercised
3- The algo attempts to sell another put but fails around line 69, which is this
with error message:
the ‘data.ContainsKey("?SPY")’ appears to be a boolean, so I've tried doing some things like this below in the OnData function
But then it sells no puts.
Thanks for any help!
Jack Pizza
Doug Walton I haven't tested it yet, but i think without the ? you should be fine as the statement will return true / false so just SPY should theoretically work.
Jack Pizza
I guess ?SPY is an options symbol? The above still didn't seem to work complained about missing data even with the check.
Doug Walton
Hi @jack-pizza - thanks for responding!
I did finally solve it by creating “self.symbol” (line #11 in the attached backtest) and using an if statement like this (line #42):
That was based on studying some different things in other forum posts. It seems like this is a common problem but is shows up a little differently and has variations on how to solve it. Maybe my solution is not the best but it runs without error.
Now it now stops trading if it gets assigned, But, I'm not going to worry about that. I just wanted to understand how to buy/sell options on the basis of a target delta.
Fred Painchaud
For the sake of All,
1- A “Slice”, the type of data in OnData(), is some sort of “Super Dictionary”. A dictionary is a map of key-value pairs. You access values with keys, like this “my_dict[key]” and you create a mapping or update an existing mapping (overwrite) like this “my_dict[key] = new_value”.
2- Now a “super” dictionary is my own term here. It's because a Slice is really a container of multiple dictionaries. It gives access to many dictionaries.
3- Those multiple dictionaries are unified in some overarching API, accessible via “data.”, that is, the “first level” of the Slice.
4- Thus, when you type “data.ContainsKey()”, you are really asking “is that key present in ANY of the multiple dictionaries you hold?”.
5- Now, which dictionaries are in a Slice?:
a) Bars (read TradeBars)
b) QuoteBars
c) Ticks
d) OptionChains
e) FuturesChains
f) FutureChain
g) Splits
h) Dividends
i) Delistings
j) SymbolChangedEvents
6- Many of those dictionaries CAN BE EMPTY depending on the type of data you are registered to. For instance, if you are only registered to Equity, don't expect OptionChains and FuturesChains.
7- Note that Slice also contains auxiliaries like Splits, Dividends, etc. Not only data. Basically, if dividend was distributed in the last period, data will contain info about it, in the Dividends dictionary.
8- When you write data.Bars.ContainsKey(), you are thus specifically asking the Bars dictionary (TradeBars) about the presence of a key. When you ask “data.ContainsKey()”, you get an answer but you do not know in which dictionary the key is present, and it can be present in multiple dictionaries. For instance, most Equity is available as TradeBars and Quotebars, and thus you have both data in each Slice you receive in OnData. You need to use .Bars or .QuoteBars.
Hope this helps some.
Fred
Doug Walton
Fred Painchaud Great explanation thanks!
.ekz.
Fred Painchaud: brilliant.
I thought to comment and ask if we could have this documented, then I realized it already is documented.
Sharing the link here for others.
An RTM reminder to all, including myself: Read The Manual.
Gv
.ekz. Is there a way to add schedule function so that OnData gets called only at certain time. In reality, option prices at open are difficult to fill with wide spreads. It might be better to execute at say 10am. Thanks
Derek Melchin
Hi Gv,
LEAN passes a Slice to the OnData method at each time step in your algorithm. It's not possible to only run it at a certain time. To run a different method at 10 AM, create a Scheduled Event.
Best,
Derek Melchin
Want to invest in QuantConnect as we build the Linux of quant finance? Checkout our Wefunder campaign to join the revolution.
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.
Gv
Derek Melchin Is there a way to check the Delta of put option position in portfolio and liquidate it if Delta reaches say 45?
Derek Melchin
Hi Gv,
Yes, we just need to iterate through the contracts in the OptionChain to check their delta values and if we are currently invested.
Best,
Derek Melchin
Want to invest in QuantConnect as we build the Linux of quant finance? Checkout our Wefunder campaign to join the revolution.
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.
Nadeem Ahmed
The algorithm still doesnt work. It gives below error. Could someone please help to resolve this?
"Runtime Error: '?SPY' wasn't found in the OptionChains object, likely because there was no-data at this moment in time and it wasn't possible to fillforward historical data. Please check the data exists before accessing it with data.ContainsKey("?SPY") in DataDictionary.cs:line 228"
Louis Szeto
Hi Nadeem
It has too little information for debugging, please attach a backtest/upload the code snippets.
Best
Louis
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.
.ekz.
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!