1. Learning Objectives

By the end of this lesson, you will be able to:

  • Design and implement autonomous agents for end-to-end financial workflows (research → analysis → decision → execution → reporting).

  • Apply agentic planning frameworks (Plan-and-Solve, Tree-of-Thoughts) to complex financial decision-making.

  • Implement tool-calling and API integration for agents to interact with market data, trading platforms, and research databases.

  • Build agents for automated due diligence, investment memo generation, and portfolio monitoring.

  • Design robust agent architectures with error handling, retry logic, and fallback mechanisms.

  • Evaluate agent performance in real-time and simulated environments.


2. The Agentic Workflow Architecture

2.1 End-to-End Workflow Design

An end-to-end financial agentic workflow typically follows a pipeline architecture with feedback loops:

text
┌─────────────────────────────────────────────────────────────────────────────┐
│                         AGENTIC WORKFLOW PIPELINE                          │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────┐    ┌──────────┐ │
│  │   PERCEPTION  │───▶│   ANALYSIS   │───▶│   PLANNING   │───▶│  ACTION  │ │
│  │  (Data Ingest)│    │  (Reasoning) │    │  (Strategy)  │    │(Execution)│ │
│  └──────────────┘    └──────────────┘    └──────────────┘    └──────────┘ │
│         │                    │                    │               │        │
│         │                    │                    │               │        │
│         └────────────────────┴────────────────────┴───────────────┘        │
│                                    │                                        │
│                                    ▼                                        │
│                          ┌─────────────────┐                               │
│                          │   REFLECTION    │                               │
│                          │  (Evaluation)   │─────────────────────────────┐ │
│                          └─────────────────┘                             │ │
│                                    │                                      │ │
│                                    ▼                                      │ │
│                          ┌─────────────────┐                              │ │
│                          │   MEMORY UPDATE │                              │ │
│                          └─────────────────┘                              │ │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
2.2 Detailed Workflow Stages
 
 
Stage Description Tools/Techniques Output
1. Perception Gather data from multiple sources. Market data APIs (Bloomberg, Yahoo Finance), News APIs (Reuters, Bloomberg), Regulatory filings (EDGAR), Social media. Structured data + Raw text.
2. Data Preprocessing Clean, normalize, and structure data. Data pipelines, time-series alignment, NLP preprocessing. Clean feature matrices.
3. Analysis Apply analytical models. Statistical models, ML models, LLM reasoning. Insights, predictions, sentiment scores.
4. Planning Determine optimal actions. Optimization, RL, LLM planning. Action plan.
5. Execution Execute actions. Trading APIs, order management systems, report generation. Trades, reports, alerts.
6. Monitoring Track execution and outcomes. Real-time dashboards, performance tracking. Performance metrics.
7. Reflection Evaluate and learn from outcomes. Post-trade analysis, model retraining. Updated strategies.

3. Planning Frameworks for Agentic AI

3.1 Plan-and-Solve

The Plan-and-Solve framework decomposes a complex task into a sequence of sub-tasks. The agent first generates a plan and then executes each step.

Algorithm:

text
def plan_and_solve(goal):
    # Step 1: Generate a plan
    plan = generate_plan(goal)
    
    # Step 2: Execute each step sequentially
    for step in plan:
        result = execute_step(step)
        # Store result for use in subsequent steps
    
    # Step 3: Synthesize final output
    return synthesize_output(plan, results)

Prompt for plan generation:

text
You are an autonomous agent. Generate a step-by-step plan to achieve the following goal:

Goal: "{goal}"

Constraints:
- Available tools: {tools}
- Time horizon: {time_horizon}
- Risk limits: {risk_limits}

Provide a detailed plan with clear dependencies between steps.
Plan:
3.2 Tree-of-Thoughts (ToT)

ToT explores multiple reasoning paths and chooses the best one. This is particularly useful for ambiguous financial decisions where there is no single correct answer.

Algorithm:

text
def tree_of_thoughts(problem, depth=3, breadth=5):
    # Step 1: Generate initial thoughts
    thoughts = generate_initial_thoughts(problem, breadth)
    
    # Step 2: For each level of depth
    for level in range(depth):
        new_thoughts = []
        for thought in thoughts:
            # Generate next steps
            next_steps = generate_next_steps(thought, breadth)
            # Evaluate each next step
            for step in next_steps:
                score = evaluate_step(step)
                new_thoughts.append((step, score))
        # Keep only the top-k thoughts
        thoughts = select_top_k(new_thoughts, breadth)
    
    # Step 3: Return the best path
    return best_path(thoughts)

Financial application: For an investment decision, ToT can explore different scenarios (bull, bear, base) and their implications.

3.3 Self-Reflection and Self-Correction

Agents can reflect on their own actions and correct mistakes. The Reflexion framework uses a self-evaluation module that critiques the agent’s actions.

Reflexion loop:

text
while not satisfied:
    action = agent.act()
    evaluation = agent.evaluate(action)
    if evaluation.is_successful():
        break
    else:
        agent.update_plan(evaluation.feedback())

Prompt for self-reflection:

text
You recently executed the following action:
Action: {action}
Result: {result}

Critique your action:
1. Was this the right decision?
2. What could you have done differently?
3. What did you learn from this experience?

Revised plan:

4. Tool Integration and API Calling

4.1 Tool Design

An agent’s tools are functions that extend its capabilities. Each tool should have:

  • Name: A unique identifier.

  • Description: What the tool does, when to use it.

  • Input schema: The parameters the tool accepts.

  • Output schema: The data the tool returns.

Example tool definitions:

python
tools = [
    {
        "name": "get_stock_price",
        "description": "Get the current price of a stock.",
        "parameters": {
            "ticker": {"type": "string", "description": "The ticker symbol."}
        },
        "output": {"type": "object", "properties": {"price": {"type": "number"}}}
    },
    {
        "name": "get_financials",
        "description": "Get the financial statements of a company.",
        "parameters": {
            "ticker": {"type": "string", "description": "The ticker symbol."}
        },
        "output": {"type": "object", "properties": {"income_statement": {}, "balance_sheet": {}}}
    },
    {
        "name": "execute_trade",
        "description": "Execute a trade.",
        "parameters": {
            "ticker": {"type": "string"},
            "quantity": {"type": "integer"},
            "side": {"type": "string", "enum": ["buy", "sell"]}
        },
        "output": {"type": "object", "properties": {"order_id": {"type": "string"}}}
    }
]
4.2 Function Calling with LLMs

LLMs can generate structured calls to tools. For example, OpenAI’s function calling API:

python
response = openai.ChatCompletion.create(
    model="gpt-4",
    messages=[{"role": "user", "content": "What is the price of AAPL?"}],
    functions=tools,
    function_call="auto"
)

The model returns a function call:

json
{
    "name": "get_stock_price",
    "arguments": {
        "ticker": "AAPL"
    }
}

The agent then executes the function and returns the result.

4.3 Handling API Errors and Retries

Financial APIs can fail due to network issues, rate limits, or maintenance. The agent must handle these gracefully.

Error handling pattern:

text
def execute_with_retry(tool, params, max_retries=3):
    for attempt in range(max_retries):
        try:
            result = tool.execute(params)
            return result
        except RateLimitError:
            wait_time = 2 ** attempt  # Exponential backoff
            time.sleep(wait_time)
        except DataUnavailableError:
            return fallback_value()
    return error_response()

5. Automated Due Diligence Agent

5.1 Use Case: Investment Due Diligence

An agent can automate the due diligence process for potential investments.

Workflow:

  1. Company identification: Identify target companies based on screening criteria.

  2. Data collection: Collect financial statements, earnings calls, news, and analyst reports.

  3. Financial analysis: Compute key metrics (revenue growth, margins, ROE, debt ratios, free cash flow).

  4. Competitive analysis: Analyze competitors and market positioning.

  5. Risk assessment: Identify key risks (financial, operational, regulatory, ESG).

  6. Valuation: Perform DCF analysis, comparable company analysis, and precedent transactions.

  7. Report generation: Generate a comprehensive due diligence report with investment recommendation.

Agent prompt:

text
You are an autonomous due diligence agent.

Your task: Conduct a thorough due diligence on Company {ticker}.

Step 1: Gather all available information.
Step 2: Analyze financials and compute key metrics.
Step 3: Analyze competitive landscape.
Step 4: Identify key risks.
Step 5: Perform valuation.
Step 6: Provide an investment recommendation (Buy/Hold/Sell) with rationale.

Available tools:
- get_financials(ticker)
- get_earnings_transcript(ticker, quarter)
- get_news(ticker, days)
- get_competitors(ticker)
- get_analyst_reports(ticker)
- compute_dcf(financials)
- get_industry_data(sector)
- generate_report(data)

Proceed methodically. Document your reasoning at each step.
5.2 Financial Metrics Computation

The agent can compute financial metrics automatically:

text
Revenue Growth = (Revenue_t - Revenue_{t-1}) / Revenue_{t-1}
Gross Margin = Gross Profit / Revenue
Operating Margin = Operating Income / Revenue
Net Margin = Net Income / Revenue
ROE = Net Income / Shareholders' Equity
ROA = Net Income / Total Assets
Debt-to-Equity = Total Debt / Shareholders' Equity
Current Ratio = Current Assets / Current Liabilities
Quick Ratio = (Current Assets - Inventory) / Current Liabilities
Free Cash Flow = Operating Cash Flow - Capital Expenditures
5.3 DCF Valuation

The agent can perform a discounted cash flow (DCF) valuation:

text
FCF_t = Free Cash Flow in year t
Terminal Value = FCF_n * (1 + g) / (WACC - g)
Enterprise Value = ∑_{t=1}^{n} FCF_t / (1 + WACC)^t + Terminal Value / (1 + WACC)^n
Equity Value = Enterprise Value - Net Debt
Target Price = Equity Value / Number of Shares

The agent can then compare the target price with the current market price to generate a recommendation.


6. Automated Investment Memo Generator

6.1 Investment Memo Structure

A standard investment memo includes:

  1. Executive Summary: The investment thesis and recommendation.

  2. Business Overview: What the company does, its products, and its market.

  3. Market Analysis: Industry trends, competitive landscape, and market positioning.

  4. Financial Analysis: Historical and projected financials, key metrics.

  5. Valuation: DCF, comparable analysis, sensitivity analysis.

  6. Risk Factors: Key risks and mitigants.

  7. Investment Recommendation: Buy/Hold/Sell with a target price.

6.2 Agentic Memo Generation

The agent can generate an investment memo by following a structured template and filling in the analysis.

Memo generation prompt:

text
You are an autonomous investment memo generator.

Based on your due diligence analysis, generate a comprehensive investment memo.

Structure:
1. Executive Summary (1 paragraph)
2. Business Overview (1-2 paragraphs)
3. Market Analysis (1-2 paragraphs)
4. Financial Analysis (with key metrics and trends)
5. Valuation (DCF and comparable analysis)
6. Risk Factors (3-5 risks)
7. Investment Recommendation (with target price and rationale)

Use the data and analysis from your due diligence. Ensure the memo is professional and well-structured.

Data: {due_diligence_data}
6.3 Multi-Agent Memo Generation

A multi-agent system can improve memo quality:

  1. Writer Agent: Drafts the memo.

  2. Reviewer Agent: Critiques the draft for completeness and accuracy.

  3. Editor Agent: Polishes the final version.


7. Automated Trading Agent

7.1 High-Frequency vs. Long-Term Trading
 
 
Aspect High-Frequency Agent Long-Term Agent
Horizon Seconds to minutes Days to months
Data Tick data, LOB Daily data, fundamentals
Strategy Market-making, arbitrage Factor investing, value
Latency Milliseconds Minutes
Toolset LOB APIs, colocation Financial APIs, research
7.2 Trading Agent Architecture
text
┌─────────────────────────────────────────────────────────────┐
│                     TRADING AGENT                          │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────────┐ │
│  │  Data Feed  │───▶│   Strategy  │───▶│  Risk Manager   │ │
│  │  (Market,   │    │   (ML/LLM)  │    │  (Constraints)  │ │
│  │   News)     │    │             │    │                 │ │
│  └─────────────┘    └─────────────┘    └─────────────────┘ │
│         │                  │                    │           │
│         └──────────────────┴────────────────────┘           │
│                              │                               │
│                              ▼                               │
│                    ┌─────────────────┐                      │
│                    │  Order Manager  │                      │
│                    │  (Execution)    │                      │
│                    └─────────────────┘                      │
│                              │                               │
│                              ▼                               │
│                    ┌─────────────────┐                      │
│                    │  Trade Logging  │                      │
│                    │  & Monitoring   │                      │
│                    └─────────────────┘                      │
│                                                             │
└─────────────────────────────────────────────────────────────┘
7.3 Risk Constraints for Trading Agents

The agent must respect risk constraints:

  • Position limits: Maximum exposure per asset.

  • Leverage limits: Maximum leverage ratio.

  • Drawdown limits: Stop loss if drawdown exceeds threshold.

  • VaR limits: Maximum VaR at 95% confidence.

  • Sector limits: Maximum exposure per sector.

  • Beta constraints: Portfolio beta within a range.

Risk prompt:

text
You are a trading agent with the following risk constraints:
- Max position size per asset: 5% of portfolio
- Max leverage: 1.5x
- Max daily drawdown: 2%
- Max VaR (95%): 3%
- Min Sharpe ratio: 1.5

Your goal: Maximize returns while strictly respecting these constraints.

Proposed action: {action}
Risk check: Pass/Fail
Reasoning: {reasoning}

8. Error Handling and Robustness

8.1 Common Failure Modes
 
 
Failure Mode Example Mitigation
API failure Market data API is down. Retry with exponential backoff; use fallback data source.
Data inconsistency Different sources give different prices. Use a consensus price; flag for human review.
LLM hallucination The agent generates a plausible but incorrect analysis. Ground with RAG; use factual validation.
Execution failure Order is rejected due to insufficient liquidity. Adjust order size; retry with limit order.
Risk violation The agent proposes an action that violates risk limits. Reject the action; escalate to human.
8.2 Recovery Mechanisms

Checkpointing: The agent periodically saves its state, allowing it to resume from a checkpoint if a failure occurs.

Graceful degradation: If a tool is unavailable, the agent uses a fallback method. For example, if real-time prices are unavailable, it uses the last known price.

Human escalation: If the agent cannot resolve an issue, it escalates to a human with a clear explanation.

8.3 Agent Monitoring

All agent actions should be logged and monitored:

 
 
Log Category Description Example
Inputs The data the agent received. {"ticker": "AAPL", "price": "175.00"}
Reasoning The agent’s thought process. "P/E ratio is 15, below industry average of 18"
Action The action taken. {"action": "buy", "ticker": "AAPL", "quantity": 100}
Outcome The result of the action. {"status": "executed", "price": "175.00"}
Performance Key metrics. {"pnl": 100, "sharpe": 1.2}

9. Summary for the AI Practitioner

  • Agentic workflows automate the entire financial pipeline: research → analysis → planning → execution → reporting.

  • Plan-and-Solve and Tree-of-Thoughts are powerful planning frameworks for complex financial decisions.

  • Tool integration (APIs, functions) enables agents to interact with financial systems and data sources.

  • Automated due diligence and investment memo generation are high-value use cases for agentic AI.

  • Risk constraints and error handling are critical for safe and reliable agent deployment.

  • Continuous monitoring and logging provide auditability and enable performance improvement.