Skip to content

Data Flow Diagrams

This document provides detailed diagrams showing how data flows through the QuantBot system.

1. Complete Data Flow - Stock Price Request

flowchart TB
    subgraph UI_Section ["User Interaction"]
        U["User: What's Apple stock price?"]
    end

    subgraph Frontend ["Frontend Processing"]
        UI[UserInput Component]
        CTX[ChatContext.sendMessage]
        API[api.getAIResponse]
    end

    subgraph Backend ["Backend Processing"]
        EP[POST /api/chat/]
        FA[FinancialAgent.process_question]

        subgraph Planning ["Plan Creation"]
            GM1[Gemini: Analyze question]
            PL[Create JSON plan]
        end

        subgraph DataGathering ["Data Gathering"]
            YF[YFinanceMCPServer]
            SP[get_stock_price AAPL]

            subgraph Fallback ["Fallback Chain"]
                YFT[Try yfinance]
                AVT[Try Alpha Vantage]
                MT[Use Mock Data]
            end
        end

        subgraph Analysis ["Analysis"]
            GM2[Gemini: Analyze data]
            FR[Format response]
        end
    end

    subgraph Response ["Response"]
        MSG[Message object]
        TOOL[Tool: StockCard]
        THINK[Thinking steps]
    end

    U --> UI
    UI --> CTX
    CTX --> API
    API --> EP
    EP --> FA
    FA --> GM1
    GM1 --> PL
    PL --> YF
    YF --> SP
    SP --> YFT
    YFT --> AVT
    YFT --> GM2
    AVT --> MT
    AVT --> GM2
    MT --> GM2
    GM2 --> FR
    FR --> MSG
    FR --> TOOL
    FR --> THINK
    MSG --> UI

    style U fill:#fbbf24
    style MSG fill:#4ade80
    style TOOL fill:#4ade80
    style THINK fill:#818cf8

2. Message Object Structure

graph TD
    subgraph "Message Object"
        M[Message]
        M --> ID[id: UUID]
        M --> ROLE[role: 'assistant']
        M --> CONTENT[content: Analysis text]
        M --> TIME[timestamp: Date]
        M --> THINK[thinking: string]
        M --> TOOLS[tools: Array]

        TOOLS --> T1[Tool 1: Stock Price]
        T1 --> T1ID[id: '1']
        T1 --> T1NAME[name: 'AAPL Stock Price']
        T1 --> T1TYPE[type: 'price']
        T1 --> T1DATA[data: StockData]

        T1DATA --> SYMBOL[symbol: 'AAPL']
        T1DATA --> NAME[name: 'Apple Inc.']
        T1DATA --> PRICE[price: 189.50]
        T1DATA --> CHANGE[change: 2.35]
        T1DATA --> CHANGEPCT[changePercent: 1.25]
    end

    style M fill:#818cf8
    style TOOLS fill:#4ade80
    style T1DATA fill:#fbbf24

3. Execution Plan Structure

graph LR
    subgraph GeminiPlan ["Gemini Creates Plan"]
        Q[Question Analysis]
        P[Plan JSON]

        Q --> P

        P --> APP[approach: string]
        P --> STEPS[steps: Array]

        STEPS --> S1[Step 1: Data Gathering]
        S1 --> AGENT1[agent: 'data_gatherer']
        S1 --> TOOLS1[tools: Array]
        S1 --> DESC1[description: string]

        TOOLS1 --> T1[Tool Definition]
        T1 --> SERVER[server: 'yfinance']
        T1 --> TOOL[tool: 'get_stock_price']
        T1 --> PARAMS[params: ticker AAPL]
        T1 --> REASON[reason: string]

        STEPS --> S2[Step 2: Analysis]
        S2 --> AGENT2[agent: 'analyzer']
        S2 --> DESC2[description: string]
    end

    style Q fill:#fbbf24
    style P fill:#818cf8
    style TOOLS1 fill:#4ade80

4. Database Schema

erDiagram
    User ||--o{ ChatSession : has
    ChatSession ||--o{ ChatMessage : contains

    User {
        int id PK
        string email
        string hashed_password
        datetime created_at
    }

    ChatSession {
        int id PK
        int user_id FK
        datetime created_at
        datetime updated_at
    }

    ChatMessage {
        int id PK
        int session_id FK
        string role
        text content
        text thinking
        json tools_used
        datetime created_at
    }

5. API Response Flow

sequenceDiagram
    participant F as Frontend
    participant B as Backend
    participant DB as Database
    participant AI as AI Service

    F->>B: POST /api/chat/<br/>{message: "What's AAPL?"}

    B->>DB: Get user session
    DB-->>B: Session data

    B->>DB: Get conversation history
    DB-->>B: Last 10 messages

    B->>AI: Process with context
    AI-->>B: Response + tools

    B->>DB: Save user message
    B->>DB: Save AI response

    B-->>F: ChatResponse {<br/>  message: {<br/>    content: "...",<br/>    tools: [...],<br/>    thinking: "..."<br/>  }<br/>}

6. Tool Result Transformation

graph TD
    subgraph "Raw yfinance Data"
        YF[DataFrame/Dict]
        YF --> CLOSE[Close prices]
        YF --> VOL[Volume]
        YF --> INFO[Company info]
    end

    subgraph "Processing"
        PROC[Data Processor]
        CALC[Calculate metrics]
        FORMAT[Format for frontend]
    end

    subgraph "Frontend Tool"
        TOOL[StockCard Tool]
        TOOL --> TYPE[type: 'price']
        TOOL --> DATA[Formatted data]
    end

    YF --> PROC
    PROC --> CALC
    CALC --> FORMAT
    FORMAT --> TOOL

    style YF fill:#fbbf24
    style PROC fill:#818cf8
    style TOOL fill:#4ade80

7. Error States and Handling

stateDiagram-v2
    [*] --> Processing

    Processing --> YFinanceCall

    state YFinanceCall {
        [*] --> TryAPI
        TryAPI --> Success: Data received
        TryAPI --> Failed: Error/Empty
        Failed --> [*]
        Success --> [*]
    }

    YFinanceCall --> CheckResult

    CheckResult --> ReturnData: Success
    CheckResult --> AlphaVantage: Failed

    state AlphaVantage {
        [*] --> TryAV
        TryAV --> AVSuccess: Data received
        TryAV --> AVFailed: Error
        AVSuccess --> [*]
        AVFailed --> [*]
    }

    AlphaVantage --> CheckAVResult

    CheckAVResult --> ReturnData: Success
    CheckAVResult --> MockData: Failed

    MockData --> CheckMock
    CheckMock --> ReturnData: Known ticker
    CheckMock --> ReturnError: Unknown ticker

    ReturnData --> [*]
    ReturnError --> [*]

8. Frontend State Updates

graph TD
    subgraph "User Action"
        TYPE[User types message]
        SEND[Clicks send]
    end

    subgraph "State Updates"
        ADD1[Add user message to state]
        LOAD[Set loading = true]
        API[Call API]
        ADD2[Add AI message to state]
        DONE[Set loading = false]
    end

    subgraph "UI Updates"
        SHOW1[Show user message]
        SPINNER[Show loading spinner]
        SHOW2[Show AI message]
        CARDS[Render tool cards]
    end

    TYPE --> SEND
    SEND --> ADD1
    ADD1 --> SHOW1
    SHOW1 --> LOAD
    LOAD --> SPINNER
    SPINNER --> API
    API --> ADD2
    ADD2 --> SHOW2
    SHOW2 --> CARDS
    CARDS --> DONE

    style TYPE fill:#fbbf24
    style SHOW2 fill:#4ade80
    style CARDS fill:#4ade80

9. Portfolio Analysis Flow

flowchart LR
    subgraph "Input"
        Q[User: Analyze AAPL 60%, MSFT 40%]
    end

    subgraph "Processing"
        PARSE[Parse symbols & weights]
        FETCH[Fetch historical data]

        subgraph "Calculations"
            RET[Calculate returns]
            VOL[Calculate volatility]
            SHARP[Calculate Sharpe ratio]
            DD[Calculate drawdown]
        end

        BENCH[Compare to SPY]
    end

    subgraph "Output"
        METRICS[Portfolio metrics]
        COMP[vs Benchmark]
        VIZ[Tool visualization]
    end

    Q --> PARSE
    PARSE --> FETCH
    FETCH --> RET
    FETCH --> VOL
    FETCH --> SHARP
    FETCH --> DD
    RET --> BENCH
    VOL --> BENCH
    SHARP --> BENCH
    DD --> BENCH
    BENCH --> METRICS
    BENCH --> COMP
    METRICS --> VIZ
    COMP --> VIZ

    style Q fill:#fbbf24
    style VIZ fill:#4ade80

Key Data Transformations

1. Question → Plan

  • Natural language analyzed by Gemini
  • Structured JSON plan created
  • Tools and parameters identified

2. Plan → Data Gathering

  • Tools called based on plan
  • Multiple data sources tried
  • Results aggregated

3. Raw Data → Analysis

  • Multiple data points synthesized
  • Gemini creates comprehensive analysis
  • Context from history incorporated

4. Analysis → Frontend Display

  • Content formatted for display
  • Tools packaged with proper types
  • Thinking steps included for transparency

5. Frontend → User Interface

  • Messages rendered in chat
  • Tool cards displayed inline
  • Interactive elements enabled