All Learn articles

Guide · · 8 min read · By Mike A.

How to stop an LLM hallucinating stock prices

An LLM invents a stock price because it predicts text and has nothing to look the number up in. Fetch the price, date it, allow null, and check the result in code before anyone sees it.

Why a model makes up a price

A language model predicts the next words. A stock price is a fact that changes every second, and the model only has the text it was trained on plus whatever you put in the prompt. Ask for a price with nothing to look up and it writes one that looks right: the format fits and the size is plausible, but the number is old or invented.

The fix is to take the number out of the model’s hands. Five patterns do that:

  1. Fetch the number first, then ask the model to explain it.
  2. Never let the model supply a number it did not retrieve.
  3. Carry a date with every number.
  4. Ask for a typed object and allow null.
  5. Check the result in code before anyone sees it.

Neurobro’s NeuroAPI applies the first pattern: its agent fetches live market data before it answers.

Pattern 1: Fetch first, then answer

Get the price from a source of record, in your code or through a tool the model calls, and put it in the prompt. The model’s job is to explain the number, and memory has no part in it.

Quote: [TICKER] [PRICE] [CURRENCY], observed at [TIMESTAMP].
Using only this quote, explain what a move of [PERCENT] today means.

Ask this in Neurobro

NeuroAPI works this way: the agent fetches live data before it answers.

Pattern 2: Never let the model supply a number it did not retrieve

Make the rule explicit in the system prompt: use only figures from the data provided, and if a figure is missing, say it is missing. Then enforce it. If the answer contains a price that is not in your input, reject the answer.

Let code do the arithmetic as well. Percent changes, ratios, and position sizes are a few lines of math, and code does them exactly.

Pattern 3: Carry a date with every number

A price without a time could be from any day. Store an as_of timestamp next to every value, pass it into the prompt, and decide how old a number can be before you refuse to use it. For a live quote that may be minutes. For a quarterly figure it may be weeks.

The same habit helps your users: an answer that says “as of 14:32 UTC” tells them how much to trust it.

Pattern 4: Ask for a typed object and allow null

When your code needs a price, ask for an object instead of prose, and write the schema so that “I couldn’t find it” is a valid answer. A model forced to fill a number field will fill it with something. A nullable field gives it an honest way out.

{
  "type": "object",
  "properties": {
    "ticker": { "type": "string" },
    "price": {
      "type": ["number", "null"],
      "description": "Latest price in the quote currency. Null if it could not be found."
    },
    "currency": {
      "type": ["string", "null"],
      "description": "ISO 4217 code such as USD. Null if unknown."
    },
    "as_of": {
      "type": ["string", "null"],
      "description": "When the price was observed, in ISO 8601 UTC. Null if unknown."
    },
    "sources": {
      "type": "array",
      "items": { "type": "string" },
      "description": "Where the price came from. Empty if none."
    }
  },
  "required": ["ticker", "price", "currency", "as_of", "sources"],
  "additionalProperties": false
}

Every field is required and extra fields are not allowed, so the shape is fixed. Only the values can be null. Describe formats such as the timestamp in the description, because the pattern keyword isn’t supported.

Pattern 5: Check the result in code

A valid object can still hold a wrong number, so the last step is a check you write yourself. Compare the price with your own feed, reject old timestamps, and refuse an answer with no source.

from datetime import datetime, timedelta, timezone

MAX_AGE = timedelta(minutes=15)
MAX_GAP = 0.02  # allowed difference from your own feed


def check_quote(output: dict, reference_price: float) -> list[str]:
    problems = []
    price, as_of = output["price"], output["as_of"]
    if price is None or as_of is None:
        return ["price or as_of is missing"]
    if price <= 0:
        problems.append("price must be positive")
    stamp = datetime.fromisoformat(as_of.replace("Z", "+00:00"))
    if stamp.tzinfo is None:
        stamp = stamp.replace(tzinfo=timezone.utc)
    if datetime.now(timezone.utc) - stamp > MAX_AGE:
        problems.append("quote is older than the limit")
    if abs(price - reference_price) / reference_price > MAX_GAP:
        problems.append("price differs from your own feed")
    if not output["sources"]:
        problems.append("no source listed")
    return problems

An empty list means the quote can be shown. Anything else goes to a retry or a human, and the user sees “price unavailable” instead of a wrong number.

Doing this with NeuroAPI

NeuroAPI covers patterns 1 and 4 in one call. The agent fetches live data before it answers, and when you pass output_schema, a value it can’t find comes back as null where the schema allows it, which gives it a way out other than a made-up number. The object arrives in output, and answer is null. Structured output is non-streaming only and the research takes time, so set a client timeout of 300 seconds. Save the schema above as quote_schema.json and the call looks like this:

import json
import os

import httpx

with open("quote_schema.json") as f:
    schema = json.load(f)

res = httpx.post(
    "https://api.neurobro.ai/api/v1/agent/ask",
    headers={"X-API-Key": os.environ["NEUROAPI_KEY"]},
    json={
        "prompt": "What is the latest price of AAPL, and as of when?",
        "mode": "smart",
        "output_schema": schema,
    },
    timeout=300,
)
output = res.json()["output"]
# check_quote is the function from pattern 5; own_feed_price comes from the data API you already use
problems = check_quote(output, reference_price=own_feed_price)

Ask this in Neurobro

To try it, pick a NeuroAPI plan and create a key. Keep pattern 5 in place, because the agent’s answers can be wrong too. Forecasts are a separate problem that no pattern here fixes, as can AI predict the stock market explains. If you are choosing where the numbers come from, data API or research API lays out the trade-off, and how to build an AI trading agent with Claude wires this into a loop.

The markets move fastNow you can too

Get Neurobro

Scan with your phone camera, or choose your store.

NeurobroSmart Trading AIDownload