API Reference

Programmatic access to the Portfolio Optimization platform. Build custom integrations for Indian equities, US equities, and Indian mutual funds, automate optimization workflows, and retrieve results using our REST API.

Base URL

All API endpoints are relative to this base URL

http
https://api.foliolab.ai

All requests must be made over HTTPS. HTTP requests will be rejected.

Authentication Overview

Two authentication methods are supported depending on your use case

JWT Tokens

Best for web applications and interactive use. Tokens are issued via login and refreshed using a secure HTTP-only refresh cookie.

Web / Interactive

API Keys

Best for server-to-server communication, scripts, and CI/CD pipelines. Keys carry the jobs:read and jobs:write scopes and cover the optimization job endpoints. Monte Carlo, standalone backtests, comparisons, tags and account endpoints need a signed-in session.

Programmatic / Server

AI assistants such as ChatGPT and Claude connect through the MCP endpoint at /mcp, which uses OAuth 2.1. See AI Assistants.

See the Authentication page for complete details on sign-up, login, token refresh, API key creation, and security best practices.

Rate Limiting and Quotas

Fair-use limits to ensure platform stability for all users

LimitValue
Sign-up, login, Google sign-in and password reset, per endpoint and client10 req/min
POST /oauth/register, per visitor address30 req/min
GET /mutual-funds/search and GET /us-stocks/search, each route per visitor address120 req/min
Optimization runs per monthFree 10, Pro 50, Enterprise unlimited
Monte Carlo simulations per monthFree none, Pro 20, Enterprise unlimited
Standalone backtests per monthFree 10, Pro 50, Enterprise unlimited
Simulations or backtests queued or running at once2 of each

A rate-limited request receives HTTP 429 Too Many Requests with the detail Too many attempts. Please retry shortly. The limit is a sliding one-minute window, and the response carries a Retry-After: 60 header. A quota refusal is also a 429, with a stable code such as monthly_limit_exceeded. Quota is consumed at submission and is not refunded when a job is cancelled. GET /billing/me reports the current usage of all three meters. It accepts a web session only: an API key receives 403.

Error Response Format

All error responses follow a consistent JSON structure

When an API request fails, the response body contains a JSON object with a human-readable error message:

json
{
  "detail": "Human-readable error message"
}

Many refusals put a stable machine-readable code at the start of detail, for example algo_not_allowed:HERC or FUND_MANAGER_NOT_ADMITTED: .... Match on the code, not on the text after it. When a query or path parameter fails type validation, detail is a list of validation errors and the status is 422. Every response carries an X-Request-ID header; quote it when you report a problem.

HTTP Status Codes

CodeStatusDescription
400Bad RequestThe request body or a query parameter is malformed or fails validation. POST /jobs answers a schema failure with "Invalid optimization request payload: " followed by up to five reasons
401UnauthorizedMissing, invalid, expired or revoked credentials
403ForbiddenValid credentials, but the plan, the API key scope, or the run owner does not allow the request. Plan refusals carry a stable code such as funds_not_allowed
404Not FoundThe requested resource does not exist
409ConflictThe request conflicts with the current state, for example a duplicate email or a parent run that has not succeeded
413Payload Too LargeThe request body exceeds 8 MiB (8,388,608 bytes). The body is {"detail": "Request body too large"}
422Unprocessable EntityThe request is well formed but cannot run, for example METHOD_REQUIREMENTS_UNMET, UNKNOWN_TICKER, INSUFFICIENT_HISTORY or FUND_MANAGER_NOT_ADMITTED. The code leads the detail and the reason follows it. These refusals come before the run is queued, so no monthly run is spent
429Too Many RequestsA rate limit, a monthly plan quota, or an in-flight limit was reached
500Internal Server ErrorAn unexpected server-side error occurred
503Service UnavailableA dependency is temporarily unavailable, or the job could not be queued. Retry later

Supported Optimization Methods

All 31 methods. Pass these enum values in the methods array when submitting an optimization job. Free accounts can use MVO, MinVol, CriticalLineAlgorithm, HRP and EquiWeighted; Pro and Enterprise can use all 31

MethodAPI ValueDescription
Mean-Variance OptimizationMVOClassic Markowitz mean-variance portfolio optimization
Minimum VolatilityMinVolMinimize portfolio volatility regardless of returns
Max Quadratic UtilityMaxQuadraticUtilityMaximize risk-adjusted utility with quadratic penalty
Equal WeightedEquiWeightedUniform allocation across all selected assets
Critical Line AlgorithmCriticalLineAlgorithmExact efficient frontier tracing via CLA
Hierarchical Risk ParityHRPTree-based clustering for robust diversification
Minimum CVaRMinCVaRMinimize Conditional Value-at-Risk (expected shortfall)
Minimum CDaRMinCDaRMinimize Conditional Drawdown-at-Risk
HERCHERCHierarchical Equal Risk Contribution
NCONCONested Clustered Optimization
HERC2HERC2Enhanced Hierarchical Equal Risk Contribution
Benchmark TrackerBenchmarkTrackerMinimize tracking error to a benchmark index
Maximum DiversificationMaximumDiversificationMaximize the portfolio diversification ratio
Risk BudgetingRiskBudgetingTarget equal or custom risk contribution per asset
Distributionally Robust CVaRDistributionallyRobustCVaRWorst-case CVaR over Wasserstein uncertainty set
Stacking OptimizationStackingOptimizationEnsemble meta-optimizer stacking multiple sub-models
Inverse VolatilityInverseVolatilityWeights inversely proportional to each asset's volatility
Sparse Markowitz (L1)SparseMarkowitzL1L1-regularized Markowitz for sparse, concentrated portfolios
HMM Regime MVOHMMRegimeMVOHidden Markov Model regime-switching mean-variance
Black-LittermanBlackLittermanBlack-Litterman with market-implied equilibrium returns and momentum views
EWMA Mean-VarianceEWMAMVOExponentially weighted moments that adapt to recent volatility
Minimum SemivarianceMinSemivarianceMinimize downside variance while leaving upside variation unpenalized
Minimum EVaRMinEVaRMinimize Entropic Value-at-Risk
Minimum EDaRMinEDaRMinimize Entropic Drawdown-at-Risk
Maximum DecorrelationMaxDecorrelationMinimize the portfolio correlation quadratic form
Robust Mean-VarianceRobustMVOWorst-case MVO under expected-return uncertainty
Resampled Mean-VarianceResampledMVOBootstrap-resampled MVO with averaged portfolio weights
Sparse Index TrackingSparseIndexTrackingTrack a benchmark with a sparse subset of assets
Quintile MomentumQuintileMomentumEqual-weight the highest-momentum asset quintile
Kelly OptimizationKellyLong-only growth-optimal expected log-wealth allocation
Kalman Pairs TradingKalmanPairsTradingLong/short pairs allocation on a Kalman-filtered time-varying hedge ratio. API and MCP only

Example usage in request body:

json
{
  "stocks": [
    { "ticker": "RELIANCE", "exchange": "NSE" },
    { "ticker": "TCS", "exchange": "NSE" },
    { "ticker": "HDFCBANK", "exchange": "NSE" },
    { "ticker": "INFY", "exchange": "NSE" }
  ],
  "methods": ["MVO", "HRP", "MinCVaR"],
  "benchmark": "nifty"
}

Indian requests take their risk-free rate from the India 10-year government bond series on FRED by default. A retail request that names no benchmark measures against the NIFTY 50 price index; a fund-manager request that names none measures against NIFTY 500 on its Total Return Index. US requests must use a US benchmark and set risk_free.region to "US". See the Optimization API for mutual-fund and US-stock schemas, asset discovery endpoints, and complete examples.

Not investment advice. Past performance is not indicative of future results.