Sequence models and responsible AI: what changes when the data is a sequence, and who it affects
On this page
The network in Neural networks: linear regression, stacked and bent got seven numbers per ticker and day and never asked which day came first. Market data does have an order, and the order changes two things: how a model must be tested, and how a model can read its input. This post takes both, then turns to the people on the other end of the model’s decisions.
The running example stays the same: predict next month’s volatilityHow much an asset's price spikes and dips; most often measured as the standard deviation of its per-period returns. (the spread of the next 20 daily returnsThe percentage change in price from one day to the next: today's price divided by yesterday's, minus one., in % a year) for SPY, NVDA, GS, XOM and GLD, 2020 to October 2025, scored by the typical size of a miss, the RMSEThe square root of the mean squared error.. The new input is the window: the last 20 daily moves of one ticker, kept in order, newest first.
Neighbouring days are near copies of each other
ISLP names the property that separates a time series from the tables earlier posts used: “the day-to-day observations are not independent of each other”, and values “nearby in time tend to be similar to each other” (section 10.5.2). That is autocorrelationThe correlation of a series with itself a fixed number of steps earlier, called the lag., the correlationCovariance rescaled into a measure that always lies between minus one and one. of a series with itself a few steps back.
The target here makes it extreme. Next month’s volatility for Monday uses the returns of the next 20 days; for Tuesday, the next 20 days shifted by one. The two share 19 of their 20 returns. Across the five tickers, a day’s target has a correlation of with the next day’s target: if you know one, you nearly know the other.
So every row in a time series has twins on the days around it, and a test that lets the model see those twins is not a test.
A shuffled split scores the leak, not the model
The test below holds the test rows fixed and changes only what the model may train on. A random 20% of all rows is set aside, and the test rows are the ones among them dated 2024 or later, 458 in all. Then each model is trained two ways:
- Shuffled: on the other 80% of rows, from every year, including days in 2024 and 2025 right next to the test days.
- Time-ordered: on 2020 to 2023 only, so every training day comes before every test day.
A third version adds a gap. The last 20 training days of 2023 have targets that reach into January 2024, so they carry a little of the test period. The chapter on machine learning in investments of the CFA Institute Research Foundation’s Handbook suggests exactly this fix, “a sufficient gap period between training and validation sets and between validation and testing” (chapter 1). Here it removes those 20 days. Table 1 gives the typical miss for all three, for two models on two inputs.
| Model and input | Shuffled | Time-ordered | Time-ordered, 20-day gap |
|---|---|---|---|
| Linear regression, seven features | 12.87 | 12.98 | 13.00 |
| Random forest, seven features | 10.99 | 12.96 | 12.99 |
| Linear regression, 20-day window | 12.12 | 12.38 | 12.40 |
| Random forest, 20-day window | 11.48 | 11.72 | 11.77 |
Guessing the 2020 to 2023 average for every test day misses by 17.21 points. Against that, the random forestMany decision trees, each grown on a bootstrap sample, where every split may only choose from a random subset of the features. on the seven price featuresAn input variable a model uses to make its prediction; also called a predictor or an independent variable. from earlier posts looks strong when shuffled, . Trained only on the past, as it would be used for real, it misses by , no better than linear regressionA simple method that predicts a numeric answer by assuming a straight-line relationship between the inputs and the answer.. Almost two points of the shuffled score were the forest recognising neighbouring days, not predicting anything. Over five different random hold-outs, the shuffled forest looked better by 1.30 to 2.10 points every time.
The Handbook calls this leakageInformation that would not be available at prediction time being used to build a model, which makes its performance estimates overly optimistic.: training dataThe observed examples a method learns from: they are used to teach it how to make its estimate. that “contain information that can be used to infer the prediction, information that would otherwise not be available to the ML model in live production”. When it happens, “the results will be overly optimistic and true out-of-sampleTested on a more recent part of the data that was kept back while the model and its parameters were built on the first part. performance … will likely disappoint” (chapter 1). The splits post showed the same effect with walk-forwardOptimise on the in-sample data, test on a short out-of-sample period after it, record the result, then optimise another window. folds; here the test rows are identical, so the gap between the columns is the leak and nothing else.
Two smaller results matter for practice. The 20-day gap changed the score by only 0.03 points, because it touched 20 of about 1,000 training days; the Handbook’s suggestion is a gap “of between a few months and a few quarters”. And the linear model barely gains from shuffling (12.87 against 12.98): a straight line cannot memorise single days, so it has little to gain from seeing their twins.
Why the raw window leaks less than the seven features
The forest on the 20-day window gained only 0.24 points from shuffling. The reason is what neighbouring rows look like. Yesterday’s seven features (a 20-day volatility, a 20-day average) are almost today’s, so in the forest’s view the twin sits right next to the test day. Yesterday’s window holds the same 20 moves shifted one place, so every column changes. The script measures it: the distance from a row to the day before is 40% of the distance to a random day for the seven features, and 90% for the window. The twin is still there in time; the model just cannot find it as easily. A test must still be later than the training, whatever the input looks like.
Three ways a network reads order
The window has 20 numbers in a fixed order. The simplest model, ISLP’s autoregressive modelA regression that predicts a series from its own previous values., puts them side by side as 20 columns of a linear regression, “a process called flatteningTreating the steps of a sequence as one long row of separate inputs, ignoring that they come in order.” (section 10.5.2). The model then knows which column is which day, but it learns nothing that carries from one day to the next. Sequence models are built to do that, in three different ways.
A carried state. A recurrent neural networkA neural network that reads a sequence one step at a time, feeding each step's hidden values into the next step. reads the sequence one step at a time, and each step’s hidden unitsOne unit inside a neural network: a weighted sum of its inputs, passed through an activation function. Its value is never observed in the data. take both the new input and their own values from the step before (ISLP equation 10.16):
A, the hidden units' values after each step
Here is the input at step (one day’s numbers), the hidden units after that step, and the activation from the network post. The same weights and are used at every step, so “the activations accumulate a history of what has been seen before” (section 10.5). The cost is in fitting: the error signal has to pass back through every step, and over long sequences it fades or blows up, the vanishing and exploding gradients that LSTM and GRU cells were designed to ease (Bishop and Bishop, section 12.2.6). Each step also waits for the one before, so one sequence cannot be processed in parallel, and recurrent networks “struggle to make efficient use of” GPUs (same section).
A sliding filter. A convolutional layer applies one small set of weights, a filter, to a short stretch of the sequence, then slides it along and applies the same weights again. Each unit sees only its receptive fieldThe small patch of the input that one unit of a convolutional layer looks at., the few steps under the filter (Bishop and Bishop, section 10.2.1), and a pattern learned in one place is recognised anywhere. Stacking layers widens what a unit in a later layer can see (section 10.2.7), but a single layer only sees the stretch under its filter.
AttentionWeighting every input by how relevant it is to the current position, with the weights computed from the inputs themselves.. A transformerA neural network built on attention, which maps a set of input vectors to a new set of the same size. lets every position look at every other position directly. Each output is a weighted blend of all the inputs (Bishop and Bishop, equation 12.2):
y, what position n outputs
The attention weights are at least zero and add up to one for each , and they are computed from the inputs themselves, from how similar position is to position (equation 12.5):
Distance costs nothing: day 1 can weigh day 80 as easily as day 79. The catch is that nothing in these two formulas knows which position is which. Bishop and Bishop show that shuffling the inputs only shuffles the outputs the same way, so “the representation learned by a transformer will be independent of the input token ordering” (section 12.1.9). Their example is two sentences with the same words, “The food was bad, not good at all” and “The food was good, not bad at all”. The fix is a positional encodingA vector for each position in a sequence, added to that position's input so a transformer can tell order., a vector for each position added to that position’s input (equation 12.24), so order becomes part of the data. Table 2 puts the four ways side by side.
| Model | What carries order | How far back one step can see | Main cost |
|---|---|---|---|
| Autoregressive, flattened | which column a number sits in | the whole window, as fixed columns | nothing carries between days |
| Recurrent network | the hidden state, step to step | everything before, through the chain | fading gradients, no parallel steps |
| Convolutional layer | the filter’s position | its receptive field | long patterns need many layers |
| Transformer | a positional encoding | every position, directly | order must be added by hand |
Zeng and colleagues combine the last two on one-minute prices of S&P 500 stocks in 2019: a convolution turns short stretches of the series into tokens that carry “the short-term patterns”, and a transformer with positional encodings learns “the long-term dependencies between these tokens”. From 80 minutes they predict whether the price at the 81st goes down, or goes up or stays flat. Their model was right 56.7% of the time, against 53.2% for an exponential moving averageA moving average that uses all past prices but gives more weight to the most recent ones. and 50% for a coin flip. The test was the last quarter of 2019, after the training quarters; training and validation rows were a random 80/20 split of the first three.
One more rule comes with attention. When a transformer is trained to predict the next step, every position could attend to the positions after it, and the network would “simply learn to copy the next input directly to the output” (Bishop and Bishop, section 12.3.1). Masked attentionAttention in which each position may not look at positions after it, so the model cannot copy the answer from the future. sets the weights on later positions to zero. It is the shuffled-split lesson built into the architecture: no position may use what comes after it.
Order is information only when the data says so
Does the order inside the window help on this data? A linear regression on the 20 days, fitted on 2020 to 2023, gives the newest days the most weight (Figure 1, panel 1): points of volatility per 1% move today, for yesterday, down to ten days ago. The newest 5 days get 59% of the total weight. That matches the intuition that recent moves say more about next month.
The test years disagree. Table 3 scores the same models on all of 2024 to October 2025 with the window as it is, with each row’s 20 numbers shuffled into a random order (the model sees the same moves but not which day each came from), and with a single input, the plain average of the 20 moves.
| Input | Linear regression | Random forest |
|---|---|---|
| The 20-day window, in order | 12.32 | 11.66 |
| The same 20 numbers, order shuffled in each row | 11.93 | 11.48 |
| One number: the average of the 20 moves | 11.91 |
The models that could not see the order did better. The weights that favour recent days were learned on 2020 to 2023, and they did not carry over to 2024 and 2025. That is one target, one window length and one test period: it says nothing about order in general, only that “recent days matter more” is a claim to test on later data, not to assume. ISLP’s own sequence example shows how little the extra machinery can buy: on daily trading volume, a recurrent network scored a test of 0.42 against 0.41 for the flattened autoregressive model, with 205 parameters against 16 (section 10.5.2).
Generative models write the next step, one at a time
A model that predicts the next step can also produce a sequence. Bishop and Bishop describe the decoder transformer behind GPT this way: it outputs a probabilityHow often an event happens if you could repeat a trial without end: the share of trials where it happens. for every possible next token; “if we draw a sample from this distribution then we have extended the sequence”, and the longer sequence goes back in for the next token (section 12.3.1). A large language modelA very large transformer trained on text to predict the next token. is this design at very large scale, trained on text where every next token is its own labelThe outputs a model learns to predict; also called the target or the response. (section 12.3.5).
Note what that objective asks for: a likely next token given the ones before. Nothing in it checks the text against a source, so that check stays with the reader. In investment work the same generative idea shows up with numbers: the Handbook’s chapter on accelerated AI describes generating “market scenarios that have never been observed before but can be viewed as realistic”, to compare portfolio methods and to generate stress-test scenarios (chapter 10).
Who the model’s errors fall on
A volatility forecast feeds a decision. It sizes a position, sets a risk limit or prices a hedge, so a miss lands on someone: a client, a fund, the desk that trusted the number. One average over five tickers and 22 months hides where the misses land. Table 4 splits the test miss by ticker.
| Ticker | Typical miss (points) | Average actual volatility (% a year) | Miss as a share of it |
|---|---|---|---|
| SPY | 9.62 | 14.4 | 67% |
| NVDA | 20.13 | 49.4 | 41% |
| GS | 12.72 | 26.7 | 48% |
| XOM | 7.45 | 21.0 | 36% |
| GLD | 6.63 | 16.3 | 41% |
| All five together | 12.32 |
In points, NVDA’s forecasts are the worst by far, 20.13 against 6.63 for GLD. Measured against how volatile each ticker actually was, SPY’s are the worst: a typical miss of two thirds of its own volatility. Which group a model serves worst depends on how the error is measured, so the measure is a decision, and someone has to own it.
The same holds over time (Figure 1, panel 2). The medianThe middle value: sort the outcomes from lowest to highest and take the one that divides the list into two equal halves. test month misses by 10.16 points, but the rows dated March 2025 miss by 24.78 and those dated April by 21.08. For most of the March rows, the next 20 days take in early April, and the data’s four largest SPY moves of 2025 all fall between 3 and 10 April. A model scored once, on average, would never show that month.
The Handbook’s chapters give the responsible-use side of this, for investment models in particular:
- Explain the decision. “With billions of investment dollars on the line, asset owners demand managers that use ML-based algorithms explain how the investment decisions are made” (chapter 1). Post hoc explainers such as SHAP report which inputs drove a model’s output (chapter 10), and chapter 1 suggests checking that what the model learned agrees with domain knowledge.
- Keep a person accountable. The rule-based system in chapter 11 makes decisions that “can be tracked down to each datapoint used”, and still needs humans for oversight and for “edge cases in which the systematic way of thinking does not translate well”.
- Monitor after launch. Markets are nonstationaryDescribes a problem whose true action values change over time.: “the rules and dynamics that govern the outcome the models try to predict also change over time” (chapter 1). Chapter 11’s own example is a system whose principles were set in the past and had not yet adjusted to March 2020. A month like March 2025 above is what monitoring is for.
- Validate before trusting. Chapter 10 calls making the model and data “transparent and explainable” a step “often forgotten or underrated”.
Check yourself
Shuffling the split helped the random forest by almost two points but linear regression by about 0.1. Why the difference?
A shuffled split puts each test day’s neighbours in training, and neighbouring targets have a correlation of 0.986. The forest can memorise single days and look up a near twin, so it scored 10.99 shuffled against 12.96 time-ordered. A straight line cannot memorise days, so it scored about the same both ways (12.87 against 12.98).
A transformer without positional encodings is given a 20-day window, then the same window in reverse order. What changes in its outputs?
Only their order. Attention weights come from how similar the inputs are to each other, not from where they sit, so shuffling the inputs shuffles the outputs in the same way. The model cannot tell “up then down” from “down then up” until a positional encoding is added to each input.
Which ticker does the window model serve worst?
It depends on the measure. In points, NVDA: a typical miss of 20.13 against GLD’s 6.63. As a share of each ticker’s own volatility, SPY: 9.62 points on an average of 14.4, about two thirds. Choosing the measure decides who looks served worst.
Traps
| People think | Actually |
|---|---|
| A random split is fine if the test rows are never trained on | the twins of the test rows are; the forest gained almost two points from them |
| A gap of a few days fixes leakage | 20 days changed 0.03 points here; the Handbook suggests months to quarters |
| A transformer understands order because it reads sequences | attention alone ignores position; order comes from a positional encoding |
| Recent days must matter more | the order-blind models tested better on 2024 to 2025 |
| One average score describes the model | the miss ran from 6.63 points on GLD to 20.13 on NVDA, and 24.78 in one month |
The code
The snippet reproduces the shuffled-against-time-ordered comparison for a random forest on two features, 5-day and 20-day volatility. It is smaller than the post’s script, so its numbers are close to, not equal to, Table 1.
| Variable | Holds |
|---|---|
px | adjusted closes, one column per ticker |
r | daily returns, one column per ticker |
X | two features per ticker and day: 5-day and 20-day volatility (% a year) |
y | the target: the volatility of the next 20 daily returns (% a year) |
held | a random 20% of all rows, set aside |
test | the held-out rows dated 2024 or later, the same for both splits |
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
url = "https://raw.githubusercontent.com/ankurtrapasiya/examples/main/data/prices.csv"
px = pd.read_csv(url, index_col="date", parse_dates=True)
r = px.pct_change()
A = np.sqrt(252) * 100 # daily standard deviation -> % a year
rows = []
for t in px.columns: # one row per ticker and day
rows.append(pd.DataFrame({
"vol_5d": r[t].rolling(5).std() * A,
"vol_20d": r[t].rolling(20).std() * A,
# target: the standard deviation of the NEXT 20 daily returns
"next_vol": r[t][::-1].rolling(20).std()[::-1].shift(-1) * A,
}).dropna())
df = pd.concat(rows)
X, y = df[["vol_5d", "vol_20d"]], df["next_vol"]
held = np.random.default_rng(0).random(len(df)) < 0.2 # a random 20% of all rows
late = df.index >= "2024-01-01"
test = held & late # the same test rows for both splits
splits = {"shuffled (other 80%, all years)": ~held,
"time-ordered (2020-2023 only)": ~late}
for name, train in splits.items():
m = RandomForestRegressor(n_estimators=200, min_samples_leaf=5, random_state=0, n_jobs=-1)
m.fit(X[train], y[train])
miss = np.sqrt(np.mean((y[test] - m.predict(X[test])) ** 2))
print(f"{name:<34} typical miss on {test.sum()} test rows: {miss:.2f} points")
It prints a typical miss of 11.23 points for the shuffled split and 12.96 for the time-ordered one, on the same 457 test rows: the same leak as Table 1.
The script behind the real numbers
The tables and the chart come from
examples/sequence-models-and-responsible-ai/sequence_split.py,
which runs on the blog’s five tickers. To run it yourself, clone the examples repo: its README has a three-command Docker setup, or run uv run sequence-models-and-responsible-ai/sequence_split.py.
Summary
| Idea | What it says | On the volatility data |
|---|---|---|
| Neighbours are twins | nearby rows of a time series are nearly the same | next-day targets correlate at 0.986 |
| Test on later data | a shuffled split lets the model look up a twin | the forest: 10.99 shuffled, 12.96 time-ordered |
| Leave a gap | drop training rows whose target reaches the test period | 20 days changed 0.03 points |
| Three ways to read order | a carried state, a sliding filter, attention | attention needs a positional encoding |
| Order is an empirical claim | test whether order helps, do not assume it | order-blind models tested better |
| Who it affects | errors fall unevenly across groups and months | NVDA 20.13, GLD 6.63, March 2025 at 24.78 |
References
- James, Witten, Hastie, Tibshirani and Taylor, An Introduction to Statistical Learning, with Applications in Python (Springer, 2023), chapter 10: recurrent networks and their shared weights (section 10.5, equations 10.16 and 10.17), autocorrelation, input windows, the autoregressive model, flattening and the NYSE volume comparison (section 10.5.2), one-dimensional convolutions on sequences (section 10.5.3)
- Christopher M. Bishop and Hugh Bishop, Deep Learning: Foundations and Concepts (Springer, 2024): receptive fields, weight sharing and one-dimensional convolution (sections 10.2.1 and 10.2.2), stacked convolutions (section 10.2.7), attention weights (section 12.1.2, equations 12.2 to 12.5), positional encoding and permutation equivariance (section 12.1.9), recurrent networks, vanishing gradients, LSTM and GRU (sections 12.2.5 and 12.2.6), decoder transformers, next-token generation and masked attention (section 12.3.1), large language models (section 12.3.5)
- Zeng, Kaur, Siddagangappa, Rahimi, Balch and Veloso, Financial Time Series Forecasting using CNN and Transformer (2023): a convolution for short-range and a transformer for long-range patterns in one-minute prices, the data split, and the accuracies of their model against the baselines
- CFA Institute Research Foundation, Handbook of Artificial Intelligence and Big Data Applications in Investments (2023): chapter 1 (Chen and Zhou) for data leakage, chronological splits, the gap period, nonstationary markets and why investment models must be explained; chapter 10 (Papenbrock) for generated market scenarios, model validation and SHAP; chapter 11 (Vaessen) for traceable decisions, human oversight and principles that lag a changed market