MULTI-AGENT AIAI FieldTradeMarket Intelligence & Risk SurveillanceSolo Build

FieldTrade AI

Turning global news noise into explainable, risk-calibrated market intelligence.

A case study on how I designed and built AI FieldTrade, a local-first market intelligence platform. It ingests live global news, deduplicates and classifies events, propagates shocks through sectors and supply chains, and issues BUY / HOLD / SELL / WATCH calls through a multi-agent forecasting graph where every number can be traced.

1. Requirements→2. User Needs→3. Architecture→4. Development→5. Testing→6. Deployment

Project Snapshot

The problem, the users and the approach at a glance

Executive Summary
01. The Problem

Thousands of news items, decrees and supply-chain shocks arrive every hour. Teams need explainable signals before the market prices them in.

02. Target Users

Portfolio managers, risk and compliance officers, quant researchers, and the IT teams who run the platform.

03. Core Insight

The reasoning core should be deterministic and auditable. An LLM is only an optional layer that phrases the output.

04. The Solution

Pure-Python NLP, 14 analytical engines and a multi-agent forecasting graph with a quality gate and adversarial critique.

05. Enterprise Layer

FastAPI and Supabase PostgreSQL with SQLite failover, Entra ID sign-in, and Microsoft Graph email alerts.

06. Learning Loop

Predictions are reconciled against realized 7–30 day outcomes, and Brier-based calibration adjusts confidence weights.

01 / Purpose

Why I Built FieldTrade

Markets react to events: a trade restriction, a rate decision, a factory fire. The hard part isn't finding the news. It's knowing which of today's thousands of headlines matter, who is affected two steps down the supply chain, and whether a model's call can be trusted and explained to a risk committee.

14Analytical engines
13Agent roles
12Event classes
40+Countries scored
🌊Information Overload

The same story appears across dozens of feeds, so the signal gets lost in duplicates.

🔗Missed Second-Order Effects

The first-order company is obvious. The suppliers and customers one hop away are where value is missed.

⬛Black-Box AI

Risk and compliance teams can't sign off on a score nobody can explain or reproduce.

💸LLM Cost & Lock-in

Running every headline through a large model is expensive, slow and ties you to one vendor.

🎲Overconfident Models

Models rarely say “I don't know”, even when data is stale or signals contradict each other.

🔁No Feedback

Most signal tools never check their past calls against what the market actually did.

The mission

“Every call the system makes should come with its reasons, its risks, its critic's view, and a record of whether it turned out right.”

02 / Step 1 — Requirement Gathering

Understanding the Problem Before Writing Code

I started from the people who would rely on the output and what each of them couldn't live without. Most of the architecture came from their constraints: explainability, cost and auditability.

👥STEP 1

Stakeholder Pain Mapping

Mapped what portfolio managers, risk officers, quant researchers and IT each need and fear.

📰STEP 2

News-to-Price Workflow

Broke down how an analyst moves from a headline to a sector view to a position decision.

⚖️STEP 3

Compliance Constraints

Listed the auditability, prompt-injection and forward-looking-statement risks the system must handle.

🧮STEP 4

Cost & Ops Constraints

Set a hard goal: the core must run locally, offline and without paid LLM inference.

Who I Was Building For

STAKEHOLDERPAIN POINTWHAT THEY NEED FROM THE SYSTEM
Portfolio ManagersSlow to spot multi-industry second-order effects.2-hop supply-chain and sector ripple analysis showing upstream and downstream winners and losers.
Risk & ComplianceBlack-box AI, audit gaps, prompt-injection risk.Deterministic scoring, guardrails and immutable prediction traces.
Quant ResearchersOverfitting and opaque deep-learning signals.A transparent multi-agent graph combining technical, macro, precedent and adversarial signals.
Operations & ITHigh LLM inference costs and vendor lock-in.A zero-dependency local analytical core with low compute overhead.
Functional · Event Intelligence
  • ✓12 macro event taxonomies
  • ✓3 impact horizons (0–5d, 1–4w, 1–12m)
  • ✓2-hop supply-chain ripple analysis
  • ✓Deduplication & clustering of news
Functional · Forecasting
  • ✓Technicals: SMA/EMA, RSI(14), MACD, Bollinger
  • ✓Volatility regimes via VIX & macro benchmarks
  • ✓Beta, sector ETF co-movement, precedents
  • ✓Integrity gate that can abstain
Functional · Portfolio Surveillance
  • ✓Match breaking news to user holdings
  • ✓Severity / shock threshold alerts
  • ✓Board-ready HTML email briefs
Functional · Adaptive Learning
  • ✓Log every recommendation (ACID)
  • ✓Reconcile against 7–30 day outcomes
  • ✓Brier-based bounded recalibration
Functional · Copilot
  • ✓Portfolio-aware chat
  • ✓Real-time quote lookups
  • ✓Guardrails & domain confinement
Functional · Dashboard
  • ✓Executive surveillance hub
  • ✓Supply-chain explorer
  • ✓3D geopolitical risk globe
  • ✓Multi-agent lab
Non-functional requirements (the constraints that shaped the architecture)

Explainability

Plain-English causal logic, catalysts, tail risks and parameter traces for every call.

Determinism

The same inputs give the same scores, regardless of which orchestration backend runs.

Local-first

The core runs offline on pure Python with SQLite, and no API keys are required.

Graceful fallbacks

Every cloud dependency has a local fallback: DB, auth, email and agent runtime.

Safety

Prompt-injection defence, domain confinement and regulatory disclaimers on forecasts.

Auditability

Predictions and alerts are persisted with timestamps, channels and recipients.

03 / Step 2 — What to Give the User

Translating Requirements Into Product Decisions

Once I had the requirements, the question became what each user should actually see and trust. I turned each complaint into the underlying need and then into a specific product decision.

What I heard

“I learn about a supply-chain shock after the price has already moved.”

What it really means

Users need early visibility of indirect effects, not just the headline company.

What I built

A 2-hop supply-chain engine plus immediate, short-term and long-term impact horizons.

What I heard

“I can't take a black-box score to the risk committee.”

What it really means

Every call must be reproducible and explained in plain language.

What I built

Deterministic scoring, an explainability engine and a stored trace ID for every prediction.

What I heard

“Half my feed is the same story ten times.”

What it really means

Events should be the unit, not articles.

What I built

TF-IDF + cosine clustering: merge at ≥ 0.62 similarity, new event cluster at ≥ 0.42.

What I heard

“Just tell me when it hits my holdings.”

What it really means

Alerts should be tied to the user's portfolio.

What I built

Holdings matching with severity thresholds and Microsoft Graph email briefs.

What I heard

“The model is confident even when the data is garbage.”

What it really means

The system should know when not to answer.

What I built

A Quality Agent that can abstain, plus a Critique Agent that attacks every thesis.

What I heard

“LLM bills scale with every headline.”

What it really means

Reasoning should not depend on paid inference.

What I built

A zero-LLM analytical core. Azure OpenAI is only an optional phrasing layer.

The User Journey I Designed For

1

Morning briefing

The executive hub shows the daily macro outlook, sector movers and portfolio warnings.

2

Live intelligence

Streaming news, event clusters, sentiment and causal breakdowns.

3

Trace the ripple

The supply-chain explorer shows upstream and downstream exposure two hops out.

4

Run a forecast

The multi-agent lab shows every agent's vote, weights, debate log and VaR.

5

Watch the portfolio

Holdings, P&L and alerts when news crosses shock thresholds.

6

Ask the copilot

Portfolio-aware questions with guardrails and live quotes.

04 / Step 3 — Designing the Architecture

How the Architecture Was Designed, Step by Step

The architecture came from one early decision: the core reasoning had to be deterministic. Everything else followed as a series of separation and fallback choices.

DESIGN STEP 01Decide what must be deterministic
THE QUESTION

Where is an LLM worth the cost and the opacity?

THE DECISION

The whole analytical core (NLP, scoring, risk, propagation) is pure Python. An LLM is optional and only rephrases outputs.

WHY

Reproducible scores for compliance, near-zero inference cost and no vendor lock-in.

DESIGN STEP 02Split the system into five tiers
THE QUESTION

How do we keep ingestion, analysis and orchestration independently testable?

THE DECISION

Ingestion & NLP → Analytical Engines → Multi-Agent Graph → API & Persistence → React presentation.

WHY

Each tier can be tested, replaced or scaled without touching the others.

DESIGN STEP 03Design the NLP pipeline around events
THE QUESTION

What is the unit of analysis?

THE DECISION

Clustered events, not articles: tokenize → TF-IDF dedup → 12-class classification → entities → sentiment → horizon.

WHY

Removes duplicate noise before any expensive analysis runs.

DESIGN STEP 04Break analysis into single-purpose engines
THE QUESTION

How do we keep the domain logic understandable?

THE DECISION

14 engines, each doing one job (sector, supply chain, policy, commodity, risk, scoring and more).

WHY

Small engines are easy to test and easy to explain.

DESIGN STEP 05Forecast with a multi-agent graph
THE QUESTION

How do we combine conflicting signals honestly?

THE DECISION

Collector → Quality Gate → Regime → parallel specialists → Risk → Conflict Resolver → Synthesizer → Critique → Narrator.

WHY

Each signal is visible, disagreement is resolved explicitly, and the thesis is always challenged.

DESIGN STEP 06Build a dual orchestration backend
THE QUESTION

What happens if LangGraph isn't installed?

THE DECISION

Use a compiled LangGraph StateGraph with parallel fan-out when available, otherwise an in-memory sequential runner. Both produce contract-identical numbers.

WHY

Scales up without losing local-first behaviour or determinism.

DESIGN STEP 07Give every cloud dependency a fallback
THE QUESTION

How does it stay usable offline or during outages?

THE DECISION

Supabase → SQLite WAL; Entra ID → Google OAuth → local session; Microsoft Graph → SMTP.

WHY

The platform degrades gracefully instead of failing.

DESIGN STEP 08Close the loop
THE QUESTION

How does the system get better?

THE DECISION

Persist every prediction, ingest realized outcomes and recalibrate category weights with bounded Brier-based updates.

WHY

It improves over time while the bounds prevent a runaway feedback spiral.

Layered System Architecture

Final Topology
Layer 1

Ingestion & Pure-Python NLP

From raw text to clean events

Tokenization & stemmingTF-IDF deduplication12-class event classificationSentimentNERMulti-horizon impact
Layer 2

Specialized Analytical Engines

Domain reasoning

Sector impactPolicy & central bankCompany exposureCommoditiesSupply chainHistorical precedentEvent scoringRisk assessment
Layer 3

Multi-Agent Prediction Graph

Forecasting & consensus

CollectorQuality GateRegimeParallel specialistsRiskConflict ResolverSynthesizerCritiqueNarrator
Layer 4

API, Persistence & Integrations

Serve, store, secure, notify

FastAPISupabase PostgreSQLSQLite fallbackEntra ID / Google OAuthMicrosoft Graph / SMTPGuardrails
Layer 5

React Web Presentation

Analyst workspace

Next.js 16 / React 19Live market pipelineHeatmaps3D globeSupply-chain graphCopilotAI workspace
How it works:Each layer has one responsibility and talks only to the layer next to it, which keeps the system testable and replaceable piece by piece.

End-to-End Data Flow

Pipeline
RSS / REST newsLive feeds
↓
NLP pipelineDedup, classify, NER, sentiment
↓
14 enginesSector, supply chain, risk…
↓
Agent graphForecast + critique
↓
FastAPI + SupabasePersist & serve
↓
Dashboard & alertsNext.js · Graph email
↓
Feedback loopOutcomes → weights
How it works:News comes in on the left and explainable forecasts go out on the right. Realized outcomes feed back into the weights that score the next event.
05 / Under the Hood

Inside the Engines and Agents

How a headline becomes an event, how an event becomes a forecast, and how the forecast learns from the market.

Pure-Python NLP Ingestion Pipeline

Tier 1
Tokenize & stemDomain stop-words removed
↓
TF-IDF vectorsSparse representation
↓
Cosine dedupMerge ≥ 0.62 · cluster ≥ 0.42
↓
12-class classifierKeyword density + proximity
↓
Entity extractionStates, central banks, commodities, tickers
↓
SentimentBounded [-1.0, +1.0]
↓
Impact horizon0–5d · 1–4w · 1–12m
How it works:Similar articles are merged when their TF-IDF cosine similarity is ≥ 0.62, and grouped into the same event cluster at ≥ 0.42. No model inference is needed.

The 14 In-House Analytical Engines

Tier 2
EnginePurpose
Sector ImpactMaps direct and secondary shocks across 14 market sectors.
Company ExposureMaps revenue streams, operational footprint and geographic exposure to catalysts.
CommodityAnalyzes supply/demand shocks across energy, metals and agriculture.
Policy & Central BankInterprets rates, QE/QT, tariffs, subsidies and fiscal stimulus.
Supply ChainModels supplier → manufacturer → distributor dependency trees across two hops.
Historical SimilarityMatches live events against benchmark historical shocks using cosine similarity.
4D Event ScoringSeverity, Urgency, Duration and Economic Breadth.
7D Risk AssessmentPolitical, Economic, Regulatory, Commodity, Currency, Supply Chain and Volatility risk.
Opportunity HeatmapNormalizes sector scores for real-time visual surveillance.
ExplainabilityTranslates quantitative models into structured natural-language briefings.
Event Timeline BuilderConstructs forward-looking milestones and catalyst calendars.
Portfolio ImpactComputes delta-risk, estimated P&L sensitivity and hedging actions.
Country & GeopoliticalScores sovereign stability, FDI attractiveness and trade vulnerability for 40+ countries.
Continuous FeedbackApplies directional Brier-score calibration to sector confidence weights.
How it works:Each engine does one job. Together they turn a classified event into sector, company, country and portfolio impact.

Multi-Agent Forecasting Graph

Tier 3
CollectorOHLCV, fundamentals, caps
↓
Quality GateStale / missing → Abstain
↓
RegimeVIX, SPY MAs, yield spread
↓
Specialists (parallel)
TrendCorrelationHistoricalNews IntelSentiment
↓
Risk95% VaR, drawdown
↓
Conflict ResolverRegime-weighted
↓
SynthesizerDirection, band, conviction
↓
CritiqueBias & tail risks
↓
NarratorBriefing bound to the trace
How it works:Bad data stops at the Quality Gate, which abstains instead of guessing. Specialists run in parallel, the Conflict Resolver weights them by volatility regime, and the Critique Agent attacks the thesis before the Narrator writes it up.

Agent Responsibilities

13 Roles
AgentResponsibilityTechniques / Metrics
CollectorGathers OHLCV history, fundamentals, market capsYahoo Finance / Finnhub, local caching, split adjustment
QualityValidates data integrity; can trigger AbstainMissing dates, stale quotes, splits, anomaly spreads
RegimeIdentifies the macro risk environmentVIX, SPY moving averages, Treasury yield spread
TrendEvaluates price action and momentumSMA/EMA, RSI, MACD, Bollinger bands
CorrelationAssesses systemic co-movementRolling beta, sector ETF correlation
HistoricalMatches corporate/sector shock patternsForward-return profiles, event similarity
News IntelExtracts active corporate catalystsEvent scoring, sentiment, disruption magnitude
SentimentMeasures institutional and retail toneNews polarity, analyst consensus
RiskEvaluates downside and tail risk95% historical VaR, max drawdown, volatility skew
Conflict ResolverResolves opposing signalsDynamic weighting by volatility regime
SynthesizerCombines signals into the forecastDirectional probability, target band, conviction
CritiqueChallenges the thesisConfirmation bias, tail risks, contrarian failure points
NarratorProduces the executive briefingNarrative constrained to the mathematical trace
How it works:Each agent's contribution is stored in the prediction trace, so you can see who voted for what and why.

Forecast API Contract

Tier 4
POST /api/stock/NVDA/predict
{
  "horizon": "SHORT_TERM",
  "risk": "balanced",
  "offline": false,
  "backend": "auto"      // LangGraph if available, else sequential runner
}
How it works:The response includes direction, expected return, confidence, abstention status, factor scores, thesis, catalysts, critique, support/resistance levels, agent contributions, trace ID and latency.

Continuous Self-Learning Calibration Loop

Feedback
PredictionDirection + confidence
↓
PersistACID database
↓
ObserveRealized 7–30 day return
↓
Ingest outcome/api/feedback/outcome
↓
ScoreBrier + category win rate
↓
RecalibrateWeights ∈ [0.50, 1.50]
How it works:W_category = W_base × (1.0 + 0.40 × (WinRate_category − 0.50)), clamped to [0.50, 1.50] so a lucky or unlucky streak can't swing the model too far.

Infrastructure With Fallbacks

Resilience
AreaPrimaryFallback / Notes
DatabaseSupabase PostgreSQLSQLite 3 with WAL for local/offline use
IdentityMicrosoft Entra ID / MSALGoogle OAuth 2.0 / OIDC, local sessions
Session securityHttpOnly, SameSite=Lax cookiesSHA-256 token verification
AI guardrailsPrompt-injection defence + domain confinementRegulatory disclaimers on forward-looking statements
NotificationsMicrosoft Graph APITLS SMTP
Agent runtimeLangGraph StateGraph (parallel)In-memory sequential runner, same numbers
How it works:Every cloud dependency has a local alternative, so the platform still runs on a laptop with no keys.
06 / Technology

Tech Stack & Why Each Piece Was Chosen

Backend

Python 3.10+ · FastAPI · Uvicorn

Lightweight async I/O for ingestion and API serving.

NLP Engine

Pure Python

Deterministic and dependency-free, with minimal compute.

Agent Orchestration

LangGraph StateGraph

Parallel fan-out, with a pure-Python sequential fallback.

Database

Supabase PostgreSQL · SQLite WAL

Cloud persistence plus offline capability.

Auth

Microsoft Entra ID · Google OAuth

Corporate SSO with a consumer and local fallback.

Notifications

Microsoft Graph · SMTP

Board-ready Outlook briefs, with SMTP as the fallback.

Frontend

Next.js 16 · React 19 · Tailwind

A modern component architecture for a dense analyst workspace.

3D Visualization

Three.js / WebGL

Interactive geopolitical risk globe.

Market Data

Yahoo Finance · Finnhub

OHLCV and fundamentals with local caching.

07 / Step 4 — Development

Building It Phase by Phase

I built FieldTrade bottom-up, following the tiers, so each layer was tested before the next one depended on it. Phase 1 (Foundation) is complete, and Phase 2 (Cloud Hardening) is where the work is now.

  1. 1

    NLP ingestion pipeline

    Goal: Turn raw feeds into clean, deduplicated events.

    • •Tokenization, stop-words, stemming
    • •TF-IDF vectors + cosine dedup/clustering
    • •12-class classifier, NER and bounded sentiment

    Output: An event stream instead of an article stream.

  2. 2

    The 14 analytical engines

    Goal: Encode domain reasoning as small, testable units.

    • •Sector, company, commodity and policy engines
    • •2-hop supply-chain propagation
    • •4D event scoring and 7D risk assessment

    Output: Per-event impact across sectors, companies and countries.

  3. 3

    Multi-agent forecasting graph

    Goal: Honest, explainable stock forecasts.

    • •Collector, Quality Gate and Regime agents
    • •Parallel specialists, Risk and Conflict Resolver
    • •Synthesizer, Critique and Narrator, with a dual backend

    Output: Forecasts with direction, conviction, critique and a full trace.

  4. 4

    API & data contracts

    Goal: Expose everything through clean endpoints.

    • •FastAPI endpoints for briefing, analysis, prediction and portfolio
    • •Stable response contracts
    • •Guardrails on the chat endpoint

    Output: A documented API the frontend and integrations can rely on.

  5. 5

    Next.js analyst dashboard

    Goal: Make the intelligence usable.

    • •Executive hub, live intelligence and supply-chain explorer
    • •3D geopolitical risk globe
    • •Portfolio hub, copilot studio and multi-agent lab

    Output: An institutional dark-theme workspace.

  6. 6

    Cloud hardening (current phase)

    Goal: Enterprise-ready persistence, identity and alerts.

    • •Supabase persistence with SQLite failover
    • •Entra ID sign-in and Microsoft Graph email
    • •Live financial news ingestion

    Output: Portfolio-linked alerts delivered to Outlook.

  7. 7

    Feedback & calibration loop

    Goal: Make the system learn.

    • •Persist every prediction
    • •Outcome ingestion endpoint
    • •Bounded Brier-based weight updates

    Output: Confidence weights that track real-world accuracy.

08 / Step 5 — Testing

How I Verified It Works

Since the core is deterministic, most of it can be tested like ordinary software, with exact expected numbers rather than a vague sense that the answer looks plausible.

Unit tests (pytest)

Engines and NLP stages are tested in isolation with fixed inputs.

  • ✓Deduplication thresholds (0.62 merge / 0.42 cluster)
  • ✓Event classification and bounded sentiment
  • ✓Scoring and risk engines return stable values
  • ✓Calibration weights stay within [0.50, 1.50]

Backend parity

Both orchestration backends must agree exactly.

  • ✓LangGraph and sequential runners give contract-identical numbers
  • ✓Response schema matches the API contract
  • ✓Agent contributions and trace ID are always present

Integrity & safety

The system must fail safe.

  • ✓Stale or missing data → Quality Gate abstains
  • ✓High agent divergence → abstention
  • ✓Prompt-injection and off-domain prompts are refused
  • ✓Disclaimers are attached to forward-looking statements

Offline & fallback paths

Every fallback is exercised on purpose.

  • ✓run_demo.py runs end to end with no network
  • ✓Supabase unavailable → SQLite WAL
  • ✓Graph unavailable → SMTP alert delivery

Success Criteria → How Each Was Verified

CRITERIONVERIFIED BY
ExplainabilityEvery forecast response includes thesis, catalysts, critique and agent contributions.
DeterminismBackend parity tests with identical numeric outputs.
Local-firstThe offline demo run with SQLite and no API keys.
Safe abstentionQuality-gate tests with corrupted and stale market data.
Bounded learningCalibration tests at extreme win rates.
ResilienceForced failures of the DB, identity and email providers.
09 / Step 6 — Deployment

Shipping It

FieldTrade runs in two modes: fully local, or connected to cloud services. The same codebase switches between them purely through configuration.

STEP 1

Configure persistence

Set the Supabase PostgreSQL connection, or leave it empty to use SQLite WAL.

STEP 2

Set agent controls

Agent mode, minimum data quality, minimum agreement, maximum risk cutoff and latency budget.

STEP 3

Wire up identity

Entra ID client and tenant settings, with Google OAuth as an alternative.

STEP 4

Connect data & notifications

Optional Finnhub enrichment and Microsoft Graph for email briefs.

STEP 5

Optional LLM phrasing

Azure OpenAI endpoint and deployment, used only to rephrase the deterministic output.

STEP 6

Run & verify

Run the test suite, the offline demo, then start the API and the dashboard.

Local-first mode

Pure-Python core, SQLite, local sessions and no keys required. Runs on a laptop.

Cloud mode

Supabase PostgreSQL, Entra ID SSO, Microsoft Graph alerts and live news ingestion.

# Run tests
python -m pytest -q

# Offline market intelligence demo
python run_demo.py

# Start FastAPI backend
python -m fieldtrade serve

# Start Next.js frontend
cd webapp && npm install && npm run dev
10 / Retrospective

What I Learned & What's Next

01

Determinism is a feature.

Keeping the reasoning core LLM-free made the system cheaper, faster, testable and explainable to compliance.

02

Let the model say “I don't know”.

A quality gate that abstains is worth more than a confident wrong answer.

03

Build in the critic.

A dedicated agent that attacks the thesis catches confirmation bias that one model can't see in itself.

04

Every dependency needs a fallback.

Designing SQLite, SMTP and a sequential runner up front made the platform usable anywhere.

05

Bound your feedback loops.

Self-learning without limits drifts. Clamping weights to [0.50, 1.50] keeps calibration stable.

06

Small engines, big picture.

Fourteen single-purpose engines turned out to be easier to reason about than one clever model.

Roadmap

Completed

Phase 1 — Foundation

Pure-Python NLP, 14 analytical engines, multi-agent graph, Next.js 16 / React 19 dashboard.

Current

Phase 2 — Cloud Hardening

Supabase persistence, SQLite failover, Entra ID, Graph email, guardrails, live news ingestion.

Future

Phase 3 — Institutional Scale

FIX/OMS/EMS connectivity, alternative data (AIS, satellite, patents), multi-tenancy and RBAC.

FieldTrade is a research and engineering project. Its outputs are analytical signals, not investment advice.