This repository provides a structured framework for an AI-driven financial engineering and market analysis agentic system using Azure AI Agent Service SDK / Microsoft Agent Framework. It includes:
- A Gradio dashboard that blends SAP (ES5 demo) data, simulated Salesforce pipeline, and business news
- Multi-agent architecture for CFO-ready insights and strategy options
- Structured Python project with required dependencies
- Configuration file templates (
.env) - Step-by-step setup guide
The system incorporates multiple AI-driven agents specialized in different aspects of financial and market analysis:
Behind the scene multi-agent orchestration in play:
| Agent Name | Role |
|---|---|
| 🌐 market-intelligence-agent | Analyzes market trends, news sentiment, customer pipeline, and currency exposure |
| 💰 finance-pulse-agent | Evaluates SAP financial health, customer/product signals, and performance metrics |
| Surfaces liquidity, compliance, and volatility risks across the dataset | |
| 📊 cfo-strategist | Fuses specialist reports into three actionable strategy options |
| 📋 board-briefing-agent | Produces a board-ready narrative with executive summary |
- Market Analysis Agent → Analyzes market trends, customer behavior, geographic demand
- Financial Analysis Agent → Evaluates financials, balance sheets, cost efficiency
- Risk Monitor Agent → Identifies compliance, liquidity, and exposure risks
- Strategic Planning Agent → Develops three unique business strategies with implementation roadmaps
- Board Briefing Agent → Creates executive-ready narrative for board distribution
📦 Stock-Analysis-AutoGen-Multi-Agent
┣ 📜 sap-finance-analysis-withUI-8-FINAL-ES5-FINAL_AgentFramework.py # Main dashboard app
┣ 📜 requirements.txt # Dependencies
┣ 📜 .env.example # Environment variables template
┣ 📜 README-financeagents.md # This documentation
┗ 📜 LICENSE # License file
- OS: Windows / macOS / Linux
- Python: 3.10 or newer
- Graphviz: Required for the flow diagram (
dotmust be on PATH) - Azure OpenAI: Chat deployment (GPT-4 recommended)
- Azure Logic App: For email automation (see setup below)
- Optional: Currents API Key for latest news
- SAP ES5 demo credentials (or your SAP OData endpoint)
git clone https://github.com/amitlals/Stock-Analysis-AutoGen-Multi-Agent.git
cd Stock-Analysis-AutoGen-Multi-Agentpython -m venv venv
# For Mac/Linux
source venv/bin/activate
# For Windows PowerShell
.\venv\Scripts\Activatepip install -U pip setuptools wheel
pip install -r requirements.txtIf requirements.txt is missing, install core libs:
pip install gradio plotly pandas requests python-dotenv graphviz pydantic urllib3 openai
⚠️ Note: This version usesagent-framework, a Microsoft internal/preview SDK.
Option A: If you have access to the package:
pip install agent-frameworkOption B: If agent-framework is unavailable:
See the standard OpenAI SDK version which uses the openai package directly:
pip install openai- Windows: Download from graphviz.org and add to PATH
- macOS:
brew install graphviz - Linux:
sudo apt-get install graphviz
Create a .env file in the project root:
# .env
# SAP Connection
SAP_USERNAME=your_sap_user
SAP_PASSWORD=your_sap_password
SAP_BASE_URL=https://sapes5.sapdevcenter.com/sap/opu/odata/IWBEP/GWSAMPLE_BASIC
SAP_CLIENT=002
# News API (optional; if unset, news is skipped)
CURRENTS_API_KEY=your_currents_api_key
# Azure OpenAI / Microsoft Agent Framework
API_KEY=your_azure_openai_api_key
AZURE_ENDPOINT=https://your-resource-name.openai.azure.com
MODEL_DEPLOYMENT_NAME=gpt-4
MODEL_API_VERSION=2024-10-21
# Email dispatch via Logic App (Options tab)
LOGICAPP_ENDPOINT=https://your-logicapp-url
EMAIL_RECIPIENT=recipient@example.comThe dashboard uses an Azure Logic App to send strategy option emails. Follow these steps to create and configure it:
- Go to Azure Portal
- Click Create a resource → Search for Logic App
- Click Create and fill in:
- Subscription: Your Azure subscription
- Resource Group: Create new or select existing
- Logic App name:
cfo-email-dispatcher(or your choice) - Region: Select your preferred region
- Plan type: Consumption (pay-per-execution) recommended for testing
- Click Review + create → Create
- Wait for deployment, then click Go to resource
- In your Logic App, click Logic app designer (or Edit if prompted)
- Select Blank Logic App template
- Search for HTTP → Select When a HTTP request is received
- Click Use sample payload to generate schema
- Paste this sample JSON:
{ "Recipient": "user@example.com", "Subject": "CFO Strategy Pick: Option 1", "Body": "<html><body><h1>Strategy Details</h1></body></html>" } - Click Done — the schema auto-generates
- Set Method to
POST
Option A: Using Office 365 Outlook
- Click + New step
- Search for Office 365 Outlook → Select Send an email (V2)
- Sign in with your Microsoft 365 account when prompted
- Configure the action:
- To: Click in field → Dynamic content → Select
Recipient - Subject: Click in field → Dynamic content → Select
Subject - Body: Click in field → Dynamic content → Select
Body - Toggle Is HTML to
Yes
- To: Click in field → Dynamic content → Select
Option B: Using SendGrid (Alternative)
- Click + New step
- Search for SendGrid → Select Send email (V4)
- Connect with your SendGrid API key
- Configure similarly with dynamic content
Option C: Using Gmail
- Click + New step
- Search for Gmail → Select Send email (V2)
- Sign in with your Google account
- Configure with dynamic content
- Click + New step
- Search for Response → Select Response
- Configure:
- Status Code:
200 - Body:
{"status": "Email sent successfully"}
- Status Code:
- Click Save in the designer toolbar
- Go back to the HTTP trigger step
- Copy the HTTP POST URL — it looks like:
https://prod-xx.eastus.logic.azure.com:443/workflows/abc123.../triggers/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers... - Add this URL to your
.envfile:LOGICAPP_ENDPOINT=https://prod-xx.eastus.logic.azure.com:443/workflows/...
┌─────────────────────────────────────────────────────────┐
│ When a HTTP request is received │
│ ├─ Method: POST │
│ └─ Schema: { Recipient, Subject, Body } │
└─────────────────────┬───────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ Send an email (V2) - Office 365 Outlook │
│ ├─ To: @{triggerBody()?['Recipient']} │
│ ├─ Subject: @{triggerBody()?['Subject']} │
│ ├─ Body: @{triggerBody()?['Body']} │
│ └─ Is HTML: Yes │
└─────────────────────┬───────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ Response │
│ ├─ Status Code: 200 │
│ └─ Body: {"status": "Email sent successfully"} │
└─────────────────────────────────────────────────────────┘
From Azure Portal:
- Click Run Trigger → Run with payload
- Enter test JSON:
{ "Recipient": "your-email@example.com", "Subject": "Test Email from Logic App", "Body": "<h1>Hello!</h1><p>This is a test.</p>" } - Click Run and check your inbox
From Command Line (curl):
curl -X POST "YOUR_LOGIC_APP_URL" \
-H "Content-Type: application/json" \
-d '{"Recipient":"your-email@example.com","Subject":"Test","Body":"<p>Test</p>"}'From PowerShell:
$body = @{
Recipient = "your-email@example.com"
Subject = "Test Email"
Body = "<h1>Test</h1>"
} | ConvertTo-Json
Invoke-RestMethod -Uri "YOUR_LOGIC_APP_URL" -Method Post -Body $body -ContentType "application/json"| Issue | Solution |
|---|---|
| HTTP 400 Bad Request | Check JSON schema matches exactly: Recipient, Subject, Body (case-sensitive) |
| HTTP 401 Unauthorized | Regenerate the trigger URL or check access policies |
| HTTP 404 Not Found | Verify the Logic App URL is correct and the app is enabled |
| Email not received | Check spam folder; verify Office 365 connection is authorized |
| Connection expired | Go to Logic App → API Connections → Reauthorize the email connector |
⚠️ Never commit the Logic App URL to version control — treat it as a secret- 🔒 Consider adding IP restrictions in Logic App settings for production
- 🔑 Use Azure Key Vault to store the endpoint URL in production environments
- 📋 Enable diagnostic logging in Logic App for monitoring
pip install azure-ai-agent-sdk# Log in to Azure CLI
az login
# Set your subscription
az account set --subscription "<your-subscription-id>"
# Deploy AI Agent Service (optional)
az ai agent create --name StockAnalysisAgent --resource-group your-resource-group --location eastus --sku StandardStore your Azure OpenAI API Key in .env as API_KEY.
python sap-finance-analysis-withUI-8-FINAL-ES5-FINAL_AgentFramework.pyThe app launches at http://127.0.0.1:7860
| Tab | Description |
|---|---|
| Performance & Analysis | KPIs, SAP/SF charts, headline table, AI insights |
| Strategic Options & Dispatch | AI-generated options + email dispatch via Logic App |
| System Flow | Click to generate agents data-flow diagram (Graphviz) |
- ✅ Connects to SAP ES5 & fetches orders/products data
- ✅ Retrieves market & financial news
- ✅ Generates simulated Salesforce pipeline data
- ✅ Processes data into structured insights
- ✅ Utilizes 5 AI agents for market, financial & risk analysis
- ✅ Generates three strategic recommendations
- ✅ Produces board-ready narrative
- Select a strategy option (Option 1, 2, or 3)
- Click Confirm & Dispatch
- The app sends a POST request to your Logic App
- Logic App sends a formatted HTML email to the configured recipient
- Confirmation message appears in the dashboard
# Core dependencies
requests>=2.31.0
urllib3>=2.0.0
python-dotenv>=1.0.0
# UI Framework
gradio>=4.0.0
# Data & Visualization
pandas>=2.0.0
plotly>=5.18.0
pydantic>=2.0.0
# Diagram Generation
graphviz>=0.20.0
# Azure OpenAI
openai>=1.3.0
# Microsoft Agent Framework (if available)
# agent-framework>=0.1.0- The code uses Microsoft Agent Framework (
agent-framework) withAzureOpenAIChatClient - Because some Azure chat models do not support JSON schema
response_format, agents are prompted to reply with raw JSON only - A tolerant parser:
- Extracts JSON from code fences or prose
- Unwraps extra root keys
- Coerces fields (severity, horizon, confidence)
- Fills defaults where needed
- Specialist outputs are merged by the cfo-strategist into
StrategyResponseModel - The board-briefing-agent produces a
BoardNarrativeModel
- The demo endpoint often omits a CSRF token for GETs
- Warnings like "Proceeding to fetch … without CSRF token" are expected for read-only calls
- If needed:
- Confirm
SAP_BASE_URLandSAP_CLIENTare correct - Increase timeouts or disable SSL verification only in trusted/dev environments
- Confirm
| Issue | Solution |
|---|---|
| HTTP 400: Invalid parameter 'response_format' | Ensure you're running the updated v8 AgentFramework file |
| Non-structured payload warnings | Reduce agent temperature (0.05–0.2) or tighten prompts |
| Pandas deprecation warning for 'M' | Addressed by using 'ME' (month-end) in simulate_sales_trend |
| Graphviz error (dot not found) | Install Graphviz and ensure dot is on your PATH |
| SAP CSRF warnings | Safe to ignore if data loads; expected for read-only demo calls |
| agent-framework not found | Use the standard openai package version instead |
| Email dispatch failed | Check Logic App URL, verify JSON schema, test Logic App directly |
- Model selection: Use GPT-4 or capable Azure OpenAI chat model for reasoning and JSON generation
- Temperature: If structured responses are inconsistent, lower temperature (0.05–0.2)
- Environment isolation: Keep this project in a clean venv to avoid library conflicts
- Logs: Review console logs for agent prompts/issues and SAP fetch diagnostics
- Add new agents: Mirror the specialist agent pattern; return
AgentInsightReportJSON - Connect real Salesforce/ERP: Replace simulated fetch with your API calls
- Adjust UI: Modify the option renderer to emphasize owner or confidence thresholds
⚠️ Do not commit.envfiles — Treat API keys and credentials as secrets⚠️ Do not commit Logic App URLs — They contain embedded authentication⚠️ Scrub sensitive data before exporting or sharing screenshots⚠️ Add.envto.gitignore
python -m venv venv
.\venv\Scripts\Activate
pip install -U pip setuptools wheel
pip install -r requirements.txt
pip install gradio plotly pandas requests python-dotenv graphviz pydantic openai
python sap-finance-analysis-withUI-8-FINAL-ES5-FINAL_AgentFramework.py- Enhance AI Agents: Add working-capital or liquidity agents for deeper analysis
- Expand Data Sources: Integrate stock market APIs for real-time analytics
- Deploy on Azure: Use Azure Functions or containerized service for production
- Connect Real Systems: Replace simulated Salesforce with actual CRM integration
- Add Approval Workflow: Extend Logic App with Microsoft Teams approval before email
If you use this project in your research or work, please cite:
@article{lal2025aiagents,
title={A Survey of AI Agent Architectures in Enterprise SAP Ecosystems},
author={Lal, Amit},
year={2025},
publisher={TechRxiv},
note={Preprint}
}@article{lal2025rpt1,
title={Evaluating SAP RPT-1 for Enterprise Business Process Prediction},
author={Lal, Amit},
year={2025},
publisher={TechRxiv},
note={Preprint}
}@book{lal2024ai2040,
title={AI in 2040},
author={Lal, Amit},
year={2024},
isbn={9798346459941}
}This project is licensed under the MIT License. See the LICENSE file for details.
