Skip to content

Research Workflow Example

This page provides a complete example of how to use Octagon's specialized public-market agents with the OpenAI Agents SDK to conduct a comprehensive investment research workflow.

Complete Public Market Research Workflow Example

The following example demonstrates how to set up a research workflow that:

  1. Reviews the latest SEC filing disclosures
  2. Analyzes financial statement trends
  3. Summarizes earnings call commentary
  4. Checks recent stock performance
  5. Synthesizes findings into a comprehensive investment report
Python
import asyncio
import os
from agents import Agent, ItemHelpers, MessageOutputItem, OpenAIResponsesModel, Runner, trace
from openai import AsyncOpenAI

openai_api_key = os.getenv("OPENAI_API_KEY", "<your-openai-api-key>")
octagon_api_key = os.getenv("OCTAGON_API_KEY", "<your-octagon-api-key>")

octagon_client = AsyncOpenAI(
    api_key=octagon_api_key,
    base_url="https://api.octagonai.co/v1",
)

openai_client = AsyncOpenAI(api_key=openai_api_key)

sec_agent = Agent(
    name="SEC Filings Analysis",
    instructions="You analyze SEC filings to extract disclosures, risk factors, MD&A commentary, and regulatory filing insights.",
    model=OpenAIResponsesModel(
        model="octagon-sec-agent",
        openai_client=octagon_client,
    ),
)

financials_agent = Agent(
    name="Financials Analysis",
    instructions="You analyze financial statements, ratios, margins, growth, and profitability trends.",
    model=OpenAIResponsesModel(
        model="octagon-financials-agent",
        openai_client=octagon_client,
    ),
)

transcripts_agent = Agent(
    name="Earnings Call Analysis",
    instructions="You analyze earnings call transcripts, management commentary, guidance, and analyst Q&A.",
    model=OpenAIResponsesModel(
        model="octagon-transcripts-agent",
        openai_client=octagon_client,
    ),
)

stock_data_agent = Agent(
    name="Stock Data Analysis",
    instructions="You analyze stock prices, trading volume, market trends, and recent performance.",
    model=OpenAIResponsesModel(
        model="octagon-stock-data-agent",
        openai_client=octagon_client,
    ),
)

deep_research_agent = Agent(
    name="Deep Research",
    instructions="You synthesize findings from multiple sources into a comprehensive investment research report.",
    model=OpenAIResponsesModel(
        model="octagon-deep-research-agent",
        openai_client=octagon_client,
    ),
)

coordinator = Agent(
    name="Research Coordinator",
    instructions=(
        "You are a research coordinator building a public-market investment research report.\n"
        "Follow this exact workflow:\n"
        "1. Use `analyze_sec_filings` to review recent disclosures and filing highlights.\n"
        "2. Use `analyze_financials` to evaluate financial statement trends and key metrics.\n"
        "3. Use `analyze_transcripts` to summarize management commentary and guidance.\n"
        "4. Use `analyze_stock_data` to review recent stock performance and market context.\n"
        "5. Use `conduct_deep_research` to synthesize all gathered findings into a final report.\n\n"
        "For each step, ask a clear, full-sentence question that explicitly mentions the company ticker."
    ),
    model=OpenAIResponsesModel(
        model="gpt-4.1",
        openai_client=openai_client,
    ),
    tools=[
        sec_agent.as_tool(
            tool_name="analyze_sec_filings",
            tool_description="Reviews SEC filings for disclosures, risk factors, and filing highlights.",
        ),
        financials_agent.as_tool(
            tool_name="analyze_financials",
            tool_description="Analyzes financial statements, ratios, margins, and growth trends.",
        ),
        transcripts_agent.as_tool(
            tool_name="analyze_transcripts",
            tool_description="Analyzes earnings call transcripts, guidance, and management commentary.",
        ),
        stock_data_agent.as_tool(
            tool_name="analyze_stock_data",
            tool_description="Analyzes recent stock performance, trading volume, and market context.",
        ),
        deep_research_agent.as_tool(
            tool_name="conduct_deep_research",
            tool_description="Synthesizes cross-source findings into a comprehensive investment report.",
        ),
    ],
)


async def run_research_workflow(company_name, ticker):
    """Run the research workflow using the Runner to handle tool calls."""
    user_input = f"Create a comprehensive public-market investment research report for {company_name} ({ticker})."

    try:
        with trace("Public Market Research Workflow"):
            result = await Runner.run(coordinator, user_input)

            for item in result.new_items:
                if isinstance(item, MessageOutputItem):
                    text = ItemHelpers.text_message_output(item)
                    if text:
                        print(f"\n{text}")

        return result.final_output
    except Exception as error:
        return f"Error: {error}"


async def main():
    final_report = await run_research_workflow("Apple", "AAPL")
    print("\nFinal report:")
    print(final_report)


if __name__ == "__main__":
    asyncio.run(main())
JavaScript
import { OpenAI } from 'openai';
import { Agent, ItemHelpers, MessageOutputItem, OpenAIResponsesModel, Runner, trace } from '@openai/agents';

const openaiApiKey = process.env.OPENAI_API_KEY || '<your-openai-api-key>';
const octagonApiKey = process.env.OCTAGON_API_KEY || '<your-octagon-api-key>';

const octagonClient = new OpenAI({
  apiKey: octagonApiKey,
  baseURL: 'https://api.octagonai.co/v1'
});

const openaiClient = new OpenAI({
  apiKey: openaiApiKey
});

const secAgent = new Agent({
  name: 'SEC Filings Analysis',
  instructions: 'You analyze SEC filings to extract disclosures, risk factors, MD&A commentary, and regulatory filing insights.',
  model: new OpenAIResponsesModel({
    model: 'octagon-sec-agent',
    openaiClient: octagonClient
  })
});

const financialsAgent = new Agent({
  name: 'Financials Analysis',
  instructions: 'You analyze financial statements, ratios, margins, growth, and profitability trends.',
  model: new OpenAIResponsesModel({
    model: 'octagon-financials-agent',
    openaiClient: octagonClient
  })
});

const transcriptsAgent = new Agent({
  name: 'Earnings Call Analysis',
  instructions: 'You analyze earnings call transcripts, management commentary, guidance, and analyst Q&A.',
  model: new OpenAIResponsesModel({
    model: 'octagon-transcripts-agent',
    openaiClient: octagonClient
  })
});

const stockDataAgent = new Agent({
  name: 'Stock Data Analysis',
  instructions: 'You analyze stock prices, trading volume, market trends, and recent performance.',
  model: new OpenAIResponsesModel({
    model: 'octagon-stock-data-agent',
    openaiClient: octagonClient
  })
});

const deepResearchAgent = new Agent({
  name: 'Deep Research',
  instructions: 'You synthesize findings from multiple sources into a comprehensive investment research report.',
  model: new OpenAIResponsesModel({
    model: 'octagon-deep-research-agent',
    openaiClient: octagonClient
  })
});

const coordinator = new Agent({
  name: 'Research Coordinator',
  instructions: [
    'You are a research coordinator building a public-market investment research report.',
    'Follow this exact workflow:',
    '1. Use `analyze_sec_filings` to review recent disclosures and filing highlights.',
    '2. Use `analyze_financials` to evaluate financial statement trends and key metrics.',
    '3. Use `analyze_transcripts` to summarize management commentary and guidance.',
    '4. Use `analyze_stock_data` to review recent stock performance and market context.',
    '5. Use `conduct_deep_research` to synthesize all gathered findings into a final report.',
    'For each step, ask a clear, full-sentence question that explicitly mentions the company ticker.'
  ].join('\n'),
  model: new OpenAIResponsesModel({
    model: 'gpt-4.1',
    openaiClient
  }),
  tools: [
    secAgent.asTool({
      toolName: 'analyze_sec_filings',
      toolDescription: 'Reviews SEC filings for disclosures, risk factors, and filing highlights.'
    }),
    financialsAgent.asTool({
      toolName: 'analyze_financials',
      toolDescription: 'Analyzes financial statements, ratios, margins, and growth trends.'
    }),
    transcriptsAgent.asTool({
      toolName: 'analyze_transcripts',
      toolDescription: 'Analyzes earnings call transcripts, guidance, and management commentary.'
    }),
    stockDataAgent.asTool({
      toolName: 'analyze_stock_data',
      toolDescription: 'Analyzes recent stock performance, trading volume, and market context.'
    }),
    deepResearchAgent.asTool({
      toolName: 'conduct_deep_research',
      toolDescription: 'Synthesizes cross-source findings into a comprehensive investment report.'
    })
  ]
});

async function runResearchWorkflow(companyName, ticker) {
  const userInput = `Create a comprehensive public-market investment research report for ${companyName} (${ticker}).`;

  try {
    const result = await trace('Public Market Research Workflow', async () => {
      const runResult = await Runner.run(coordinator, userInput);

      for (const item of runResult.newItems) {
        if (item instanceof MessageOutputItem) {
          const text = ItemHelpers.textMessageOutput(item);
          if (text) {
            console.log(`\n${text}`);
          }
        }
      }

      return runResult;
    });

    return result.finalOutput;
  } catch (error) {
    return `Error: ${error.message}`;
  }
}

runResearchWorkflow('Apple', 'AAPL')
  .then(finalReport => {
    console.log('\nFinal report:');
    console.log(finalReport);
  })
  .catch(console.error);

How the Research Workflow Works

The example uses the Agents SDK tool pattern to let an OpenAI coordinator delegate focused tasks to specialized Octagon agents. Each specialist gathers one slice of the research packet, and the Deep Research agent synthesizes the findings into a final report.

Key Components

  1. Specialized Agents: The workflow uses SEC filings, financials, transcripts, stock data, and deep research agents.
  2. Coordinator Agent: An OpenAI coordinator model (gpt-4.1 in this example) orchestrates the workflow and delegates each step to the specialized tools.
  3. Context Passing: Each agent's findings are passed as context to subsequent steps, ensuring a cohesive analysis flow.

Running the Example

To run this example:

  1. Save the code to a file (e.g., octagon_research_workflow.py or octagon_research_workflow.js)
  2. Install the required dependencies:
sh
pip install openai openai-agents
sh
npm install openai @openai/agents
  1. Replace the API key placeholders with your actual keys
  2. Run the script:
sh
python octagon_research_workflow.py
sh
node octagon_research_workflow.js

Customizing the Workflow

You can customize this workflow for your specific research needs:

  • Different Company: Change the company_name and ticker values to research another public company.
  • Additional Agents: Add more supported Octagon agents, such as holdings or crypto, when relevant.
  • Custom Instructions: Modify each agent's instructions to focus on specific aspects of financial analysis.
  • Different Output Format: Customize the report generation step to output in different formats such as PDF, JSON, or Markdown.

Next Steps