Ask me anything
Ithy Logo
Sign in to save

Python Script for Volatility Skew Calculation

A comprehensive script to fetch option chain data and compute implied volatility skew

financial charts and stock options data visualization

Key Highlights

  • Data Acquisition: Retrieve option chain data using reliable sources like Yahoo Finance via the yfinance library.
  • Data Processing: Merge calls and puts and prepare the dataset by extracting strike prices and implied volatilities for each expiration date.
  • Skew Calculation: Compute the volatility skew using linear regression on the implied volatilities across strike prices. Optionally, visualize the skew.

Overview

In options trading, the implied volatility (IV) indicates market expectations regarding the future volatility of the underlying asset. Often, IV is not constant across different strike prices for a given expiration date, leading to the "volatility skew." This script demonstrates how to reach out to financial data providers like Yahoo Finance to retrieve option chain data, extract the implied volatility for both call and put options, and then compute as well as visualize the volatility skew for each expiration date.

Python Script Details

Required Libraries

This script employs several Python libraries:

  • yfinance: For fetching financial data and the option chain.
  • pandas: For efficient data manipulation and organization.
  • numpy: For numerical calculations including regression analysis.
  • scipy: Optionally for advanced regression techniques if needed.
  • matplotlib: For optional visualization of the volatility skew.

Installing Dependencies

Before running the script, ensure that the required libraries are installed. You can install them using pip:

# Install dependencies using pip
pip install yfinance pandas numpy scipy matplotlib

Script Functionality

The script follows these core steps:

  • Fetch Option Chain Data: Using yfinance, fetch option chain data for a selected ticker. Data for each expiration date is stored separately.
  • Data Aggregation: For each expiration, the script combines call and put option data, ensuring that only the necessary columns (strike and implied volatility) are processed.
  • Volatility Skew Calculation: By applying a linear regression on the implied volatility versus strike price, the slope of the line is used as the measure of volatility skew. A positive slope indicates higher volatility for options with higher strike prices, and vice versa.
  • Visualization: Optionally, plot the implied volatility against strike prices for both calls and puts to visually inspect the skew.

The Python Script

import yfinance as yf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

def fetch_option_chain(ticker):
    """
    Fetch the option chain data for a specified ticker from Yahoo Finance.
    The data is organized by expiration dates.
    """
    asset = yf.Ticker(ticker)
    expirations = asset.options
    options_data = {}
    
    for exp in expirations:
        opt = asset.option_chain(exp)
        # Retrieve calls and puts, and add an identifier for each option type
        calls = opt.calls.copy()
        puts = opt.puts.copy()
        calls['optionType'] = 'call'
        puts['optionType'] = 'put'
        
        # Combine call and put data
        chain = pd.concat([calls[['strike', 'impliedVolatility', 'optionType']], 
                           puts[['strike', 'impliedVolatility', 'optionType']]], ignore_index=True)
        
        # Store under the expiration date key
        options_data[exp] = chain
    return options_data

def calculate_volatility_skew(options_data):
    """
    Calculate the volatility skew for each expiration date.
    Skew is computed as the slope from a linear regression of implied volatility vs. strike price.
    """
    skew_results = {}
    
    for exp, data in options_data.items():
        # Remove entries with missing or zero implied volatility
        filtered_data = data[data['impliedVolatility'] > 0].dropna(subset=['impliedVolatility'])
        if len(filtered_data) < 5:
            continue  # skip if insufficient data
        
        strikes = filtered_data['strike'].values
        ivs = filtered_data['impliedVolatility'].values
        
        # Compute linear regression to determine the skew; slope is our skew measure.
        coefficients = np.polyfit(strikes, ivs, 1)
        slope = coefficients[0]
        
        # Save the computed skew, along with additional metrics
        skew_results[exp] = {
            'volatility_skew': slope,
            'mean_iv': np.mean(ivs),
            'median_iv': np.median(ivs)
        }
    return skew_results

def plot_volatility_skew(options_data):
    """
    Plot the implied volatility vs. strike price for each expiration date
    for both call and put options.
    """
    for exp, data in options_data.items():
        # Filter data for non-NaN implied volatility values.
        data = data[data['impliedVolatility'] > 0].dropna(subset=['impliedVolatility'])
        if data.empty:
            continue
        
        plt.figure(figsize=(10, 6))
        # Separate calls and puts for plotting
        calls = data[data['optionType'] == 'call']
        puts = data[data['optionType'] == 'put']
        
        plt.plot(calls['strike'], calls['impliedVolatility'], 'bo-', label='Calls')
        plt.plot(puts['strike'], puts['impliedVolatility'], 'ro-', label='Puts')
        
        plt.title(f'Implied Volatility Skew for Expiration: {exp}')
        plt.xlabel('Strike Price')
        plt.ylabel('Implied Volatility')
        plt.legend()
        plt.grid(True)
        plt.show()

def main():
    # Specify the stock ticker (e.g., AAPL)
    ticker = "AAPL"
    
    # Fetch option chain data
    options_data = fetch_option_chain(ticker)
    
    # Calculate volatility skew for each expiration date
    skew_results = calculate_volatility_skew(options_data)
    
    # Print the results
    print("Volatility Skew Results:")
    for exp, results in skew_results.items():
        print(f"Expiration Date: {exp}")
        print(f"    Volatility Skew (Slope): {results['volatility_skew']:.4f}")
        print(f"    Mean Implied Volatility: {results['mean_iv']:.4f}")
        print(f"    Median Implied Volatility: {results['median_iv']:.4f}")
        print("--------------------------------------------------")
    
    # Optional: Plot the volatility skew for visual inspection
    plot_volatility_skew(options_data)

if __name__ == "__main__":
    main()

Data Summary

The table below summarizes the key aspects of the script:

Component Description
Data Acquisition Fetches option chain data across different expiration dates using Yahoo Finance via yfinance.
Data Processing Merges call and put data, filters based on valid implied volatility values, and organizes by expiration date.
Skew Calculation Uses linear regression (np.polyfit) to determine the slope of the IV curve, representing volatility skew.
Visualization Plots iv vs. strike price for both call and put options, allowing you to visually inspect the skew.
Main Process Integrates data fetching, processing, computation, and optional plotting into a single cohesive program.

References

Recommended Related Queries


Last updated March 9, 2025

AI-assisted research. Sources, methodology and corrections · Source-checked guides and tools · Explore published answers

Ask Ithy AI