LLM Stock Selection Feeding a Classical Optimizer: Evidence, a Runnable Pipeline, and Where It Breaks

LLM Stock Selection Feeding a Classical Optimizer: Evidence, a Runnable Pipeline, and Where It Breaks

The hybrid pattern: LLMs pick, optimizers weigh

A consistent pattern appears across the published record: a large language model produces a universe, ranking, or view set, while a classical optimizer turns those inputs into portfolio weights. In ChatGPT-based Investment Portfolio Selection, the authors report, “ChatGPT is effective in stock selection but may not perform as well in assigning optimal weights to stocks within the portfolio. But when stocks selection by ChatGPT is combined with established portfolio optimization models, we achieve even better results.” A later multi-provider study, Generative AI-enhanced Sector-based Investment Portfolio Construction, reaches a similar conclusion: “combined with traditional optimization techniques, portfolio outcomes improve in both performance and consistency.”

This division of labour is the core design choice. The LLM contributes selection or structured views; the optimizer enforces constraints, diversification, and a risk objective. The evidence below is drawn from published papers and library documentation, and every reported figure is an authors’ reported backtest result.

What the published evidence shows

The four studies below describe different LLM roles and evaluation setups. All figures in the table are authors’ reported backtest results.

Study (linked) LLM’s job Optimizer’s role Universe & period Authors’ reported result Stated limitation
ChatGPT-based Investment Portfolio Selection Produce a universe of potentially attractive stocks from the S&P 500 Various portfolio optimization strategies applied to the AI-generated universe S&P 500; period not stated in the supplied abstract Hybrid beats LLM weighting — no numeric metrics in the supplied abstract Model “hallucinations”, necessitating careful verification and validation of the output
Generative AI-enhanced Sector-based Investment Portfolio Construction Select and weight 20 stocks per sector across multiple LLM providers Traditional optimization techniques combined with LLM-based selection S&P 500 sector indices; stable window Jan–Mar 2025 and volatile window Apr–Jun 2025 Stable phase: frequent outperformance on cumulative return and Sharpe; volatile phase: many underperformed — no numeric values in the supplied abstract Regime-shift struggle; reliability remains market-dependent
MarketSenseAI GPT-4 with Chain of Thought and In-Context Learning generates and evaluates signals from trends, news, fundamentals, and macro Not stated in the supplied abstract S&P 100; 15 months Excess alpha 10%–30%; cumulative return up to 72%; risk profile comparable to the broader market None stated in the supplied abstract
3S-Trader Scoring, strategy, and selection modules summarize signals and assemble a portfolio Score-based selection; no classical optimizer named in the supplied abstract DJIA constituents plus three sector-specific stock sets; period not stated in the supplied abstract 131.83% accumulated return, Sharpe 0.31, Calmar 11.84 on DJIA constituents; consistently strong results across other sectors Prior methods lack multi-candidate reasoning and adaptability to market shifts

ChatGPT-selected universes + classical optimization

The first study uses ChatGPT to obtain a universe of stocks from the S&P 500 market index that are potentially attractive for investing. The authors compare various portfolio optimization strategies that utilized this AI-generated trading universe against quantitative portfolio optimization models and popular investment funds. The supplied abstract reports no numeric metrics, but it states the directional finding clearly: LLM selection is useful, LLM weighting is weaker, and the hybrid is better.

Five providers, sector portfolios, regime dependence

The sector study evaluates LLMs from OpenAI, Google, Anthropic, DeepSeek, and xAI. Each model was prompted to select and weight 20 stocks per sector from S&P 500 sector indices. The authors compare two out-of-sample periods: a stable market phase (Jan–Mar 2025) and a volatile phase (Apr–Jun 2025). During stable conditions, LLM-weighted portfolios frequently outperformed sector indices on cumulative return and risk-adjusted (Sharpe ratio) measures. During the volatile period, many underperformed, suggesting strong temporal dependence in LLM portfolio performance.

MarketSenseAI and 3S-Trader: scores, signals, selection

MarketSenseAI uses GPT-4 with Chain of Thought and In-Context Learning to analyze trends, news, fundamentals, and macroeconomic factors. It employs GPT-4 both as a predictive mechanism and signal evaluator. Over S&P 100 stocks for 15 months, the authors report excess alpha of 10%–30% and cumulative return of up to 72%, while maintaining a risk profile comparable to the broader market.

3S-Trader is a training-free framework with scoring, strategy, and selection modules. It addresses a motivating gap: most existing methods focus on single-stock trading and lack the capacity to reason over multiple candidates for portfolio construction. Across four distinct stock universes, including DJIA constituents and three sector-specific stock sets, the authors report 131.83% accumulated return, Sharpe 0.31, and Calmar 11.84 on DJIA constituents.

Where the LLM plugs into the optimizer

The expected-returns problem

The PyPortfolioOpt Expected Returns documentation states that the expected_returns module provides functions for estimating expected returns, “which is a required input in mean-variance optimization.” By convention, outputs are annual returns from daily prices, and the frequency parameter defaults to 252. The module documents mean_historical_return, ema_historical_return (span=500), and capm_return (risk_free_rate=0.02).

The documentation also gives two direct cautions: “Supplying expected returns can do more harm than good.” and “This is the main flaw in mean-variance optimization – the optimization procedure is sound, and provides strong mathematical guarantees, given the correct inputs.” For historical means, it adds that estimates are subject to large uncertainty and that a mean-variance optimizer “will maximise the erroneous inputs.” This is why LLM-generated scores should be treated as inputs requiring validation, not as direct truth.

Black-Litterman: the documented interface for model-generated views

The PyPortfolioOpt Black-Litterman documentation describes Black-Litterman as a Bayesian model that combines a prior estimate of returns with views on certain assets to produce a posterior estimate. It is especially relevant because “You don’t technically have to provide a prior estimate to the Black-Litterman model. This is particularly useful if your views (and confidences) were generated by some proprietary model, in which case BL is essentially a clever way of mixing your views.”

The documented components are Q (Kx1 vector of views), P (KxN picking matrix), Ω (KxK uncertainty matrix of views), Π (Nx1 vector of prior expected returns), Σ (NxN covariance matrix of asset returns), and τ (“a scalar tuning constant”). The posterior covariance formula is Σ̂ = Σ + [(τΣ)^-1 + PᵀΩ^-1 P]^-1. The docs support absolute and relative views. Their illustrative examples include “AAPL will return 10%” and “XOM will drop 40%” for absolute views, and “GOOG will outperform FB by 3%” for a relative view — these are documentation examples, not ticker recommendations. The same page warns that “mean historical returns are a completely uninformative prior.”

The optimizer side: risk models and library choices

The PyPortfolioOpt Risk Models documentation argues that risk models are often more important than expected returns because historical variance is generally more persistent than mean historical returns. It cites Kritzman et al. (2010), as cited there, for the finding that minimum variance portfolios formed without providing expected returns actually perform much better out of sample.

Covariance estimation remains difficult: in practice the covariance matrix is estimated from past data, and “Not all the calculated covariance matrices will be positive semidefinite (PSD).” PyPortfolioOpt documents fix_nonpositive_semidefinite(matrix, fix_method='spectral'), where spectral sets negative eigenvalues to zero then rebuilds the matrix. The documented risk_matrix methods include sample_cov, semicovariance, exp_cov, ledoit_wolf, ledoit_wolf_constant_variance, ledoit_wolf_single_factor, ledoit_wolf_constant_correlation, and oracle_approximating. The PyPortfolioOpt User Guide recommends sensible defaults: expected_returns.mean_historical_return() and CovarianceShrinkage(df).ledoit_wolf(). It also states the data contract: a date/timestamp index, one price column per asset, and the same frequency across assets. For the long-only efficient frontier, it describes minimizing wᵀΣw subject to wᵀμ ≥ μ*, wᵀ1 = 1, and wᵢ ≥ 0.

Riskfolio-Lib is another documented option, built on CVXPY and integrated with Pandas. Its documented surface includes four objective functions — Minimum Risk, Maximum Return, Maximum Utility Function, and Maximum Risk Adjusted Return Ratio — and Mean Risk / Logarithmic Mean Risk optimization with 26 convex risk measures, plus Risk Parity with 22 convex risk measures. Named examples include CVaR, EVaR, MAD, and CDaR. The supplied excerpt contains no function signatures, keyword flags, or default values, so this article does not assert them.

Runnable demo: from hand-authored scores to capped weights

The script below demonstrates the plumbing only: hand-authored scores become views, views are blended with a prior, and a pure-numpy optimizer produces capped weights. It runs on Python 3, numpy, and pandas. The supplied PyPortfolioOpt excerpts do not document EfficientFrontier class methods, so the optimizer is implemented in numpy as an excerpt limitation, not as a claim that PyPortfolioOpt lacks them.

import numpy as np
import pandas as pd

# ---------------------------------------------------------------------------
# llm_scores_to_weights.py
# Illustrative demo: hand-authored scores -> Black-Litterman-style views ->
# capped mean-variance weights. Synthetic data only; not investment advice.
# ---------------------------------------------------------------------------

# Optional PyPortfolioOpt swap-ins (documented in PyPortfolioOpt docs).
# This script does NOT require pypfopt; it runs on numpy + pandas alone.
# try:
#     from pypfopt import risk_models
#     # Documented sensible default: CovarianceShrinkage(df).ledoit_wolf()
#     # S = risk_models.CovarianceShrinkage(price_df).ledoit_wolf()
#     from pypfopt import black_litterman
#     # Documented functions requiring market prices and market caps:
#     # delta = black_litterman.market_implied_risk_aversion(market_prices)
#     # prior = black_litterman.market_implied_prior_returns(mcaps, delta, cov_matrix)
# except ImportError:
#     pass

rng = np.random.default_rng(42)

# Hand-authored "LLM-style" scores and confidences for placeholder candidates.
# These are stand-ins for an LLM ranking, not real model output.
# Names are placeholders, not tickers or recommendations.
candidates = pd.DataFrame(
    {
        "candidate": ["CAND_A", "CAND_B", "CAND_C", "CAND_D", "CAND_E", "CAND_F", "CAND_G", "CAND_H"],
        "score": [8.5, 7.0, 6.5, 5.5, 4.5, 3.5, 2.5, 1.5],       # 0-10, hand-authored
        "confidence": [0.8, 0.7, 0.6, 0.6, 0.5, 0.5, 0.4, 0.4],  # 0-1, hand-authored
    }
)

# Synthetic prices: ~3 years of daily business-day random walks.
# Data contract: DatetimeIndex, one price column per asset, same frequency.
n_days = 252 * 3
dates = pd.bdate_range("2021-01-01", periods=n_days)
n_assets = len(candidates)
drift = rng.normal(0.0002, 0.0001, size=n_assets)
vol = rng.uniform(0.01, 0.03, size=n_assets)
shocks = rng.normal(0, 1, size=(n_days, n_assets))
log_returns = drift + vol * shocks
prices = 100 * np.exp(np.cumsum(log_returns, axis=0))
price_df = pd.DataFrame(prices, index=dates, columns=candidates["candidate"])

# Sample covariance, annualized by 252 (documented frequency default).
rets = price_df.pct_change().dropna()
S_sample = rets.cov().values * 252

# Manual shrinkage toward diagonal (a documented shrinkage category).
# S = (1-delta_shrink) * S_sample + delta_shrink * diag(S_sample)
delta_shrink = 0.2  # demo choice, not a documented default
S = (1 - delta_shrink) * S_sample + delta_shrink * np.diag(np.diag(S_sample))

# Scores -> absolute views Q (monotone map; demo choice).
# P is identity over scored candidates (views on a subset, picked by P).
# Omega is diagonal from hand-specified confidences (confidence in views).
score_min, score_max = candidates["score"].min(), candidates["score"].max()
view_min, view_max = -0.05, 0.15  # demo annual-view range, not a documented default
Q = view_min + (candidates["score"].values - score_min) / (score_max - score_min) * (view_max - view_min)
P = np.eye(n_assets)
omega_diag = (0.05 / candidates["confidence"].values) ** 2  # demo uncertainty mapping
Omega = np.diag(omega_diag)

# Prior Pi = delta_mkt * Sigma * w_mkt (documented prior formula).
# Equal-weight is a stand-in for market-cap weights; delta_mkt and tau are demo
# scalars. tau is described in the docs as "a scalar tuning constant".
w_mkt = np.ones(n_assets) / n_assets
delta_mkt = 2.5  # demo stand-in, not a documented default
tau = 0.05       # demo scalar tuning constant
Pi = delta_mkt * (S @ w_mkt)

# Standard Black-Litterman precision-weighted posterior mean.
# The supplied PyPortfolioOpt Black-Litterman documentation excerpt documents
# the components (Q, P, Ω, Π, Σ, τ) and the posterior covariance formula, but
# not this posterior-mean equation verbatim; this is the standard mechanic.
tau_S_inv = np.linalg.inv(tau * S)
Omega_inv = np.diag(1.0 / np.diag(Omega))
M = tau_S_inv + P.T @ Omega_inv @ P
mu_post = np.linalg.solve(M, tau_S_inv @ Pi + P.T @ Omega_inv @ Q)

# Posterior covariance (documented formula): Σ̂ = Σ + [(τΣ)^-1 + P^T Ω^-1 P]^-1
Sigma_hat = S + np.linalg.inv(M)


def project_capped_simplex(v, cap, tol=1e-12, max_proj_iter=10000):
    """Project vector onto {w : sum(w)=1, 0 <= w <= cap}."""
    w = np.clip(v, 0.0, cap)
    for _ in range(max_proj_iter):
        gap = 1.0 - w.sum()
        if abs(gap) < tol:
            break
        free = (w > tol) & (w < cap - tol)
        if not np.any(free):
            free = w < cap - tol
            if not np.any(free):
                break
        w[free] += gap / free.sum()
        w = np.clip(w, 0.0, cap)
    total = w.sum()
    if total > 0:
        w = w / total
    return np.clip(w, 0.0, cap)


# Classical optimizer (pure numpy): min w^T Σ̂ w - λ * w^T μ_post
# s.t. sum(w)=1, 0 <= w <= cap. Cap and lambda are demo choices.
cap = 0.30
lam = 1.0
w = np.ones(n_assets) / n_assets
step = 0.01
max_iter = 20000
tol = 1e-8
converged = False

for _ in range(max_iter):
    grad = 2 * Sigma_hat @ w - lam * mu_post
    w_new = project_capped_simplex(w - step * grad, cap)
    if np.linalg.norm(w_new - w) < tol:
        w = w_new
        converged = True
        break
    w = w_new

# Output diagnostics (computed, not market evidence).
port_var = float(w.T @ Sigma_hat @ w)
port_vol = float(np.sqrt(port_var))
max_weight = float(w.max())
at_cap = candidates["candidate"].values[w >= cap - 1e-6].tolist()
herfindahl = float(np.sum(w ** 2))
effective_n = float(1.0 / herfindahl) if herfindahl > 0 else np.nan

out = candidates.copy()
out["view"] = Q
out["weight_pct"] = (w * 100).round(2)
print(out[["candidate", "score", "confidence", "view", "weight_pct"]].to_string(index=False))
print(f"\nConverged: {converged}")
print(f"Annualized portfolio variance (Sigma_hat): {port_var:.6f}")
print(f"Annualized portfolio volatility: {port_vol:.6f}")
print(f"Max weight: {max_weight:.4f}")
print(f"Names at cap: {at_cap}")
print(f"Effective positions (1/Herfindahl): {effective_n:.2f}")
print("Caveat: illustrative synthetic demo only; not a backtest, not investment advice.")

What the script does (and what it doesn’t claim)

The script generates synthetic prices with a fixed seed, builds an annualized covariance matrix with manual shrinkage, maps hand-authored scores to absolute views, constructs a diagonal uncertainty matrix from hand-authored confidences, computes a standard Black-Litterman precision-weighted posterior blend, and solves a capped mean-variance objective by projected gradient descent. The optional PyPortfolioOpt imports are commented and guarded; the script does not rely on them.

It makes no performance claim. It reports no returns, Sharpe, alpha, or drawdown. It is not a backtest: it uses one synthetic window with no train/test split. The scores are hand-authored, the weights are illustrative, and nothing generalizes to any market, period, or paper result. No ticker appears. The demo demonstrates plumbing, not edge.

Failure modes of the hybrid pipeline

Hallucination and the verification burden

The ChatGPT portfolio study warns that trusting GPT investment advice is challenged by model “hallucinations”, “necessitating careful verification and validation of the output”. The supplied sources name hallucination as a general risk requiring verification; they do not provide a measured hallucinated-universe count or hallucination frequency.

Training-cutoff staleness and regime shifts

The sector study reports strong temporal dependence in LLM portfolio performance. It finds that during the volatile period many LLM portfolios underperformed and suggests that “current models may struggle to adapt to regime shifts or high-volatility environments underrepresented in their training data.” Reliability remains market-dependent, so a pipeline that worked in one window cannot be assumed stable in another.

Estimation-error amplification

Classical optimization is mathematically sound only given correct inputs. The PyPortfolioOpt expected-returns documentation warns that “Supplying expected returns can do more harm than good” and that a mean-variance optimizer “will maximise the erroneous inputs.” The risk-model documentation adds that covariance must be estimated from past data and is a deep, actively researched topic. Black-Litterman documentation also warns that mean historical returns are a “completely uninformative prior.” In a hybrid pipeline, an LLM view error can be amplified by a confident optimizer.

Backtest overfitting and multiple testing

Bailey, Borwein, López de Prado, and Zhu show in Pseudo-Mathematics and Financial Charlatanism that backtest overfitting is easy to produce. They report that with N = 10 alternative configurations, a researcher is expected to find an in-sample Sharpe ratio of 1.57 despite zero expected out-of-sample Sharpe. Their Minimum Backtest Length rule states that with 5 years of data, no more than 45 independent configurations should be tried; MinBTL is a necessary, non-sufficient condition. They also note a disclosure gap because analysts rarely report the number of configurations tried, and under memory effects backtest overfitting can lead to negative expected out-of-sample returns.

This matters directly for LLM pipelines: every prompt variant, model choice, temperature, scoring rubric, and selection threshold multiplies N. The supplied paper excerpts do not report configuration counts, so the reader cannot assess how much selection was tried before the reported backtest results.

FAQ

Does the LLM pick the weights?

The documented evidence favors a split. The ChatGPT portfolio study reports that ChatGPT is effective in stock selection but may not perform as well in assigning optimal weights, while combining selection with established portfolio optimization models achieves better results. The sector study similarly finds improved performance and consistency when LLM-based selection is combined with traditional optimization techniques.

Can I feed LLM scores straight in as expected returns?

The PyPortfolioOpt documentation cautions that supplying expected returns can do more harm than good and that the optimizer will maximise erroneous inputs. Black-Litterman provides a documented interface for views and confidences, and the risk-models documentation discusses risk-based objectives such as minimum variance. The sources do not establish a universal best conversion; they do establish that validation and uncertainty handling matter.

Are the reported returns reproducible?

The figures cited here are authors’ reported backtest results. MarketSenseAI reports excess alpha 10%–30% and cumulative return up to 72% over S&P 100 stocks for 15 months; 3S-Trader reports 131.83% accumulated return, Sharpe 0.31, and Calmar 11.84 on DJIA constituents. The backtest-overfitting paper shows how small configuration counts can inflate in-sample Sharpe. The supplied sources contain no live, cost-adjusted, or out-of-deployment evidence.

Should I use PyPortfolioOpt or Riskfolio-Lib?

The supplied sources document different surfaces. PyPortfolioOpt documents expected-return estimators, risk models, and a Black-Litterman interface for views. Riskfolio-Lib documents CVXPY/Pandas integration, four objective functions, and 26/22 convex risk measures for Mean Risk and Risk Parity. The Riskfolio excerpt does not include function signatures or keyword flags, so implementation details beyond those labels are not established by this dossier.

Is this investment advice?

No. This article is desk research on published papers and library documentation, plus a synthetic-data demo. Any real deployment would need careful verification and validation of model output, as the ChatGPT portfolio study states.

The Bottom Line

The hybrid pattern is documented and coherent: use the LLM for selection, ranking, or views, and use a classical optimizer for weighting. The evidence-backed split is LLM selection plus classical weighting, not LLM-only weight assignment. All performance evidence in the supplied sources is backtest-only and exposed to overfitting. Verification of LLM outputs and disclosure of configuration counts are non-negotiable. Nothing here is investment advice.

How This Guide Was Built

This article is desk research on published papers and library documentation — no live trading, no hands-on backtest, every number attributed to its source. No transaction costs, slippage, or capacity claims are made because the supplied sources do not establish them. Where the dossier lacked an implementation detail, such as the Black-Litterman posterior-mean equation verbatim or PyPortfolioOpt EfficientFrontier method signatures, the article states that limitation rather than inventing it.

← Back to all posts