Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 4 min read

Beyond Black-Box Prompts: Building an Explainable Multi-Agent Financial Intelligence Platform with FastAPI & React

In quantitative finance and retail investing, treating Large Language Models as a single "oracle" prompt is dangerous. When you ask a single LLM whether a stock is a buy, it frequently exhibits confirmation bias, halluci

In quantitative finance and retail investing, treating Large Language Models as a single "oracle" prompt is dangerous. When you ask a single LLM whether a stock is a buy, it frequently exhibits confirmation bias, hallucinations with financial figures, and a total lack of calibrated risk management.

Real-world institutional investment committees don't rely on a single analyst. They rely on specialized, competing personas:

  1. A Quantitative Analyst focused strictly on mathematical momentum and price action.
  2. A Fundamental Researcher verifying facts from SEC disclosures and regulatory filings.
  3. A Risk Manager whose sole job is to protect capital, cap drawdowns, and challenge aggressive assumptions.

To solve this problem, I built Vibe-Finance: an end-to-end multi-agent financial intelligence and explainability platform built with a Python/FastAPI backend, vector RAG over corporate filings, and a modern React/Vite/Tailwind client.

Here is a breakdown of how the architecture works, how the adversarial debate engine resolves conflict, and the engineering trade-offs made along the way.

πŸ›οΈ System Architecture

Instead of feeding everything into one monolithic prompt, Vibe-Finance separates data ingestion, analysis, adversarial cross-examination, and synthesis into dedicated layers:

flowchart TD
    UI[Frontend: React 18 + Vite + Tailwind + TradingView Charts] -->|REST / JSON| API[Backend: FastAPI]

    subgraph MultiAgentEngine [Multi-Agent Intelligence Layer]
        QA[Quant Agent\nWilder RSI-14, 50-EMA, 200-SMA, MACD]
        FA[Fundamental RAG Agent\nSEC 10-K Filings & Polarity Extraction]
        BM[Behavioral Risk Manager\nDrawdown Caps & Beta Exposure Limits]
        DEB[Adversarial Debate Engine\nCross-Examination & Calibration]
        SYN[Synthesis Agent\nHybrid Gemini 1.5 Flash + Deterministic Fallback]
    end

    API --> MultiAgentEngine
    QA --> DEB
    FA --> DEB
    BM --> DEB
    DEB --> SYN
    SYN --> API

    subgraph Storage [Persistence & Ingestion Layer]
        SQLITE[(SQLite: Profiles, Holdings, Decision Memos)]
        CACHE[(Market Cache: Live Feed + Offline Snapshot Fallback)]
    end
    API --- Storage

πŸ€– The Multi-Agent Trinity

1. The Quantitative Agent

The Quant Agent operates purely on hard mathematical indicators. It executes:

  • Wilder's RSI-14 for overbought/oversold boundaries.
  • Moving Average Convergence/Divergence (MACD) tracking signal and histogram shifts.
  • 50-day EMA & 200-day SMA to identify Golden Crosses or Death Crosses.
  • Volume Anomaly Ratios evaluating institutional accumulation or distribution.

2. The Fundamental RAG Agent

This agent parses regulatory corporate filings (SEC 10-Ks, 10-Qs, earnings conference transcripts) using vector embeddings.

  • Corpus Isolation: Each ticker's vector index is isolated to guarantee zero cross-contamination between unrelated equities.
  • Contextual Grounding: Extracts polarities and specific financial disclosures, attaching exact citations so users can audit the evidence behind every claim.

3. The Behavioral Risk Manager

The Risk Manager protects the investor against behavioral pitfalls. It evaluates:

  • The user's risk profile (Conservative, Moderate, or Aggressive).
  • Maximum historical drawdown caps.
  • High-beta concentration limits, injecting pre-trade "What-If" nudges if an order threatens portfolio balance.

βš”οΈ The Heart of the System: Adversarial Debate

The most critical component of the platform is the Debate Engine. When the Quant Agent sees a strong breakout signal (Bullish) but the Fundamental RAG Agent detects margin compression in recent filings (Bearish), the system detects agent friction.

Rather than averaging their scores, the engine runs a structured adversarial exchange:

class AdversarialDebateEngine:
    """Detects agent friction and calibrates overall decision confidence."""

    def evaluate_consensus(self, quant_signal, rag_signal, risk_profile):
        friction_detected = quant_signal.polarity != rag_signal.polarity

        if friction_detected:
            # Cross-examine: Penalize overall confidence and challenge bull bias
            calibrated_confidence = min(quant_signal.confidence, rag_signal.confidence) * 0.85
            debate_summary = (
                f"Friction Detected: Technical momentum is {quant_signal.polarity}, "
                f"but corporate disclosures indicate {rag_signal.polarity} risks."
            )
        else:
            calibrated_confidence = (quant_signal.confidence + rag_signal.confidence) / 2.0
            debate_summary = "Agents aligned on directional momentum."

        return {
            "friction": friction_detected,
            "calibrated_confidence": round(calibrated_confidence, 2),
            "debate_summary": debate_summary
        }

The resulting debate log is passed to a hybrid Gemini 1.5 Flash synthesis engine that returns structured JSON. If the LLM provider experiences network latency or rate-limiting, the system automatically falls back to an algorithmic deterministic engineβ€”ensuring 100% operational uptime.

πŸ“Š Interactive TradingView Visualization & Telemetry

On the client side (React 18 + Vite + Tailwind CSS), technical analysis is visualized using TradingView Lightweight Charts (lightweight-charts v5.2.1):

  • Interactive 30-day candlestick bars with dynamic timeframes (1M, 3M, 14D).
  • Real-time volume histograms and volatility simulations.
  • An interactive Telemetry Audit Drawer displaying model latency, scanned regulatory chunk counts, and token consumption for complete transparency.

πŸ›‘οΈ Reliability & 21 Verified Test Scenarios

Building autonomous agents in finance demands strict testing. The repository includes an end-to-end automated test suite verifying 21 critical scenarios (python -u backend/test_suite.py):

  1. Uncataloged Ticker Isolation: Mathematical proof that searching Ticker A never extracts citations from Ticker B.
  2. Graceful Degradation: Automatic 25-point confidence penalty when live price feeds go stale.
  3. RAG Timeout Fallbacks: Seamless fallback to technical momentum and risk constraints if regulatory vector stores time out.
  4. Pydantic Boundary Validation: Strict rejection of negative trade sizes, zero-cost assets, or invalid dates.

πŸš€ Key Takeaways

  1. Orchestration Beats Monoliths: Dividing tasks across specialized agents produces far more nuanced, explainable results than an exhaustive mega-prompt.
  2. Deterministic Fallbacks are Essential: In production, AI APIs will experience timeouts. Having an algorithmic fallback ensures user workflows never crash.
  3. Transparency Builds Trust: Surfacing the debate between opposing agents makes AI recommendations actionable rather than mysterious.

πŸ’» Try It Out & Contribute

The entire codebase is open-source under the Apache 2.0 License:

  git clone https://github.com/Khare69/Vibe-Finance.git
  cd Vibe-Finance
  docker compose up --build

I’d love to hear your thoughts, feedback, and architectural questions in the comments below! If you find the project interesting, feel free to drop a ⭐ on the repository!

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.