BSOptionPricing()

Greek Pricing tool for yfinance data (NFA). For development purposes only.

This documentation provides an overview of the Option Greeks Calculator tools, designed to calculate option Greeks using data fetched from Yahoo Finance via the yfinance library. The tool is organized into classes for modularity and reusability, allowing developers to calculate each Greek individually or all together.

Do understand the black Scholes model by itself is a de facto. I do not believe it is an efficient way to price American options, however, it gives us a simple framework for development purposes.

Why did I create this tool?

As you may know, Yahoo Finance does not natively calculate Greeks. These calcualtions are typically done by the data provider or exchange. These data providers generally are pretty costly. For development purposes only (NFA), I have created a simple tool to semi-accurately price Option Greeks using the information given by yfinance. The Option Greeks Calculator script is a Python tool that calculates the Greeks (Delta, Gamma, Theta, Vega, Rho) for options using the Black-Scholes model. It leverages real-time option data from Yahoo Finance via the yfinance library. The script is designed to be flexible and efficient, allowing developers to calculate Greeks for entire option chains or specific options. The calculations are not perfect, nor is any black Scholes pricing model.


Getting Started

Import

Before importing, ensure you have the correct version installed:

pip install marketquant # Must be version 0.4.5 or later

Then:

from marketquant.math import BSOptionPricing # "Black Scholes Option Pricing"

Usage

The script is organized into three main classes:

  • Option: Represents a single option contract and calculates its Greeks.

  • OptionChain: Represents a chain of options for a specific stock, option type, and expiration date.

  • BSOptionPricing: Provides static methods to fetch option data and compute Greeks.

Fetching Option Chain Greeks

To fetch the Greeks for an entire option chain:

from marketquant.math import BSOptionPricing

# Fetch call option Greeks for AAPL with the next expiration date
chain_greeks = BSOptionPricing.get_chain_greeks(
    stock_ticker='AAPL',
    dividend_yield=0.005,
    option_type='c',
    risk_free_rate=0.05  # 5% annual risk-free rate
)

# Display the DataFrame
print(chain_greeks)

Fetching Greeks for a Specific Option

To fetch the Greeks for a specific option:

from marketquant.math import BSOptionPricing


option_greeks = BSOptionPricing.get_option_greeks(
    stock_ticker='SPY',
    expiration_date='2024-01-19',
    option_type='c',
    strike=150,
    dividend_yield=0.0125, # dividend
    risk_free_rate=0.05 # Treasury Rate
)


print(option_greeks)
# Output Example

{'Symbol': 'SPY240919C00570000', 'Strike': 570.0, 'Last Price': 0.9, 'Bid': 0.9, 'Ask': 0.91, 'Implied Volatility': 0.15210808837890627, 'Delta': 0.12930980218494964, 'Gamma': 0.030509112475178887, 'Theta': -0.31520781487961064, 'Vega': 0.09572414164023538, 'Rho': 0.004717777025458283}

Classes and Methods

Option Class

Represents a single option contract and calculates its Greeks.

Initialization

Option(
    option_data: dict,
    underlying_price: float,
    expiration_date: datetime.datetime,
    option_type: str,
    risk_free_rate: float,
    dividend_yield: float
)
  • option_data: Dictionary containing option data from yfinance.

  • underlying_price: Current price of the underlying stock.

  • expiration_date: Expiration date of the option.

  • option_type: 'c' for call options, 'p' for put options.

  • risk_free_rate: Annual risk-free interest rate (as a decimal).

  • dividend_yield: Annual dividend yield of the stock (as a decimal).

Methods

  • delta(): Calculates the option's Delta.

  • gamma(): Calculates the option's Gamma.

  • theta(): Calculates the option's Theta.

  • vega(): Calculates the option's Vega.

  • rho(): Calculates the option's Rho.

  • compute_all_greeks(): Calculates all Greeks and caches the results.

OptionChain Class

Represents a chain of options for a specific stock, option type, and expiration date.

Initialization

OptionChain(
    stock_ticker: str,
    option_type: str,
    dividend_yield: float = 0.0,
    expiration_date: str = None,
    risk_free_rate: float = 0.05
)
  • stock_ticker: Ticker symbol of the stock.

  • option_type: 'c' for call options, 'p' for put options.

  • dividend_yield: Annual dividend yield of the stock (as a decimal).

  • expiration_date: Expiration date in 'YYYY-MM-DD' format. If None, uses the next available expiration date.

  • risk_free_rate: Annual risk-free interest rate (as a decimal).

Methods

  • fetch_options(): Fetches option data using yfinance.

  • compute_all_greeks(): Calculates all Greeks for each option in the chain.

  • get_options_data(): Returns option data as a pandas DataFrame.

  • get_greeks_data(): Returns option data with Greeks as a pandas DataFrame.

BSOptionPricing Class

Provides static methods to fetch option data and compute Greeks.

Static Methods

  • get_chain_greeks(stock_ticker, dividend_yield, option_type, risk_free_rate=0.05): Fetches Greeks for an option chain.

  • get_chain_greeks_date(stock_ticker, dividend_yield, option_type, expiration_date, risk_free_rate=0.05): Fetches Greeks for an option chain with a specific expiration date.

  • get_option_greeks(stock_ticker, expiration_date, option_type, strike, dividend_yield, risk_free_rate=0.05): Fetches Greeks for a specific option.

  • get_expiration_dates(stock_ticker): Returns available expiration dates for a stock's options.

  • get_underlying_price(stock_ticker): Returns the current price of the underlying stock.


Examples

Example 1: Fetching Option Chain Greeks and Saving to JSON

import json
from marketquant.math import BSOptionPricing

# This is how you would fetch call option Greeks for AAPL
chain_greeks = BSOptionPricing.get_chain_greeks(
    stock_ticker='AAPL',
    dividend_yield=0.005, # Example
    option_type='c',
    risk_free_rate=0.05 # Example
)

# Optional: for best practice, make sure data is available
if not chain_greeks.empty:
    # Optional but recommended: Make sure to Convert DataFrame to JSON with .to_json
    json_output = chain_greeks.to_json(orient='records', indent=4)
    # Then, save to JSON file
    with open('aapl_call_options_greeks.json', 'w') as f:
        f.write(json_output)
    print("Option Greeks data for AAPL call options has been saved to 'aapl_call_options_greeks.json'")
else:
    print("No data available to save for AAPL call options.")

Sample Output:

Option Greeks data for AAPL call options has been saved to 'aapl_call_options_greeks.json'

Example 2: Fetching Greeks for a Specific Option

import json
from marketquant.math import BSOptionPricing

# Fetch Greeks for a specific SPY call option
option_greeks = BSOptionPricing.get_option_greeks(
    stock_ticker='SPY',
    expiration_date='2024-09-19',
    option_type='c',
    strike=560.0,
    dividend_yield=0.0,
    risk_free_rate=0.05
)

# Optional: for best practice, make sure data is available
if option_greeks:
    # Make sure to convert the dictionary to JSON
    json_output = json.dumps(option_greeks, indent=4)
    print("Option Greeks data for the specific SPY option:")
    print(json_output)
else:
    print("No data available for the specific SPY option.")

Sample Output:

Option Greeks data for the specific SPY option:
{
    "Symbol": "SPY240919C00560000",
    "Strike": 560.0,
    "Last Price": 4.91,
    "Bid": 4.93,
    "Ask": 4.95,
    "Implied Volatility": 0.15406119384765626,
    "Delta": 0.009739074237783637,
    "Gamma": 3.8877618477386045e-05,
    "Theta": -0.007168591665577183,
    "Vega": 0.016849684947838482,
    "Rho": 0.2348128592243039
}

Notes and Best Practices

Potential Issues and Redundancies

  • Data Availability: Not all stocks have options available. Always check if the options attribute from yfinance is not empty.

  • Expiration Dates: Ensure the provided expiration date is valid and available in the stock's option chain.

  • Implied Volatility: The impliedVolatility from yfinance is provided as a decimal (e.g., 0.3044 for 30.44%). Do not divide it by 100.

  • Time to Expiration (t): Ensure that t is positive to avoid division by zero or complex numbers.

  • Numerical Stability: Small values of v (volatility) or t can lead to numerical instability. Use safeguards like setting a minimum value.

Best Practices

  • Error Handling: Implement robust error handling to catch exceptions and provide meaningful messages.

  • Caching Results: Cache computed Greeks to avoid redundant calculations when the same option data is used multiple times.

  • Data Types: Convert NumPy data types to native Python types when outputting data to ensure compatibility with JSON or other serialization formats.


Conclusion

The Option Greeks Calculator script provides a simple way to calculate option Greeks using real-time data from Yahoo Finance. Although I enjoy giving Black Scholes a hard time, it gives us a basic framework for pricing while developing our system.


Note: Always ensure you comply with the terms of service of data providers like Yahoo Finance when using their data in your applications.

Last updated