Tutorial
October 22, 2021

Tutorial: How to Pick Options Contracts Using Python

Use IEX Cloud data to create a Python script that helps you write profitable cash-covered put option contracts.

Cloud icon

Krisztian Gyuris

https://iexcloud.io/community/blog/tutorial-how-to-pick-options-contracts-using-python
@iexcloud
https://iexcloud.io/community/blog/tutorial-how-to-pick-options-contracts-using-python
@iexcloud

Use IEX Cloud data to create a Python script that helps you write profitable cash-covered put options contracts.

Options contracts can be a great addition to an investor's toolbelt. If options are understood well and used correctly, they can serve many purposes: as insurance to defend a portfolio against downward price moves, or even as a way to make money up front while waiting to sell or buy a particular stock.

There are hundreds of combinations for how we can use put and call options together, but in this article we will concentrate on one of these strategies: writing cash-covered puts. (“Writing” an options contract just means selling an options contract.)

Let's say you identified one or more stocks that you would like to buy. You have enough money to purchase them, but you would like their price to be a bit lower. As one approach, you might simply wait for the stock to drop in price. In the world of options trading, however, another strategy is to sell a cash-covered put option and get paid a “premium” while waiting to purchase the stock at a lower price.

In this article, you’ll see an example of how you could write a Python script using IEX Cloud data to help you take this second approach.

Disclaimer: This article is not an endorsement of any particular investment strategy and is not investment advice. This is simply a coding exercise and one investor’s approach to using options data from IEX Cloud.

About Options Contracts

Overall, this article is intended for audiences with prior knowledge of options. If you’re relatively new to options, we suggest learning the basics before following this tutorial. For instance, you can get a basic introduction from Investopedia here.

That being said, here’s a very quick review of the key terms and concepts.

An options contract is an agreement between the buyer and seller that in exchange for some money (the “premium”), the buyer acquires the right to buy/sell a given stock (the “underlying”) at a certain price (the “strike price”) on or before a specific date (the “expiry date”).

We can break down that statement into the essential properties of an options contract:

  • Premium: This is the price of the options contract that the seller receives from the buyer. When you’re writing a put options contract, this is how you can earn money up front.
  • Type: This refers to either “put” or “call,” the two major types of options contracts. A “put” gives the right to sell a stock at the strike price, whereas a “call” gives the right to buy a stock at the strike price.
  • Contract size: Each options contract typically represents 100 stock shares.
  • Underlying: This is the underlying security. In our case, this is the stock that our options contract represents.
  • Strike price: This is the price at which that the options contract buyer has the right to sell or buy the stock – regardless of what the market price is.
  • Expiration date: This is the date when the contract expires. For a “put,” if the strike price is below the market price at expiry, then the holder of the contract (most likely) takes no action. The contract seller pockets the premium, and nothing else happens. If the strike price is greater than the market price, then the holder of that contract sells the stocks at the strike price. The contract seller still keeps the premium.


Here is an example to understand this better. At the time of writing this article, the AAPL stock price is at $153.12. By calling the IEX Cloud API, we found a PUT contract that is represented by this subkey: AAPL20211119P00140000

This contract itself can be sold for $3.75 USD.

Let's decode this string. The underlying is Apple (AAPL). The expiration date for this contract is the 19th of November, 2021. This is 80 days away. The strike price is $140.

This means that by selling this put contract – or “writing” the contract – I get to collect a $375 premium (100 shares times $3.75). If at expiration, the stock price is above $140, the holder of the contract probably won’t sell the stocks. Why sell at a price that’s lower than the market price? Either way, I keep the premium.

If the stock price is below $140, I will pay the buyer $14,000 and get the 100 AAPL stock shares and the premium. Overall, my purchase price is going to be $136.25 per share (strike price minus premium) – a better price than the original $153.12!

So if I’d like to do this with other stocks, how can I go about finding options contracts that fit my requirements? That’s where a Python script and data from IEX Cloud come in handy.

Tutorial Overview

This tutorial will show how you can write a simple Python script using IEX Cloud data that searches for profitable put options contracts. Here is the outline of what our script is going to do:

  1. We specify our search parameters and the list of symbols we are interested in.
  2. Next, for each stock symbol on our list, we will do the following:
  • Using the IEX Cloud Quote endpoint, we will download the stock's closing price. This is necessary to calculate the desired strike price for the options contract.
  • Using the Options endpoint, we will download the options contracts where the expiry date is between 20 and 90 days. This is to help us limit the number of options contracts that we evaluate.
  1. With the data downloaded from IEX Cloud API, we will construct a pandas dataframe, so it is easy to do filtering and calculations on our data table.
  2. Next, our script will add a few calculated values as columns to our data table. “Days remaining” will show how many days are left for the options contract. We will also examine “mid-price.” Calculating the mid-price from the options contract's ask and bid will help us set our selling price a bit higher. This is just a nice practice that I personally like to use when trading options.
  3. Then, we will remove call contracts since we are working with puts only.
  4. Next, remove put contracts where the strike price is higher than our ideal strike price. In this tutorial’s example, our search parameter requires that the strike price is 8 percent lower than the current closing price. We will also filter our any contracts that do not pay a high enough premium.
  5. Lastly, we will display the contract that pays us the highest premium.


Writing the Scripts

Once again, our Python script will look like this:

  • Setup: Setting up our environment
  • Parameters: Input parameters that will help us to find the right options contracts.
  • Gather the data
  • Filtering: Filter out options contracts that do not meet our criteria
  • Print out the best contracts

Note: the complete source code is accessible at this github repo.

Setup

To run this script, you will need to have Python v3.6 and pip on your machine. This should already be installed on your computer if you use a Mac, and if you use Windows, I suggest using Anaconda.

To check if you have these installed, issue the following commands from your command line:

Also, make sure that you have the pandas and pyEX libraries installed. pyEX is a third-party library for accessing the IEX Cloud API, and pandas is for manipulating data. To install these libraries, run these commands:

To use the IEX Cloud API to get data, you will need to register for an IEX Cloud account and use the API token generated with your account. For the script to work, please set up this token in an environment variable.

Options data is available with all paid IEX Cloud plans. However, you can also try out scrambled test data from the platform for free using sandbox data (deprecated). If you’re just getting started, this is a great way to try out the API without any cost.

Create an IEX Cloud account

Parameters

Our Python script starts by importing the necessary dependencies and specifying our parameters:

First, we imported a few libraries that we are going to use. Then we define the parameters that we will use to find the best options contracts. (Again, how you want to define the best options contracts is up to you and depends on your investment strategy – the script below is just an example.)

  • symbols: This is a simple string array holding the stock symbols of the stocks we are interested in.
  • min_days and max_days: We will filter for options contracts within a certain window of expiry – for instance, for contracts that will expire in no less than 20 days but no more than 90 days.
  • monthly_profit_perc: This is the expected monthly profit percentage. Here we hope to get at least 1% per month.
  • strike_price_perc: This is the strike price that we find acceptable. If our stock is currently trading at $100 and our strike price percentage is 8%, then only puts below $92 strike price are sufficient for us.
  • today: This is today’s date.

On the following line, we are instantiating the client from pyEX library to access the IEX Cloud API. Next, we’ll start gathering the data.

Gather the Data

In the data-gathering phase, we will loop through our array of symbols and get the expirations for each stock. Then we calculate the days remaining from the contract expiration date, so we only get the options contracts that satisfy our minimum and maximum day requirements.

If the expiration date satisfies our conditions, then the options for that symbol and expiration are downloaded. The optionsDF method is used to generate a pandas dataframe because it makes further data manipulation easier.

Note that each time you pull new data from IEX Cloud, you use credits (link). That’s why IEX Cloud offers a neat feature called Cloud Cache with its paid plans, so the second time you make the same API request it costs only one credit instead of the full credit price.

Filtering

Next, we will add some extra data to our dataframe to help us with the selection. The dataframe has multiple rows and multiple columns, and with each operation, a new column will be added to the dataframe.

First, we added a new column called “days remaining.” This is the same for all the options because we are processing all the contracts for one expiration at a time. Then the mid-price point is calculated by taking the average of the ask and bid. This is going to be the price for the options contract at which we will try to sell.

Next, we calculate the optimal premium paid for 30 days by taking the mid-price, dividing it by the days remaining from the contract, and multiplying by 30. Then the monthly premium percentage is calculated by dividing the 30-day premium by the strike price. Lastly, the stock price is added to the dataframe.

Finally, we append this data to the cached option dataframe:

Once we have processed all suitable expirations for our symbol, we are ready to start dropping contracts that do not satisfy our search criteria. First, we drop the columns from our dataframe that are not relevant for us and sort the rows by their type, strike price, and days remaining.

Next, we separate puts and calls. We are currently interested in puts, so we’ll filter out the calls:

Let's filter out the strike prices that are larger than our target strike price for puts:

Next, we filter out all the puts that don’t pay us the target premium.

Display the Remaining Contracts

Finally, we are ready to display our filtered puts.

First, we check to see if we managed to find any puts to display. Then we drop and reorder the columns and order by the premium. The result for our put finding script with our first symbols looks like the below.

Top put contracts for BABA:

Alternative puts to sell:

Summary

In this short article, we learned how to connect with the IEX Cloud API, get the expirations for a given stock symbol, and find the best put options contracts with the optimal premium paid to us. For more detail, please visit the GitHub repository where I uploaded the complete source code for the script. Let me know if you have any questions or find a bug!

My Personal Details

I want to know your thoughts and opinions on this article. If you find an error in the script, please raise an issue to the linked GitHub repo or contact me @gyurisc on Twitter or visit my site littlebigtomatoes.com if you are interested in more options-related articles.

Resources

Here are resources for your reference:

IEX Cloud Services LLC makes no promises or guarantees herein regarding results from particular products and services, and neither the information, nor any opinion expressed here, constitutes a solicitation or offer to buy or sell any securities or provide any investment advice or service.