# How the Director Agent Discovers Tickers in AutoHedge: Implementation and Code Analysis

> Discover how AutoHedge's Director Agent uses LLM prompts to extract stock tickers from user tasks into a JSON array for precise analysis. Learn the implementation and code.

- Repository: [Swarms/AutoHedge](https://github.com/The-Swarm-Corporation/AutoHedge)
- Tags: internals
- Published: 2026-09-08

---

**The Director Agent discovers tickers by submitting the user's natural-language task to a specialized LLM prompt (`DIRECTOR_TICKER_DISCOVERY_PROMPT`) that extracts stock symbols into a strict JSON array, enabling deterministic routing to downstream analysis agents.**

The AutoHedge repository implements a multi-agent trading system where the Director Agent serves as the central orchestration layer. When users submit free-form trading tasks, the Director must first identify which specific securities require analysis before delegating work to specialized Quant, Sentiment, and Risk agents. This ticker discovery process relies on structured prompt engineering and deterministic JSON parsing to ensure reliable symbol extraction from unstructured input.

## The DIRECTOR_TICKER_DISCOVERY_PROMPT Template

The core mechanism for ticker extraction resides in [`autohedge/prompts.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/autohedge/prompts.py), which defines the `DIRECTOR_TICKER_DISCOVERY_PROMPT` constant. This template instructs the LLM to analyze the user's task description and return only a JSON array of relevant ticker symbols.

According to the source code in [`autohedge/prompts.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/autohedge/prompts.py) (lines 95-104), the prompt template is defined as:

```python
DIRECTOR_TICKER_DISCOVERY_PROMPT = """
Given the following task, determine which stock tickers are relevant to analyze.

Task: {task}

Reply with ONLY a JSON array of ticker symbols (e.g. ["NVDA", "MSFT", "GOOG"]). Use US exchange symbols. No other text.
"""

```

The `{task}` placeholder allows the Director Agent to dynamically inject the user's natural-language instruction at runtime. By explicitly constraining the LLM to output **only** a JSON array, the system eliminates parsing ambiguity and guarantees a machine-readable data structure that downstream agents can consume without additional text processing.

## Runtime Workflow of Ticker Discovery

When a trading request enters the system, the Director Agent executes a structured sequence to transform free-form text into validated financial symbols.

### Prompt Population and LLM Invocation

The Director Agent receives the raw task string—such as *"Analyze the impact of recent AI announcements on semiconductor leaders"*—and interpolates it into the prompt template. As implemented in the orchestration layer (referenced in [`autohedge/workers.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/autohedge/workers.py)), the formatted prompt is then sent to the configured LLM provider (e.g., OpenAI or Anthropic models).

The LLM processes the semantic content of the task to identify relevant securities. For example, given a task mentioning "Nvidia and AMD," the model recognizes these entities and maps them to their respective ticker symbols based on the explicit instruction to use US exchange conventions.

### Response Parsing and Validation

The Director Agent expects the LLM response to be a parsable JSON array. Upon receiving the output, the system performs the following validation steps:

- **JSON deserialization** using `json.loads()` to convert the string response into a Python list
- **Type checking** to ensure each element is a string
- **Normalization** converting symbols to uppercase (e.g., `nvda` → `NVDA`)
- **Non-empty verification** to filter out null or blank entries

If the LLM returns malformed JSON or additional explanatory text, the Director raises a `ValueError` and halts the pipeline, preventing corrupted data from reaching downstream agents.

## Integration with the Agent Orchestration Pipeline

Once validated, the ticker list flows through the AutoHedge agent hierarchy. The Director Agent passes the discovered symbols to specialized workers:

- **Quant Agent**: Receives tickers for technical analysis and statistical modeling
- **Sentiment Agent**: Analyzes news and social media specific to those symbols
- **Risk Agent**: Calculates portfolio exposure and volatility metrics for the identified securities

This architectural separation ensures that the Director focuses solely on task comprehension and delegation, while domain-specific agents receive explicitly defined inputs. The deterministic JSON contract between the Director and downstream components eliminates the need for secondary parsing logic in worker nodes.

## Practical Implementation Example

The following implementation demonstrates how to replicate the Director's ticker discovery mechanism using the actual prompt template from the repository:

```python
from autohedge.prompts import DIRECTOR_TICKER_DISCOVERY_PROMPT
import json

def discover_tickers(task_text, llm_client):
    """
    Replicates the Director Agent's ticker discovery workflow.
    
    Args:
        task_text: Natural language description of the trading task
        llm_client: Configured LLM interface with .complete() method
    
    Returns:
        list: Validated uppercase ticker symbols
    """
    # Format the prompt with user task

    prompt = DIRECTOR_TICKER_DISCOVERY_PROMPT.format(task=task_text)
    
    # Invoke LLM

    llm_response = llm_client.complete(prompt)
    
    # Parse and validate JSON response

    try:
        tickers = json.loads(llm_response.strip())
        
        # Ensure list of non-empty uppercase strings

        tickers = [
            t.upper() for t in tickers 
            if isinstance(t, str) and t.strip()
        ]
        
        return tickers
        
    except json.JSONDecodeError:
        raise ValueError("LLM did not return valid JSON ticker array")

# Example usage

if __name__ == "__main__":
    task = "Look at the effect of recent AI breakthroughs on Nvidia and AMD."
    tickers = discover_tickers(task, llm_client)
    print(tickers)  # Output: ["NVDA", "AMD"]

```

This implementation mirrors the production logic found in [`autohedge/workers.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/autohedge/workers.py), utilizing the same prompt template and validation strategy employed by the actual Director Agent.

## Summary

- The **Director Agent** discovers tickers using the `DIRECTOR_TICKER_DISCOVERY_PROMPT` defined in [`autohedge/prompts.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/autohedge/prompts.py).
- The prompt mandates **strict JSON output** (e.g., `["AAPL", "MSFT"]`) to ensure deterministic parsing.
- User tasks are injected into the template at runtime via string interpolation of the `{task}` placeholder.
- The system validates LLM responses through JSON deserialization, type checking, and uppercase normalization before routing to downstream agents.
- This architecture decouples natural language understanding from financial analysis, enabling specialized agents to receive explicit, validated ticker inputs.

## Frequently Asked Questions

### What file contains the ticker discovery prompt?

The `DIRECTOR_TICKER_DISCOVERY_PROMPT` template is defined in [`autohedge/prompts.py`](https://github.com/The-Swarm-Corporation/AutoHedge/blob/main/autohedge/prompts.py) (lines 95-104). This file centralizes all LLM prompt strings used across the AutoHedge system, ensuring consistent instruction formatting for various agent tasks.

### What format does the Director Agent require for ticker responses?

The Director Agent requires the LLM to return **only** a JSON array of strings, such as `["NVDA", "AMD", "INTC"]`. The prompt explicitly forbids additional text, explanations, or markdown formatting to guarantee clean deserialization without regex extraction or string manipulation.

### How does the system handle invalid ticker responses?

If the LLM returns malformed JSON, non-array structures, or empty responses, the Director Agent raises a `ValueError` during the parsing phase. This validation failure prevents the pipeline from proceeding, ensuring that downstream Quant and Risk agents never receive corrupted or undefined ticker symbols.

### Can the Director Agent discover tickers from ambiguous task descriptions?

Yes, the LLM underlying the Director Agent interprets semantic context to map company names, sectors, or themes to specific ticker symbols. For example, a task stating *"semiconductor leaders benefiting from AI"* would likely return `["NVDA", "AMD", "TSM"]` based on the model's training data, even without explicit ticker mentions.