### Python Example: Get Equity Options Data Source: https://www.ivolatility.com/api/docs This snippet demonstrates how to use the iVolatility Python client to retrieve equity options data. It shows how to set the API method and call the function with various parameters like symbol, date range, days to expiration, moneyness, delta, and region. ```python getMarketData = ivol.setMethod('/equities/eod/nearest-option-tickers-with-prices') marketData = getMarketData(symbol='TQQQ', startDate='2022-03-15', endDate='2022-03-30', dte=100, moneyness=5, cp='C') marketData = getMarketData(symbol='BMW', dte=100, delta=-.9, cp='P', region='EUROPE') ``` -------------------------------- ### Install ivolatility Python Library Source: https://www.ivolatility.com/api/docs Installs the ivolatility Python library using pip. This is the first step to begin accessing the IVolatility© API with Python. ```bash pip install ivolatility ``` -------------------------------- ### CAPM Model Setup with iVolatility API (Python) Source: https://www.ivolatility.com/api/docs This snippet shows the initial setup for using the Capital Asset Pricing Model (CAPM) with financial data. It imports necessary libraries including numpy, pandas, matplotlib, seaborn, sklearn, and ivolatility, and sets up login parameters for the ivolatility API. This is a precursor to performing portfolio optimization analysis. ```python import numpy as np import pandas as pd import datetime import matplotlib.pyplot as plt import seaborn as sns from sklearn.metrics import r2_score import ivolatility as ivol ivol.setLoginParams(apiKey={your_api_key}) ``` -------------------------------- ### HTTP Request Example for EOD Equity Options Source: https://www.ivolatility.com/api/docs This snippet provides an example of an HTTP request to the iVolatility API for retrieving end-of-day equity options data. It shows the structure of a GET request with query parameters for symbol, trade date, DTE, delta, and option type. ```http GET /equities/eod/stock-opts-by-param?symbol=AAPL&tradeDate=2021-12-16&dteFrom=0&dteTo=30&deltaFrom=0.5&deltaTo=0.8&cp=C®ion=ASIA HTTP/1.1 Host: restapi.ivolatility.com Content-Type: application/json ``` -------------------------------- ### Python Request Examples for EOD Equity Options Source: https://www.ivolatility.com/api/docs These Python examples demonstrate how to use the iVolatility API to retrieve end-of-day equity options data. They show setting the API method and making requests with different parameters, including symbol, trade date, DTE, delta, moneyness, and region. ```python getMarketData = ivol.setMethod('/equities/eod/stock-opts-by-param') marketData = getMarketData(symbol='12',tradeDate='2021-12-16',dteFrom=0,dteTo=30,deltaFrom=0.5,deltaTo=0.8,cp='C',region='ASIA') marketData = getMarketData(symbol='AAPL',tradeDate='2021-12-16',dteFrom=0,dteTo=30,moneynessFrom=-10,moneynessTo=100,cp='C') ``` -------------------------------- ### Retrieve 15:45 Equity Options NBBO Data (HTTP) Source: https://www.ivolatility.com/api/docs This HTTP request example illustrates how to call the iVolatility API to get 15:45 snapshot equity options chain data. It shows the structure of a GET request for a specific symbol and date, or a date range. The API key is a required parameter. ```http GET /equities/eod/options-nbbo_1545?symbol=AAPL&date=2021-12-16 HTTP/1.1 Host: restapi.ivolatility.com apiKey: YOUR_API_KEY GET /equities/eod/options-nbbo_1545?symbol=AAPL&from_=2021-12-10&to=2021-12-17 HTTP/1.1 Host: restapi.ivolatility.com apiKey: YOUR_API_KEY ``` -------------------------------- ### Get Equity Yield Data (HTTP) Source: https://www.ivolatility.com/api/docs Example HTTP request to retrieve the 12-month average dividend yield for an equity index. This demonstrates the structure of a GET request to the iVolatility API. ```http GET https://restapi.ivolatility.com/equities/yield?apiKey=YOUR_API_KEY&symbol=SPX®ion=USA ``` -------------------------------- ### Retrieve EOD Equity Options NBBO Data (HTTP) Source: https://www.ivolatility.com/api/docs This HTTP request example demonstrates how to query the iVolatility API for End of Day (EOD) equity options chain data. It outlines the GET request format for specifying a symbol and date or date range, including the necessary API key. ```http GET /equities/eod/options-nbbo?symbol=AAPL&date=2021-12-16 HTTP/1.1 Host: restapi.ivolatility.com apiKey: YOUR_API_KEY GET /equities/eod/options-nbbo?symbol=AAPL&from_=2021-12-10&to=2021-12-17 HTTP/1.1 Host: restapi.ivolatility.com apiKey: YOUR_API_KEY ``` -------------------------------- ### GET /api/openapi Source: https://www.ivolatility.com/api/docs Downloads the complete OpenAPI specification file in YAML format for integration and validation purposes. ```APIDOC ## GET /api/openapi ### Description Downloads the current API specification in YAML format, useful for automatic SDK generation, CI/CD pipeline validation, and documentation synchronization. ### Method GET ### Endpoint https://restapi.ivolatility.com/api/openapi ### Response #### Success Response (200) - **body** (file) - OpenAPI specification file in YAML format #### Error Response (500) - **message** (string) - Internal server error - failed to read the specification file ``` -------------------------------- ### Find Nearest Option Tickers (HTTP) Source: https://www.ivolatility.com/api/docs This is an HTTP request example for finding the nearest option tickers. It shows a GET request to the relevant endpoint with query parameters such as symbol, days to expiration (dte), moneyness, and call/put type. The response is in JSON format and contains option tickers closest to the specified criteria. ```http GET /equities/eod/nearest-option-tickers?symbol=TQQQ&startingDate=2022-03-15&dte=100&moneyness=5&callPut=C HTTP/1.1 Host: restapi.ivolatility.com ``` -------------------------------- ### Get Upcoming Earnings Calendar Data (Python) Source: https://www.ivolatility.com/api/docs This Python code snippet demonstrates how to fetch upcoming earnings calendar data using the IVolatility API. It shows examples of calling the API with different parameters like stock IDs, symbols, and stock groups. Ensure you have the 'ivol' library installed and configured with your API key. ```python getMarketData = ivol.setMethod('/equities/eod/upcoming-earnings-calendar') marketData = getMarketData(startDate='2022-08-10',endDate='2025-11-18',stockID='1350') #OR: marketData = getMarketData(startDate='2022-08-10', endDate='2025-11-18',symbols='META,AAPL') #OR: marketData = getMarketData(startDate='2025-11-18', endDate='2026-11-18',stockGroup='ALL_USA') ``` -------------------------------- ### Options Pricing with QuantLib and iVolatility API (Python) Source: https://www.ivolatility.com/api/docs This example demonstrates building a Black-Scholes-Merton QuantLib options pricing engine using data fetched from the ivolatility API. It calculates European and American option prices based on specified parameters and visualizes the results against the number of steps. Requires pandas, datetime, QuantLib, matplotlib, statistics, and ivolatility. ```python import pandas as pd import datetime import QuantLib as ql import matplotlib.pyplot as plt from statistics import mean import ivolatility as ivol ivol.setLoginParams(apiKey={your_api_key}) # OR: ivol.setLoginParams(username={your_IVol_username}, password={your_IVol_password}) period = 360 OTMpct = 20 optType = 'C' date_str = '2022-06-30' date = datetime.datetime.strptime(date_str, '%Y-%m-%d') option_type = ql.Option.Call calculation_date = ql.Date(date.day, date.month, date.year) maturity_date = calculation_date + period getMarketData = ivol.setMethod('/equities/eod/stock-prices') spot_price = getMarketData(symbol='AAPL', from_=date_str, to=date_str).at[0, 'close'] getMarketData = ivol.setMethod('/equities/eod/ivs') marketData = getMarketData(symbol='AAPL', from_=date_str, to=date_str) marketData['period'] = pd.to_numeric(marketData['period']) marketData = marketData.loc[(marketData['call/put'] == optType) & (marketData['out-of-the-money_%'] == OTMpct) & (marketData['period'] == period)] strike_price = marketData['strike'].values[0] volatility = marketData['iv'].values[0] dividend_rate = 0.023 risk_free_rate = 0.001 day_count = ql.Actual365Fixed() calendar = ql.UnitedStates() ql.Settings.instance().evaluationDate = calculation_date payoff = ql.PlainVanillaPayoff(option_type, strike_price) settlement = calculation_date am_exercise = ql.AmericanExercise(settlement, maturity_date) american_option = ql.VanillaOption(payoff, am_exercise) eu_exercise = ql.EuropeanExercise(maturity_date) european_option = ql.VanillaOption(payoff, eu_exercise) spot_handle = ql.QuoteHandle( ql.SimpleQuote(spot_price) ) flat_ts = ql.YieldTermStructureHandle( ql.FlatForward(calculation_date, risk_free_rate, day_count) ) dividend_yield = ql.YieldTermStructureHandle( ql.FlatForward(calculation_date, dividend_rate, day_count) ) flat_vol_ts = ql.BlackVolTermStructureHandle( ql.BlackConstantVol(calculation_date, calendar, volatility, day_count) ) bsm_process = ql.BlackScholesMertonProcess(spot_handle, dividend_yield, flat_ts, flat_vol_ts) def binomial_price(option, process, steps): binomial_engine = ql.BinomialVanillaEngine(process, 'crr', steps) option.setPricingEngine(binomial_engine) return option.NPV() steps = range(5, 200, 1) eu_prices = [binomial_price(european_option, bsm_process, step) for step in steps] am_prices = [binomial_price(american_option, bsm_process, step) for step in steps] #theoretical European option price european_option.setPricingEngine(ql.AnalyticEuropeanEngine(bsm_process)) bsm_price = european_option.NPV() print('BSM price:', bsm_price) print('European option:', mean(eu_prices)) print('American option:', mean(am_prices)) plt.plot(steps, am_prices, label='American Option', lw=2, alpha=0.6) plt.plot(steps, eu_prices, label='European Option', lw=2, alpha=0.6) plt.plot([5,200],[bsm_price, bsm_price], 'r--', label='BlackScholesMerton', lw=2, alpha=0.6) plt.xlabel('Steps') plt.ylabel('Price') plt.legend() plt.show() ``` -------------------------------- ### Get MSRB Trades Data (HTTP) Source: https://www.ivolatility.com/api/docs Example HTTP request to retrieve historical trade data for MSRB bonds. This demonstrates the structure of a GET request to the API endpoint, including necessary query parameters like date ranges and identifiers. ```http GET https://restapi.ivolatility.com/fixedincome/eod/msrb-trades?apiKey=YOUR_API_KEY&from=2023-12-24&to=2024-01-30&companyName=gold&CUSIP=38058FAK3&maturityFrom=2023-10-01&maturityTo=2024-10-01&couponFrom=2&couponTo=4.5 ``` -------------------------------- ### Initialize IVolatility API with API Key using Python Source: https://www.ivolatility.com/api/docs This snippet shows how to initialize the IVolatility API client using an API key. This is a prerequisite for making subsequent API calls. It requires the 'ivolatility' library. ```python import ivolatility as ivol ivol.setLoginParams(apiKey={your_api_key}) ``` -------------------------------- ### Get Upcoming Earnings Calendar Data (HTTP) Source: https://www.ivolatility.com/api/docs This HTTP request example shows how to retrieve upcoming earnings calendar data from the IVolatility API. It illustrates a GET request to the specified endpoint with query parameters for date ranges and stock identifiers. This can be used with any HTTP client. ```http GET /equities/eod/upcoming-earnings-calendar?startDate=2022-08-10&endDate=2025-11-18&stockID=1350 HTTP/1.1 Host: restapi.ivolatility.com GET /equities/eod/upcoming-earnings-calendar?startDate=2022-08-10&endDate=2025-11-18&symbols=META,AAPL HTTP/1.1 Host: restapi.ivolatility.com GET /equities/eod/upcoming-earnings-calendar?startDate=2025-11-18&endDate=2026-11-18&stockGroup=ALL_USA HTTP/1.1 Host: restapi.ivolatility.com ``` -------------------------------- ### POST /api-keys Source: https://www.ivolatility.com/api/docs Create a new API key by providing user credentials. ```APIDOC ## POST /api-keys ### Description Creates a new API key linked to a specific name for the authenticated user. ### Method POST ### Endpoint /api-keys ### Request Body - **username** (string) - Required - Your IVolatility username - **password** (string) - Required - Your IVolatility password - **api_key_name** (string) - Required - A custom name for the new API key ### Request Example { "username": "your_ivol_username", "password": "your_ivol_password", "api_key_name": "my_trading_app" } ### Response #### Success Response (200) - **api_key** (string) - The newly generated API key #### Response Example { "api_key": "ivol_live_xxxxxxxxxxxx" } ``` -------------------------------- ### Example Usage of Bearer Token Source: https://www.ivolatility.com/api/docs Demonstrates how to use the obtained bearer token for authentication in subsequent API requests. The token should be included in the 'Authorization' header. ```http GET /api/v1/some/endpoint Authorization: Bearer YOUR_GENERATED_TOKEN ``` -------------------------------- ### GET /equities/eod/upcoming-earnings-calendar Source: https://www.ivolatility.com/api/docs Retrieves a forward-looking earnings calendar with event dates, tickers, market cap, and analyst estimates for upcoming corporate reports. Requires a start date and end date, along with one of symbols, stockID, or stockGroup. ```APIDOC ## GET /equities/eod/upcoming-earnings-calendar ### Description Retrieves a forward-looking earnings calendar providing event dates, tickers, market cap, and analyst estimates for upcoming corporate reports. ### Method GET ### Endpoint /equities/eod/upcoming-earnings-calendar ### Parameters #### Query Parameters - **apiKey** (string) - Required - REST API apiKey - **startDate** (string) - Required - Example: startDate=2021-12-24. Minimum earning date. - **endDate** (string) - Required - Example: endDate=2021-12-30. Maximum earning date. - **symbols** (Array of strings) - Optional - Example: symbols=AAPL,META. Equity tickers separated by commas. If parameter is not provided then endpoint returns all available equities. Parameters `symbols` OR `stockID` OR `stockGroup` are required. - **stockID** (Array of strings) - Optional - Example: stockID=31505,31699,31333,31700,31704,31705,31701,31706,31707. Internal IVOL identifiers. Parameter values are separated by commas if multiple values are specified. Parameters `symbols` OR `stockID` OR `stockGroup` are required. - **stockGroup** (any) - Optional - Enum: "ALL_ETFS", "ALL_US_INDEXES", "ALL_US_STOCKS", "ALL_USA", "B3_STOCKS", "CAC_STOCKS", "CANADIAN_STOCKS", "DAX_STOCKS", "DJIA_STOCKS", "DJX", "EUROPIAN_STOCKS", "MSH_STOCKS", "NASDAQ_100_STOCKS", "NSE_STOCKS", "OEX_STOCKS", "OSX_STOCKS", "RUSSELL_2000_STOCKS", "SOX_STOCKS", "SP500_STOCKS", "SX5E", "TOP200_OPTIONS_OPEN_INTEREST", "TOP200_OPTIONS_VOLUME", "TX60", "USA_WEEKLIES". Parameters `symbols` OR `stockID` OR `stockGroup` are required. ### Responses #### Success Response (200) OK #### Error Responses - **204**: No data found for requested data - **400**: Parameters are not valid - **401**: Authentication problems - **403**: No access to data - **500**: Internal server error ### Request Example (Python) ```python getMarketData = ivol.setMethod('/equities/eod/upcoming-earnings-calendar') marketData = getMarketData(startDate='2022-08-10', endDate='2025-11-18', stockID='1350') #OR: marketData = getMarketData(startDate='2022-08-10', endDate='2025-11-18', symbols='META,AAPL') #OR: marketData = getMarketData(startDate='2025-11-18', endDate='2026-11-18', stockGroup='ALL_USA') ``` ### Response Example (JSON) ```json { "status": { "executionTime": 1772, "recordsFound": 234, "code": "PENDING", "urlForDetails": "https://restapi.ivolatility.com/data/info/B2FC976D-7AB4-41B4-ADDD-89460B67E5C8" }, "query": { "requestUUID": "B2FC976D-7AB4-41B4-ADDD-89460B67E5C8" }, "data": [ { "earning_date": "2024-09-05", "stock_id": 25301, "market_cap": 4301367296, "estimate": 0.59, "stock_price": 45.97, "implied_move": 15.55 } ] } ``` ``` -------------------------------- ### Subscribe to Options IV Surface via WebSocket Source: https://www.ivolatility.com/api/docs Demonstrates how to initiate a subscription to the IV_SURFACE topic using a JSON payload. This requires an API key and specific parameters for symbols, terms, and option types. ```JSON { "eventType": "SUBSCRIBE", "headers": { "topic": " IV_SURFACE ", "apiKey": "{api_key}" }, "body": { "symbols": ["VIX","SPX","RUT"], "terms": ["7", "14", "30"], "otms": ["30","60"], "callPut": "C" } } ``` -------------------------------- ### Get 15:45 Implied Dividend Yield (Python) Source: https://www.ivolatility.com/api/docs Retrieves 15:45 snapshot proprietary implied dividends calculations for US ETFs. Requires an API key, symbol, start date, and end date. This data is calculated using ATM options and call-put parity. ```Python getMarketData = ivol.setMethod('/equities/1545-implied-yield') marketData = getMarketData(symbol='DIA' , startDate='2023-11-01', endDate='2023-11-10') ``` -------------------------------- ### Get Single Option Raw IV and Greeks (HTTP) Source: https://www.ivolatility.com/api/docs This HTTP request example shows how to fetch raw implied volatility and Greeks for a single options contract. It requires parameters such as symbol, date, expiration date, strike price, option type, and minute type. ```http getMarketData = ivol.setMethod('/equities/intraday/single-equity-option-rawiv') marketData = getMarketData(symbol='SPY', date='2021-09-20', expDate='2022-06-17', strike='450', optType='CALL', minuteType='MINUTE_15') ``` -------------------------------- ### Create and Use IVolatility API Key Source: https://www.ivolatility.com/api/docs Creates a new API key for your IVolatility account (up to 5 keys allowed) using your username and password, then sets this API key for authentication. API keys provide a more persistent authentication method than tokens. ```python apiKey = ivol.createApiKey(nameKey = 'your_apiKey_name',username={your_IVol_username}, password={your_IVol_password}) ivol.setLoginParams(apiKey=apiKey) ``` -------------------------------- ### Get 15:45 Implied Dividend Yield (HTTP) Source: https://www.ivolatility.com/api/docs Retrieves 15:45 snapshot proprietary implied dividends calculations for US ETFs using HTTP requests. Requires an API key, symbol, start date, and end date. This data is calculated using ATM options and call-put parity. ```HTTP GET /equities/1545-implied-yield?symbol=DIA&startDate=2023-11-01&endDate=2023-11-10 HTTP/1.1 Host: restapi.ivolatility.com apiKey: YOUR_API_KEY ``` -------------------------------- ### Retrieve Trading Calendar Data using Python Source: https://www.ivolatility.com/api/docs Demonstrates how to initialize the trading calendar method and fetch data for a specific date range. Requires the iVolatility client library and valid API credentials. ```python getMarketData = ivol.setMethod('/equities/trading-calendar') marketData = getMarketData(startDate='2025-01-01', endDate='2030-12-31') ``` -------------------------------- ### Retrieve Market Data via iVolatility API Source: https://www.ivolatility.com/api/docs Demonstrates how to initialize the market data method and perform a query using a stock group and date range. The input requires an API key and specific filtering parameters to return the desired equity data. ```python getMarketData = ivol.setMethod('/equities/stock-market-data') marketData = getMarketData(stockGroup='ALL_USA', from='2025-12-14', to='2025-12-15') ``` -------------------------------- ### Configure iVolatility Websocket Subscription Source: https://www.ivolatility.com/api/docs Sets up the template and connection parameters for subscribing to real-time market data streams from the iVolatility API. ```python import json import websocket WEBSOCKET_URL = "wss://restapi.ivolatility.com/v1/ws" REQUEST_TEMPLATE = { "eventType": "SUBSCRIBE", "headers": { "topic": "OPTIONS_RAWIV_FV", "apiKey": "{api_key}" }, "body": { "symbols": [ "SPX","VIX" ] } } ``` -------------------------------- ### Retrieve EOD Option Series on Date (HTTP) Source: https://www.ivolatility.com/api/docs This is an HTTP request example for retrieving End-of-Day (EOD) option series data. It shows the structure of a GET request to the specified endpoint with query parameters for symbol, expiration range, strike range, call/put type, and the trading date. The response is expected in JSON format. ```http GET /equities/eod/option-series-on-date?symbol=AAPL&expFrom=2022-10-21&expTo=2022-10-21&strikeFrom=100&strikeTo=105&callPut=C&date=2022-02-16 HTTP/1.1 Host: restapi.ivolatility.com ``` -------------------------------- ### Retrieve Equity Options Raw IV Data via Python SDK Source: https://www.ivolatility.com/api/docs Demonstrates how to initialize the API method and fetch options data for a specific symbol using either a single date or a date range. Requires the iVolatility Python client library. ```python getMarketData = ivol.setMethod('/equities/eod/options-rawiv_1545') marketData = getMarketData(symbol='AAPL', date='2021-12-16') marketData = getMarketData(symbol='AAPL', from_='2021-12-10', to='2021-12-17') ``` ```python getMarketData = ivol.setMethod('/equities/eod/options-rawiv') marketData = getMarketData(symbol='AAPL', date='2021-12-16') marketData = getMarketData(symbol='AAPL', from_='2021-12-10', to='2021-12-17') ``` -------------------------------- ### Download OpenAPI Specification Source: https://www.ivolatility.com/api/docs Retrieves the complete API specification in YAML format, useful for SDK generation, CI/CD validation, and documentation sync. ```http GET /api/openapi HTTP/1.1 Host: restapi.ivolatility.com ``` ```bash curl -X GET https://restapi.ivolatility.com/api/openapi ``` ```python import requests response = requests.get('https://restapi.ivolatility.com/api/openapi') ``` -------------------------------- ### Fetch Options Chain and Market Data using Python Source: https://www.ivolatility.com/api/docs This snippet demonstrates how to set up IVolatility API credentials, retrieve an options chain for a given symbol and date range, and then fetch historical market data for each option in the chain. It includes error handling for API requests and concatenates the results into a single DataFrame. Dependencies include the 'ivolatility' and 'pandas' libraries. ```python import pandas as pd import ivolatility as ivol import requests ivol.setLoginParams(username={your_IVol_username}, password={your_IVol_password}) getOptionsChain = ivol.setMethod('/equities/eod/option-series-on-date') optionsChain = getOptionsChain(symbol='SPX', expFrom='2021-12-23', expTo='2025-12-23', strikeFrom=3000, strikeTo=3025, callPut='C', date='2021-09-15') print(optionsChain) #optionsChain.to_csv('optionsChain.csv', header=True) allData = pd.DataFrame() getMarketData = ivol.setMethod('/equities/eod/single-stock-option') for optionSymbol in optionsChain['OptionSymbol']: try: marketData = getMarketData(symbol=optionSymbol, from_='2021-09-01', to='2021-09-01', delayBetweenRequests = 1) allData = pd.concat([allData, marketData], axis=0) except requests.exceptions.RequestException as e: print(f"Error fetching data for {optionSymbol}: {e}") print(allData) #allData.to_csv('allData.csv', header=True, index=False) ``` -------------------------------- ### Token Authentication via GET /token/get Source: https://www.ivolatility.com/api/docs Obtain a bearer token by calling the GET /token/get endpoint using your IVolatility login and password. This token is then used for subsequent authenticated requests and expires after 30 minutes. ```http GET /token/get?username=YOUR_USERNAME&password=YOUR_PASSWORD ``` -------------------------------- ### Manage API Keys via POST Request Source: https://www.ivolatility.com/api/docs Create new API keys by sending a POST request with your username and password in the JSON body. This allows programmatic management of your API access credentials. ```http POST /api/v1/keys Content-Type: application/json { "username": "your_ivol_username", "password": "your_ivol_password" } ``` -------------------------------- ### GET /equities/trading-calendar Source: https://www.ivolatility.com/api/docs Returns US market trading calendar information. ```APIDOC ## GET /equities/trading-calendar ### Description This endpoint returns US market trading calendar information. ### Method GET ### Endpoint `/equities/trading-calendar` ### Parameters This endpoint does not appear to have any documented query parameters, path parameters, or request body. Authentication might be handled via headers or a pre-configured client. ### Responses #### Success Response (200) OK. Returns trading calendar data. #### Error Responses Specific error codes and messages are not detailed in the provided text, but common API errors like 400, 401, 403, 500 may apply. ### Request Example ```python # Assuming 'ivol' is an initialized client object # Example: Fetching trading calendar data trading_calendar = ivol.get('/equities/trading-calendar') ``` ### Response Example (Response structure not provided in the input text) ``` -------------------------------- ### Example JSON Response for Empty Options Chain Data Source: https://www.ivolatility.com/api/docs This is a sample JSON response for the equity options raw IV endpoint when no data is found for the requested parameters. It indicates a pending status with no records found. ```json { "status": { "executionTime": 1772, "recordsFound": 0, "code": "PENDING", "urlForDetails": "https://restapi.ivolatility.com/data/info/B2FC976D-7AB4-41B4-ADDD-89460B67E5C8" }, "query": { "requestUUID": "B2FC976D-7AB4-41B4-ADDD-89460B67E5C8" }, "data": [ ] } ``` -------------------------------- ### GET /token/get Source: https://www.ivolatility.com/api/docs Retrieve a temporary bearer token for session-based authentication. ```APIDOC ## GET /token/get ### Description Generates a bearer token valid for 30 minutes. Requires login credentials. ### Method GET ### Endpoint /token/get ### Request Body - **username** (string) - Required - Your IVolatility username - **password** (string) - Required - Your IVolatility password ### Response #### Success Response (200) - **token** (string) - The bearer token for subsequent requests - **expires_in** (integer) - Expiration time in seconds #### Response Example { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "expires_in": 1800 } ``` -------------------------------- ### Example JSON Response for Options Chain Data Source: https://www.ivolatility.com/api/docs This is a sample JSON response for the equity options raw IV endpoint. It includes status information, query details, and an array of data points for options contracts. ```json { "status": { "executionTime": 1772, "recordsFound": 234, "code": "PENDING", "urlForDetails": "https://restapi.ivolatility.com/data/info/B2FC976D-7AB4-41B4-ADDD-89460B67E5C8" }, "query": { "requestUUID": "B2FC976D-7AB4-41B4-ADDD-89460B67E5C8" }, "data": [ { "timestamp": "2021-09-20 09:30:00", "stockId": 627, "stockSymbol": "SPY", "optionExpirationDate": "2022-06-17", "optionStrike": 450, "optionType": "C", "optionStyle": "A", "optionSymbol": "SPY 220617C00450000", "optionBidPrice": 0, "optionAskPrice": 0, "optionBidDateTime": "2021-09-20 09:25:06", "optionAskDateTime": "2021-09-20 09:25:06", "optionBidSize": 0, "optionAskSize": 0, "optionBidExchange": "*", "optionAskExchange": "*", "optionVolume": 0, "optionIv": 0.4455, "underlyingPrice": 434.855, "optionDelta": 0.5357, "optionGamma": 0.002428, "optionTheta": -0.123286, "optionVega": 1.472, "optionRho": 1.24654, "optionPreIv": -1, "optionImpliedYield": 0, "calcTimestamp": "2021-09-20 09:29:34" } ] } ``` -------------------------------- ### Backtest Trading Strategy with iVolatility API (Python) Source: https://www.ivolatility.com/api/docs This snippet demonstrates how to backtest a trading strategy using daily stock price data fetched from the ivolatility API. It calculates daily and total Profit and Loss (PNL) and visualizes the results. Requires the pandas, numpy, and matplotlib libraries. ```python import pandas as pd import numpy as np import matplotlib.pyplot as plt import ivolatility as ivol ivol.setLoginParams(apiKey={your_api_key}) # OR: ivol.setLoginParams(username={your_IVol_username}, password={your_IVol_password}) getMarketData = ivol.setMethod('/equities/eod/stock-prices') marketData = getMarketData(symbol='SPX', from_='1980-01-01', to='2021-12-31') marketData['date'] = pd.to_datetime(marketData['date']) marketData = marketData.sort_values(by='date') pnl_df = pd.DataFrame(columns=['date', 'day_pnl', 'total_pnl']) date_col = marketData.columns.get_loc('date') open_col = marketData.columns.get_loc('open') close_col = marketData.columns.get_loc('close') pnl = 0 loc = 0 for i in range(marketData.shape[0]-1): currentTrade = -np.sign(marketData.iat[i, close_col] - marketData.iat[i, open_col]) * marketData.iat[i+1, open_col] if currentTrade == 0: continue currentTrade = np.sign(currentTrade)*marketData.iat[i+1, close_col] - currentTrade pnl += currentTrade pnl_df.loc[loc] = [marketData.iat[i+1, date_col], currentTrade, pnl] loc += 1 pnl_df.plot(title='SPX', x='date', y='total_pnl', kind='line') plt.show() ``` -------------------------------- ### GET /equities/underlying-info Source: https://www.ivolatility.com/api/docs This call retrieves a financial instrument's underlying pricing information. ```APIDOC ## GET /equities/underlying-info ### Description This call retrieves a financial instrument's underlying pricing information. ### Method GET ### Endpoint /equities/underlying-info ### Parameters #### Query Parameters - **apiKey** (string) - Required - REST API apiKey - **symbol** (string) - Required - The equity symbol for which to retrieve information. ### Response #### Success Response (200) - **currency** (string) - The currency of the pricing information (e.g., "USD"). - **cumulativePrice** (integer) - The cumulative price of the instrument. - **cumulativeValue** (integer) - The cumulative value of the instrument. - **vwap** (float) - The volume-weighted average price. - **ivxlow90** (float) - Implied volatility low for 90 days. - **ivxhighdate90** (string) - Date of the implied volatility high for 90 days. - **ivxlowdate90** (string) - Date of the implied volatility low for 90 days. - **ivxhigh120** (float) - Implied volatility high for 120 days. - **ivxlow120** (float) - Implied volatility low for 120 days. - **ivxhighdate120** (string) - Date of the implied volatility high for 120 days. - **ivxlowdate120** (string) - Date of the implied volatility low for 120 days. - **ivxhigh150** (float) - Implied volatility high for 150 days. - **ivxlow150** (float) - Implied volatility low for 150 days. - **ivxhighdate150** (string) - Date of the implied volatility high for 150 days. - **ivxlowdate150** (string) - Date of the implied volatility low for 150 days. - **ivxhigh180** (float) - Implied volatility high for 180 days. - **ivxlow180** (float) - Implied volatility low for 180 days. - **ivxhighdate180** (string) - Date of the implied volatility high for 180 days. - **ivxlowdate180** (string) - Date of the implied volatility low for 180 days. - **hv30hl** (float) - Historical volatility high-low for 30 days. - **hv60hl** (float) - Historical volatility high-low for 60 days. - **hv90hl** (float) - Historical volatility high-low for 90 days. - **hv120hl** (float) - Historical volatility high-low for 120 days. - **hv150hl** (float) - Historical volatility high-low for 150 days. - **hv180hl** (float) - Historical volatility high-low for 180 days. #### Response Example (200) ```json { "ivxlow90": 0.1892559975385666, "ivxhighdate90": "2023-10-26", "ivxlowdate90": "2024-05-20", "ivxhigh120": 0.2788729965686798, "ivxlow120": 0.18897099792957306, "ivxhighdate120": "2023-10-27", "ivxlowdate120": "2024-05-20", "ivxhigh150": 0.27636951208114624, "ivxlow150": 0.1909244954586029, "ivxhighdate150": "2023-10-27", "ivxlowdate150": "2024-05-21", "ivxhigh180": 0.27541500329971313, "ivxlow180": 0.20031699538230896, "ivxhighdate180": "2023-10-26", "ivxlowdate180": "2024-01-23", "hv30hl": 0.14991378784179688, "hv60hl": 0.16620635986328125, "hv90hl": 0.16761398315429688, "hv120hl": 0.16073894500732422, "hv150hl": 0.15521812438964844, "hv180hl": 0.1595144271850586, "currency": "USD", "cumulativePrice": 106578680, "cumulativeValue": 8000816640, "vwap": 195.31964111328125 } ``` #### Error Responses - **400**: Invalid parameters provided. - **401**: Authentication failed. - **403**: Access denied to the requested data. - **500**: Internal server error. ```