Skip to content

๐Ÿ’ธAgent-based stock analysis and investment strategy application ๐Ÿ”ทMicrosoft Agent Framework ๐ŸŽฐAutoGen

Notifications You must be signed in to change notification settings

kimtth/agent-quant-stock-invest

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

27 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿ’ธ Quantitative Investment Agent

Multi-agent quantitative investment analysis system

๐Ÿ“– Overview

An automated trading analysis system that:

  • Fetches stock data from Yahoo Finance
  • Generates technical trading signals (MACD, RSI, etc.)
  • Backtests strategies with performance metrics (CAGR, MDD, Sharpe Ratio)
  • Uses workflow-based orchestration for agent coordination

Architecture: Workflow-based with executors, function tools, and type-safe schemas.

๐Ÿš€ Quick Start

# 1. Install dependencies
uv sync
# Or if using poetry: poetry install

# 2. Set up environment variables
cp .env.example .env
# Edit .env and add your Azure OpenAI credentials

# 3. Run the workflow
python main.py

Samples

See the generated files under output.

  • Input sample
Analyze Apple (AAPL) stock using a momentum trading strategy:
1. Fetch historical data from 2023-01-01 to 2024-01-01
2. Generate buy/sell signals using MACD and RSI indicators
3. Backtest the strategy with initial capital of $10,000
4. Report performance metrics (CAGR, total return, final value)
  • Output sample
===== Final Output =====
Summary report โ€” backtest outcome

Key results
- Final portfolio value: $11,157.97
- Total return: 11.58% (profit $1,157.97 on implied $10,000 start)
- CAGR: 11.68% (close to total return โ†’ consistent with ~1-year test horizon)
- Result files: backtest_results.xlsx / backtest_metrics.txt

Quick interpretation
- The strategy produced a positive return (~11.6%) on the test period with a final value of $11.16k.
- The near-equality of CAGR and total return indicates the backtest covers roughly one year (or that returns were concentrated in a short single-period test).
- The absolute profit ($1,157.97) is modest but meaningful for a single-year horizon; risk-adjusted conclusions require volatility and drawdown data (not included here).

๐Ÿ—๏ธ Architecture

Data-Flow Workflow Pattern

flowchart TD
    classDef start fill:#2e7d32,color:#fff;
    classDef task fill:#1976d2,color:#fff;
    classDef decision fill:#f9a825,color:#000;
    
    A[fetch_data]:::start --> B[generate_signals]:::task
    B -->|signals exist| C[backtest]:::task
    B -->|no signals| D[summary_report]:::task
    C --> D
Loading

Key Components:

  • Executors: Workflow building blocks (agents with tools)
  • Edges: Data flow connections with conditional routing
  • WorkflowBuilder: Constructs the data-flow graph
  • Function Tools: agent_tools.py

๐Ÿ”‘ Key Differences from AutoGen

Aspect Legacy AutoGen Microsoft Agent Framework
Orchestration GroupChat + select_speaker WorkflowBuilder + edges
Message Flow Broadcast to all agents Data flows through edges
Agents AssistantAgent, ConversableAgent ChatAgent (stateless)
Tools FunctionTool class class or @ai_function decorator
State Built into agents AgentThread for context
Pattern Control-flow (event-driven) Data-flow (workflow-based)
Routing Custom logic in manager Conditional edges

๐Ÿ“Š System Architecture Comparison

Legacy AutoGen Architecture

flowchart TD
    classDef proxy fill:#455a64,color:#fff;
    classDef manager fill:#6a1b9a,color:#fff;
    classDef agent fill:#1976d2,color:#fff;
    
    A[User Input] --> B[UserProxyAgent]:::proxy
    B --> C[GroupChatManager<br/>Custom speaker selection]:::manager
    C --> D[Stock Analysis Agent]:::agent
    C --> E[Signal Analysis Agent<br/>Pytho code executor]:::agent
    C --> F[Code Executor Agent]:::agent
    D --> G[Tools]
    E --> G
    F --> G
    G --> H[Manual Result Collection]
Loading

Microsoft Agent Framework Architecture

flowchart TD
    classDef orchestrator fill:#6a1b9a,color:#fff;
    classDef agent fill:#1976d2,color:#fff;
    classDef decision fill:#f9a825,color:#000;
    
    A[User Input] --> B[QuantInvestWorkflow]:::orchestrator
    B --> C[WorkflowBuilder]:::orchestrator
    
    subgraph Pipeline [Type-Safe Workflow Pipeline]
        D[Stock Data Agent]:::agent --> E[Signal Generation Agent<br/>Pytho code executor]:::agent
        E --> F{signals file?}:::decision
        F -->|exists| G[Backtest Agent]:::agent
        F -->|missing| H[Skip to Summary]:::agent
        G --> I[Summary Report Agent]:::agent
        H --> I
    end
    
    C --> D
    I --> J[Final Output]
Loading

Key Improvements:

  • โœ… Automatic routing via conditional edges
  • โœ… Built-in error handling via WorkflowOutputEvent, ExecutorCompletedEvent
  • โœ… Type safety with Pydantic models (AgentCompletedResult)
  • โœ… Streaming support via Workflow.run_stream
  • โœ… State management via WorkflowContext
  • โœ… Visualization via WorkflowViz (generates Mermaid diagrams)

๐Ÿ“ Project Structure

autogen-quant-invest-agent/
โ”œโ”€โ”€ main.py                  # Entry point
โ”œโ”€โ”€ agent_workflow.py        # Workflow orchestration
โ”œโ”€โ”€ agent_quant.py           # Agent definitions
โ”œโ”€โ”€ agent_tools.py           # Function tools
โ”œโ”€โ”€ constants.py             # Configuration
โ”œโ”€โ”€ pyproject.toml           # Dependencies
โ”œโ”€โ”€ human_in_loop/           # Human oversight samples
โ”‚   โ””โ”€โ”€ main_invest_approval.py  # Investment approval workflow
โ”œโ”€โ”€ output/                  # Generated files
โ”‚   โ”œโ”€โ”€ stock_data.csv
โ”‚   โ”œโ”€โ”€ stock_signals.csv
โ”‚   โ”œโ”€โ”€ backtest_results.xlsx
โ”‚   โ””โ”€โ”€ backtest_metrics.txt
โ””โ”€โ”€ legacy_autogen/          # Original AutoGen implementation

๐Ÿง‘โ€๐Ÿ’ผ Human-in-the-Loop: Investment Approval Workflow

The human_in_loop/main_invest_approval.py sample demonstrates a human oversight pattern for critical investment decisions using RequestInfoExecutor.

Features

  • Human approval gates: Agent generates investment recommendations, then pauses for human approval
  • Iterative refinement: Humans can request modifications with specific feedback (e.g., "refine focus on risk factors")
  • Structured output: Uses Pydantic response_format for type-safe investment recommendations (ticker, action, rationale, confidence)
  • Multi-turn workflow: Continues until human approves, requests changes, or exits

Workflow Pattern

flowchart TD
    classDef human fill:#e65100,color:#fff;
    classDef agent fill:#1976d2,color:#fff;
    classDef decision fill:#f9a825,color:#000;
    
    A[User Input<br/>Stock Ticker] --> B[Investment Agent<br/>Analyzes Stock]:::agent
    B --> C[Generate<br/>Recommendation]:::agent
    C --> D{Human Decision}:::human
    D -->|approve| E[Execute Decision]
    D -->|refine| F[Provide Feedback]:::human
    D -->|exit| G[Cancel]
    F --> B
Loading

Usage

# Run the human-in-the-loop workflow
python human_in_loop/main_invest_approval.py

# Example interaction:
# Enter ticker: MSFT
# [Agent analyzes and generates recommendation]
# Your decision: refine focus on risk factors
# [Agent refines based on feedback]
# Your decision: approve

Key Components

  • InvestmentTurnManager: Coordinates agent-human turns and processes approval/feedback
  • RequestInfoExecutor: Pauses workflow for human input at critical decision points
  • InvestmentRecommendation: Pydantic model for structured output (BUY/SELL/HOLD with rationale)
  • Multi-turn loop: Continues until human approval or cancellation

This pattern is essential for high-stakes AI applications where human oversight is required before executing decisions.


๐Ÿ“Š Dev UI

The dev_ui/main_dev_ui.py sample demonstrates Dev UI Integration with QuantInvestWorkflow.

Dev_UI

๐Ÿ“š Resources

๐Ÿ“ License

MIT

About

๐Ÿ’ธAgent-based stock analysis and investment strategy application ๐Ÿ”ทMicrosoft Agent Framework ๐ŸŽฐAutoGen

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •