Building LLM-Powered Portfolio Generation for Robo-Advisors: A Practical Engineering Guide

    This article presents a practical architecture for using large language models to generate structured, verifiable, and backtestable asset allocation portfolios. It explains why passing raw natural language directly to a model fails, then walks through a five-layer design that isolates the LLM to candidate generation while deterministic code handles constraint extraction, normalization, validation, and backtesting. Key topics include risk profile modeling, prompt design with structured JSON output, weight normalization with cap enforcement, rolling-window robustness checks, explainability, and common anti-patterns. The goal is to position the LLM as a constrained candidate generator rather than a free-form product recommender.

    1. Scenario and Problem Definition

    Over the past two years, general-purpose LLM applications have entered a phase of rapid adoption. A newly released AI assistant reached over ten million downloads within its first week of public beta and entered the top three free apps in a major app store within three days, growing faster than several well-known apps before it. As traffic surged, a typical user need emerged: users describe their risk preference in a single natural-language sentence and expect the system to return an executable asset allocation portfolio.

    The model output in the original case was approximately 20% in dividend low-volatility ETFs, about 55% in technology growth themes (covering STAR Market broad-based indices and overseas technology indices), with the remainder in bonds and gold. Looking through to the underlying assets, the growth exposure was highly concentrated in a single theme, and the historical backtest window happened to cover that theme’s strong cycle. The conclusion therefore showed clear sample-period bias and concentration risk.

    This lets us frame the problem as a general technical proposition: how to make an LLM output a structured, verifiable, and backtestable asset allocation plan under constraints, rather than letting the model freely “recommend products.”

    2. Why Passing Natural Language Directly to the Model Does Not Work

    Letting the model generate a portfolio directly typically produces four types of defects:

    1. Constraint drift: The user says “conservative,” but the model may return a high-volatility portfolio; after multiple turns, early constraints are gradually forgotten.
    2. Numerical inconsistency: Weights do not sum to 100%, or negative weights appear, or a single item exceeds its limit.
    3. Sample-period bias: The model tends to repeat the best-performing assets in its training corpus, which is equivalent to an implicit “momentum over the past N years” strategy.
    4. Non-reproducibility: Small changes in temperature, context length, or system prompt alter the output, making it impossible to audit.

    The engineering solution is to decouple “generation” from “validation”: the model only produces candidate plans and reasons, while deterministic code handles constraint validation, weight normalization, and backtesting.

    3. Overall Architecture

    A five-layer structure is recommended:

    • Access layer: A unified session entry point handling identity, rate limiting, and audit logging.
    • Intent and constraint extraction layer: Converts natural language into a structured risk profile.
    • Candidate generation layer: The model produces candidate portfolios based on the asset pool and constraints.
    • Deterministic validation layer: Weight normalization, cap clipping, concentration and correlation checks.
    • Evaluation and presentation layer: Backtest metrics, stress testing, explainability reports.

    The third layer is the only place that uses an LLM; all other layers should be deterministic, testable logic.

    4. Constraint Modeling: Turning Wording into Parameters

    The risk profile can be structured as follows (illustrative):

    1. {
    2. "risk_level": "balanced",
    3. "max_single_asset": 0.25,
    4. "max_category": 0.55,
    5. "min_liquid_ratio": 0.10,
    6. "horizon_years": 5,
    7. "exclude": ["high_volatility_single_theme"]
    8. }

    There are three key design points. First, map “conservative/balanced/aggressive” to volatility and drawdown tolerance ranges rather than adjectives. Second, set a category cap in addition to a single-asset cap, to avoid pseudo-diversification of “multiple items, same theme.” Third, retain exclusion items for compliance and investor suitability management.

    5. Prompts and Structured Output

    The system prompt should clearly state the role, asset pool, constraints, and output mode, and require the model to give reasons rather than conclusions:

    1. You are an asset allocation assistant. Select only from the given asset pool.
    2. Hard constraints: non-negative weights, sum to 1, no category exceeds max_category.
    3. Output JSON: { "allocations":[{"asset_id":"","weight":0,"reason":""}],
    4. "risk_note":"", "rebalance":"quarterly" }
    5. If the constraints cannot be satisfied, return status="infeasible" and explain the conflicting items.

    Combined with structured output constraints (JSON Schema validation) and a low temperature setting, reproducibility improves significantly. The asset pool should come from an internal master data service; the model must not “recall” ticker codes on its own.

    6. Deterministic Validation and Normalization

    Model output must pass through a code gate:

    1. def normalize(alloc, caps):
    2. alloc = {k: max(0.0, float(v)) for k, v in alloc.items()}
    3. total = sum(alloc.values()) or 1.0
    4. alloc = {k: v / total for k, v in alloc.items()}
    5. for _ in range(50): # iterative projection to satisfy caps
    6. over = {k: v - caps[k] for k, v in alloc.items() if v > caps[k]}
    7. if not over:
    8. break
    9. excess = sum(over.values())
    10. for k in over:
    11. alloc[k] = caps[k]
    12. free = [k for k in alloc if alloc[k] < caps[k]]
    13. base = sum(alloc[k] for k in free) or 1.0
    14. for k in free:
    15. alloc[k] += excess * alloc[k] / base
    16. return alloc

    After normalization, run concentration checks (top three holdings combined), category exposure, and an inter-asset correlation matrix check. If any check fails, fall back to “regenerate” or “return infeasible.”

    7. Backtesting and Evaluation: Avoiding Persuasion by a Strong Cycle

    Evaluation should include at least four categories of metrics: annualized return and volatility; maximum drawdown and recovery period; turnover and rebalancing cost; and rolling-window robustness. The rolling robustness method is to split the sample period into multiple equal-length sub-intervals and backtest each separately. If a portfolio only significantly outperforms in a single sub-interval, flag it as highly sample-period dependent.

    Also introduce benchmark comparisons (equal-weight portfolio, risk parity portfolio, classic stock-bond ratio portfolios). A candidate portfolio may be presented externally only if it is no worse than the benchmarks in most sub-intervals.

    8. Explainability and Compliant Presentation

    What is presented to the user should be three things: why it is allocated this way (from a factor and risk-budget perspective), what the worst case looks like (drawdown estimates under stress scenarios), and under what conditions adjustment is needed (rebalancing triggers). It must be explicitly stated that this is a quantitative result based on historical data and does not constitute a return guarantee.

    9. Engineering Implementation

    The inference service is best deployed on a container platform, using a message queue to smooth peak traffic at public-beta scale. Sessions and structured outputs should be stored in object storage for auditing. Use a logging service and monitoring alerts to track three core metrics: time to first token, structured parsing failure rate, and constraint infeasibility rate. A cache layer can reuse results by “risk profile hash,” significantly reducing cost.

    10. Common Anti-Patterns

    • Letting the model output ratios directly without normalization;
    • Asset pool provided by model memory rather than pushed from master data;
    • Validating only single-asset caps while ignoring theme concentration;
    • Running backtests only on the full sample without rolling splits;
    • No infeasible return path, causing the model to force numbers to fit.

    In summary, position the LLM as a “constrained candidate generator” and place deterministic logic in validation and evaluation. Only then can you build robo-advisor capabilities that are both flexible and controllable. The general-purpose containers, message queues, object storage, and monitoring alerts offered by Baidu AI Cloud are sufficient to support stable operation of this pipeline.