Files
quanxiel/course/Full Algorithmic Trading Using Python/12-options-trading.md
T

14 KiB
Raw Blame History

12 · Options Trading(期权入门)

  • 系列:Full Algorithmic Trading Using Python
  • 频道:TradeOptionsWithMe | 本集:Options Trading(期权入门)
  • 时长:15 分 28 秒 | 原视频:https://youtu.be/d3j2zYXKSUs
  • 本地视频:videos/12-options-trading.mp4

🎯 本集要点(中文导读)

本集讲 期权(Options)算法。

  • 背景:QuantConnect 支持约 4000 个标的的美股期权(CBOE);仅支持分钟分辨率。期权按标的/类型/行权价/到期日划分,一个标的可有上百个合约 → 数据量大,效率尤其重要。
  • 方式一:AddOption + SetFilter(本集采用)
    • self.AddOption(underlying) 添加期权数据;SetFilter(...) 限定行权价区间与到期区间。
    • 在 OnData 里遍历 OptionChain(期权链),按行权价、到期、希腊字母(greeks)、持仓量(open interest)、隐含波动率、价格等筛选合约。
  • 方式二:Option Chain Provider(更高效)
    • 只取某标的某日可用合约列表,筛选出目标合约后用 self.AddOptionContract(...) 单独添加——订阅数据少、回测更快。回测过慢时推荐改用此法。
  • 示例 bot:一个简单的期权策略(标的创新高时入场买期权等);self.Plot 可视化。
  • ⚠️ 作者强调:示例参数(到期时间、突破周期等)很随意、交易样本少(43 笔),不可直接实盘;且表现高度依赖标的本身。

📝 完整文稿(英文 · 自动转写)

由本地 ASR(faster-whisper)从视频音轨转录,未人工校对,供检索/精读使用。原始讲解以上方视频为准。

Hello and welcome to the 12th video of my free algorithmic trading course. In this video we will look at how to create options trading algorithms inside of QuantConnect. Currently QuantConnect supports options for about 4000 symbols trading on the CBOE. Unlike for other asset types, QuantConnect only supports minutely resolution for options. Options are divided by underlying asset, option type, strike price and expiration date. This means there can be hundreds of different options for each underlying asset. That's why options trading algorithms usually have to go through a lot more data than simple equity bots which is why it is particularly important to pay special attention to efficiency. If you're not familiar with how options work, I highly recommend checking up my website on which I offer a free course breaking down everything you need to know about options. That said, let's now look at how you can add options data to your algorithm. For this you can use the add option method. Here you can specify for which underlying asset you want to add the option data for. After that you can use set filter to filter which options you want to add. Here you can specify which strike price range around the underlying price and which expiration range you are interested in. Typically you would add the data and apply the filter in the initialised method. To then actually use the option data and trade options you can then iterate through option chain objects in the on data method. You can then filter the option contract in these option chains by strike price, expiration, greeks, open interest, implied volatility, price and more. I will show this in more detail in a few minutes when we get to the coding part of this video. The problem with using add option and set filter is that it adds a lot of option data to your algorithm that you might not actually need if you only intend on trading one or two contracts. That's why QuantConnect also offers an alternative that allows you to only add the data for individual options to boost efficiency and back test speed. This method uses the so called option chain provider. The option chain provider allows you to get the list of available option contracts for one security on a specific date. You can then filter this list to find a particular contract that you are interested in. To then actually trade it you would need to first add its data which you can accomplish with self.add option contract. Typically algorithms using the option chain provider method are much more efficient since they don't subscribe to that much data. So if you find an option algorithm to take too long to back test you could try switching to an option chain provider implementation. In this video I will demonstrate the add option and set filter method by implementing a simple options trading bot. However, I also have another video in which I use the option chain provider that I highly recommend watching after this video. If the demand is there I can also create another video in which I implement a bot that trades more complex multi-legged option strategies such as iron condors, butterflies, strangles, straddles or something else. With that being said let me now quickly present to you the strategy that we will be implementing for this video. For simplicity's sake we will be implementing a simple bot that buys coal options if the underlying assets price breaks out of its one month high price. This means we will use an indicator to keep track of the underlying securities high price. If a new high price is reached we want to buy an add the money coal option. For this strategy we will allocate 5% of our available portfolio capital to the coal option. This 5% might not seem like that much but since you can easily lose your entire investment with options it is actually a very risky strategy. Since we do not want to exercise our options we close them a few days before expiration. That said let's now head over to QuantConnect and start writing some actual code for this trading bot. As always we will go to the lab tab and click on the Create New Algorithm button which will bring us to a sample template algorithm. If you haven't already make sure to create your free QuantConnect account using the link in the description box below. For this video I will choose the back test time frame to be 3 years between 2018 and 2021 but feel free to try out different periods. I will leave the starting cash balance at the default 100,000. Next up we can already add the data for the underlying security using the add equity method. Here I will use Microsoft as the underlying asset but you can of course try it out with different securities. As for the resolution of the data I will specify minutely data since options currently are only supported with minutely data. Furthermore options only support row price data which is why we set the data normalization mode for this equity to row. Thereafter we save Microsoft symbol to the self dot equity variable and set it to be the benchmark for this algorithm. Now we can add the data for the options themselves. In this video I will use the set filter approach but there's a link to a video using the option chain provider in the description box below that I highly recommend watching after this video. So to add the option data we first use the add option method and specify Microsoft as the underlying asset add minutely resolution. Next up we apply the filter to this option data. Here the first two arguments specify how many strike prices above and below the underlying assets price we want to consider. Since we only want to buy at the money cool options we don't need a very wide range here. The next two arguments determine the time span for the expiration dates that are being considered. We will consider options with an expiration date between 20 and 40 days from now. Note that if your filtering criteria is not very specific a lot of option data will need to be added to the algorithm which might make it very slow and inefficient. After that there's only one thing left to do in the initialised method namely add an indicator that keeps track of the high price of Microsoft over the past month. For this we can use the ready to use max help from indicator and specify our equity as the data source. Here we just use daily resolution since smaller intraday changes are not that important for the high price. Since we are interested in the high price we specify that we want to keep track of the high price as the last argument of this method. With that we are now done with the initialised method and can move on to implementing the on data method in which we will implement when to enter and exit positions. However, before we can actually move on to that part we need to check if our max indicator is ready to use. If it is not yet ready we just return. Otherwise, we move on and in the next step we want to check if you already have any open option positions. For this we create a list with any potential open option positions. To create this list we iterate through our portfolio objects and save those that are of the type option and invested. So if this list is not empty it means that we have an open option position. In that case we want to check if there still is enough time until expiration since we do not want to accidentally let it expire and thereby exercise the option. So if there are under 4 days left until expiration we simply liquidate the position. If there is more time left but we still have an open position we just return since we already are invested. In the case that we are not invested we first check whether the underlying price made a new high. We check this by comparing its price to the max indicator's value. If there is a new high we want to open a long call position. To accomplish this we iterate through any available option chains and pass the available option chains on to another method that we will call buy call. So next up let's actually create this custom buy call method. Like the name implies this method is supposed to find the right call option and buy it. For this we first need to filter out the correct option from the option chains that were passed onto this method. Here we first sort the available chains by expiration date and pick the furthest away expiration date. Note that this will always be at least 20 days and at most 40 days from now since we applied a 20 to 40 day filter in the initialised method. Next up we filter out only the call options with this expiration date as we are not interested in trading any pull options for this strategy. After doing that we now just have to sort these call options by the strike price and then we are ready to actually buy the option. We want the option with a strike price that is closest to the underlying price. That's why we sort them from closest to furthest away from the underlying price. If this list is not empty we save the first element of this call contracts list to the variable save.call. This will be the call option that we want to buy. However, before we can actually buy it we need to calculate the order quantity. For this we first divide the available portfolio value by the options price. Since an option controls 100 shares of the underlying asset we then divide this quantity by 100 and multiply it by 5%. We multiply it by 5% because we only want to invest 5% of our portfolio into one position. We round this value down to the nearest integer and then we can finally buy it. Buying the options can be accomplished with self.buy and then passing the option contract and the order quantity. Now we are done with implementing the trade logic for this bot. However, before I backtest it I quickly want to mention that you usually need to pay special attention to option exercising and assignment when developing options trading algorithms. Especially when you're shorting options assignment is a big topic. When buying options and letting them expire, QuantConnect automatically exercises them. This algorithm should never exercise any options since we closed them early enough. However, if you want to handle option exercise differently you can for example do so in the unorder event method. To check that an order event is an exercise you can check the order type. If for example you don't want any shares of the underlying asset in your portfolio you could use self.liquid to close all open positions and reset your portfolio. That said, let's now click on build and backtest to check out this strategy's performance over the specified time frame. If we look at the equity chart we can see that this strategy performed quite well over the specified time frame. However, here it is important to remember that this performance is heavily dependent on the performance of the underlying asset. If the underlying asset which here is Microsoft would not be performing so well this strategy would likely not either. So if you would go with a different underlying or time frame the performance might be much much worse. Besides that you can see that this strategy performs best when the underlying price rises fast. Due to the payoff profile of options this strategy would not be nearly as profitable if the underlying price would climb up slowly or more sideways for a while. However, this strategy does seem to handle market crashes and down trending markets relatively well. This is the case since it does only invest when the underlying price makes a new high which typically does not happen in a down trending market. So in such a market environment this bot just stays flat. Nonetheless I can't recommend actually trading this strategy with real money without any further development and testing. Firstly, a lot of the parameters such as the time to expiration, breakout period and more are chosen very arbitrarily. Furthermore, over this back test time frame that strategy only made 43 trades which isn't a very significant amount that you should use to draw many conclusions from. Nevertheless I hope that this bot gave you a good idea about how to trade options inside of QuantConnect. For another options trading example bot video in which I used the more efficient option chain provider I highly recommend checking out the video that I linked in the description box below. That said, make sure to smash the like button, subscribe and turn on the notification bell for more content like this. Thanks for watching.