### Quick Start: Fetching Market Data Source: https://docs.thetadata.us/Python-Library/Getting-Started.html Demonstrates how to initialize the client, get a list of stock symbols, retrieve historical End-of-Day data, and fetch a stock quote snapshot. ```python from datetime import date from thetadata import ThetaClient client = ThetaClient() symbols = client.stock_list_symbols() print(symbols) eod = client.stock_history_eod( symbol="AAPL", start_date=date(2024, 1, 1), end_date=date(2024, 1, 31), ) print(eod) quote = client.stock_snapshot_quote(symbol=["AAPL"]) print(quote) ``` -------------------------------- ### Python: Fetch Calendar Schedule by Date Source: https://docs.thetadata.us/operations/calendar_on_date.html Fetches the equity market schedule for a given date using httpx. This example streams the response and parses it as CSV line by line. Ensure httpx is installed (`pip install httpx`). ```python import httpx # install via pip install httpx import csv import io BASE_URL = "http://127.0.0.1:25503/v3" # all endpoints use this URL base # set params params = { 'date': '2024-11-07', } # # This is the streaming version, and will read line-by-line # url = BASE_URL + '/calendar/on_date' with httpx.stream("GET", url, params=params, timeout=60) as response: response.raise_for_status() # make sure the request worked for line in response.iter_lines(): for row in csv.reader(io.StringIO(line)): print(row) # Now you get a parsed list of fields ``` -------------------------------- ### Python Example: Fetch Third Order Greeks Source: https://docs.thetadata.us/operations/option_snapshot_greeks_third_order.html This Python script demonstrates how to fetch third order greeks for options using the httpx library. Ensure the Theta Terminal is running and install httpx via pip. ```python import httpx # install via pip install httpx import csv import sys import io from datetime import datetime BASE_URL = "http://127.0.0.1:25503/v3" # all endpoints use this URL base # set params params = { 'symbol': 'AAPL', 'expiration': '2025-01-17', } ``` -------------------------------- ### Install Java on Ubuntu Source: https://docs.thetadata.us/Articles/Getting-Started/Getting-Started.html Install OpenJDK 21 JDK and JRE on Ubuntu systems. Elevated privileges may be required. ```shell apt install openjdk-21-jdk openjdk-21-jre ``` -------------------------------- ### Install Node Modules Source: https://docs.thetadata.us/README.html Installs all necessary Node.js modules for the project using Yarn. ```bash yarn install --frozen-lockfile ``` -------------------------------- ### Run Development Server Source: https://docs.thetadata.us/README.html Starts a local development server to preview changes to the documentation. ```bash yarn run docs:dev ``` -------------------------------- ### Python Example: Fetching Trade Quotes Source: https://docs.thetadata.us/operations/option_history_trade_quote.html This Python script demonstrates how to fetch trade quote data using the httpx library. It requires the Theta Terminal to be running and the httpx library to be installed. ```python import httpx # install via pip install httpx import csv import io from datetime import datetime, timedelta BASE_URL = "http://127.0.0.1:25503/v3" # all endpoints use this URL base ``` -------------------------------- ### Get Today's Market Schedule (Python) Source: https://docs.thetadata.us/operations/calendar_open_today.html Retrieves the current day's equity market schedule using a streaming HTTP request. This example uses the httpx library and processes the CSV response line by line. ```python import httpx # install via pip install httpx import csv import io BASE_URL = "http://127.0.0.1:25503/v3" # all endpoints use this URL base # set params params = { } # # This is the streaming version, and will read line-by-line # url = BASE_URL + '/calendar/today' with httpx.stream("GET", url, params=params, timeout=60) as response: response.raise_for_status() # make sure the request worked for line in response.iter_lines(): for row in csv.reader(io.StringIO(line)): print(row) # Now you get a parsed list of fields ``` -------------------------------- ### Python Example: Fetching Index Prices at a Specific Time Source: https://docs.thetadata.us/operations/index_at_time_price.html This Python script demonstrates how to fetch historical index price reports for a given date range and time of day using the httpx library. It iterates through specified dates, constructs the API URL, and processes the CSV response line by line. Ensure the Theta Terminal is running and httpx is installed (`pip install httpx`). ```python import httpx # install via pip install httpx import csv import io from datetime import datetime, timedelta BASE_URL = "http://127.0.0.1:25503/v3" # all endpoints use this URL base # set params RAW_PARAMS= { 'symbol': 'SPX', 'start_date': '2024-11-07', 'end_date': '2024-11-07', 'time_of_day': '09:31:00.000', } # define date range start_date = datetime.strptime('2024-11-07', '%Y-%m-%d') end_date = datetime.strptime('2024-11-07', '%Y-%m-%d') dates_to_run = [] while start_date <= end_date: if start_date.weekday() < 5: # skip Sat/Sun dates_to_run.append(start_date) start_date += timedelta(days=1) print("Dates to request:", [d.strftime("%Y-%m-%d (%A)") for d in dates_to_run]) # # This is the streaming version, and will read line-by-line # for day in dates_to_run: day_str = day.strftime("%Y%m%d") # set params params = RAW_PARAMS if 'start_date' in params: params['start_date'] = day_str if 'end_date' in params: params['end_date'] = day_str url = BASE_URL + '/index/at_time/price' with httpx.stream("GET", url, params=params, timeout=60) as response: response.raise_for_status() # make sure the request worked for line in response.iter_lines(): for row in csv.reader(io.StringIO(line)): print(row) # Now you get a parsed list of fields ``` -------------------------------- ### Install thetadata with pip Source: https://docs.thetadata.us/Python-Library/Getting-Started.html Use pip to install the thetadata Python library. Requires Python 3.12 or higher. ```bash pip install thetadata ``` -------------------------------- ### Install thetadata with uv Source: https://docs.thetadata.us/Python-Library/Getting-Started.html Use uv to add the thetadata Python library. Requires Python 3.12 or higher. ```bash uv add thetadata ``` -------------------------------- ### Install Yarn Package Manager Source: https://docs.thetadata.us/README.html Enables the Yarn package manager. Ensure Node.js version 20.18 or higher is installed. ```bash corepack enable ``` -------------------------------- ### Check Java Version Source: https://docs.thetadata.us/Articles/Getting-Started/Getting-Started.html Verify your installed Java version. Ensure it is 21 or higher for optimal performance. ```shell java -version ``` -------------------------------- ### Sample Trade Output Source: https://docs.thetadata.us/Streaming/US-Stocks/Trade-Stream.html This is an example of the JSON output received for each trade. It includes trade details such as size, price, and exchange. ```json { "header": { "type": "TRADE", "status": "CONNECTED" }, "contract": { "security_type": "STOCK", "root": "AAPL" }, "trade": { "ms_of_day": 38437607, "sequence": 12150295, "size": 500, "condition": 0, "price": 184.5099, "exchange": 57, "date": 20240503 } } ``` -------------------------------- ### Create a credentials file Source: https://docs.thetadata.us/Python-Library/Getting-Started.html Create a 'creds.txt' file with your email on the first line and password on the second. This file is used for authentication. ```text your-email@example.com your-password ``` -------------------------------- ### Go Example: Subscribe to Full Trade Stream Source: https://docs.thetadata.us/Streaming/US-Options/Full-Trade-Stream.html This Go code snippet shows how to establish a WebSocket connection and subscribe to the full US Options trade stream. It uses the 'gorilla/websocket' library and handles connection, message sending, and receiving. ```go package main import ( "encoding/json" "fmt" "log" "net/url" "os" "os/signal" "syscall" "github.com/gorilla/websocket" ) type InitialMessage struct { MsgType string `json:"msg_type"` SecType string `json:"sec_type"` ReqType string `json:"req_type"` Add bool `json:"add"` ID int `json:"id"` } func main() { interrupt := make(chan os.Signal, 1) signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM) u := url.URL{Scheme: "ws", Host: "127.0.0.1:25520", Path: "/v1/events"} log.Printf("connecting to %s", u.String()) c, _, err := websocket.DefaultDialer.Dial(u.String(), nil) if err != nil { log.Fatal("dial:", err) } defer c.Close() done := make(chan struct{}) go func() { defer close(done) for { _, message, err := c.ReadMessage() if err != nil { log.Println("read:", err) return } fmt.Printf("%s\n", message) } }() initialMessage := InitialMessage{ MsgType: "STREAM_BULK", SecType: "OPTION", ReqType: "TRADE", Add: true, ID: 0, } msg, err := json.Marshal(initialMessage) if err != nil { log.Println("error in marshalling:", err) return } err = c.WriteMessage(websocket.TextMessage, msg) if err != nil { log.Println("write:", err) return } for { select { case <-done: return case <-interrupt: log.Println("interrupt") err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) if err != nil { log.Println("write close:", err) return } <-done return } } } ``` -------------------------------- ### Build Documentation Source: https://docs.thetadata.us/README.html Builds the static files for the documentation site. This is typically automated by the deploy script. ```bash yarn run docs:build ``` -------------------------------- ### Fetch Stock Quote at Specific Time (Pandas) Source: https://docs.thetadata.us/operations_python/stock_at_time_quote.html Retrieves the last NBBO quote for a given symbol at a specified time of day. This example uses the pandas DataFrame type. Ensure you have the 'thetadata' library installed and a valid client initialized. ```python from thetadata import ThetaClient from datetime import date client = ThetaClient(dataframe_type='pandas') df = client.stock_at_time_quote( symbol='SPY', start_date=date(2024, 1, 16), end_date=date(2024, 1, 16), time_of_day='09:30:00.100', ) ``` -------------------------------- ### Deploy Documentation Source: https://docs.thetadata.us/README.html Deploys the documentation files to the server. Requires an SSH key named `td-do` to be present. ```bash ./deploy.sh ``` -------------------------------- ### Basic Pipeline with Polars and Asyncio Source: https://docs.thetadata.us/Code-Examples/Python/basic_pipeline.html This example shows how to fetch stock data for a range of dates concurrently using Polars and asyncio. It retrieves trading days, defines an async fetch function, and then gathers results from multiple requests. ```Python import asyncio import httpx import polars as pl import io # ---------------------------------------------------- # Constant Variables # ---------------------------------------------------- BASE_URL = 'http://127.0.0.1:25503/v3' CONCURRENCY_LIMIT = 4 SEMAPHORE = asyncio.Semaphore(CONCURRENCY_LIMIT) # ---------------------------------------------------- # STEP 1: Get avaliable trading days # ---------------------------------------------------- # Make the request (Using ndjson as an example) r = httpx.get(BASE_URL + '/stock/list/dates/quote?symbol=AAPL&format=ndjson', timeout=60) r.raise_for_status() # Load response data into Polars avalible_dates = pl.read_ndjson(io.StringIO(r.text)) request_date_range = avaliable_dates['date'][-30:] # ---------------------------------------------------- # STEP 2: Create async request function # ---------------------------------------------------- async def fetch(client: httpx.AsyncClient, date: str): async with SEMAPHORE: params = {'symbol': 'AAPL', 'date': date, 'interval': '1s', 'format': 'ndjson'} r = await client.get(BASE_URL + '/stock/history/quote', params=params) r.raise_for_status() df = pl.read_ndjson(io.StringIO(r.text)) return df # ---------------------------------------------------- # Main Runner # ---------------------------------------------------- async def run_requests(): async with httpx.AsyncClient(timeout=60.0) as client: tasks = [fetch(client, date) for date in request_date_range] results = await asyncio.gather(*tasks) # Combine all dataframes into one results = pl.concat(results) return results # ---------------------------------------------------- # Running the script # ---------------------------------------------------- if __name__ == "__main__": results = asyncio.run(run_requests()) print(results) ``` -------------------------------- ### Get Option Market Value (Python) Source: https://docs.thetadata.us/operations/option_snapshot_market_value.html Fetches real-time market values for option contracts using the v3 API. This example uses httpx to stream CSV data line by line. It includes a check for market closure on weekends. ```python import httpx # install via pip install httpx import csv import sys import io from datetime import datetime BASE_URL = "http://127.0.0.1:25503/v3" # all endpoints use this URL base # set params params = { 'symbol': 'AAPL', 'expiration': '2025-01-17', } # Weekend Check (Sat/Sun) now = datetime.now() if now.weekday() >= 5: # 5=Sat, 6=Sun print("Market is Closed snapshots may not work") sys.exit(0) # # This is the streaming version, and will read line-by-line # url = BASE_URL + '/option/snapshot/market_value' with httpx.stream("GET", url, params=params, timeout=60) as response: response.raise_for_status() # make sure the request worked for line in response.iter_lines(): for row in csv.reader(io.StringIO(line)): print(row) # Now you get a parsed list of fields ``` -------------------------------- ### Python: Fetch Option History Greeks Second Order Source: https://docs.thetadata.us/operations/option_history_greeks_second_order.html Fetches historical second-order greeks for a specified option symbol and expiration date. This example demonstrates streaming the response line by line and parsing it as CSV. Ensure you have the 'httpx' library installed. ```Python import httpx # install via pip install httpx import csv import io from datetime import datetime, timedelta BASE_URL = "http://127.0.0.1:25503/v3" # all endpoints use this URL base # set params RAW_PARAMS= { 'symbol': 'AAPL', 'expiration': '2025-01-17', 'interval': '1m', } # define date range start_date = datetime.strptime('2024-11-07', '%Y-%m-%d') end_date = datetime.strptime('2024-11-07', '%Y-%m-%d') dates_to_run = [] while start_date <= end_date: if start_date.weekday() < 5: # skip Sat/Sun dates_to_run.append(start_date) start_date += timedelta(days=1) print("Dates to request:", [d.strftime("%Y-%m-%d (%A)") for d in dates_to_run]) # # This is the streaming version, and will read line-by-line # for day in dates_to_run: day_str = day.strftime("%Y%m%d") # set params params = RAW_PARAMS if 'start_date' in params: params['start_date'] = day_str if 'end_date' in params: params['end_date'] = day_str url = BASE_URL + '/option/history/greeks/second_order' with httpx.stream("GET", url, params=params, timeout=60) as response: response.raise_for_status() # make sure the request worked for line in response.iter_lines(): for row in csv.reader(io.StringIO(line)): print(row) # Now you get a parsed list of fields ``` -------------------------------- ### Deploy Local Live Algorithm with ThetaData Source: https://docs.thetadata.us/Articles/Getting-Started/QuantConnect.html Deploy a local live trading algorithm using ThetaData as the data provider. Specify the brokerage and required options. Historical data provider can also be set. ```shell lean live deploy [projectName] --data-provider-live ThetaData --thetadata-subscription-plan [plan] --brokerage [brokerageName] [requiredBrokerageOptions] ``` ```shell $ lean live deploy "My Project" --data-provider-live ThetaData --thetadata-subscription-plan Standard --brokerage "Paper Trading" ``` ```shell lean live deploy [projectName] --brokerage [brokerageName] ``` -------------------------------- ### Launch ThetaTerminal with Staging Config Source: https://docs.thetadata.us/Articles/Data-And-Requests/Staging-Environment.html Run the ThetaTerminal Java application using the staging configuration file. ```bash java -jar ThetaTerminal3.jar --config config-staging.toml ``` -------------------------------- ### option_snapshot_greeks_first_order() Source: https://docs.thetadata.us/operations_python/option_snapshot_greeks_first_order.html Retrieves a real-time last greeks calculation for all option contracts that lie on a provided expiration. You might need to change the default expiration date to a different date if it is past the current date. Some quotes are omitted in the example to reduce the space of the sample output. Make `expiration` * if you want to get the snapshot for every expiration chain for the underlying. This endpoint will return no data if the market was closed for the day. Theta Data resets the snapshot cache at midnight ET every night. ```APIDOC ## GET /option_snapshot_greeks_first_order ### Description Retrieve a real-time last greeks calculation for all option contracts that lie on a provided expiration. This endpoint can fetch data for all expirations or specific strikes and rights, and allows for customization of Greeks calculation parameters. ### Method GET ### Endpoint /option_snapshot_greeks_first_order ### Parameters #### Query Parameters - **symbol** (str) - Required - The stock or index symbol, or underlying symbol for options. - **expiration** (datetime.date) - Required - The expiration of the contract in `YYYY-MM-DD` or `YYYYMMDD` format, or `*` for all expirations. - **strike** (str) - Optional - The strike price of the contract in dollars (ie `100.00` for `$100.00`), or `*` for all strikes. (Default: *) - **right** (str) - Optional - The right (call or put) of the contract. Enum: call, put, both (Default: both) - **annual_dividend** (float) - Optional - The annualized expected dividend amount to be used in Greeks calculations. - **rate_type** (str) - Optional - The interest rate type to be used in a Greeks calculation. Enum: sofr, treasury_m1, treasury_m3, treasury_m6, treasury_y1, treasury_y2, treasury_y3, treasury_y5, treasury_y7, treasury_y10, treasury_y20, treasury_y30 (Default: sofr) - **rate_value** (float) - Optional - The interest rate, as a percent, to be used in a Greeks calculation. - **stock_price** (float) - Optional - The underlying stock price to be used in the Greeks calculation. - **version** (str) - Optional - Used to adjust Greeks calculation methodology. "1" uses a fixed .15 DTE for 0DTE; "latest" uses real TTE (down to a minimum of 1 hour). Enum: latest, 1 (Default: latest) - **max_dte** (int) - Optional - If specified, only contracts with a full calendar day 'Days to Expiration' (DTE) less than or equal to this number will be returned. - **strike_range** (int) - Optional - Limits the number of contracts returned relative to the underlying's spot price. For a specified value 'n', this returns 'n' strikes above and 'n' strikes below the spot price, plus one at-the-money (ATM) strike (where spot price = strike price), if available. This results in a maximum of `2n + 1` strikes. - **min_time** (Union[datetime.time, str]) - Optional - Filters snapshots to include only data with a timestamp greater or equal to the specified value (HH:mm:ss.SSS format). - **use_market_value** (boolean) - Optional - Use the market value bid, ask, and price (Default: false) ### Response #### Success Response (200) Returns first order greeks for an option contract. - **symbol** (str) - The symbol of the contract, or stock / underlying asset / option / index. - **expiration** (datetime.date) - Expiration date of the contract in YYYY-MM-DD format. - **strike** (float) - Strike price of the contract in dollars 180.00 - **right** (str) - Indicates whether the contract is a call or put option. - **timestamp** (datetime.datetime) - The timestamp in YYYY-MM-DDTHH:mm:ss.SSS format. - **bid** (float) - The last NBBO bid price. - **ask** (float) - The last NBBO ask price. - **delta** (float) - The delta. - **theta** (str) - The Theta. - **vega** (float) - The vega. - **rho** (float) - The rho. - **epsilon** (str) - The epsilon. - **lambda** (float) - The lambda. - **implied_vol** (float) - The implied volatiltiy calculated using the trade price. - **iv_error** (str) - IV Error: the value of the option calculated using the implied volatiltiy divided by the actual value reported in the quote. This value will increase as the strike price recedes from the underlying price. - **underlying_timestamp** (datetime.datetime) - The underlying date formated as YYYY-MM-DDTHH:mm:ss.SSS format. - **underlying_price** (float) - The midpoint of the underlying at the time of the option trade. ### Request Example ```python from thetadata import ThetaClient from datetime import date client = ThetaClient(dataframe_type='pandas') df = client.option_snapshot_greeks_first_order(symbol='AAPL', expiration=date(2027, 1, 15)) ``` ``` -------------------------------- ### Authenticate by specifying a credentials file path Source: https://docs.thetadata.us/Python-Library/Getting-Started.html Instantiate ThetaClient by providing the path to your credentials file. ```python from thetadata import ThetaClient client = ThetaClient(creds_file="/path/to/creds.txt") ``` -------------------------------- ### Get First Order Greeks for All Option Contracts of a Symbol Source: https://docs.thetadata.us/operations/option_snapshot_greeks_first_order.html Retrieve first-order Greeks for all option contracts associated with a given symbol by using '*' for the expiration parameter. This is useful for getting a snapshot of all expirations. ```url http://127.0.0.1:25503/v3/option/snapshot/greeks/first_order?symbol=AAPL&expiration=* ``` -------------------------------- ### Staging Environment Configuration Source: https://docs.thetadata.us/Articles/Data-And-Requests/Staging-Environment.html Create a TOML configuration file to specify the port and environment type for the staging connection. ```toml port = 25504 [env] mdds_type = "STAGE" ``` -------------------------------- ### Simultaneous Streaming Connections with Python Source: https://docs.thetadata.us/Articles/Data-And-Requests/Staging-Environment.html Establish and process streaming data from both production and staging ThetaData instances concurrently using Python's httpx library. Ensure httpx is installed (`pip install httpx`). ```python import httpx import csv import io # Point each URL at the correct port for each instance BASE_URL_PROD = "http://127.0.0.1:25503/v3" BASE_URL_STAGE = "http://127.0.0.1:25504/v3" url_prod = BASE_URL_PROD + '/stock/list/symbols' url_stage = BASE_URL_STAGE + '/stock/list/symbols' # Open both streams at the same time, then read from each with httpx.stream("GET", url_prod, timeout=60) as response_prod, \ httpx.stream("GET", url_stage, timeout=60) as response_stage: response_prod.raise_for_status() # raises an error if the request failed for line in response_prod.iter_lines(): for row in csv.reader(io.StringIO(line)): print(row) response_stage.raise_for_status() for line in response_stage.iter_lines(): for row in csv.reader(io.StringIO(line)): print(row) ``` -------------------------------- ### Python: Stream Year Holidays Source: https://docs.thetadata.us/operations/calendar_year.html This Python snippet demonstrates how to stream and parse year holiday data line by line using httpx and the csv module. Ensure the httpx library is installed (`pip install httpx`). ```Python import httpx # install via pip install httpx import csv import io BASE_URL = "http://127.0.0.1:25503/v3" # all endpoints use this URL base # set params params = { 'year': '', } # # This is the streaming version, and will read line-by-line # url = BASE_URL + '/calendar/year_holidays' with httpx.stream("GET", url, params=params, timeout=60) as response: response.raise_for_status() # make sure the request worked for line in response.iter_lines(): for row in csv.reader(io.StringIO(line)): print(row) # Now you get a parsed list of fields ``` -------------------------------- ### Production Environment Configuration Source: https://docs.thetadata.us/Articles/Data-And-Requests/Staging-Environment.html Create a TOML configuration file to specify the port and environment type for the production connection. ```toml port = 25503 [env] mdds_type = "PROD" ``` -------------------------------- ### List all dates for an index symbol (Python) Source: https://docs.thetadata.us/operations/index_list_dates.html This Python snippet demonstrates how to stream and parse CSV data for available dates for a given index symbol using the httpx library. Ensure httpx is installed (`pip install httpx`). ```python import httpx # install via pip install httpx import csv import io BASE_URL = "http://127.0.0.1:25503/v3" # all endpoints use this URL base # set params params = { 'symbol': 'SPX', } # # This is the streaming version, and will read line-by-line # url = BASE_URL + '/index/list/dates' with httpx.stream("GET", url, params=params, timeout=60) as response: response.raise_for_status() # make sure the request worked for line in response.iter_lines(): for row in csv.reader(io.StringIO(line)): print(row) # Now you get a parsed list of fields ``` -------------------------------- ### Launch ThetaTerminal with Production Config Source: https://docs.thetadata.us/Articles/Data-And-Requests/Staging-Environment.html Run the ThetaTerminal Java application using the production configuration file. ```bash java -jar ThetaTerminal3.jar --config config-prod.toml ``` -------------------------------- ### Retrieve Open Interest for a Specific Option Contract (Python) Source: https://docs.thetadata.us/operations/option_snapshot_open_interest.html This Python snippet uses the httpx library to stream and parse CSV data for option open interest. It includes a check for weekends, as snapshots may not be available. Ensure you have httpx installed (`pip install httpx`). ```python import httpx # install via pip install httpx import csv import sys import io from datetime import datetime BASE_URL = "http://127.0.0.1:25503/v3" # all endpoints use this URL base # set params params = { 'symbol': 'AAPL', 'expiration': '2025-01-17', } # Weekend Check (Sat/Sun) now = datetime.now() if now.weekday() >= 5: # 5=Sat, 6=Sun print("Market is Closed snapshots may not work") sys.exit(0) # # This is the streaming version, and will read line-by-line # url = BASE_URL + '/option/snapshot/open_interest' with httpx.stream("GET", url, params=params, timeout=60) as response: response.raise_for_status() # make sure the request worked for line in response.iter_lines(): for row in csv.reader(io.StringIO(line)): print(row) # Now you get a parsed list of fields ``` -------------------------------- ### Python: Fetch Option Implied Volatility History Source: https://docs.thetadata.us/operations/option_history_greeks_implied_volatility.html This Python script uses httpx to stream historical implied volatility data for option contracts. It handles date range iteration and CSV parsing for each line of the response. Ensure httpx is installed (`pip install httpx`). ```python import httpx # install via pip install httpx import csv import io from datetime import datetime, timedelta BASE_URL = "http://127.0.0.1:25503/v3" # all endpoints use this URL base # set params RAW_PARAMS= { 'symbol': 'AAPL', 'expiration': '2025-01-17', 'interval': '1m', } # define date range start_date = datetime.strptime('2024-11-07', '%Y-%m-%d') end_date = datetime.strptime('2024-11-07', '%Y-%m-%d') dates_to_run = [] while start_date <= end_date: if start_date.weekday() < 5: # skip Sat/Sun dates_to_run.append(start_date) start_date += timedelta(days=1) print("Dates to request:", [d.strftime("%Y-%m-%d (%A)") for d in dates_to_run]) # # This is the streaming version, and will read line-by-line # for day in dates_to_run: day_str = day.strftime("%Y%m%d") # set params params = RAW_PARAMS if 'start_date' in params: params['start_date'] = day_str if 'end_date' in params: params['end_date'] = day_str url = BASE_URL + '/option/history/greeks/implied_volatility' with httpx.stream("GET", url, params=params, timeout=60) as response: response.raise_for_status() # make sure the request worked for line in response.iter_lines(): for row in csv.reader(io.StringIO(line)): print(row) # Now you get a parsed list of fields ```