### Install Latest Amberdata Derivatives SDK Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/README.md Use this command to install the most recent version of the SDK. ```bash pip install git+https://github.com/amberdata/amberdata-derivatives-sdk.git ``` -------------------------------- ### Install Specific Amberdata Derivatives SDK Version Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/README.md Use this command to install a particular version of the SDK, such as 1.0.8. ```bash pip install git+https://github.com/amberdata/amberdata-derivatives-sdk@1.0.8 ``` -------------------------------- ### Store API Key in .env File Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/README.md Example of how to store your API key in a .env file for dynamic loading. ```bash $ cat .env API_KEY= ``` -------------------------------- ### Initialize Derivatives Client and Get Volatility Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/README.md Initializes the AmberdataDerivatives client with an API key and retrieves volatility term structures for BTC on Deribit. ```python from amberdata_derivatives import AmberdataDerivatives amberdata_client = AmberdataDerivatives(api_key='') amberdata_client.get_volatility_term_structures_constant(currency='BTC', exchange='deribit') ``` -------------------------------- ### Install Jupyter Kernel for Virtual Environment Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/README.md Installs the Jupyter kernel for a Python virtual environment. Ensure your virtual environment is created before running this command. ```bash python -m venv .venv ipython kernel install --user --name=venv ``` -------------------------------- ### Initialize TradFi Client and Get Volatility Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/README.md Initializes the AmberdataTradFi client with an API key and retrieves volatility term structures for MSTR. ```python from amberdata_tradfi import AmberdataTradFi amberdata_client = AmberdataTradFi(api_key='') amberdata_client.get_volatility_term_structures_constant(currency='MSTR') ``` -------------------------------- ### Get Normalized Gamma Exposure (USD) Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/options_flow.ipynb Retrieves and plots the normalized gamma exposure in USD over time for a specified currency. Requires the Amberdata client and pandas/matplotlib. The y-axis is displayed in millions of USD. ```python data = amberdata_client.get_trades_flow_gamma_exposures_normalized_usd(exchange='deribit', currency='btc') data = pd.DataFrame(data['payload']['data']) data.index = pd.to_datetime(data.snapshotTimestamp, unit='ms') plt.figure(figsize=(15, 7)) plt.plot(data.normalizedGammaUSD/1_000_000) plt.axhline(0, linestyle='--', c='r') plt.title("BTC Normalized Gamma Exposure USD: 2022-11-17 to 2024-06-13") plt.ylabel("USD Gamma Exposure ($ Millions)"); ``` -------------------------------- ### Get Gamma Exposure Snapshots Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/options_flow.ipynb Fetches gamma exposure snapshots for a given exchange, currency, and date range. The output is a pandas DataFrame containing detailed information about each snapshot. ```python data = amberdata_client.get_trades_flow_gamma_exposures_snapshots(exchange='deribit', currency='btc', startDate='2024-01-01', endDate='2024-01-02') data = pd.DataFrame(data['payload']['data']) data ``` -------------------------------- ### Get Put/Call Trade Distribution Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/options_flow.ipynb Visualizes the distribution of put and call trades (bought/sold) for a given currency and date range. Requires the Amberdata client and pandas/matplotlib. ```python data = amberdata_client.get_trades_flow_put_call_distribution(exchange='deribit', currency='BTC', startDate='2024-06-07', endDate='2024-06-12') data = pd.DataFrame(data['payload']['data']) plt.figure(figsize=(15, 7)) labels = ['Calls Bought', 'Puts Bought', 'Calls Sold', 'Puts Sold'] plt.pie(data.iloc[:, :4].values.flatten(), labels=labels, autopct='%1.1f%%') plt.title("BTC Put Call Trade Distribution: 2024-06-07 to 2024-06-12"); ``` -------------------------------- ### Get Top 10 Instruments Traded Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/options_flow.ipynb Retrieves and visualizes the top 10 instruments by contract volume for a specified currency and date range. Requires the Amberdata client and pandas/matplotlib. ```python data = amberdata_client.get_instruments_most_traded(exchange='deribit', currency='BTC', startDate='2024-06-07', endDate='2024-06-12') data = pd.DataFrame(data['payload']['data']) plt.figure(figsize=(15, 7)) plt.barh(data.instrument[:10], data.contractVolume[:10][::-1]) plt.title("BTC Top 10 Instruments Traded: 2024-06-07 to 2024-06-12") plt.xlabel("Number of Contracts Traded"); ``` -------------------------------- ### Initialize Derivatives Client with API Key from Environment Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/README.md Loads API key from environment variables using dotenv and initializes the AmberdataDerivatives client. ```python from amberdata_derivatives import AmberdataDerivatives from dotenv import load_dotenv load_dotenv() amberdata_client = AmberdataDerivatives(api_key=os.getenv('API_KEY')) amberdata_client.get_volatility_term_structures_constant(currency='BTC', exchange='deribit') ``` -------------------------------- ### Import Libraries and Initialize SDK Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/options_flow.ipynb Imports necessary libraries and initializes the AmberdataDerivatives client with an API key. Ensure your API key is set as an environment variable. ```python # Import libraries import datetime as datetime import pandas as pd import matplotlib.pyplot as plt import numpy as np import os as os import seaborn as sns import time as time from amberdata_derivatives import AmberdataDerivatives import warnings warnings.filterwarnings("ignore") # Load environment variables from dotenv import load_dotenv load_dotenv() # Retrieve API key API_KEY = os.getenv("API_KEY") ``` ```python amberdata_client = AmberdataDerivatives(api_key=API_KEY) ``` -------------------------------- ### Initialize Derivatives Client with ISO Time Format Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/README.md Initializes the AmberdataDerivatives client with an API key and configures the time format to 'iso'. ```python from amberdata_derivatives import AmberdataDerivatives from dotenv import load_dotenv load_dotenv() amberdata_client = AmberdataDerivatives(api_key=os.getenv('API_KEY'), time_format='iso') amberdata_client.get_volatility_term_structures_constant(currency='BTC', exchange='deribit') ``` -------------------------------- ### Run Unit Tests Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/README.md Command to execute unit tests for the SDK. Ensure you are in the project directory. ```bash python3 -m unittest -v tests/*.py ``` -------------------------------- ### Initialize Amberdata Derivatives Client Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/realized_volatility.ipynb Initializes the AmberdataDerivatives client with the provided API key. ```python amberdata_client = AmberdataDerivatives(api_key=API_KEY) ``` -------------------------------- ### Initialize Amberdata SDK Client Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/svi_curves.ipynb Initializes the AmberdataDerivatives client with an API key and sets up headers for making REST API calls. ```python # Create SDK client amberdata_client = AmberdataDerivatives(api_key=API_KEY) # Headers for REST calls headers = { "accept" : "application/json", "Accept-Encoding" : "gzip", "x-api-key" : API_KEY } ``` -------------------------------- ### Import Libraries and Load Environment Variables Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/svi_curves.ipynb Imports necessary Python libraries and loads API keys from a .env file for authentication with the Amberdata API. ```python # Import libraries import pandas as pd import datetime as dt import numpy as np import os as os import plotly.graph_objects as go import requests as requests from PIL import Image from datetime import date from datetime import timedelta from amberdata_derivatives import AmberdataDerivatives # Load environment variables from dotenv import load_dotenv load_dotenv() # Retrieve API key from .env file API_KEY = os.getenv('API_KEY') # Amberdata Logo AMBERDATA_LOGO = Image.open("amberdata_logo_bug_color_100p.png") ``` -------------------------------- ### Import Libraries and Load Environment Variables Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/realized_volatility.ipynb Imports necessary libraries for data analysis and visualization, and loads API keys from environment variables. ```python # Import libraries import datetime as datetime import pandas as pd import matplotlib.pyplot as plt import os as os from amberdata_derivatives import AmberdataDerivatives import warnings warnings.filterwarnings("ignore") # Load environment variables from dotenv import load_dotenv load_dotenv() # Retrieve API key API_KEY = os.getenv("API_KEY") ``` -------------------------------- ### Visualize BTC Open Interest Distribution Across Strikes Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/open_interest.ipynb Fetches BTC option contract data, separates calls and puts, groups them by strike price to sum open interest, and visualizes the distribution using a bar plot. The plot shows open interest in thousands of contracts for both calls and puts across different strike prices. ```python data = pd.DataFrame(amberdata_client.get_volatility_level_1_quotes(exchange='deribit', currency='btc')['payload']['data']) calls = data[data.putCall=='C'] puts = data[data.putCall=='P'] call_strike_oi = calls.groupby("strike").sum()[['openInterest']].reset_index() put_strike_oi = puts.groupby("strike").sum()[['openInterest']].reset_index() plt.figure(figsize=(15, 7)) sns.barplot(x=call_strike_oi.strike, y=call_strike_oi.openInterest/1000, color='blue', label='Call') sns.barplot(x=put_strike_oi.strike, y= put_strike_oi.openInterest/1000, color='orange', label='Put', bottom=call_strike_oi.openInterest/1000) plt.tight_layout() plt.gca().xaxis.set_major_locator(MaxNLocator(20)) plt.legend() plt.title("BTC Open Interest By Strike as of " + str(data.timestamp[0])) plt.ylabel("Open Interest (Thousands of Contracts)") plt.xlabel("Strike"); ``` -------------------------------- ### Generate and Apply Pylint Configuration Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/README.md Generates a .pylintrc configuration file and then runs pylint on all Python files in the repository. ```bash pylint --generate-rcfile > .pylintrc pylint $(git ls-files '*.py') ``` -------------------------------- ### Fetch and Display Instrument Information Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/options_flow.ipynb Retrieves all available instrument information for a specified exchange and displays the first 10 entries. This is useful for understanding the available trading instruments. ```python # Use this endpoint to get back all of the available instruments on deribit instruments = pd.DataFrame(amberdata_client.get_instruments_information(exchange='deribit')['payload']['data']) instruments.head(10) ``` -------------------------------- ### Fetch and Plot BTC Monthly vs Daily Realized Volatility Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/realized_volatility.ipynb Fetches and plots the ratio of monthly to daily realized volatility for BTC. It selects a subset of data and displays both monthly and daily RV values. ```python data = amberdata_client.get_realized_volatility_monthly_vs_daily_ratio(exchange='gdax', pair='btc_usd') data = pd.DataFrame(data['payload']['data']) data.index = pd.to_datetime(data.timestamp, unit='ms') # only look at a subset of data data = data[:1000][::-1] plt.figure(figsize=(15, 7)) plt.title("BTC Monthly vs Daily RV: " + str(data.index[0]) + " to " + str(data.iloc[-1].name)) plt.plot(data.monthlyHistoricalVolatility, label='Monthly RV') plt.plot(data.dailyHistoricalVolatility30Days, label='Daily RV') plt.ylabel("Realized Volatility (%)") plt.legend(); ``` -------------------------------- ### Import Libraries and Load Environment Variables Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/open_interest.ipynb Imports necessary Python libraries for data manipulation, plotting, and API interaction. It also loads environment variables, specifically the API key, required for authenticating with the Amberdata API. ```python # Import libraries import pandas as pd import matplotlib.pyplot as plt import os as os import seaborn as sns from amberdata_derivatives import AmberdataDerivatives from matplotlib.ticker import MaxNLocator import warnings warnings.filterwarnings("ignore") # Load environment variables from dotenv import load_dotenv load_dotenv() # Retrieve API key API_KEY = os.getenv("API_KEY") ``` -------------------------------- ### Plot BTC DVOL Index Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/implied_volatility.ipynb Fetches and plots the BTC DVOL index using mplfinance. Requires pandas for data manipulation and mplfinance for plotting. ```python dvol = amberdata_client.get_volatility_index(exchange='deribit', currency='btc', startDate='2024-01-01', endDate='2024-06-01', timeInterval='day') dvol = pd.DataFrame(dvol['payload']['data']) dvol.index = pd.to_datetime(dvol.exchangeTimestamp, unit='ms') dvol = dvol[dvol.currency=='BTC'] dvol = dvol.sort_index() mpf.plot(dvol, type='candle', style='charles', figratio=(15, 7), ylabel='DVOL Index', axtitle='BTC DVOL: 2024-01-01 to 2024-06-01', tight_layout=True) ``` -------------------------------- ### Calculate and Plot 24hr Change in BTC Open Interest Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/open_interest.ipynb Fetches daily Open Interest data, calculates the 24-hour change for call and put options by expiration date, and visualizes the results using a bar plot. Requires the amberdata-derivatives-sdk and pandas, matplotlib, and seaborn libraries. ```python data = pd.DataFrame(amberdata_client.get_volatility_level_1_quotes(exchange='deribit', currency='btc', startDate='2024-06-05', endDate='2024-06-08', timeInterval='day')['payload']['data']) data['timestamp'] = pd.to_datetime(data.timestamp) yday = data[data.timestamp == '2024-06-06 00:00:00+00:00'] tday = data[data.timestamp == '2024-06-07 00:00:00+00:00'] tday_c = tday[tday.putCall=='C'].groupby("expirationTimestamp')[['openInterest']].sum() tday_p = tday[tday.putCall=='P'].groupby("expirationTimestamp')[['openInterest']].sum() yday_c = yday[yday.putCall=='C'].groupby("expirationTimestamp')[['openInterest']].sum() yday_p = yday[yday.putCall=='P'].groupby("expirationTimestamp')[['openInterest']].sum() calls = pd.concat([tday_c, yday_c], axis=1) calls.columns = ['today', 'yesterday'] calls['diffs'] = calls.today - calls.yesterday puts = pd.concat([tday_p, yday_p], axis=1) puts.columns = ['today', 'yesterday'] puts['diffs'] = puts.today - puts.yesterday calls['Option Type'] = 'Call' puts ['Option Type'] = 'Put' t = pd.concat([calls, puts], axis=0).reset_index() t['expirationTimestamp'] = pd.to_datetime(t.expirationTimestamp).dt.date plt.figure(figsize=(15, 7)) sns.barplot(data=t, x='diffs', y='expirationTimestamp', hue='Option Type', orient='h') plt.xticks(rotation=45, ha='right'); plt.title("24hr Change in BTC OI By Maturity between " + str(yday.timestamp.iloc[0]) + " to " + str(tday.timestamp.iloc[0])) plt.ylabel("Expiration") plt.xlabel("Change in OI") plt.legend(title='Option Type') ``` -------------------------------- ### 24-Hour Change in BTC Option Open Interest by Strike Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/open_interest.ipynb Analyzes the daily change in open interest for BTC options, comparing today's and yesterday's values for both call and put options at different strike prices. Visualizes the difference using a bar plot. ```python data = pd.DataFrame(amberdata_client.get_volatility_level_1_quotes(exchange='deribit', currency='btc', startDate='2024-06-05', endDate='2024-06-08', timeInterval='day')['payload']['data']) data['timestamp'] = pd.to_datetime(data.timestamp) yday = data[data.timestamp == '2024-06-06 00:00:00+00:00'] tday = data[data.timestamp == '2024-06-07 00:00:00+00:00'] tday_c = tday[tday.putCall=='C'].groupby("strike")[['openInterest']].sum() tday_p = tday[tday.putCall=='P'].groupby("strike")[['openInterest']].sum() yday_c = yday[yday.putCall=='C'].groupby("strike")[['openInterest']].sum() yday_p = yday[yday.putCall=='P'].groupby("strike")[['openInterest']].sum() call = pd.concat([tday_c, yday_c], axis=1) call.columns = ['today', 'yesterday'] call['diffs'] = call.today - call.yesterday put = pd.concat([tday_p, yday_p], axis=1) put.columns = ['today', 'yesterday'] put['diffs'] = put.today - put.yesterday call = call.reset_index() put = put.reset_index() plt.figure(figsize=(15, 7)) sns.barplot(x=call.diffs, y=call.strike, orient = 'h', color='blue', label='Call') sns.barplot(x=put.diffs, y=put.strike, orient = 'h', color='orange', label='Put') plt.gca().yaxis.set_major_locator(MaxNLocator(10)) plt.title("24hr Change in BTC OI By Strike between " + str(yday.timestamp.iloc[0]) + " to " + str(tday.timestamp.iloc[0])) plt.ylabel("Strike") plt.xlabel("Change in OI") plt.legend(title='Option Type') ``` -------------------------------- ### Distribution of BTC Option Open Interest by Expiration Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/open_interest.ipynb Fetches and processes BTC option data to visualize the distribution of open interest across different expiration dates. It separates call and put options, aggregates open interest by expiration, and plots the results. ```python data = pd.DataFrame(amberdata_client.get_volatility_level_1_quotes(exchange='deribit', currency='btc')['payload']['data']) calls = data[data.putCall=='C'] puts = data[data.putCall=='P'] calls['expirationTimestamp'] = pd.to_datetime(calls.expirationTimestamp).dt.date puts ['expirationTimestamp'] = pd.to_datetime( puts.expirationTimestamp).dt.date c = calls.groupby("expirationTimestamp").sum().reset_index() p = puts .groupby("expirationTimestamp").sum().reset_index() c['openInterest'] /= 1000 p['openInterest'] /= 1000 c['op_type'] = 'Call' p['op_type'] = 'Put' t = pd.concat([c, p]).reset_index(drop=True) # Create the bar plot plt.figure(figsize=(15, 7)) sns.barplot(data=t, x='expirationTimestamp', y='openInterest', hue='op_type') plt.xticks(rotation=45, ha='right'); plt.title("BTC Open Interest By Expiration as of " + str(data.timestamp[0])) plt.ylabel("Open Interest (Thousands of Contracts)") plt.xlabel("Expiry") plt.legend(title='Option Type') ``` -------------------------------- ### Visualize BTC Open Interest by Option Type Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/open_interest.ipynb Fetches BTC option contract data from Deribit, calculates the total open interest for calls and puts, and visualizes this data using a horizontal bar chart. The data is displayed in thousands of contracts. ```python data = pd.DataFrame(amberdata_client.get_volatility_level_1_quotes(exchange='deribit', currency='btc')['payload']['data']) oi = data.groupby("putCall").sum() plt.figure(figsize=(15, 7)) plt.barh(['Calls'], oi['openInterest']['C']/1_000, color='orange') plt.barh(['Puts'], oi['openInterest']['P']/1_000, color='blue') plt.title("BTC Open Interest By Option Type as of " + str(data.timestamp[0])) plt.xlabel("Option Contracts (Thousands)") ``` -------------------------------- ### BTC Realized Volatility Cones Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/realized_volatility.ipynb Generates and plots realized volatility cones for BTC over a specified date range. This involves fetching cone data, processing it into a DataFrame, and plotting different percentile levels. Requires datetime, pandas, and the Amberdata client. ```python last_x_days = 120 # 4 months now = datetime.datetime.now() end_date = now.strftime('%Y-%m-%d') start_date = (now + datetime.timedelta(days=-last_x_days)).strftime('%Y-%m-%d') data = amberdata_client.get_realized_volatility_cones(exchange='gdax', pair='btc_usd', startDate=start_date, endDate=end_date) data = pd.DataFrame(data['payload']['data']) data = data.drop(columns=['exchange', 'pair']).T data['dte'] = [ int(''.join([char for char in column.split("_")[1] if char.isdigit()])) for column in data.index ] data['vol_level'] = [data.index[i].split("_")[0] for i in range(len(data))] data.columns = ['rv', 'dte', 'vol_level'] cone_max = data[data.vol_level=='max'].sort_values('dte', ascending=True) cone_min = data[data.vol_level=='min'].sort_values('dte', ascending=True) cone_25p = data[data.vol_level=='p25'].sort_values('dte', ascending=True) cone_50p = data[data.vol_level=='p50'].sort_values('dte', ascending=True) cone_75p = data[data.vol_level=='p75'].sort_values('dte', ascending=True) cone_current = data[data.vol_level=='current'].sort_values('dte', ascending=True) plt.figure(figsize=(15, 7)) plt.plot(cone_max.dte, cone_max.rv, label='Maximum') plt.plot(cone_25p.dte, cone_25p.rv, label='25th Percentile') plt.plot(cone_50p.dte, cone_50p.rv, label='50th Percentile') plt.plot(cone_75p.dte, cone_75p.rv, label='75th Percentile') plt.plot(cone_current.dte, cone_current.rv, label='Current') plt.plot(cone_min.dte, cone_min.rv, label='Minimum') plt.legend() plt.title(f"BTC RV Volatility Cone: {start_date} to {end_date}") plt.ylabel("Realized Volatility (%)") plt.xlabel("DTE") ``` -------------------------------- ### Fetch and Process SVI Data Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/svi_curves.ipynb Fetches SVI data for a given exchange and currency, converts timestamps, calculates underlying price, and sorts the data by timestamp. Use this to prepare SVI data for further analysis. ```python svi = fecth_svi(exchange, currency) svi['timestamp'] = pd.to_datetime(svi['timestamp'], unit='ms') svi['expirationTimestamp'] = pd.to_datetime(svi['expirationTimestamp']).dt.tz_localize(None) svi['underlyingPrice'] = svi['indexPrice'] + svi['forwardDifference'] svi.sort_values('timestamp', ascending=False, inplace=True) svi_ts = svi[svi['timestamp'] == svi['timestamp'].max()-timedelta(hours=0)] svi_ts ``` -------------------------------- ### Fetch and Display Market Data Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/svi_curves.ipynb Fetches and displays market data, including bid/ask prices, implied volatilities, and other relevant metrics. The data is presented in a pandas DataFrame. ```python quotes_and_svi = pd.read_csv("/amberdata/amberdata-derivatives-sdk/jupyter_notebooks/quotes_and_svi.csv") print(quotes_and_svi) ``` -------------------------------- ### Fetch and Process Block Trade Data Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/options_flow.ipynb Fetches block trade data for a specified currency and date range, then processes it to calculate adjusted volume and filter by expiration and strike price. Requires the amberdata_client, pandas, and numpy libraries. ```python data = amberdata_client.get_trades_flow_block_volumes(exchange='deribit', currency='btc', startDate='2024-06-14', endDate='2024-06-21') data = pd.DataFrame(data['payload']['data']) data['expirationTimestamp'] = pd.to_datetime(data.expirationTimestamp, unit='ms') data['adj_volume'] = np.where(data.putCall=='P', -data.contractVolume, data.contractVolume) # only look at expiries that are valid today data = data[data.expirationTimestamp >= pd.to_datetime(time.time(), unit='s')] exps = set(data.expirationTimestamp) store = [] for exp in exps: sub = data[data.expirationTimestamp == exp].reset_index(drop=True) sub = sub[['expirationTimestamp', 'strike', 'putCall', 'adj_volume']] # filter out strikes to allow for better visual plotting sub = sub[(sub.strike > 60_000) & (sub.strike < 80_000)] sub['maturity'] = exp store.append(sub) combined_df = pd.concat(store) pivot_df = combined_df.pivot_table(index='strike', columns='maturity', values='adj_volume', aggfunc='sum').fillna(0) ``` -------------------------------- ### BTC Volatility Seasonality by Day of Week Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/realized_volatility.ipynb Fetches and plots the average realized volatility for BTC by day of the week. Requires the Amberdata client and pandas. ```python data = amberdata_client.get_realized_volatility_seasonality_day_of_week(exchange='gdax', pair='btc_usd', startDate='2024-01-01', endDate='2024-05-01') data = pd.DataFrame(data['payload']['data']) data = data[::-1] plt.figure(figsize=(15, 7)) plt.bar(data.weekday, data.historicalVolatility1day) plt.ylabel("Average Realized Volatility (%)") plt.title("BTC Seasonality: Volatility Day of Week: 2024-01-01 to 2024-05-01"); ``` -------------------------------- ### Plot BTC Delta Ratio (Call - Put) Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/implied_volatility.ipynb Fetches BTC delta surface data from Amberdata and plots the ratio of deltaCall10 to deltaCall25 for different days to expiration (DTE). Requires pandas and matplotlib for data manipulation and plotting. ```python data = amberdata_client.get_volatility_delta_surfaces_constant(currency='BTC', exchange='deribit', startDate='2019-04-01', endDate='2022-06-01', timeInterval='day') data = data['payload']['data'] data = pd.DataFrame(data) s7 = data[data.daysToExpiration==7] s30 = data[data.daysToExpiration==30] s90 = data[data.daysToExpiration==90] plt.figure(figsize=(15, 7)) plt.plot(s7.deltaCall10 / s7.deltaCall25, label='7 DTE ∆10/∆25') plt.plot(s30.deltaCall10 / s30.deltaCall25, label='30 DTE ∆10/∆25') plt.plot(s90.deltaCall10 / s90.deltaCall25, label='90 DTE ∆10/∆25') plt.axhline(1, linestyle='--', c='r', alpha=0.50) plt.legend() plt.title("BTC ∆25/∆35 Ratio [Call - Put]: 2022-01-01 to 2024-06-01") plt.ylabel("Skew [Call - Put] (%)") ``` -------------------------------- ### Analyze and Visualize BTC Put Call Trade Distribution Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/options_flow.ipynb Fetches trade flow volumes for BTC on Deribit, calculates the distribution of put and call trades, and visualizes it as a pie chart. This helps in understanding market sentiment. ```python data = amberdata_client.get_trades_flow_block_volumes(exchange='deribit', currency='btc') data = pd.DataFrame(data['payload']['data']) data = data.groupby("putCall").sum() plt.figure(figsize=(15, 7)) labels = ['Calls', 'Puts'] plt.pie(data.contractVolume.values.flatten(), labels=labels, autopct='%1.1f%%') plt.title("BTC Put Call Trade Distribution Over the Past 7 Days") ``` -------------------------------- ### BTC Volatility Seasonality by Month of Year Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/realized_volatility.ipynb Fetches and plots the average realized volatility for BTC by month of the year. Requires the Amberdata client and pandas. ```python data = amberdata_client.get_realized_volatility_seasonality_month_of_year(exchange='gdax', pair='btc_usd', startDate='2024-01-01', endDate='2024-05-01') data = pd.DataFrame(data['payload']['data']) plt.figure(figsize=(15, 7)) plt.bar(data.month, data.historicalVolatility1day) plt.ylabel("Average Realized Volatility (%)") plt.title("BTC Seasonality: Volatility Month of Year: 2024-01-01 to 2024-05-01"); ``` -------------------------------- ### Scatter Plot ATM IV vs Spot Price Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/implied_volatility.ipynb Fetches decorated volatility data and creates a scatter plot of ATM IV against spot price, colored by days ago. Requires pandas and matplotlib. ```python data = amberdata_client.get_volatility_index_decorated(exchange='deribit', currency='btc', startDate='2024-01-01', endDate='2024-06-01', timeInterval='day') data = pd.DataFrame(data['payload']['data']) data.index = pd.to_datetime(data.exchangeTimestamp, unit='ms') data = data[data.currency=='BTC'] data = data.sort_index() plt.figure(figsize=(15, 7)) scatter = plt.scatter(data.indexPrice, data.atm, c=data.daysAgo, cmap='coolwarm') cbar = plt.colorbar(scatter) cbar.set_label('Days Ago') plt.title("BTC ATM IV & Spot: 2024-01-01 to 2024-06-01") plt.xlabel("Spot Price") plt.ylabel("ATM IV") ``` -------------------------------- ### Fetch and Plot BTC vs. ETH ATM Term Structures Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/implied_volatility.ipynb Fetches the ATM term structure data for BTC and ETH from Deribit and plots them for comparison. This helps visualize how implied volatility changes with time to expiration for both assets. ```python btc = pd.DataFrame(amberdata_client.get_volatility_term_structures_constant(currency='BTC', exchange='deribit')['payload']['data']) eth = pd.DataFrame(amberdata_client.get_volatility_term_structures_constant(currency='ETH', exchange='deribit')['payload']['data']) # plot the atm BTC + ETH term structure plt.figure(figsize=(15, 7)) plt.plot(eth.daysToExpiration, eth.atm, label='ETH') plt.plot(btc.daysToExpiration, btc.atm, label='BTC') plt.title("ATM Term Structure Comparison BTC vs. ETH as of " + str(str(pd.to_datetime(btc.timestamp[0])))) plt.ylabel("Implied Volatility (%)") plt.xlabel("DTE") plt.legend() ``` -------------------------------- ### Define Currency and Exchange Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/svi_curves.ipynb Sets the currency and exchange variables for subsequent API calls. ```python currency = 'BTC' exchange = 'deribit' ``` -------------------------------- ### Plotting SVI Implied Volatility Curves Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/svi_curves.ipynb Generates interactive plots of SVI implied volatility against strike prices for each expiration date. Includes market bid/ask quotes and visualizes the underlying price. Use this for analyzing SVI model fit to market data. ```python import matplotlib.pyplot as plt for expiration in curves.expirationTimestamp.unique(): try: fig = go.Figure() curves_at_expiry = curves[curves['expirationTimestamp'] == expiration].sort_values('strike') quotes_at_expiry = quotes[quotes['expirationTimestamp'] == expiration].sort_values('strike') fig.add_trace(go.Scatter(x=curves_at_expiry.strike, y=curves_at_expiry.sviIv, name="SVI current", legendrank=1, line=dict(color='green'))) fig.add_trace(go.Scatter(x=quotes_at_expiry.strike, y=quotes_at_expiry.bidIv, name='bid', legendrank=3, mode='markers', marker_symbol="cross-thin", marker_color="grey", marker_line_width=1, visible='legendonly')) fig.add_trace(go.Scatter(x=quotes_at_expiry.strike, y=quotes_at_expiry.askIv, name='ask', legendrank=4, mode='markers', marker_symbol="x-thin", marker_color="grey", marker_line_width=1, visible='legendonly')) fig.add_vline( x = curves_at_expiry['underlyingPrice_svi'].values[0], line_dash = 'dashdot', line_width = 2, line_color = "green" ) curves_at_expiry.replace('C', 'call', inplace=True) curves_at_expiry.replace('P', 'put', inplace=True) fig.add_annotation( text = str(pd.to_datetime(curves_at_expiry.timestamp_quotes.values[0])), opacity = 0.5, xref = "paper", yref = "paper", x = 1, y = 0.05, showarrow = False, font = dict(color='green') ) fig.update_layout( title = currency + " - " + str(expiration)[0:10] + " - $" + "{:,}".format(round(curves_at_expiry['underlyingPrice_svi'].values[0], 2)), title_x = 0.50, xaxis_title = "", yaxis_title = "iv", legend = dict(orientation="h", yanchor="bottom", y=-0.20, xanchor="center", x=0.5), template = 'plotly_white' ) fig.layout.images = [dict( source = AMBERDATA_LOGO, xref = "paper", yref = "paper", x = 0.96, y = 1.05, sizex = 0.13, sizey = 0.13, xanchor = "center", yanchor = "bottom" )] fig.update_xaxes(showline=True, showgrid=True, tickmode='auto') fig.show() except Exception as e: print(f"Error: {e}") ``` -------------------------------- ### Merge and Calculate SVI Curves Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/svi_curves.ipynb Merges the generated strikes with the SVI market data and calculates moneyness and SVI implied volatility. Uses forward fill to handle missing values. ```python curves = strikes.merge(quotes_and_svi, left_on=['strike','expirationTimestamp'], right_on=['strike','expirationTimestamp_quotes'],how='left').ffill() curves['moneyness'] = np.log(curves['strike'] / curves['underlyingPrice_svi']) curves['sviIv'] = curves.apply(apply_svi, axis=1) curves ``` -------------------------------- ### Fetch and Display BTC Volatility Metrics Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/implied_volatility.ipynb Retrieves historical volatility metrics for Bitcoin from the Amberdata API for Deribit exchange over the last 7 days. The results are then converted into a pandas DataFrame for easier analysis. ```python data = amberdata_client.get_volatility_metrics(exchange='deribit', currency='btc', daysBack=7) data = pd.DataFrame(data['payload']['data']) data ``` -------------------------------- ### Fetch Level 1 Quotes for SVI Analysis Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/svi_curves.ipynb Retrieves level 1 options quotes for a specific timestamp and currency/exchange. It processes and filters quotes to include only Out-of-the-Money (OTM) put options. ```python def fetch_level_1_quotes(exchange, currency, hours_ago): svi_timestamp_last = pd.to_datetime(svi_ts['timestamp'].unique()[0]).strftime('%Y-%m-%dT%H:%M:%S.%f') svi_timestamp_last_end = (pd.to_datetime(svi_ts['timestamp'].unique()[0]) + timedelta(minutes=1)).strftime('%Y-%m-%dT%H:%M:%S') data = amberdata_client.get_volatility_level_1_quotes( exchange = exchange, currency = currency, startDate = svi_timestamp_last, endDate = svi_timestamp_last_end ) quotes = pd.json_normalize(data['payload']['data']) quotes['timestamp'] = pd.to_datetime(quotes['timestamp'] ).dt.tz_localize(None) quotes['expirationTimestamp'] = pd.to_datetime(quotes['expirationTimestamp']).dt.tz_localize(None) quotes['expirationTimestampDate'] = pd.to_datetime(quotes['expirationTimestamp'].dt.date).dt.tz_localize(None) quotes.loc[(quotes['strike'] < quotes['underlyingPrice']) & (quotes['putCall'] == 'P'), 'moneyness'] = 'OTM' quotes.loc[(quotes['strike'] >= quotes['underlyingPrice']) & (quotes['putCall'] == 'P'), 'moneyness'] = 'ITM' quotes.loc[(quotes['strike'] < quotes['underlyingPrice']) & (quotes['putCall'] == 'C'), 'moneyness'] = 'ITM' quotes.loc[(quotes['strike'] >= quotes['underlyingPrice']) & (quotes['putCall'] == 'C'), 'moneyness'] = 'OTM' return quotes[quotes['moneyness']=='OTM'] ``` -------------------------------- ### Plot BTC 25 Delta RR Skew vs. Spot Price Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/implied_volatility.ipynb Generates a scatter plot to visualize the relationship between BTC's spot price and its 25 Delta Risk Reversal Skew. The color intensity of the points indicates the number of days ago the data was recorded. ```python plt.figure(figsize=(15, 7)) scatter = plt.scatter(data.indexPrice, data.delta25RrSkew, c=data.daysAgo, cmap='coolwarm') cbar = plt.colorbar(scatter) cbar.set_label('Days Ago') plt.title("BTC 25 Delta RR Skew & Spot: 2024-01-01 to 2024-06-01") plt.xlabel("Spot Price") plt.ylabel("25 RR Skew") ``` -------------------------------- ### Plot BTC Volatility Curves Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/implied_volatility.ipynb Retrieves BTC implied volatility quotes from Deribit and plots the implied volatility against strike price for each expiration date. Requires pandas and matplotlib. ```python data = pd.DataFrame(amberdata_client.get_volatility_level_1_quotes(exchange='deribit', currency='btc')['payload']['data']) mats = sorted(set(data.expirationTimestamp)) plt.figure(figsize=(15, 7)) for mat in mats: sub = data[data.expirationTimestamp == mat] sub = sub.sort_values("strike").reset_index(drop=True) plt.plot(sub.strike, sub.markIv, label=mat[:10]) plt.legend() plt.title("BTC Volatility Curves as of " + str(data.timestamp[0])) plt.ylabel("Implied Volatility (%)") plt.xlabel("Strike ($)") ``` -------------------------------- ### Plot BTC ATM vs. Forward Volatility Term Structure Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/implied_volatility.ipynb Fetches and plots the ATM and ATM Forward volatility term structures for BTC. This comparison highlights the difference between the current market price (mark) and the forward-looking implied volatility. ```python # plot BTC atm + atm forward vol plt.figure(figsize=(15, 7)) plt.plot(btc.daysToExpiration, btc.atm, label='Mark') plt.plot(btc.daysToExpiration, btc.fwdAtm, label='Forward', linestyle='--') plt.title("ATM Term Structure Comparison BTC Mark vs Forward Curve " + str(str(pd.to_datetime(btc.timestamp[0])))) plt.ylabel("Implied Volatility (%)") plt.xlabel("DTE") plt.legend() ``` -------------------------------- ### Plot BTC DVOL / ATM 30 DTE IV Ratio Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/implied_volatility.ipynb Creates a line plot showing the ratio of BTC's realized volatility (DVOL) to its at-the-money implied volatility (ATM) for options with 30 days to expiration. This helps visualize changes in market expectations of future volatility. ```python plt.figure(figsize=(15, 7)) plt.plot(data.close/data.atm) plt.title("BTC DVOL / ATM 30 DTE IV: 2024-01-01 to 2024-06-01") plt.ylabel("Butterfly Ratio") ``` -------------------------------- ### Generate Equidistant Strikes Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/svi_curves.ipynb Generates a series of equidistant strike prices for options, based on the provided market data. This is a prerequisite for merging with SVI data. ```python strikes = generate_equidistant_strikes(quotes_and_svi, step_size=50) strikes ``` -------------------------------- ### Fetch and Plot BTC/ETH Correlation Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/realized_volatility.ipynb Fetches realized volatility correlation data between BTC and ETH, processes it into a pandas DataFrame, and plots the 180-day rolling correlation. ```python data = amberdata_client.get_realized_volatility_correlation_beta(exchange='gdax', pair='btc_usd', pair2='eth_usd') data = pd.DataFrame(data['payload']['data']) data.index = pd.to_datetime(data.timestamp, unit='ms') data = data[::-1] plt.figure(figsize=(15, 7)) plt.plot(data.correlation180) plt.title("BTC <> ETH 180 Day RV Rolling Correlation: " + str(data.index[0]) + " to " + str(data.iloc[-1].name)) plt.ylabel("Rolling Correlation") ``` -------------------------------- ### SVI Raw Formula and Application Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/svi_curves.ipynb Defines the raw SVI formula and a function to apply it to a DataFrame row, calculating implied volatility. ```python def svi_raw(params, k): ''' This function is the raw SVI formula. Return volatility (varianace squared) params: list of 5 SVI parameters k: list of log moneyness values to fit ''' a, b, sigma, rho, m = params return np.sqrt(a + b * (rho * (k - m) + np.sqrt((k - m) ** 2 + sigma ** 2))) ``` ```python def apply_svi(row): params = [row['sviA'], row['sviB'], row['sviSigma'], row['sviRho'], row['sviM']] k = row['moneyness'] return svi_raw(params, k) * 100 ``` -------------------------------- ### Generate Equidistant Strikes Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/svi_curves.ipynb Generates a DataFrame with equidistant strike prices for a given set of options quotes, based on a specified step size and expiration timestamp. ```python def generate_equidistant_strikes(quotes, step_size, timestamp_column='expirationTimestamp_quotes'): df = pd.DataFrame() for expiration in quotes[timestamp_column].unique(): quotes_at_expiry = quotes[quotes[timestamp_column] == expiration] strikes = quotes_at_expiry.sort_values('strike')['strike'].unique() # Define the minimum and maximum strikes strike_min = min(strikes) strike_max = max(strikes) # Generate equidistant strikes using np.arange() new_strikes = np.arange(strike_min, strike_max + step_size, step_size) # Add step_size to include max # Create the DataFrame for the generated strikes df_strikes = pd.DataFrame(new_strikes, columns=['strike']) df_strikes['expirationTimestamp'] = expiration # Concatenate the results to the final DataFrame df = pd.concat([df, df_strikes]) return df ``` -------------------------------- ### Fetch and Plot BTC ATM Volatility Surface Over Time Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/implied_volatility.ipynb Retrieves daily ATM volatility data for BTC over a specified date range and plots the volatility surface for different expirations (7, 30, 60, 180 DTE). This visualizes how ATM IV has evolved for various time horizons. ```python data = amberdata_client.get_volatility_delta_surfaces_constant(currency='BTC', exchange='deribit', startDate='2024-01-01', endDate='2024-06-01', timeInterval='day') data = data['payload']['data'] data = pd.DataFrame(data) date = pd.to_datetime(data[data.daysToExpiration==7].timestamp) plt.figure(figsize=(15, 7)) plt.plot(date, data[data.daysToExpiration==7].atm, label='7 DTE') plt.plot(date, data[data.daysToExpiration==30].atm, label='30 DTE') plt.plot(date, data[data.daysToExpiration==60].atm, label='60 DTE') plt.plot(date, data[data.daysToExpiration==180].atm, label='180 DTE') plt.legend() plt.title("BTC ATM Volatility: 2024-01-01 to 2024-06-01") plt.ylabel("ATM IV (%)") ``` -------------------------------- ### BTC Largest 10 Vega Option Trades Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/realized_volatility.ipynb Fetches and plots the top 10 largest option trades by 'sizeVega' for BTC on Deribit for a given date range. Requires datetime, pandas, and the Amberdata client. ```python now = datetime.datetime.now() end_date = now.strftime('%Y-%m-%d') start_date = (now + datetime.timedelta(days=-1)).strftime('%Y-%m-%d') data = amberdata_client.get_options_scanner_top_trades(exchange='deribit', currency='btc', startDate=start_date, endDate=end_date) data = pd.DataFrame(data['payload']['data']) # only look at top 10 & sort by descending order data = data.sort_values("sizeVega", ascending=False).head(10).reset_index(drop=True) plt.figure(figsize=(15, 7)) plt.barh(data.instrument, data.sizeVega[::-1]) plt.title(f"BTC Largest 10 Vega Option Trades: {start_date} to {end_date}") plt.xlabel("Size Vega") ``` -------------------------------- ### Fetch Historical SVI Data Source: https://github.com/amberdata/amberdata-derivatives-sdk/blob/main/jupyter_notebooks/svi_curves.ipynb Fetches historical SVI data for a given currency and exchange from the Amberdata API. Handles potential request errors. ```python def fecth_svi(exchange, currency): try: base_url = "https://api.amberdata.com" endpoint = f"/markets/derivatives/analytics/volatility/svi-historical?currency={currency}&exchange={exchange}&timeInterval=minute" url = f"{base_url}{endpoint}" response = requests.get(url, headers=headers) response.raise_for_status() data = response.json() svi = pd.json_normalize(data['payload']['data']) svi['timestamp'] = pd.to_datetime(svi['timestamp'], unit='ms') svi['atmIv'] = svi_raw([svi['sviA'], svi['sviB'], svi['sviSigma'], svi['sviRho'], svi['sviM']], 0) * 100 svi.sort_values('timestamp', ascending=False, inplace=True) return svi except requests.RequestException as e: print (f"Erorr: {e}") ```