Time Series Forecasting with LLMs
Language models can forecast â sometimes. Knowing which cases those are saves a quarter of experimentation.
ForecastingPrerequisites
- !Train/test splits for sequential data
- !MAPE, MAE and RMSE error metrics
- !How autoregressive models generate sequences
What You'll Learn
- 1Compare classical baselines against LLM forecasters on equal footing
- 2Describe the three mainstream approaches to representing a series for an LLM
- 3Design backtests that cannot leak future information
- 4Decide between classical, LLM and hybrid pipelines per use case
Start with a baseline that is hard to beat
Every forecasting project should begin with seasonal naive and ARIMA-class baselines, not with a transformer. On clean, stationary, univariate series those methods remain competitive, they are orders of magnitude cheaper, and their failure modes are documented across decades of practice.
LLMs change the calculus in three specific situations. When the series is entangled with text â sales affected by news, support volume affected by a product launch â a multimodal model can reason about both. When there are many related series and few observations each, a foundation model pretrained across thousands of series transfers structure that a per-series fit cannot. And when forecasts must be explained to non-technical stakeholders, a model that can narrate its reasoning produces output a committee will actually read and act upon.
The mistake to avoid is comparing an LLM against nothing. If the language model cannot beat seasonal naive by a meaningful margin on your backtest, the correct conclusion is that your problem does not need one.
It also pays to be precise about what is being forecast. Point forecasts, prediction intervals and scenario branches are different products with different consumers, and a method strong at the first can be weak at the others. Interval quality matters more than point accuracy for anyone who plans around the forecast, so evaluate coverage â how often the stated band actually contains the realized value â alongside error magnitude.
Three ways to give a model a series
Representations differ enough that they behave like different methods. Prompting a frozen LLM with raw numbers in text asks it to do arithmetic it was never explicitly trained for, and results are mixed. Fine-tuned sequence models learn the numeric patterns directly. Tokenization approaches â discretizing values into bins and treating the series as a vocabulary â let the model use next-token machinery on numeric data.
def format_series_for_prompt(series, timestamps, horizon, context_window=192):
"""Render recent history as text a frozen LLM can condition on."""
tail = list(zip(timestamps[-context_window:], series[-context_window:]))
lines = [f"{ts}: {value:.2f}" for ts, value in tail]
return (
"You are forecasting a univariate time series. Below is recent history "
"as timestamp: value pairs. Predict the next values and answer ONLY "
"with a JSON array of numbers, one per step.\n\n"
"HISTORY:\n" + "\n".join(lines) + f"\n\nHORIZON: {horizon}\n"
"FORECAST:"
)
def parse_forecast(text, horizon):
"""Pull numbers out of a model response, tolerating extra prose."""
import json, re
match = re.search(r"\[[^\]]+\]", text)
if not match:
raise ValueError("no forecast array in response")
values = json.loads(match.group(0))
if len(values) != horizon:
raise ValueError(f"expected {horizon} values, got {len(values)}")
return [float(v) for v in values]
Bin-based tokenization deserves attention because it makes arithmetic a pattern the model can learn. Coarse bins lose precision; fine bins blow up the vocabulary. Eight to sixteen quantile-based bins per series is a workable starting point, with a separate token reserved for missing values.
Backtesting without leakage
Time series cannot use random train-test splits â the future must stay in the future. Walk-forward validation is the honest protocol: fit on everything up to time t, predict the next h steps, advance t, repeat. Aggregating errors across those folds gives a variance estimate no single split provides.
import numpy as np
def walk_forward(actual, predict_fn, train_min, horizon, step=1):
"""Expanding-window backtest with no look-ahead."""
errors = []
t = train_min
while t + horizon <= len(actual):
history = actual[:t]
forecast = predict_fn(history, horizon)
truth = actual[t:t + horizon]
errors.append(np.abs(np.array(forecast) - truth).mean())
t += step
return {
"mae": float(np.mean(errors)),
"mae_std": float(np.std(errors)),
"n_folds": len(errors),
}
def seasonal_naive(history, horizon):
"""Repeat the last full seasonal cycle â the baseline to beat."""
period = 7
last_cycle = history[-period:]
return [last_cycle[i % period] for i in range(horizon)]
Report error by horizon step as well as in aggregate. A model that matches the baseline at step one and collapses by step twelve has a different problem â and a different remedy â than one that is uniformly mediocre. Horizon-decomposed error is the single most informative chart in a forecasting review.
Calendars, gaps and messy real-world series
Textbook series arrive at even intervals with no missing points. Production series arrive with daylight saving jumps, a week of downtime from a logging outage, holidays that shift every year, and a schema change in April that tripled the measured value. Handle these before modeling, because every one of them produces an apparent anomaly or a learned seasonal artifact.
import pandas as pd
def clean_series(values, timestamps, expected_cadence_minutes=60):
"""Normalize a raw series before any forecaster sees it."""
frame = pd.DataFrame({"ts": pd.to_datetime(timestamps), "value": values})
frame = frame.sort_values("ts").drop_duplicates("ts").reset_index(drop=True)
gaps = frame["ts"].diff().dt.total_seconds().div(60)
frame["gap_minutes"] = gaps
frame["missing"] = gaps > expected_cadence_minutes * 1.5
expected = pd.date_range(frame["ts"].min(), frame["ts"].max(), freq=f"{expected_cadence_minutes}min")
frame = frame.set_index("ts").reindex(expected).rename_axis("ts").reset_index()
frame["value"] = frame["value"].interpolate(limit=6)
frame["was_filled"] = frame["value"].isna()
return frame
Filling small gaps by interpolation is reasonable; filling a two-day outage is fiction. Mark filled points explicitly so the model can treat them differently, and exclude long outages from backtesting entirely â evaluating against a period you fabricated tells you nothing about the future.
Explaining forecasts to people who act on them
A forecast that nobody understands does not get used, and the explanation layer is where language models genuinely earn their place. The audience for a forecast is usually a planner or an operator who needs to know direction, uncertainty and what would change the answer â not the model architecture.
from openai import OpenAI
client = OpenAI()
def explain_to_operator(forecast, baseline, horizon_label, drivers_note):
"""Produce a decision-oriented summary grounded in computed numbers."""
delta = forecast[-1] - baseline[-1]
direction = "above" if delta > 0 else "below"
prompt = (
"Write a three-sentence operations briefing for a forecast. "
"State direction and magnitude using only the given numbers, mention "
"the uncertainty band, and name one thing that would change the call. "
"Do not invent causes.\n"
f"Forecast final step: {forecast[-1]:.1f}\n"
f"Baseline final step: {baseline[-1]:.1f}\n"
f"Change: {abs(delta):.1f} {direction} baseline\n"
f"Horizon: {horizon_label}\nKnown context: {drivers_note}"
)
return client.chat.completions.create(
model="gpt-4o-mini",
temperature=0,
max_tokens=140,
messages=[{"role": "user", "content": prompt}],
).choices[0].message.content.strip()
Keep the numbers in code and the language in the model. The briefing is grounded because every quantity it uses was computed by the forecasting pipeline, and the instruction to name what would change the call forces the output to be actionable rather than descriptive.
Close the loop by recording which forecasts were acted on and what actually happened. That log becomes the labeled data for the next round of tuning, and it is also the only way to prove the forecast product is worth its running cost. Forecasting systems that never compare predictions against outcomes quietly keep shipping numbers nobody trusts.
Where LLMs win, and where they lose
The honest comparison table below summarizes where each approach tends to earn its cost. These are patterns, not laws â your backtest is the authority.
| Situation | Recommended approach | Why |
|---|---|---|
| Clean univariate, strong seasonality | Classical or foundation model | Simplicity wins on signal-rich data |
| Many related series, short histories | Foundation model | Cross-series transfer |
| Text events drive the series | LLM or multimodal model | Reasons over both modalities |
| Hard latency or cost limits | Classical | LLM inference is expensive at volume |
| Stakeholder explanation required | LLM with structured rationale | Narrative output |
Notice what is absent: there is no row where an LLM wins on raw numeric accuracy alone against a well-tuned classical baseline on clean data. The wins come from context, transfer and communication.
Building a hybrid pipeline
The pragmatic production design combines a classical or foundation forecaster for the numbers with an LLM for the parts it genuinely improves: feature generation from text signals, scenario commentary, anomaly explanation and stakeholder-facing summaries.
from statsmodels.tsa.statespace.sarimax import SARIMAX
from openai import OpenAI
client = OpenAI()
def hybrid_forecast(history, horizon, context_note):
"""Classical numbers, LLM commentary grounded in those numbers."""
model = SARIMAX(history, order=(1, 1, 1), seasonal_order=(1, 1, 1, 7))
fit = model.fit(disp=False)
point = fit.forecast(steps=horizon)
interval = fit.get_forecast(steps=horizon).conf_int()
commentary = client.chat.completions.create(
model="gpt-4o-mini",
temperature=0,
max_tokens=180,
messages=[
{
"role": "system",
"content": "Explain the forecast in two sentences for a business "
"audience. Use only the provided numbers and context. "
"Never invent drivers.",
},
{
"role": "user",
"content": (
f"Forecast: {[round(float(v), 2) for v in point]}\n"
f"Interval lows: {[round(float(v), 2) for v in interval.iloc[:, 0]]}\n"
f"Context: {context_note}"
),
},
],
).choices[0].message.content
return {
"point_forecast": [float(v) for v in point],
"lower": [float(v) for v in interval.iloc[:, 0]],
"upper": [float(v) for v in interval.iloc[:, 1]],
"commentary": commentary.strip(),
}
Notice that the model never touches the arithmetic. It receives the point forecast and the interval and is forbidden from inventing drivers. That constraint is what keeps the commentary honest â the number comes from a method you can validate, and the language comes from a model that can explain it.
đĄLet the model see the residuals
When an LLM does contribute to forecasting, feeding it residual diagnostics rather than raw series produces more useful commentary: it can say where the classical model is struggling instead of re-describing the trend.
Common Mistakes
Random train-test splits on sequential data
Fix: Use walk-forward backtesting with an expanding window so the future never leaks into training.
Comparing an LLM forecaster against no baseline at all
Fix: Always include seasonal naive and a classical method â the margin over baseline is the only defensible claim.
Letting the LLM recompute the numeric forecast inside a hybrid pipeline
Fix: Compute numbers with a validated model and constrain the LLM to grounded explanation.
Reporting only aggregate error across the horizon
Fix: Break error out by step so degradation patterns are visible and addressable.
Best Practices
- Establish seasonal naive and ARIMA baselines before any neural experiment
- Backtest with expanding windows and report error by horizon step
- Represent series with explicit timestamps so the model can infer cadence
- Combine classical forecasting with LLM commentary for stakeholder-ready output
- Re-run the full backtest whenever the horizon or cadence changes
Key Takeaways
- Classical baselines set the bar; an LLM must clear it on your backtest, not in a paper
- Series representation â text, tokens or embeddings â determines what the model can learn
- Walk-forward validation is the only honest evaluation protocol for sequential data
- LLM advantage comes from context, transfer and explanation, not raw numeric accuracy
- Hybrid pipelines keep arithmetic in validated models and language in the LLM