Overview

8 Forecasting as a language task

This chapter explores reframing time series forecasting as a language task so that large language models can be prompted to produce numeric predictions. Building on the PromptCast idea, the workflow turns past values into a natural language prompt, sends it to an LLM, and then post-processes the textual output to recover future values. The chapter reviews key prompting strategies—zero-shot, few-shot, and chain-of-thought—and shows how model choice shapes prompt design (for example, phrasing as questions for Flan-T5 versus explicit instructions for Llama). It also stresses practical safeguards such as scaling targets to avoid large numbers, constraining outputs to comma-separated numerals, and writing robust parsers to handle imperfect generations.

Using Flan-T5 locally, the chapter implements a forecasting function that scales inputs, applies few-shot prompting, and parses the response into numeric predictions before inverting the scale. In zero-shot settings the model often produced too few steps and repeated values, yielding flat forecasts; however, under rolling cross-validation its error landed in the same ballpark as one of the prior foundation models tested on the book’s retail dataset (albeit worse than finetuned, time-series–specific baselines). Incorporating an exogenous holiday flag through prompt conditioning notably degraded performance, suggesting sensitivity to covariates in this setup. For anomaly detection, a chain-of-thought style prompt and chunked processing failed to generalize: Flan-T5 tended to output a single “normal” label for entire chunks, leading to near-zero detection metrics.

Llama-3.2-3b-instruct was accessed via API with a system prompt to shape behavior and concise user prompts to request fixed-length numeric outputs. Despite simpler post-processing and stronger instruction following, its zero-shot forecasts were frequently unreasonable, and cross-validation results were clearly worse than Flan-T5 and prior specialized models in this scenario. For anomaly detection, the model over-flagged points, achieving high recall but very low precision and a poor F1 score. Overall, the chapter concludes that while LLMs can be coerced into forecasting and anomaly detection through careful prompt engineering and parsing, they are not purpose-built for time series, often underperform specialized methods, and require extra glue code. They are most useful when a natural language interface is essential and an LLM is already available; the next chapter explores making LLMs more fit-for-purpose for time series tasks.

General steps of forecasting with large language models. The values of the input sequence must be formatted as a prompt. This prompt is sent to the LLM which outputs a string. The string must then be processed to extract the future values.
Steps to forecast with a large language model like Flan-T5. First, we scale the data to avoid working with too large numbers. Then, we use few-shot prompting. The output is then processed to extract the numerical values. Finally, we inverse the scaling to bring the predictions back to the original scale.
Zero-shot predictions using Flan-T5. Here, most of the predictions are flat as the LLM seem to output the same values. Also, the model does not output all eight values, forcing us to repeat the last prediction to complete the sequence.
Predictions obtained from cross-validation with Flan-T5. The predictions seem to overlap with the actual values and some peaks and valleys were correctly predicted.
Cross-validation with exogenous features. Here, the quality of the predictions has clearly degraded compared to not using features.
Comparing the performance between using and not using features. Lower is better. Here, the model that uses features is significantly worse than the model not using features.
Zero-shot predictions from Llama-3.2. While we are forecasting for time steps with unknown values, the predictions for Store 1 seem unreasonable.
Predictions from cross-validation with Llama-3.2 Here, the predictions seem to be fairly off from the actual values.
Comparing the performance of Flan-T5 and Llama-3.2 from cross-validation. Here, Flan-T5 performs much better than Llama-3.2, as it achieves lower scores on both performance metrics. Lower is better.
Anomaly detection with Llama-3.2 Flagged anomalies are shown as diamonds. Here, we notice that the model labels way too many points as anomalies. Therefore, the recall will be high, but the precision will be very low, making the F1-score low as well.
F1-score of each foundation model tested so far for anomaly detection. Higher is better. Here, Moirai remains the top model for anomaly detection in this particular scenario, and Llama-3.2 achieves the worst performance.

Summary

  • Large language models (LLMs) are foundation models in natural language processing that can handle different natural language tasks, like question answering, text classification and more.
  • Since LLMs are trained for language tasks, we can frame the forecasting problem as a language task to use LLMs. This involves building a prompt and asking the model to predict the next set of values from an input sequence.
  • To interact with LLMs, we use prompting and using few-shot prompts and chain-of-thought prompts usually give better results.
  • We can work with LLMs both locally and via API calls.
  • LLMs can perform forecasting tasks, but they were not built for this purpose, which may result in poor performances.

References

FAQ

What does “forecasting as a language task” mean in this chapter?It means converting a numerical time series problem into a natural-language prompt that an LLM can understand. You format past values (and optional metadata) into a prompt, send it to the LLM, then post-process the string output to extract the numeric forecasts. The pipeline typically includes input scaling, prompt construction (often few-shot), generation, parsing/compliance checks (e.g., horizon length), clipping, and inverse scaling.
Which LLMs are used, and how should I interact with them?The chapter uses Flan-T5 (base) locally and Llama-3.2-3B-Instruct via API. Flan-T5 responds best to question–answer prompts (e.g., “What will be the next values?”), while Llama-3.2-Instruct is tuned to follow explicit instructions (e.g., “Output exactly N numbers, comma-separated”).
What prompting techniques are covered and when should I use them?- Zero-shot: simplest; just ask the question/instruction. - Few-shot: include one or more input–output examples to guide format and improve reliability. - Chain-of-thought: outline reasoning steps (e.g., anomaly rules) to improve performance on more complex tasks. In this chapter, few-shot is used to force clean numeric output; chain-of-thought is used for anomaly detection.
Why scale the input series before prompting an LLM?LLMs generate text autoregressively. Large or long numeric tokens increase the chance of format and value errors. Scaling to [0, 1] shortens numeric tokens and reduces mistakes. After generation, predictions are clipped to [0, 1] and inverse-transformed to the original scale.
How do I make sure the LLM outputs the right number of predictions and clean numbers?Use few-shot examples that show comma-separated numbers only, add explicit instructions like “Output exactly H comma-separated numbers between 0 and 1,” and post-process the output: parse floats, truncate or pad (e.g., repeat last value) to match the horizon, and clip to [0, 1].
How is cross-validation done with LLMs here, and how did Flan-T5 perform?Rolling-origin evaluation is used: for each window, prompt the LLM with the last h context points and request h-step forecasts, then concatenate results. On the weekly sales dataset, Flan-T5 produced reasonable but often flat outputs and sometimes fewer than h values (padded in post-processing). Its MAE/sMAPE were worse than the best time-series foundation models but better than Llama-3.2 in this setup.
Can I use exogenous features with LLM-based forecasting?Yes. Extend the prompt to include recent exogenous values and the known future exogenous sequence (e.g., holiday flags), and ask for future target values “knowing” those covariates. In the chapter’s experiment, adding Holiday_Flag degraded Flan-T5 performance, suggesting either low feature utility or prompt/model difficulty handling that covariate.
How is anomaly detection posed to LLMs, and what were the results?It’s framed as a labeling task with chain-of-thought guidance: provide statistics (mean, Q1, Q3), a rule (“flag if <Q1 or >Q3”), and examples; ask for a sequence of 0/1 labels. Flan-T5 largely failed (often returning a single label, leading to all normals). Llama-3.2 labeled too many points as anomalies (high recall, very low precision). Overall, purpose-built time-series models (e.g., Moirai) outperformed LLMs here.
How do I use Llama-3.2 via API in this chapter, and are there licensing constraints?The chapter uses OpenRouter for API access: send a system prompt (context/behavior) and a user message (values + instruction), then parse the JSON response. The specific model is meta-llama/llama-3.2-3b-instruct:free. Note: Llama 3 models are for research use only; do not use them in commercial settings. The same pattern can be adapted to other OpenRouter models per their licenses.
When should I consider LLMs for forecasting versus dedicated time-series models?Consider LLMs if you already have access to one, need a natural-language interface, and can engineer robust prompts and safeguards. Otherwise, dedicated time-series foundation models (e.g., TimeGPT, Chronos, Moirai, TimesFM) generally require less prompt engineering, offer better control and metrics, and often perform better—especially with exogenous features and anomaly detection.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Time Series Forecasting Using Foundation Models ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Time Series Forecasting Using Foundation Models ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Time Series Forecasting Using Foundation Models ebook for free