Sequence models and responsible AI: what changes when the data is a sequence, and who it affects

On this page
  1. Neighbouring days are near copies of each other
  2. A shuffled split scores the leak, not the model
  3. Three ways a network reads order
  4. Order is information only when the data says so
  5. Generative models write the next step, one at a time
  6. Who the model’s errors fall on
  7. Check yourself
  8. Traps
  9. The code
  10. Summary
  11. References

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 0.986\key{0.986} 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.

Table 1. Typical miss on next month’s volatility, the same 458 test days in 2024 to October 2025 (points)
Model and inputShuffledTime-orderedTime-ordered, 20-day gap
Linear regression, seven features12.8712.9813.00
Random forest, seven features10.9912.9612.99
Linear regression, 20-day window12.1212.3812.40
Random forest, 20-day window11.4811.7211.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, 10.99\risk{10.99}. Trained only on the past, as it would be used for real, it misses by 12.96\risk{12.96}, 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

Aℓk=g(wk0+∑jwkjXℓj+∑suksAℓ−1,s)\key{A_{\ell k}} = g\left(w_{k0} + \textstyle\sum_{j} w_{kj} X_{\ell j} + \textstyle\sum_{s} u_{ks} \key{A_{\ell-1,s}}\right)

Here XℓX_\ell is the input at step ℓ\ell (one day’s numbers), AℓA_\ell the hidden units after that step, and gg the activation from the network post. The same weights ww and uu are used at every step, so “the activations AℓA_\ell 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

yn=∑manmxm\key{y_n} = \textstyle\sum_m a_{nm} x_m

The attention weights anma_{nm} are at least zero and add up to one for each nn, and they are computed from the inputs themselves, from how similar position nn is to position mm (equation 12.5):

anm=exp⁡(xn⊤xm)∑m′exp⁡(xn⊤xm′)a_{nm} = \frac{\exp(x_n^\top x_m)}{\sum_{m'} \exp(x_n^\top x_{m'})}

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.

Table 2. How each kind of sequence model sees the order of a window
ModelWhat carries orderHow far back one step can seeMain cost
Autoregressive, flattenedwhich column a number sits inthe whole window, as fixed columnsnothing carries between days
Recurrent networkthe hidden state, step to stepeverything before, through the chainfading gradients, no parallel steps
Convolutional layerthe filter’s positionits receptive fieldlong patterns need many layers
Transformera positional encodingevery position, directlyorder 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): 2.06\key{2.06} points of volatility per 1% move today, 1.84\key{1.84} for yesterday, down to 0.25\key{0.25} 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.

Table 3. Typical miss on next month’s volatility, all test days 2024 to October 2025 (points)
InputLinear regressionRandom forest
The 20-day window, in order12.3211.66
The same 20 numbers, order shuffled in each row11.9311.48
One number: the average of the 20 moves11.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 R2R^2 of 0.42 against 0.41 for the flattened autoregressive model, with 205 parameters against 16 (section 10.5.2).

{"panels":[{"x0":52.28,"x1":565.2,"y0":29.16,"y1":223.28,"title":"1. The newest days in the window get the most weight","xlabel":"Days before today (0 = today)","ylabel":"Weight (points of volatility per 1% move)","xlog":false},{"x0":52.28,"x1":565.2,"y0":311.96,"y1":506.08,"title":"2. One average hides the months the model gets badly wrong","xlabel":"Test month","ylabel":"Typical miss (points of % a year)","xlog":false}],"series":[{"panel":0,"label":"the same total, spread evenly","color":"var(--chart-grey, #a3a19c)","kind":"line","x":[0.0,1.0],"y":[0.670933,0.670933],"sx":[85.02,108.57],"sy":[163.18,163.18]},{"panel":1,"label":"typical miss, each test month","color":"var(--chart-maroon, #b6262c)","kind":"line","x":["2024-01-01","2024-02-01","2024-03-01","2024-04-01","2024-05-01","2024-06-01","2024-07-01","2024-08-01","2024-09-01","2024-10-01","2024-11-01","2024-12-01","2025-01-01","2025-02-01","2025-03-01","2025-04-01","2025-05-01","2025-06-01","2025-07-01","2025-08-01","2025-09-01","2025-10-01"],"y":[10.4597,14.8511,9.22141,11.4299,6.93071,7.48315,15.9543,7.25026,8.09758,12.3499,11.0938,12.7915,17.7174,10.714,24.7834,21.0838,9.01029,6.72182,5.70276,6.16823,6.69947,9.85396],"sx":[75.6,98.22,119.38,142.0,163.89,186.51,208.41,231.03,253.65,275.54,298.16,320.05,342.67,365.29,385.73,408.35,430.24,452.86,474.75,497.37,519.99,541.89],"sy":[432.93,402.22,441.59,426.14,457.61,453.74,394.5,455.37,449.45,419.71,428.49,416.62,382.17,431.15,332.76,358.63,443.06,459.07,466.2,462.94,459.23,437.16]},{"panel":1,"label":"typical miss on the training years","color":"var(--chart-blue, #3b6ea5)","kind":"line","x":["1970-01-01","1970-01-02"],"y":[13.8754,13.8754],"sx":[-14316.6,-14315.87],"sy":[409.04,409.04]}]} 2026-11-27T02:55:44.022208 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/ 0 2 4 6 8 10 12 14 16 18 Days before today (0 = today) 0.00 0.25 0.50 0.75 1.00 1.25 1.50 1.75 2.00 Weight (points of volatility per 1% move) 1. The newest days in the window get the most weight the same total, spread evenly weight the linear model gives each day 2024-01 2024-04 2024-07 2024-10 2025-01 2025-04 2025-07 2025-10 Test month 0 5 10 15 20 25 Typical miss (points of % a year) 2. One average hides the months the model gets badly wrong typical miss, each test month typical miss on the training years
Figure 1. The weight on each day of the window, and the test miss month by month

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.

Table 4. The linear window model’s typical miss on 2024 to October 2025, by ticker
TickerTypical miss (points)Average actual volatility (% a year)Miss as a share of it
SPY9.6214.467%
NVDA20.1349.441%
GS12.7226.748%
XOM7.4521.036%
GLD6.6316.341%
All five together12.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

Table 5. Common mistakes with time series and sequence models
People thinkActually
A random split is fine if the test rows are never trained onthe twins of the test rows are; the forest gained almost two points from them
A gap of a few days fixes leakage20 days changed 0.03 points here; the Handbook suggests months to quarters
A transformer understands order because it reads sequencesattention alone ignores position; order comes from a positional encoding
Recent days must matter morethe order-blind models tested better on 2024 to 2025
One average score describes the modelthe 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.

Table 6. What the snippet’s variables hold
VariableHolds
pxadjusted closes, one column per ticker
rdaily returns, one column per ticker
Xtwo features per ticker and day: 5-day and 20-day volatility (% a year)
ythe target: the volatility of the next 20 daily returns (% a year)
helda random 20% of all rows, set aside
testthe 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

Table 7. The ideas, one line each
IdeaWhat it saysOn the volatility data
Neighbours are twinsnearby rows of a time series are nearly the samenext-day targets correlate at 0.986
Test on later dataa shuffled split lets the model look up a twinthe forest: 10.99 shuffled, 12.96 time-ordered
Leave a gapdrop training rows whose target reaches the test period20 days changed 0.03 points
Three ways to read ordera carried state, a sliding filter, attentionattention needs a positional encoding
Order is an empirical claimtest whether order helps, do not assume itorder-blind models tested better
Who it affectserrors fall unevenly across groups and monthsNVDA 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
Tagged machine-learning, neural-networks, volatility, backtesting← Home