1- # 💸 Quantitative Investment Agent
1+ < div align = " center " >
22
3- ** Multi-agent quantitative investment analysis system **
3+ ** [ Agent Framework ] ( README.md ) ** & nbsp ; | & nbsp ; [ Legacy AutoGen ] ( legacy_autogen/README.md )
44
5- - Built with [ Microsoft Agent Framework] ( https://github.com/microsoft/agent-framework ) (Semantic Kernel + AutoGen), featuring a workflow inspired by [ Pregel] ( https://research.google/pubs/pub37252/ ) .
6- - Legacy version built with AutoGen (See the [ README.md] ( ./legacy_autogen/README.md ) under ` legacy_autogen ` )
7- - [ Assumptions behind the CAGR calculation] ( ./legacy_autogen/README.md/#cagr-calculation )
5+ </div >
86
9- ## 📖 Overview
7+ ---
108
11- An automated trading analysis system that:
12- - Fetches stock data from Yahoo Finance
13- - Generates technical trading signals (MACD, RSI, etc.)
14- - Backtests strategies with performance metrics (CAGR, MDD, Sharpe Ratio)
15- - Uses workflow-based orchestration for agent coordination
9+ # 💸 Quantitative Investment Agent
1610
17- Architecture: Workflow-based with executors, function tools, and type-safe schemas .
11+ Multi-agent quantitative investment analysis system built with [ Microsoft Agent Framework ] ( https://github.com/microsoft/agent-framework ) (Semantic Kernel + AutoGen), using a [ Pregel ] ( https://research.google/pubs/pub37252/ ) -inspired data-flow workflow .
1812
1913## 🚀 Quick Start
2014
2115``` bash
22- # 1. Install dependencies
2316uv sync
24-
25- # 2. Set up environment variables
26- cp .env.example .env
27- # Edit .env and add your Azure OpenAI credentials
28-
29- # 3. Run the workflow
30- python main.py
17+ cp .env.example .env # add Azure OpenAI credentials
18+ uv run main.py
3119```
3220
33- ## Samples
21+ ## 📖 Overview
3422
35- See the generated files under ` output ` .
23+ Fetches stock data → generates technical signals (MACD, RSI) → backtests → reports metrics (CAGR, MDD, Sharpe Ratio) .
3624
37- - Input sample
25+ ** Sample input **
3826```
3927Analyze Apple (AAPL) stock using a momentum trading strategy:
40281. Fetch historical data from 2023-01-01 to 2024-01-01
@@ -43,7 +31,7 @@ Analyze Apple (AAPL) stock using a momentum trading strategy:
43314. Report performance metrics (CAGR, total return, final value)
4432```
4533
46- - Output sample
34+ ** Sample output **
4735```
4836===== Final Output =====
4937Summary report — backtest outcome
@@ -56,184 +44,91 @@ Key results
5644
5745Quick interpretation
5846- The strategy produced a positive return (~11.6%) on the test period with a final value of $11.16k.
59- - 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) .
60- - 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) .
47+ - The near-equality of CAGR and total return indicates the backtest covers roughly one year.
48+ - The absolute profit ($1,157.97) is modest but meaningful for a single-year horizon.
6149```
6250
6351## 🏗️ Architecture
6452
65- ### Data-Flow Workflow Pattern
66-
67- ``` mermaid
68- flowchart TD
69- classDef boot fill:#fffacd,stroke:#333,stroke-width:2px
70- classDef mem fill:#fff0f5,stroke:#333,stroke-width:2px
71-
72- A[fetch_data]:::boot --> B[generate_signals]:::mem
73- B -->|signals exist| C[backtest]:::mem
74- B -->|no signals| D[summary_report]:::mem
75- C --> D:::mem
76- ```
77-
78- ** Key Components** :
79- - ** Executors** : Workflow building blocks (agents with tools)
80- - ** Edges** : Data flow connections with conditional routing
81- - ** WorkflowBuilder** : Constructs the data-flow graph
82- - ** Function Tools** : ` agents/tools.py `
83-
84- ## 🔑 Key Differences from AutoGen
85-
86- | Aspect | Legacy AutoGen | Microsoft Agent Framework |
87- | --------| ---------------| --------------------------|
88- | ** Orchestration** | ` GroupChat ` + ` select_speaker ` | ` WorkflowBuilder ` + edges |
89- | ** Message Flow** | Broadcast to all agents | Data flows through edges |
90- | ** Agents** | ` AssistantAgent ` , ` ConversableAgent ` | ` ChatAgent ` (stateless) |
91- | ** Tools** | ` FunctionTool ` class | class or ` @ai_function ` decorator |
92- | ** State** | Built into agents | ` AgentThread ` for context |
93- | ** Pattern** | Control-flow (event-driven) | Data-flow (workflow-based) |
94- | ** Routing** | Custom logic in manager | Conditional edges |
95-
96- ## 📊 System Architecture Comparison
97-
98- ### Legacy AutoGen Architecture
99-
10053``` mermaid
10154flowchart TD
102- classDef hw fill:#e6e6fa,stroke:#333,stroke-width:2px
103- classDef kernel fill:#f5f5dc,stroke:#333,stroke-width:2px
104- classDef cpu fill:#f0f8ff,stroke:#333,stroke-width:2px
105-
106- A[User Input]:::hw --> B[UserProxyAgent]:::hw
107- B --> C[GroupChatManager<br/>Custom speaker selection]:::kernel
108- C --> D[Stock Analysis Agent]:::cpu
109- C --> E[Signal Analysis Agent<br/>Python code executor]:::cpu
110- C --> F[Code Executor Agent]:::cpu
111- D --> G[Tools]:::hw
112- E --> G
113- F --> G
114- G --> H[Manual Result Collection]:::kernel
115- ```
116-
117- ### Microsoft Agent Framework Architecture
55+ classDef orchestrator fill:#f0fff0,stroke:#999,stroke-width:1px
56+ classDef agent fill:#f0f8ff,stroke:#333,stroke-width:2px
57+ classDef decision fill:#ffe4e1,stroke:#333,stroke-width:2px
11858
119- ``` mermaid
120- flowchart TD
121- classDef kernel fill:#f5f5dc,stroke:#333,stroke-width:2px
122- classDef cpu fill:#f0f8ff,stroke:#333,stroke-width:2px
123- classDef proc fill:#ffe4e1,stroke:#333,stroke-width:2px
124-
125- A[User Input]:::kernel --> B[QuantInvestWorkflow]:::kernel
126- B --> C[WorkflowBuilder]:::kernel
59+ A[User Input]:::orchestrator --> B[QuantInvestWorkflow]:::orchestrator
60+ B --> C[WorkflowBuilder]:::orchestrator
12761
12862 subgraph Pipeline [Type-Safe Workflow Pipeline]
129- D[Stock Data Agent]:::cpu --> E[Signal Generation Agent<br/>Python code executor]:::cpu
130- E --> F{signals file?}:::proc
131- F -->|exists| G[Backtest Agent]:::cpu
132- F -->|missing| H[Skip to Summary]:::cpu
133- G --> I[Summary Report Agent]:::cpu
63+ D[Stock Data Agent]:::agent --> E[Signal Generation Agent<br/>Python code executor]:::agent
64+ E --> F{signals file?}:::decision
65+ F -->|exists| G[Backtest Agent]:::agent
66+ F -->|missing| H[Skip to Summary]:::agent
67+ G --> I[Summary Report Agent]:::agent
13468 H --> I
13569 end
70+ style Pipeline fill:none,stroke:#333,stroke-width:1px
13671
13772 C --> D
138- I --> J[Final Output]:::kernel
73+ I --> J[Final Output]:::orchestrator
13974```
14075
141- ** Key Improvements** :
142- - ✅ ** Automatic routing** via conditional edges
143- - ✅ ** Built-in error handling** via WorkflowOutputEvent, ExecutorCompletedEvent
144- - ✅ ** Type safety** with Pydantic models (AgentCompletedResult)
145- - ✅ ** Streaming support** via Workflow.run_stream
146- - ✅ ** State management** via WorkflowContext
147- - ✅ ** Visualization** via WorkflowViz (generates Mermaid diagrams)
76+ | Component | Description |
77+ | -----------| -------------|
78+ | ** Executors** | Agents with tools — the workflow building blocks |
79+ | ** Edges** | Data-flow connections with conditional routing |
80+ | ** WorkflowBuilder** | Constructs the directed graph |
81+ | ** Tools** | ` agents/tools.py ` — function tools for each agent |
14882
149- ## 📁 Project Structure
83+ ## 📐 Calculation Assumptions
15084
151- ```
152- agent-quant-stock-invest/
153- ├── main.py # Entry point
154- ├── pyproject.toml # Dependencies (uv)
155- ├── agents/ # Core agent package
156- │ ├── __init__.py
157- │ ├── workflow.py # Workflow orchestration
158- │ ├── agents.py # Agent definitions
159- │ ├── tools.py # Function tools
160- │ └── constant.py # Configuration constants
161- ├── human_in_loop/ # Human oversight samples
162- │ └── main_invest_approval.py # Investment approval workflow
163- ├── output/ # Generated files
164- │ ├── stock_data.csv
165- │ ├── stock_signals.csv
166- │ ├── backtest_results.xlsx
167- │ └── backtest_metrics.txt
168- └── legacy_autogen/ # Original AutoGen implementation
169- ```
85+ ### CAGR & Returns
17086
171- ---
87+ - All trading decisions are based on the ** previous day's signal** (no look-ahead bias).
88+ - ** Buy signal** — daily return = change in Adjusted Close price.
89+ - ** Sell signal** — daily return = ` (Open / Prev Day Close) − 1 ` (captures overnight gap).
90+ - ** Consecutive identical signals** are treated as ** Hold** (no new trade opened).
91+ - A ** sell cannot be executed** without a prior buy.
17292
173- ## 🧑💼 Human-in-the-Loop: Investment Approval Workflow
93+ ### Signal Validity
17494
175- The ` human_in_loop/main_invest_approval.py ` sample demonstrates a ** human oversight pattern** for critical investment decisions using ` RequestInfoExecutor ` .
95+ | Rule | Behaviour |
96+ | ------| -----------|
97+ | No prior buy | Sell signal skipped |
98+ | Duplicate signal | Treated as Hold |
99+ | Partial-year test | CAGR ≈ Total Return (expected) |
176100
177- ### Features
101+ ## 🧑💼 Human-in-the-Loop
178102
179- - ** Human approval gates** : Agent generates investment recommendations, then pauses for human approval
180- - ** Iterative refinement** : Humans can request modifications with specific feedback (e.g., "refine focus on risk factors")
181- - ** Structured output** : Uses Pydantic ` response_format ` for type-safe investment recommendations (ticker, action, rationale, confidence)
182- - ** Multi-turn workflow** : Continues until human approves, requests changes, or exits
183-
184- ### Workflow Pattern
103+ ` human_in_loop/main_invest_approval.py ` — human approval gate before executing investment decisions using ` RequestInfoExecutor ` .
185104
186105``` mermaid
187106flowchart TD
188- classDef note fill:#f0fff0,stroke:#999,stroke-width:1px,stroke-dasharray:4 2,color:#555
189- classDef cpu fill:#f0f8ff,stroke:#333,stroke-width:2px
190- classDef proc fill:#ffe4e1,stroke:#333,stroke-width:2px
191-
192- A[User Input<br/>Stock Ticker]:::note --> B[Investment Agent<br/>Analyzes Stock ]:::cpu
193- B --> C[Generate<br/> Recommendation]:::cpu
194- C --> D{Human Decision}:::proc
195- D -->|approve| E[Execute Decision ]:::cpu
196- D -->|refine| F[Provide Feedback]:::note
197- D -->|exit| G[Cancel]:::note
107+ classDef human fill:#f0fff0,stroke:#999,stroke-width:1px
108+ classDef agent fill:#f0f8ff,stroke:#333,stroke-width:2px
109+ classDef decision fill:#ffe4e1,stroke:#333,stroke-width:2px
110+
111+ A[User Input<br/>Stock Ticker]:::human --> B[Investment Agent]:::agent
112+ B --> C[Recommendation]:::agent
113+ C --> D{Human Decision}:::decision
114+ D -->|approve| E[Execute]:::agent
115+ D -->|refine| F[Feedback]:::human
116+ D -->|exit| G[Cancel]:::human
198117 F --> B
199118```
200119
201- ### Usage
202-
203120``` bash
204- # Run the human-in-the-loop workflow
205- python human_in_loop/main_invest_approval.py
206-
207- # Example interaction:
208- # Enter ticker: MSFT
209- # [Agent analyzes and generates recommendation]
210- # Your decision: refine focus on risk factors
211- # [Agent refines based on feedback]
212- # Your decision: approve
121+ uv run human_in_loop/main_invest_approval.py
213122```
214123
215- ### Key Components
216-
217- - ** InvestmentTurnManager** : Coordinates agent-human turns and processes approval/feedback
218- - ** RequestInfoExecutor** : Pauses workflow for human input at critical decision points
219- - ** InvestmentRecommendation** : Pydantic model for structured output (BUY/SELL/HOLD with rationale)
220- - ** Multi-turn loop** : Continues until human approval or cancellation
221-
222- This pattern is essential for ** high-stakes AI applications** where human oversight is required before executing decisions.
223-
224- ---
225-
226124## 📊 Dev UI
227125
228- The ` dev_ui/main_dev_ui.py ` sample demonstrates Dev UI Integration with ` QuantInvestWorkflow ` .
229-
230126![ Dev_UI] ( output/dev_ui.png )
231127
232128## 📚 Resources
233129
234- - Official documentation: [ Overview] ( https://learn.microsoft.com/en-us/agent-framework/user-guide/workflows/overview ) | [ Tutorials] ( https://learn.microsoft.com/en-us/agent-framework/tutorials/overview ) | [ Migration from-autogen] ( https://learn.microsoft.com/en-us/agent-framework/migration-guide/ )
235- - Official GitHub repository: [ Microsoft Agent Framework] ( https://github.com/microsoft/agent-framework )
236- - [ Microsoft Agent Framework Sample] ( https://github.com/microsoft/Agent-Framework-Samples )
130+ - Docs: [ Overview] ( https://learn.microsoft.com/en-us/agent-framework/user-guide/workflows/overview ) | [ Tutorials] ( https://learn.microsoft.com/en-us/agent-framework/tutorials/overview ) | [ Migration from AutoGen] ( https://learn.microsoft.com/en-us/agent-framework/migration-guide/ )
131+ - [ Microsoft Agent Framework] ( https://github.com/microsoft/agent-framework ) | [ Samples] ( https://github.com/microsoft/Agent-Framework-Samples )
237132
238133## 📝 License
239134
0 commit comments