6.3 KiB
This code uses the OpenBB Terminal SDK to analyze option chains for the SPY ETF. It fetches option chains and expiration dates from the Yahoo Finance source, and identifies the at-the-money (ATM) strike price for SPY options. It then plots the implied volatility (IV) term structure for ATM call options and the IV skew for call options with a specific expiration date. This is useful for visualizing how implied volatility varies across different strike prices and expiration dates, aiding in options trading strategies.
from openbb_terminal.sdk import openbb
import matplotlib.pyplot as plt plt.rc("font", size=10)
Fetch option chains for SPY from Yahoo Finance
chains = openbb.stocks.options.chains( symbol="SPY", source="YahooFinance" )
Fetch expiration dates for SPY options
expirations = openbb.stocks.options.expirations("SPY")
Retrieve the last adjusted closing price for SPY
last = ( openbb .stocks .load("SPY") .iloc[-1]["Adj Close"] )
last
Identify the index of the strike price closest to the last adjusted closing price
idx = ( (chains.strike - last) .abs() .sort_values() .index[0] )
Retrieve the at-the-money (ATM) strike price
atm_strike = ( chains .iloc[idx] .strike )
Filter the option chains to get only the ATM call options
calls = ( chains[ (chains.strike == atm_strike) & (chains.optionType == "call") ] )
Plot the implied volatility term structure for ATM call options
( calls .set_index("expiration") .impliedVolatility.plot(title="IV term structure for ATM call options") )
Filter the option chains to get call options expiring on a specific date
calls = ( chains[ (chains.expiration == expirations[4]) & (chains.optionType == "call") ] )
Plot the implied volatility skew for call options with the specified expiration date
( calls .set_index("strike") .impliedVolatility .plot(title=f"IV term structure for call options expiring {expirations[1]}") )
PyQuant News is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to get started with Python for quant finance. For educational purposes. Not investment advise. Use at your own risk.
