How to trade Stock Options using Data Science and AI techniques — Making Passive Income Part 2 (Volatility)

Abdalla A. Mahgoub, MSc / CISI
CodeX
Published in
8 min readApr 16, 2023

Introduction

Now that we know how to establish to know the current & historical open interest of stock option on the market which will be a one of the deciding factor to select the most suitable stock to trade stock options , based on our own investment objective that could deliver us a better success rate if we wish to get a cash secured strategy by selling stock options. We managed to get the open interest by adopting data science technologies hence we can easily obtain these information on the fly , please visit my previous paper for more information (https://medium.com/codex/how-to-trade-stock-options-using-data-science-and-ai-techniques-making-passive-income-part-1-caf4fea6dff9)

On this new series we will talk about the second deciding factor , which is volatility. For cash secured strategy options such as selling options , we seek stocks with low volatility and static or stable price range . so without any further duo let’s start deciphering the reason why do we need to seek low volatility in our case , also how big corporation and institution use this to their advantage and not only hedge there over all risk but also enjoy the constant premiums they receive by selling low volatility related stocks.

What is Stock Volatility ?

Stock Volatility or market volatility is simply a mathematical measure of dispersion of returns for given stock or market index or any rate of return of any given asset class over a particular period of time . In another word the volatility of stock signify an increase and decrease in prices for stock. Obviously higher the volatility means the stock is fluctuating at a great magnitude offering a risker play for investor than low volatility stocks, Hence the higher the volatility, the riskier the security.

How can I use volatility to trade stock options ?

Now using volatility readings in your analysis is a crucial step for a successful stock option pick, in my opinion this is part of your intelligent Market research .

A higher volatility means that a security’s value can potentially be spread out over a larger range of values. This means that the price of the security can change dramatically over a short time period in either direction, hence having a high volatility stock option selection is perfect for options traders who are buyers (e.g. Buying calls or puts) .

A lower volatility means that a security’s value does not fluctuate dramatically, and tends to be more steady, Hence seeking a low volatility stock option selection is perfect strategy for stock options traders who are sellers (e.g. Selling calls or puts)

How Volatility is calculated ?

Volatility is often calculated using dispersion methods such as standard deviation or variance. The results are used to measure how much an asset’s prices swing around the mean. In finance, this dispersion is known as standard deviation. I will assume that you already know how to mathematically calculate the standard deviation from historical stock prices. In case you don’t, please visit the following link to refresh your memory about the topic. . (Link : https://www.investopedia.com/terms/s/standarddeviation.asp) , The most important thing to remember about Standard Deviation (STD) is that it is the square root of stock performance variance. Standard deviation is a statistical measurement in finance that, when applied to the annual rate of return of an investment, sheds light on that investment’s historical volatility. Therefore, the greater the STD of a stock, the greater the variance between each price and the mean, which shows a larger price range, indicating a volatile stock. Conversely, a lower STD of a stock signifies lower variance between each price and the mean, indicating a lower stock movement with less volatility.

In finance, it is always a good measure to have a wider picture of volatility and obtain not only annual volatility but also semi-annual, monthly, and weekly volatility, especially for investors who seek to trade stock options.

Below is the formula for calculating volatility on an annual, monthly, and weekly basis :

Let’s implement a quick example of both. Assuming the daily standard deviation of Stock A is around 0.05, and we would like to calculate its annual volatility. We know that in a year, there are 252 trading working days, which represents T. We can simply use the following formula :

If you want to obtain monthly volatility, you should use 1/12 as an input for T. Therefore, your results will look like the following :

For weekly volatility, you should use 1/52 as the input for T, as there are 52 weeks in a year. For semi-annual volatility, use 1/6. I bet you’re starting to get the hang of it.

Congratulations! You have unlocked a new skill on how to calculate different volatility measure for different periods of the year. Let’s use data science techniques to extract stock information and calculate not only annual volatility but also semi-annual, monthly, and weekly volatility altogether at the same time. We will briefly compare the results with other potential stocks that we want to consider as a stock options target. Please note that all the stock names that we will use are for illustration purposes only.

Python Implementation

Similar to our previous paper , to complete this task you need to install yfinance library on your jupyterlab or any other IDEs of your choosing, you can simply type

“Pip install yfinance”

You will also need Pandas , Numpy and matplotlib

Importing libraries

import pandas as pd
import numpy as np
import yfinance as yf

Below, we will extract all the information we need for a specific stock for a period of one year. We will be using the year 2022 as an example, and we will calculate the annual, monthly, semi-annual, and weekly volatility of Exxon stock in 2022.

# Download stock price data for a given symbol
symbol = "XOM"
start_date = "2022-01-01"
end_date = "2022-12-31"
stock_data = yf.download(symbol, start=start_date, end=end_date)

Now that we’ve established that we would like to extract the stock prices of Exxon in 2022, we can calculate the rate of return of the stock over different periods: annual, semi-annual, monthly, and weekly.

We can use the following Python code:

# Calculate the returns of the stock over different time intervals
returns_yearly = stock_data['Adj Close'].resample('Y').ffill().pct_change().dropna()
returns_semiannual = stock_data['Adj Close'].resample('6M').ffill().pct_change().dropna()
returns_monthly = stock_data['Adj Close'].resample('M').ffill().pct_change().dropna()
returns_weekly = stock_data['Adj Close'].resample('W').ffill().pct_change().dropna()

Now that we have obtained all the required returns, we can calculate the variance and then take the square root of that number to obtain the standard deviation, which we can use to calculate the volatility of the stock.

# Calculate the volatility (standard deviation of returns) over each time interval
volatility_yearly = np.std(returns_yearly) * np.sqrt(252)
volatility_semiannual = np.std(returns_semiannual) * np.sqrt(252/2)
volatility_monthly = np.std(returns_monthly) * np.sqrt(252/12)
volatility_weekly = np.std(returns_weekly) * np.sqrt(252/52)

by doing so we have the data needed to print our final result which is our list of volatility for the stock Exxon .

# Print the results
print(f"Yearly volatility: {volatility_yearly:.2%}")
print(f"Semi-annual volatility: {volatility_semiannual:.2%}")
print(f"Monthly volatility: {volatility_monthly:.2%}")
print(f"Weekly volatility: {volatility_weekly:.2%}")

Let’s do the same and replicate these previous steps for another stock and compare , let’s go with TESLA this time .

Interpreting the results

As you can see, the yearly volatility for both EXXON and Tesla is zero, which means that the stock did not move that much around the mean. However, the monthly and weekly volatility present a different story. Exxon shows lower volatility readings in all aspects of volatility, while Tesla is more volatile and swings at a larger scale around the mean than Exxon.

These readings are important to a stock options trader. For a riskier maneuver, a trader will go for Tesla if the investment objective dictates buying calls or puts, while a stable and lower volatility could be a perfect sell puts and cover calls play. In a nutshell, the lower the volatility, the better chance you might get the sweet cash secured premium. The higher the swing and volatility, the better chance you might have of being in the money if you decide to buy puts or calls, of course, depending on the direction of the market and many other factors, such as the fundamental position of the particular stock, and so on.

By analyzing the given volatility data, I would sell some puts of Exxon with a strike price closer to or at 10% volatility, and the period of the contract should be for a week.

Congratulations if you have made it this far! You have just gained the necessary knowledge to read the basic fundamentals needed to select the perfect or more suitable stock for your stock options trading. Now, you can select a stock based on liquidity or open interest, as well as whether the volatility profile meets your expectations or not.

Big corporations and financial institutions, such as Goldman Sachs and JP Morgan, have their own criteria for stock options allocation and selection, based on many different factors. However, most of their stock options and derivatives trading are executed with the intention of hedging the risk of their existing portfolio.

Thank you once again for supporting my Medium channel. Kindly join and follow my channel to stay informed about Part 3 and the rest of the series. In the next article, we will discuss stock option prices and how to interpret the stock’s fundamentals if you decide to purchase them. We will utilize Data Science techniques to analyze the market. Managing your DELTA based on the knowledge and abilities we have gained from previous topics about open interest, liquidity, and volatility profiles, all of those will assist us in minimizing risk and earning profits. Part 3 will be fascinating, so please feel free to connect with me here or add me on LinkedIn and reach out to me.

linkedin: https://www.linkedin.com/in/abdallamahgoub/

--

--

Abdalla A. Mahgoub, MSc / CISI
CodeX
Writer for

Master's in Data Science. Technology Entrepreneur ,Data Scientist, Ops Analyst (ICT),Strategic Business developer, Speaker ,Writer, Full Stack developer