Momentum Transformer: attention-based position sizing with changepoint detection
This code accompanies the the paper Trading with the Momentum Transformer: An Intelligent and Interpretable Architecture (https://arxiv.org/pdf/2112.08534.pdf).
At a glance
- What is it?
- The repository is research code for two papers on deep momentum trading: an attention-LSTM architecture that outputs positions directly, and a changepoint detection module that feeds regime information into the same pipeline. It is usable, but only if you can supply the Quandl futures data and accept the pipeline order the README prescribes.
- Who is it for?
- Adopt this if you are reproducing the papers, teaching attention over financial time series, or building a research pipeline where a per-asset Sharpe-ratio objective and interpretable attention weights are the point. Do not adopt it as a production trading system: it depends on a free third-party futures dataset, it ships no releases, and the README's own next step points to a separate PyTorch reimplementation for portfolio-level work.
- Can I use it commercially?
- Yes. MIT is a permissive licence: you can use, modify and sell software built on it, as long as you keep its copyright and licence notices.
- Is it still maintained?
- Yes. The repository last received commits 180 days ago.
- What is it written in?
- Mainly Python, according to GitHub's language statistics.
Answers come from the project's GitHub data, last synced on September 15, 2026, and from our analysis. They are not legal advice.
DEEP OPEN-SOURCE ANALYSIS
The problem it addresses: momentum strategies that fail at turning points
Time-series momentum is a simple rule. If an asset has trended up, hold it long; if it has trended down, hold it short. The README states the failure mode plainly: after a momentum turning point, where a trend reverses, time-series momentum strategies are prone to making bad bets. The 2020 market crash is given as the example. A second problem is cost. The README notes degradation of performance when returns are considered net of transaction costs, which matters because a model that flips positions often pays for every flip. The third problem is regime change. A model trained on one volatility regime tends to carry those assumptions into the next one.
The repository is aimed at researchers and quantitative developers who want to test whether attention helps with these three issues, and who are willing to work from a paper plus a script pipeline rather than an installable library. It is not aimed at someone who wants a strategy object with a fit and predict API. The code accompanies two papers, and the README describes both implementations living in the same tree.
How the architecture works: positions as the output layer
The core idea is a Deep Momentum Network. Instead of predicting a return and then converting that forecast into a position with a separate sizing rule, the network is optimised directly on a risk-adjusted performance metric such as the Sharpe ratio, and its output is the position size. The README describes this as an extension to the LSTM-based DMN that directly outputs position sizing.
The architecture the README identifies as best performing is an attention-LSTM hybrid decoder-only Temporal Fusion Transformer style model. Attention lets the network weight past time steps rather than compressing all history into a single hidden state, and the README reports that attention patterns show peaks of importance at momentum turning points, with the series segmented into regimes and the model tending to attend to earlier steps in similar regimes. That claim is a property of the trained models in the paper, not something a reader can confirm without training.
The second paper's contribution sits alongside rather than inside that architecture. An online changepoint detection module is inserted into the DMN pipeline, and it outputs a changepoint location and a severity score. The model then learns to balance a slow momentum strategy against a fast mean-reversion strategy, flipping position quickly after a changepoint and swapping back to exploit the local move. The README also notes that with an interpretable variable selection network, CPD helps the model move away from trading predominantly on daily returns data.
Getting it running: five scripts and a data account
The README gives a numbered sequence, and the order matters because later steps consume files written by earlier ones. First, create a Nasdaq Data Link account to reach the free Quandl continuous futures dataset, which the README describes as continuous contracts for over 600 futures built on raw data from CME, ICE and LIFFE. Download it with:
python -m data.download_quandl_data <<API_KEY>>
Then build features:
python -m examples.create_features_quandl
The README says this example uses the 100 futures tickers with the longest history, more than 90 percent of trading days populated, and data through at least December 2021. That filter is a hard constraint on the universe, and it is baked into the example rather than exposed as a flag in the commands shown.
Changepoint detection is optional and run separately per lookback window:
python -m examples.concurent_cpd_quandl 21 python -m examples.concurent_cpd_quandl 126
Note the spelling of the module name, concurent, which is what the README shows. After the CPD run completes, rebuild features with the window as an argument, for example python -m examples.create_features_quandl 21, and a second window can be added by passing both, as in python -m examples.create_features_quandl 126 21. The README is explicit that the 126 day run must have completed and a 21 day feature file must already exist. Finally, run an experiment by name:
python -m examples.run_dmn_experiment <<EXPERIMENT_NAME>>
The README does not list valid experiment names, so the first thing to check after cloning is the examples directory.
Where the pipeline is brittle
The dependency on a free third-party dataset is the largest practical risk. The README asks for a Nasdaq Data Link account and points at the Quandl wiki continuous futures documentation. If that dataset changes schema, is rate limited, or the ticker universe shifts, the feature script's selection criteria (long history, 90 percent coverage, data through December 2021) produce a different set of instruments and the reported results no longer correspond to what you get. Nothing in the README suggests a pinned data snapshot or a checksum.
The second issue is sequencing. Features are rebuilt after CPD, and the multi-window case requires that one window's CPD output and another window's feature file both already exist. That is a manual dependency graph maintained by the user, not by a build system. Running steps out of order gives you a feature file missing CPD columns rather than an error explaining why.
The third issue is scope. The repository is univariate per asset in its objective, and the README's own pointer to the newer DeePM work describes portfolio-level loss, asset-specific transaction costs inside the training objective, and cross-sectional attention as things added there. If your question is how to size a book across correlated futures, this repository is the wrong starting point. It is also the wrong tool if you need a supported package: there are no releases listed, so you track the master branch.
Compared with an LSTM-only Deep Momentum Network
The natural alternative is the plain LSTM DMN that this work extends, which is also the baseline the papers measure against. The difference is where the model spends its capacity. An LSTM carries a fixed-size hidden state forward, so long-range structure has to survive compression through every intervening step. Attention keeps the past steps addressable and learns weights over them, which is what makes the turning-point peaks in the README's interpretability discussion possible in the first place.
The cost of that choice is data and compute. Attention over long sequences needs more history to fit its weights, and the README's own framing is that attention is a response to learning long-term dependencies. A second alternative is the changepoint detection route on its own, without a transformer: the README describes CPD as another technique for responding to regime change that can complement multi-headed attention, and reports that running CPD at multiple timescales is where the combination helps. If your data is short or your universe is small, CPD features into a simpler model may be the more defensible experiment, because the added parameters of attention are harder to justify.
Maintenance, licence and the migration path the README points to
The repository is MIT licensed, which permits commercial use and modification provided the copyright notice and permission notice are retained. That is the standard reading of the identifier; it is not legal advice, and if you are shipping a strategy built on this code you should have your own counsel look at how the papers, the data provider terms, and the code licence interact. The Quandl data has its own terms, separate from the MIT grant on the code.
Maintenance cost is mostly the data pipeline. There is no release channel, so upgrades mean diffing master. The README's most prominent note is that a separate project, DeePM, extends this work to end-to-end portfolio construction and is re-implemented in PyTorch. The listed additions there are graph neural networks over macroeconomic priors, cross-sectional attention with a directed delay, a pooled portfolio Sharpe loss, a SoftMin proxy for entropic value at risk, asset-specific transaction costs in the loss, and two-pass exact gradient accumulation. The README also states that in backtests from 2010 to 2025 DeePM roughly doubles the net risk-adjusted returns of classical trend-following and improves on the Momentum Transformer by about fifty percent. Those are the authors' reported numbers for a different repository, not something established here.
That note changes the adoption calculus. If you want the interpretability study and the CPD module as published, this repository is the artifact. If you want the current architecture from the same author, the README is telling you to look at DeePM instead.
Editorial conclusion
Adopt this if you are reproducing the papers, teaching attention over financial time series, or building a research pipeline where a per-asset Sharpe-ratio objective and interpretable attention weights are the point. Do not adopt it as a production trading system: it depends on a free third-party futures dataset, it ships no releases, and the README's own next step points to a separate PyTorch reimplementation for portfolio-level work. Verify first that the Quandl continuous futures download still returns the tickers the feature script expects, and check whether the changepoint detection step has to finish before the feature file with CPD columns can be rebuilt.
Community notes