HomeCase studiesRegulated AI Financial Advisor Platform Separating Deterministic...

Case study · New York, United States

Regulated AI Financial Advisor Platform Separating Deterministic Planning Math from LLM Guidance

Advisory WealthTech & Portfolio Guidance

Retail investors and registered advisory teams often distrust conversational AI tools that blend fluent prose with fabricated yield assumptions or unverified tax rules. We built an AI financial advisor platform in New York using Python, FastAPI, and orchestrated LLM APIs that isolates all portfolio mathematics inside deterministic simulation engines before any language model drafts a response. Clients explore retirement horizons, tax-advantaged account allocations, and rebalancing scenarios in a React workspace, while compliance officers audit every cited figure against immutable calculation snapshots.

Industry
Advisory WealthTech & Portfolio Guidance
Solution
A compliance-first WealthTech advisory web platform and API pairing deterministic Python financial simulation kernels with guardrail-enforced LLM API synthesis and human advisor escalation.
Platforms
Web & API
Stack
Python · FastAPI · LLM APIs · React · TypeScript · PostgreSQL
Location
New York, United States · delivered remotely
Role
Engineering, with the team behind for mobile and QA

Delivered remotely for a business based in New York, United States. Names withheld by agreement.

Project Overview

Wealth management firms in New York face a widening gap between self-directed investors expecting immediate conversational clarity and compliance departments bound by strict fiduciary documentation standards. Standard chatbot wrappers fail both groups: they hallucinate compound growth rates, overlook tax-deferred account rules, and leave no reproducible trail explaining why a particular allocation adjustment was suggested.

To bridge that gap, we engineered an AI financial advisor platform built on Python, FastAPI, and external LLM APIs. Rather than allowing generative models to speculate over raw account balances, the platform enforces a hard architectural boundary: deterministic Python engines execute all cash-flow modeling, Monte Carlo stress tests, and tax-tier calculations first, while LLM APIs serve strictly as a citation-bound communication layer over verified outputs and compliance-approved research.

Advisory & Compliance Gaps

Deploying generative AI inside regulated US WealthTech exposes four failure modes that conventional consumer chatbots cannot tolerate:

  • Unbounded arithmetic synthesis: Language models asked to project 25-year IRA drawdowns or capital gains liabilities routinely drift on compounding math and state tax brackets.
  • Unauthorized suitability leaps: Without explicit policy gates, models may suggest concentrated equity trades or options strategies incompatible with a client's documented liquidity horizon.
  • Unverifiable narrative provenance: Compliance officers reviewing client transcripts need exact visibility into which holding snapshot and policy memo justified each statement.
  • Stale regulatory context: Tax-year contribution ceilings and firm-approved model portfolios shift annually; static prompt instructions quickly become non-compliant.

Architectural Strategy

The architecture rests on tool-grounded calculation, cited retrieval, and advisor-governed escalation. Every user prompt entering FastAPI is evaluated by a lightweight intent and policy router before reaching external LLM APIs. Quantitative inquiries trigger deterministic Python functions—covering retirement glidepaths, Social Security timing heuristics, asset-location tax drag, and portfolio drift—that emit strictly typed JSON summaries.

In parallel, qualitative planning questions query pgvector across compliance-vetted knowledge bases tagged with effective dates and jurisdictional scope. The LLM receives only anonymized scenario summaries, retrieved policy excerpts with source identifiers, and strict output schemas requiring inline citation tags. Any discrepancy between a numeric token in the generated text and the underlying Python output triggers an automatic regeneration or safe fallback response.

Core Capabilities

  • Conversational Goal Modeling: Clients test "what-if" scenarios—earlier retirement dates, mortgage payoff trade-offs, or college savings ramps—with side-by-side cash-flow curves updated in React.
  • Portfolio Drift & Tax-Lot Diagnostics: Normalized custodian holdings highlight sector concentration, overlapping ETF expense ratios, and short- versus long-term unrealized gain exposure.
  • Cited Policy Retrieval: Explanations of Roth conversions, required minimum distributions, and emergency reserve targets cite specific internal firm guidance memos.
  • Compliance Escalation Workflow: Sensitive queries (estate restructuring, concentrated stock hedging, or distressed liquidity events) pause autonomous drafting and package full context for a human CFP.
  • Immutable Audit Transcripts: Every message stores the exact portfolio snapshot hash, Python simulation parameters, retrieved chunk IDs, and LLM API model version.

Technical Architecture

FastAPI acts as the central orchestration plane between the React TypeScript client, PostgreSQL/pgvector, and external LLM APIs. Client sessions authenticate over short-lived JWTs with role claims distinguishing retail clients, licensed advisors, and compliance auditors. When a prompt arrives over Server-Sent Events (SSE), FastAPI runs pre-flight PII scrubbing—stripping account numbers, SSNs, and legal names before any payload leaves the VPC—then executes tool calls against Python quantitative modules and pgvector.

Flow: React Client (SSE) → FastAPI Policy Router & PII Redactor → Python Deterministic Simulation Engine + pgvector Approved Corpus → LLM APIs (Structured Grounded Synthesis) → Numeric & Suitability Validator → PostgreSQL Audit Log → React Workspace

Separating simulation state from conversational prose allows clients to adjust sliders in the React goal planner without triggering redundant LLM API calls. FastAPI recalculates deterministic percentiles immediately and only invokes narrative synthesis when the user requests commentary on the updated plan.

Technology Stack

Category Technology detail
Advisory Client UI React and TypeScript conversational workspace paired with interactive goal projections
Core API Gateway Python FastAPI serving authenticated SSE streams, tool execution, and advisor endpoints
Language Orchestration LLM APIs constrained via strict JSON tool schemas and post-generation claim verification
Quantitative Engine Python Decimal cash-flow projectors, tax-bracket schedules, and Monte Carlo samplers
Knowledge Retrieval pgvector indexing compliance-approved research memos, IRS rules, and ETF fact sheets
System of Record PostgreSQL persisting client risk profiles, scenario snapshots, and immutable audit logs
Guardrail Layer Pydantic intent classifiers and policy filters blocking unlicensed buy/sell directives
Brokerage Aggregation Read-only custodian connectors normalizing holdings, cost basis, and cash balances
Observability Structured trace IDs linking every chat turn to tool inputs, retrieved chunks, and math runs

Engineering Trade-offs & Solutions

Engineering Challenge Solution & Trade-off
LLM APIs fabricate realistic-sounding returns or misstate marginal tax tiers Blocked direct numeric reasoning in prompts; Python computes all projections via Decimal tables and injects read-only outputs with a regex/AST post-check, adding an extra verification pass in exchange for arithmetic certainty.
Outbound LLM API calls risk leaking sensitive client identity and account data Implemented deterministic token replacement in FastAPI that maps names and account IDs to ephemeral aliases prior to model inference, trading minor preprocessing overhead for zero PII egress.
Multi-step planning tools increase time-to-first-token during chat streams Streamed deterministic simulation status events and chart updates immediately to React while narrative synthesis streams behind them, keeping perceived latency low without masking tool execution.
Broad vector retrieval pulls outdated tax-year guidance into responses Enforced mandatory SQL metadata filters (effective_from, effective_to, jurisdiction, approved = true) inside pgvector queries, requiring strict document lifecycle tagging in exchange for compliance accuracy.

Security, Privacy & Regulatory Controls

Because advisory conversations combine household net-worth disclosures with actionable financial planning, security controls operate at both the transport and prompt layers. Custodian connections operate strictly read-only, preventing any conversational workflow from initiating fund transfers or order execution. Within FastAPI, outbound payloads to LLM APIs pass through a deterministic redaction pipeline so raw brokerage account numbers, taxpayer IDs, and household addresses never leave controlled infrastructure.

Inside PostgreSQL, row-level access policies isolate each client household while granting scoped read access to assigned advisors and compliance auditors. Every advisory artifact—generated summaries, simulation inputs, and escalation tickets—writes append-only audit records with cryptographic timestamps to support SEC Books and Records examinations.

Latency & Simulation Reliability

Running multi-path Monte Carlo simulations alongside external LLM API inference can easily stall synchronous web requests. We structured FastAPI around async worker execution for heavy simulation matrices while caching deterministic baseline runs against the hash of a client's holdings and risk profile. Subsequent conversational follow-ups reuse cached distribution arrays unless the client alters an input variable.

To insulate user sessions from upstream LLM provider throttling, the orchestration layer maintains circuit breakers, bounded exponential backoff, and schema-validated fallback templates. If an external model endpoint degrades, clients still receive live deterministic chart updates and an option to route their question directly to an advisor inbox.

Operational Outcomes

Combining deterministic Python wealth modeling with tightly scoped LLM APIs gave advisory teams and their clients a transparent, audit-ready guidance experience:

  • Mathematically consistent planning: Projections for retirement income, tax drag, and allocation drift remain reproducible across every conversation and export.
  • Inspectable compliance trails: Reviewers trace every narrative paragraph back to the exact simulation snapshot and approved research document behind it.
  • Focused human advisor capacity: Routine educational inquiries and scenario walkthroughs resolve autonomously while complex suitability decisions escalate cleanly with full structured context.
  • Zero-PII external inference: Strict redaction and read-only custodian boundaries let teams adopt modern language models without exposing sensitive client identifiers.

01 — Questions

asked about this kind of project

How do you prevent LLM APIs from inventing portfolio returns or miscalculating tax brackets?

Language models never compute financial figures or assume market returns. Whenever a user asks about retirement savings, withdrawal rates, or tax impact, FastAPI routes the question to typed Python simulation functions that run deterministic Decimal math and return read-only summary tables. The LLM only translates those verified outputs into plain-English explanations.

How does the system enforce regulatory boundaries around personalized investment advice?

Every prompt and response passes through a policy firewall in FastAPI. Client profiles carry suitability flags, and an intent classifier detects requests for specific ticker recommendations, margin leverage, or guaranteed-return claims, automatically routing those inquiries into an advisor-review queue rather than letting the model improvise.

Why choose FastAPI and pgvector instead of a standalone vector database and separate Python worker?

Running FastAPI directly alongside PostgreSQL and pgvector keeps transactional user holdings, compliance audit trails, and document embeddings inside one ACID boundary. Advisory firms can filter vector searches by client jurisdiction and approval status in a single SQL query without cross-service sync lag.

How are external market commentaries and tax rule updates kept current without retraining models?

Compliance-approved research notes, contribution limits, and product prospectuses are chunked with effective-date metadata and embedded into pgvector. Retrieval filters exclude expired tax-year documents automatically, ensuring LLM APIs cite only currently approved firm literature.

What happens when a client's linked brokerage holdings change mid-conversation?

Each conversational turn binds to a versioned portfolio snapshot ID in PostgreSQL. If a custodian webhook updates balances or asset weights during an active session, FastAPI invalidates stale cached projections, recomputes allocation drift, and refreshes the client's React side-panel metrics before the next guidance turn.

03 — Similar project?

describe what is different about yours

Build yours.

Tell me what exists, what you need and the deadline. Fixed price for a defined scope, or $55/day (8–9 hours work) with a written plan first.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.