Theta Data - Every Trade. Every Quote. Zero Filtering.


A Practical Guide to More Reliable Market Data Workflows

Large Language Models (LLMs) like Claude and ChatGPT have become a powerful tool for Theta Data users, especially those who aren’t deeply experienced in Python. With a well-phrased prompt, users can quickly generate scripts to pull historical or real-time market data, test strategies, and build workflows.

However, while LLMs are incredibly helpful, they are not perfect. The code they generate can sometimes include subtle errors, inefficiencies, or incorrect assumptions about APIs and data structures. The difference between frustration and success often comes down to how you interact with the model.

This guide outlines best practices to help you consistently generate higher-quality Python code when working with Theta Data.

IMPORTANT: Treat LLM-generated code as a strong first draft—not as verified production code.


1. Be Extremely Specific in Your Prompt

LLMs perform best when given precise instructions. Vague prompts lead to vague or incorrect code.

Instead of:

WEAK PROMPT: “Write Python code to get options data”

Use:

BETTER PROMPT: “Write Python code using the Theta Data Python library to pull 1-minute historical OHLC bars for AAPL on January 2, 2024, restricted to regular trading hours (9:30 to 16:00), and return it as a pandas DataFrame.”

Why it matters:

  • Reduces hallucinated functions or parameters
  • Ensures correct data fields and structure
  • Produces code closer to production-ready

Official SDK example: a precise, bounded intraday request

from datetime import date, time
from thetadata import ThetaClient

client = ThetaClient(dataframe_type="pandas")

bars = client.stock_history_ohlc(
    symbol="AAPL",
    date=date(2024, 1, 2),
    interval="1m",
    start_time=time(9, 30),
    end_time=time(16, 0),
)

print(bars.head())

2. Always Specify the Theta Data Interface

Theta Data offers multiple access methods including a Python Library and if you don’t specify which one, the model may guess incorrectly.

Best practice:

  • Explicitly say: “using the Theta Data Python library”
  • If applicable, include version or install method

Example:

PROMPT LANGUAGE: “Using the Theta Data Python package from PyPI, write a script that…”

Official SDK setup pattern

# pip install thetadata

from thetadata import ThetaClient

# By default, ThetaClient reads credentials from ./creds.txt
client = ThetaClient(dataframe_type="pandas")

3. Provide a Known-Good Starting Pattern

LLMs improve dramatically when anchored to correct examples. If you already have a working snippet, include it and ask the model to modify or extend it.

Example:

PROMPT LANGUAGE: “Here is working code that connects to Theta Data. Modify it to pull daily OHLC data for AAPL.”

This prevents:

  • Incorrect imports
  • Wrong authentication assumptions
  • Misuse of client objects

Known-good starting pattern

from datetime import date
from thetadata import ThetaClient

client = ThetaClient(dataframe_type="pandas")

# Known-good request to give the LLM as a starting point
bars = client.stock_history_eod(
    symbol="AAPL",
    start_date=date(2024, 1, 2),
    end_date=date(2024, 1, 5),
)

print(bars.head())

4. Constrain the Output Format

Tell the model exactly how you want the output structured.

Examples:

  • “Return results as a pandas DataFrame”
  • “Save output to CSV named ‘spy_options.csv’”
  • “Plot the results using matplotlib”

Without this, the model may:

  • Return inconsistent structures
  • Mix print statements with data logic
  • Omit key transformations

Explicit pandas and CSV output

from datetime import date
from thetadata import ThetaClient

client = ThetaClient(dataframe_type="pandas")
quotes = client.stock_history_quote(
    symbol="AAPL",
    date=date(2024, 1, 2),
    interval="1m",
)

quotes.to_csv("aapl_quotes.csv", index=False)
print(quotes.head())

5. Ask for Error Handling Explicitly

By default, LLM-generated code often lacks robustness.

Add this to your prompt:

PROMPT LANGUAGE: “Include proper error handling for connection issues and missing data.”

This will typically introduce:

  • Try/except blocks
  • Clear error messages
  • Safer execution patterns

Official SDK exception handling

from datetime import date
from thetadata import ThetaClient
from thetadata.errors import AuthenticationError, NoDataFoundError

try:
    client = ThetaClient(dataframe_type="pandas")
    data = client.stock_history_eod(
        symbol="AAPL",
        start_date=date(2024, 1, 1),
        end_date=date(2024, 1, 31),
    )
    print(data.head())
except AuthenticationError:
    print("Authentication failed. Check your credentials.")
except NoDataFoundError:
    print("No data was returned for this request.")

6. Validate Assumptions (Don’t Trust Blindly)

LLMs can produce confident but incorrect code—especially around:

  • Function names
  • Parameter formats
  • Data availability

Best practice:

  • Cross-check against Theta Data documentation
  • Run code in small sections
  • Confirm returned fields match expectations

VALIDATION CHECK: Print the DataFrame columns, row count, date range, and a few sample rows before relying on the result.


7. Use Iterative Prompting (Don’t Expect Perfection in One Shot)

The best results come from refinement.

Workflow:

  1. Generate initial code
  2. Run it
  3. Paste errors back into the LLM
  4. Ask for fixes

Example:

PROMPT LANGUAGE: “This code returned an error: [paste error]. Please fix it and explain what was wrong.”


8. Ask the Model to Explain the Code

Understanding the output is critical—especially for debugging and modification.

Prompt addition:

PROMPT LANGUAGE: “Explain each section of the code and what it does.”

Benefits:

  • Helps you catch incorrect logic
  • Builds your own Python proficiency
  • Makes future modifications easier

9. Request Efficiency and Performance Improvements

Initial outputs are often functional—but not optimized.

Follow-up prompt:

PROMPT LANGUAGE: “Refactor this code to be more efficient and minimize API calls.”

This can improve:

  • Latency
  • Data transfer size
  • Execution time

A bounded request that avoids unnecessary repeated calls

from datetime import date
from thetadata import ThetaClient

# Ask for one bounded request rather than many overlapping requests.
# Also ask the LLM to preserve the same output schema.

client = ThetaClient(dataframe_type="pandas")
quotes = client.stock_history_quote(
    symbol="AAPL",
    date=date(2024, 1, 2),
    interval="1m",
)

10. Use Guardrails to Prevent Common Mistakes

You can proactively prevent issues by adding constraints:

Examples:

  • “Do not assume any undocumented Theta Data functions.”
  • “Only use officially supported methods.”
  • “Avoid placeholder or pseudo-code.”

RECOMMENDED ADDITION:

“Use only methods shown in the current Theta Data Python library documentation, and flag any uncertainty before writing the code.”


11. Keep a Personal Prompt Library

As you discover prompts that work well, save them. Over time, you’ll build a library for:

  • Historical data pulls
  • Real-time streaming
  • Options chain analysis
  • Backtesting workflows

PRACTICAL TIP:

Store each prompt with the working code, the SDK version, the expected output, and one sample response.


12. When in Doubt, Simplify

If the model produces overly complex or broken code, ask:

PROMPT LANGUAGE: “Rewrite this in the simplest possible way while maintaining functionality.”

Simple code is:

  • Easier to debug
  • More reliable
  • Faster to adapt

FINAL THOUGHTS

LLMs are a powerful accelerator for working with Theta Data—but they are best viewed as collaborators, not authorities. Users who take a structured, iterative approach to prompting will:

  • Generate more accurate code
  • Reduce debugging time
  • Access Theta Data more effectively
  • Move faster from idea to execution

KEY TAKEAWAY: Better prompts lead to better code—and better results.

If you’re building something interesting with Theta Data using LLMs, we’d love to hear about it.

QUICK-START PROMPT TEMPLATE

COPY AND CUSTOMIZE: Using the current Theta Data Python library from PyPI, write complete executable Python code to [describe the task]. Use [symbol(s)], [date/time range], [interval], and [required fields]. Return the result as a pandas DataFrame and [save/plot/transform it]. Use only officially supported methods, include authentication assumptions, handle AuthenticationError and NoDataFoundError, validate the returned schema, avoid pseudo-code, and explain each section.