Skip to main content

Endpoint

POST /api/simulation/simulate-enhanced
Runs an enhanced Monte Carlo simulation that automatically derives financial parameters from linked Plaid accounts. This endpoint fetches real-time account data, calculates sophisticated metrics like investment allocation and spending volatility, and runs a simulation with minimal user input.

Request Body

plaidUserId
string
required
The Plaid user ID for the linked account. Used to retrieve the stored access token and fetch account data.
userInputs
object
required
Basic user information that cannot be derived from account data.
goal
object
required
Financial goal parameters for the simulation.
simulationParams
object
Optional parameters to control simulation execution.

Response

Returns simulation results enhanced with Plaid-derived data and metadata about the accounts included.
successProbability
number
Probability (0.0 - 1.0) of achieving the specified goal.
medianOutcome
number
Median portfolio value at the goal timeline.
percentiles
object
Portfolio value percentiles (p10, p25, p50, p75, p90).
mean
number
Mean portfolio value across all simulations.
std
number
Standard deviation of outcomes.
worstCase
number
Minimum portfolio value observed.
bestCase
number
Maximum portfolio value observed.
assumptions
object
Enhanced assumptions object with Plaid-specific metadata.

Example Request

curl -X POST "https://api.drift.example/api/simulation/simulate-enhanced" \
  -H "Content-Type: application/json" \
  -d '{
    "plaidUserId": "user_abc123xyz",
    "userInputs": {
      "age": 32,
      "riskTolerance": "medium"
    },
    "goal": {
      "targetAmount": 50000,
      "timelineMonths": 36,
      "goalType": "house_downpayment"
    },
    "simulationParams": {
      "nSimulations": 100000
    }
  }'

Example Response

{
  "successProbability": 0.78,
  "medianOutcome": 54250.75,
  "percentiles": {
    "p10": 41300.25,
    "p25": 47850.50,
    "p50": 54250.75,
    "p75": 61200.00,
    "p90": 70150.25
  },
  "mean": 54820.40,
  "std": 11230.60,
  "worstCase": 25800.00,
  "bestCase": 95200.50,
  "assumptions": {
    "annualReturnMean": 0.08,
    "annualReturnStd": 0.14,
    "inflationRate": 0.03,
    "inflationVolatility": 0.01,
    "annualRaiseMean": 0.03,
    "annualRaiseFrequency": "annual",
    "promotionProbabilitySemiAnnual": 0.05,
    "promotionRaiseMean": 0.10,
    "emergencyProbabilityMonthly": 0.02,
    "emergencyAmountRange": "500-3000",
    "incomeVolatility": 0.04,
    "expenseVolatility": 0.16,
    "dataSource": "plaid",
    "accountsIncluded": {
      "depository": 3,
      "credit": 2,
      "loans": 1,
      "investments": 2
    },
    "derivedParams": {
      "annualReturnMean": 0.08,
      "annualReturnStd": 0.14,
      "incomeVolatility": 0.04,
      "expenseVolatility": 0.16,
      "creditCardsModeled": 2,
      "loansModeled": 1
    }
  }
}

How It Works

Data Retrieval Process

  1. Access Token Lookup: Retrieves stored Plaid access token for the user
  2. Account Data Fetch: Calls Plaid API to get all account information:
    • Depository accounts (checking, savings)
    • Credit card accounts
    • Loan accounts
    • Investment accounts with holdings
  3. Profile Mapping: Transforms raw Plaid data into EnhancedFinancialProfile
  4. Parameter Derivation: Calculates sophisticated simulation parameters

Enhanced Parameter Derivation

Investment Returns (simulation.ts:321-342)
  • Aggregates actual investment allocations across all investment accounts
  • Calculates weighted average using historical return assumptions:
    • Stocks: 10% annual return, 18% volatility
    • Bonds: 4% annual return, 6% volatility
    • Cash: 2% annual return, 1% volatility
    • Other: 6% annual return, 12% volatility
  • Defaults to 7% return / 15% volatility if no investment accounts
Income Volatility (simulation.ts:259-261)
  • Derived from Plaid income stability score
  • Formula: max(0.02, min(0.15, (1 - stabilityScore) × 0.15))
  • Higher stability score = lower income volatility
Expense Volatility (simulation.ts:264)
  • Calculated from variance in actual spending patterns
  • Based on transaction history analysis
Credit Card Modeling (simulation.ts:267-274)
  • Filters to cards with non-zero balances
  • Captures individual APR and minimum payment for each card
  • Enables account-level interest calculations
Loan Modeling (simulation.ts:277-284)
  • Filters to loans with non-zero balances
  • Captures interest rate and monthly payment for amortization
  • Supports home, auto, and personal loans

Financial Profile Construction

The endpoint automatically calculates:
  • Total Liquid Assets: Sum of all depository account balances
  • Credit Debt: Sum of all credit card balances
  • Loan Debt: Sum of all loan principals
  • Monthly Income: Derived from income transactions
  • Monthly Spending: Calculated from transaction history
  • Spending by Category: Aggregated from categorized transactions

Error Responses

error
string
Error message describing what went wrong.
details
string
Additional error details (included on 500 errors).
400 Bad Request
{
  "error": "plaidUserId is required"
}
404 Not Found
{
  "error": "No linked Plaid account found"
}
500 Internal Server Error
{
  "error": "Failed to run enhanced simulation",
  "details": "Plaid API rate limit exceeded"
}

Usage Notes

  • Requires a valid Plaid link for the specified user (established via Plaid Link flow)
  • Real-time data fetch may take 2-5 seconds depending on number of accounts
  • Investment allocation analysis requires investment accounts with holdings data
  • Income and spending calculations improve with more transaction history
  • The derivedParams object provides transparency into how real data influenced the simulation
  • Future enhancement: Pass enhancedParams.creditCards and enhancedParams.loans arrays to Python engine for account-level modeling

Advantages Over Standard Simulation

  1. Accuracy: Uses real account data instead of user estimates
  2. Completeness: Automatically includes all linked accounts
  3. Sophistication: Derives volatility and allocation from actual patterns
  4. Convenience: Requires minimal user input (age, risk tolerance, goal)
  5. Transparency: Returns detailed metadata about accounts and derived parameters
  6. Up-to-date: Fetches current balances and recent transactions

Build docs developers (and LLMs) love