The post has been translated automatically. Original language: Russian
The market punishes overconfidence. Any one model, even an excellent one, sooner or later encounters a mode for which it was not created. The solution is not to find the perfect model. The solution is to teach several good models to work together under the guidance of someone who understands the context.
Imagine a trader who only looks at the price chart and ignores the news. Or, on the contrary, an analyst who reads headlines perfectly, but does not know how to count. Both will lose in their own way. It is this dilemma that has divided the world of quantitative forecasting for decades: specialized mathematical models are brilliant at catching patterns in numbers, but are blind to the real world, whereas language models understand news and events, but stumble on the exact arithmetic of time series.
A trading bot that we built so that we would not choose between these two worlds, but rather combine them. It is based on an agent-based architecture inspired by the Nexus framework, which considers forecasting not as a simple extrapolation of numbers, but as a reasoning task. Instead of forcing one giant model to do everything at once, we have built a team of specialized agents where everyone is responsible for their area, and the conductor brings their voices into a single solution.
The problem of the lone Genius
In algotrading, it's easy to fall in love with one model. She has shown a fantastic result based on historical data, and I would like to entrust her with all the capital. But the market is not a static picture. It changes character: today there is a smooth trend, tomorrow there is a panic sale on unexpected news, the day after tomorrow there is a sideways trend with deceptive seasonality.
Specialized time series forecasting models such as PatchTST and ITransformer are the pinnacle of engineering in their field. They are trained on huge arrays of numerical sequences and masterfully recognize complex seasonality, trends and long-term dependencies. But they have an Achilles heel, they work in a vacuum. When the central bank's decision comes out, when a company publishes a disappointing report, when a geopolitical shock reverses the market in an hour, these models do not see the reason. They only see that the numbers have suddenly stopped obeying the usual logic, and they get lost in the structural gaps.
Language models are the opposite extreme. They instantly comprehend the flow of news, reports, and macroeconomic summaries, and are able to reason about causes and effects. But as soon as they are asked to accurately predict the number step by step, they succumb to specialized models: their architecture simply does not have a built-in mathematical mechanism for fine-tuning time dependencies.
The point is in one phrase
Numerical models skip shock events. Language models stumble on a multi-seasonal periodicity. Any approach that relies only on one side is bound to make mistakes where the other would be strong.
Until recently, the trader had to compromise: either abandon the qualitative context for the sake of statistical accuracy, or rely on the reasoning of the language model, sacrificing the understanding of numerical dynamics. Our architecture removes this compromise. We don't choose, we orchestrate.
Architecture: a team instead of a loner
The key idea borrowed from Nexus is deceptively simple: divide and orchestrate. We divide the complex task of forecasting into specialized stages, and each stage has its own agent with its own area of responsibility. This is similar to how a good investment committee works, where a strategist, tactician, and risk manager look at the same situation from different angles before making a decision.
STAGE 1 · CONTEXTUALIZATION
Context Agent
Before anyone starts predicting, this agent brings order to the chaos of input data. It takes a raw stream of prices, volumes, news, and reports and turns it into a clean chronological feed, where a reason is associated with each price movement. It filters out the noise and leaves only the signal so that the rest of the agents do not drown in garbage and lose what is important in a long context.
STAGE 2A · MACRO VIEW
Macro Reasoning Agent + ITransformer
This agent looks down from above and draws a broad trajectory over the entire forecast horizon: what mode the market is in, where the fundamental trend is leading. ITransformer is particularly strong here - its architecture, which treats each time series as an independent entity, perfectly captures inter-market connections and major structural shifts. The macro agent ensures that the final forecast does not detach from the big picture.
STAGE 2B · MICRO-VIEW
Micro Reasoning Agent + PatchTST
This agent goes step by step along the forecast horizon, analyzing each individual moment: the nearest catalysts, short-term fluctuations, local volatility. This is where PatchTST comes in with its technique of splitting a series into patches - it captures subtle local structure and rapid changes that are easy to miss when viewed from above. The micro-agent keeps the system alert to sudden events.
STAGE 3A · SYNTHESIS
Synthesizer Agent
Orchestra conductor. It receives the macro trajectory, micro details, and numerical predictions from PatchTST, ITransformer, and other ensemble models and dynamically weights these votes. When the signals contradict each other, it is the synthesizer that decides who to trust in a given situation, and issues a final forecast along with a clear explanation of why it made that decision.
STAGE 3B · CALIBRATION
Calibration Agent
The memory and conscience of the system. He runs the strategy through a variety of historical periods, compares forecasts with what actually happened, and deduces specific rules: where the system overestimates risk, where it underestimates volatility, which model should be trusted in which mode. These rules apply only if they actually improve the result during the test period.
The most important thing is that this ensemble is not static. The weight of each model is not fixed once and for all. PatchTST can dominate a calm, volatile market, ITransformer can set the tone for a major reversal, and a language agent can take over when unexpected news comes out that the numbers haven't had time to reflect yet. The conductor redistributes attention in real time.
Why does an ensemble under the control of an agent beat a single model

This is not a theory. In the research on which the Nexus approach is based, the agent architecture was tested on data strictly beyond what the models saw during training in order to eliminate "peeping." Based on volatile stocks and real estate market data, it consistently outperformed or at least matched both flagship specialized models and strong language solutions.

What does this mean for capital
When the market behaves predictably, the ensemble makes the most of the mathematical accuracy of its numerical models. When the unexpected happens, the language agent catches the reason before it is reflected in the price, and the conductor manages to outweigh the solution. You don't lose money in a class of situations where your only model would be blind.
Scenario: one day in the life of a bot
A LIVING EXAMPLE OF THE ORCHESTRA'S WORK
Morning. The minutes of the Fed meeting are coming out.
The context agent instantly extracts a key signal from the news stream: the tone of the regulator turned out to be tougher than expected. It links this event to the current point on the price band and transmits the clean summary further.
PatchTST and ITransformer, looking only at the numbers, continue to draw a smooth continuation of yesterday's upward movement by inertia, because the reversal has not yet appeared in the numbers.
"Numerical models predict growth of 1.2%. But the context points to a tightening of the Fed's rhetoric, which has historically caused a short-term correction in this sector. The micro-agent captures the risk of a sharp downward movement in the coming sessions."
The synthesizer agent sees a conflict: mathematics says "up," context says "careful." Based on the rules deduced by the calibration agent from previous similar episodes, it reduces the weight of a purely numerical forecast and shifts the final estimate towards a conservative scenario in advance, rather than retroactively.
The result: the bot does not enter into a position on a false continuation of the trend and avoids a loss that a single numerical model would almost certainly fall for. And most importantly, each of these decisions is documented in clear text, and not hidden in opaque scales.
Transparency that the "black box" does not have
Most trading bots give you a single number and tell you to just believe it. When the system is wrong, and everyone is wrong., you're left with no explanation and no way to figure out what went wrong. Our architecture works differently.
In addition to the forecast itself, the system traces the reasoning of a coherent text that shows the fundamental drivers behind each decision. You can see not only "the bot expects a downward movement," but also why: which event it considered significant, how it weighed the voices of different models, which signal it trusted, and based on what historical experience.
→ Audit and trust. Every decision can be tested and challenged. The system explains the logic in human language.
→ Risk control. You can see in advance what the forecast is based on, and you can step in if the logic is at odds with your understanding of the market.
Open architecture, ready for growth
The strength of the orchestral approach also lies in its extensibility. PatchTST and ITransformer are our current soloists, but the conductor is not tied to a specific line-up. Is there a new, more powerful forecasting model? She can be added to the ensemble as another voice, and the synthesizer agent will learn by itself in which situations to trust her, and the calibration agent will check whether she really improves the result.
This transforms the trading bot from a frozen product into a living system that gets smarter with each new tool at its disposal and with each passing market day. You are investing not in a single model that will one day become obsolete, but in an architecture that absorbs the progress of the entire industry.
What do you get in practice
→ Continuous improvement. Tracing and calibration turn each error into a specific rule for the future, rather than random noise.
A good forecast answers the question "how much". The great forecast also answers the question "why."
→ Multi-model reliability. Capital does not depend on the success of a single model. The risk of error is distributed among specialists of different profiles.
→ Reaction to the real world. The bot sees not only the chart, but also news, reports, and macroeconomics and integrates them into the forecast before they are reflected in the price.
→ Adapt to any mode. From calm seasonality to panic reversals, the orchestra redistributes attention to the nature of the current market.
→ Clear solutions. Each forecast is accompanied by an explanation that can be read, checked, and discussed.
→ A system that learns. Calibration based on historical data turns past errors into rules that improve future accuracy.
Stop betting on one horse
The market is too complex to entrust to one model, no matter how brilliant it may be. The future of algotrading belongs to teams of specialized models led by an intelligent conductor who understands numbers, context, and his own mistakes.
The trading bot that we unwritten already works on this principle. He doesn't choose between mathematics and meaning. He connects them.
The material is informational in nature and describes the technological architecture of the trading solution. It is not an individual investment recommendation, offer, or guarantee of profitability. Trading in financial markets involves the risk of capital loss; the results obtained on historical data do not guarantee future profitability. The technological framework is inspired by the Nexus agent-based time series forecasting framework (arXiv:2605.14389); the mentioned PatchTST, ITransformer and TimesFM models are the developments of independent research teams. Consult with a qualified financial professional before making investment decisions.
Модель может показать «лучшую в мире» точность на тесте и при этом быть совершенно бесполезной в реальной работе. Чаще всего виновата не магия и не «плохая архитектура», а утечка данных, когда модель во время обучения подсмотрела ответы, которые должна была угадывать. Эта статья без формул объясняет, как это происходит, почему трансформеры для временных рядов особенно уязвимы и как защититься.

История, которая случается чаще, чем кажется
Представьте, команда обучила новую модель прогнозирования. На экране заветная цифра, ошибка почти ноль, графики прогноза и факта сливаются в одну линию. Все радуются, метрика бьёт рекорды бенчмарков, в презентации появляется слайд «лучший результат в индустрии». Модель торжественно выкатывают в продакшн.
А дальше начинается странное. На свежих данных тех, что приходят уже после запуска, прогнозы «гуляют» как попало. Ошибка вырастает в десятки раз. Бизнес недоумевает: «Вы же показывали идеальные результаты, почему всё сломалось?» Команда лихорадочно перепроверяет код, меняет гиперпараметры, обучает заново, но чуда не происходит.
Знакомая ситуация? В подавляющем большинстве таких случаев модель не «сломалась». Она никогда и не работала. Просто на этапе тестирования ей по ошибке дали возможность подсмотреть в ответы. Красивая метрика была иллюзией и эта статья о том, как такие иллюзии возникают и как их распознать.
Что такое утечка данных?
Чтобы честно проверить ученика, мы не показываем ему ответы перед экзаменом. Мы учим его на одних задачах (это обучающая выборка, train), а проверяем на других, которые он раньше не видел (это тестовая выборка, test). Если ученик заранее раздобыл ответы к экзамену, его «отличная оценка» ничего не говорит о реальных знаниях.
Утечка данных (по английски - data leakage) - это и есть та самая ситуация, когда «ответы с экзамена» каким-то образом просочились в подготовку. Модель видела во время обучения информацию, которой в реальной жизни в этот момент быть не могло. В результате на тесте она демонстрирует блестящий результат, а в бою проваливается, потому что подсматривать там уже не во что.
Почему «идеально на одном периоде, бесполезно на другом»
Заголовок этой статьи описывает самый частый симптом утечки именно во временных рядах данных, у которых есть ось времени: продажи по дням, котировки по минутам, нагрузка на сервер по часам, потребление электричества и так далее.
Время здесь, не просто ещё одна колонка. Это направление, в котором информация может «течь» только в одну сторону: из прошлого в будущее. Сегодня мы не знаем, что будет завтра. Но если при подготовке данных мы случайно нарушили этот порядок, например, перемешали все наблюдения в кучу или посчитали какие-то общие статистики сразу по всему набору, модель получает крупицы знания о будущем. И честно ими пользуется.
Отсюда и раздвоение личности модели:
• На тестовом периоде, который пересекается с «подсмотренным», она почти идеальна ведь по сути она вспоминает, а не прогнозирует.
• На по-настоящему новом периоде, где подглядывать не во что, она беспомощна, потому что прогнозировать она так и не научилась.

Пять типичных мест
Утечка редко бывает результатом грубой ошибки. Чаще это маленькая невнимательность в подготовке данных. Вот самые распространённые источники.
1. Случайное перемешивание во времени:
Классический приём «перемешать данные перед делением на train и test» отлично работает для фотографий котиков, но смертелен для временных рядов. После перемешивания вчерашний и завтрашний дни оказываются по разные стороны, и модель спокойно учится на «будущем», чтобы предсказывать «прошлое».
2. Нормировка по всему набору сразу:
Прежде чем кормить числа модели, их обычно приводят к единому масштабу вычитают среднее, делят на разброс. Если эти среднее и разброс посчитаны по всему датасету целиком (включая тест), то в каждое тестовое наблюдение уже «вшита» информация обо всём периоде, в том числе будущем. Статистики нужно считать только по обучающей части.
3. Пересекающиеся окна
Модели временных рядов обычно «нарезают» историю на окна: берут отрезок прошлого и учатся предсказывать следующий кусочек. Если окна для обучения и для теста накладываются друг на друга, одни и те же точки оказываются и там, и там. Между блоками нужен защитный зазор небольшой пропуск, гарантирующий, что окна не подсматривают друг у друга.
4. Признаки «из будущего»
Иногда в данные добавляют поясняющие признаки и незаметно затаскивают туда информацию, которой на момент прогноза ещё не существовало. Например, «средняя выручка за месяц» в строке за 3-е число месяца - это подсматривание, ведь весь месяц ещё не закончился. Такие признаки называют lookahead, и они частый виновник подозрительно идеальных метрик.
5. Дубликаты и утечка через предобработку
После очистки, заполнения пропусков или изменения частоты данных в наборе могут появиться одинаковые или почти одинаковые фрагменты, часть которых попадает в train, а часть в test. Модель снова получает возможность «вспоминать».
Почему трансформеры особенно коварны
В последние годы прогнозирование временных рядов захватили трансформеры, тот же тип моделей, что стоит за современными языковыми системами. Архитектуры с названиями вроде PatchTST и iTransformer регулярно занимают верхние строчки исследовательских рейтингов. И именно с ними история про красивые-но-обманчивые метрики становится особенно острой. Вот почему.
Они очень хорошо запоминают. Трансформеры - модели с огромной ёмкостью. Их сила в том, что они умеют улавливать тончайшие закономерности. Но у этой силы есть тёмная сторона: если в данные просочилась подсказка, такая модель ухватится за неё мёртвой хваткой и выдаст почти идеальный результат там, где подсказка доступна. Чем мощнее модель, тем убедительнее выглядит иллюзия.
PatchTST режет ряд на кусочки-«патчи» (как нарезают батон на ломтики) и работает с ними. Это эффективно, но добавляет ещё одно место, где легко ошибиться с границами: если патчи для обучения и для теста перекрываются хотя бы немного, кусочки «завтра» просачиваются в подготовку. Граница между train и test должна проходить между патчами, а не сквозь них.
iTransformer смотрит на данные «перевёрнуто»: он анализирует связи между разными показателями (рядами) на одном и том же отрезке времени. Это даёт отличное качество, но и создаёт лишний канал для утечки: если хотя бы один из показателей содержит информацию из будущего, модель аккуратно распространит её на все остальные. Один протёкший признак заражает весь прогноз.
Парадокс мощных моделей.
Чем способнее модель, тем легче принять утечку за гениальность. Слабая модель при утечке покажет «неплохой» результат, и это насторожит. А мощный трансформер выдаст почти идеальную цифру и её хочется не перепроверять, а праздновать. Поэтому именно с топовыми архитектурами особенно важна дисциплина проверки.
Мини-кейсы: как это выглядит в жизни
Кейс 1. «Рекордный» прогноз спроса
Ритейлер обучает PatchTST прогнозировать продажи. На тесте почти нулевая ошибка, команда в восторге. В продакшне модель промахивается на десятки процентов. Разбор показывает: данные перемешали случайным образом перед делением, и для каждой «тестовой» недели в обучении нашлись соседние дни из той же недели. Модель не прогнозировала спрос она вспоминала его.
Кейс 2. Прогноз нагрузки, который рассыпался в понедельник
Команда прогнозирует нагрузку на сервис. Метрика на тесте прекрасная, но в первый же рабочий понедельник после запуска прогноз оказывается бесполезным. Причина: масштабирование данных считалось по всему периоду сразу, и в каждую тестовую точку просочилась информация о будущих пиках. Стоило пересчитать статистики только по обучающей части и «идеальная» метрика честно ухудшилась, зато совпала с реальностью.
Кейс 3. Один признак заразил всё
Аналитики добавили в iTransformer удобный признак агрегат, который на самом деле подсчитывался с захватом будущих значений. Поскольку iTransformer смешивает информацию между всеми рядами, этот единственный «протёкший» столбец поднял качество всей модели до неправдоподобного уровня. На новых данных, где агрегат считался честно, эффект исчез.
Во всех трёх случаях ни код модели, ни архитектура не были «плохими». Протекала подготовка данных. Именно поэтому проверять нужно не только модель, но и весь путь данных до неё.
Чеклист честной проверки модели
Прежде чем поверить в красивую цифру, пройдитесь по этим пунктам. Большинство утечек ловятся именно здесь, без сложной математики, на одной внимательности.

Как защититься: четыре привычки здоровой команды
1. Делите данные по времени и фиксируйте границы заранее. Решите, какой период обучающий, какой тестовый, до того как начнёте экспериментировать, и не меняйте это под результат.
2. Стройте подготовку данных как «трубу», обучаемую только на train. Любое преобразование сначала «учится» на обучающей части, а затем применяется к тесту никогда не наоборот.
3. Не доверяйте одной цифре. Проверяйте модель на нескольких разных периодах. Стабильность важнее одного рекорда.
4. Сравнивайте с простым ориентиром. Если сложный трансформер обгоняет наивный прогноз «завтра как сегодня» в сто раз - это повод не радоваться, а искать утечку.
Красивая метрика, самый приятный и самый опасный результат в машинном обучении. Приятный, потому что её хочется показать всем. Опасный, потому что за ней может скрываться не работающая модель, а просто хорошо замаскированное подглядывание в ответы.
Чем мощнее инструмент, а трансформеры вроде PatchTST и iTransformer действительно мощны — тем убедительнее выглядит иллюзия и тем дороже обходится ошибка. Поэтому здоровый скепсис к слишком хорошим цифрам не занудство, а профессиональная гигиена. Бойтесь красивых метрик. Проверяйте их. И доверяйте только тем, что повторяются.