Artificial intelligenceIntermediate26 min read

What convolution and memory add to a trading model

How to investigate a CNN-LSTM model for Forex: axes, causality, state, parameters and ablations before assigning economic value to the architecture.

Training finishes, the loss falls and no line of code raises an exception. Yet the convolution has travelled across six variables as though they were six moments in time. The dimension containing 48 historical observations has taken the place of the channels. The program has learned something about the matrix it received; it has not yet learned the temporal relationship its author thought they were investigating.

This imaginary mistake explains why a hybrid architecture deserves a more careful reading than its name. Combining a convolutional neural network, or CNN, with an LSTM recurrent network can be a reasonable way to organise information. It can also introduce a chain of transformations whose mistakes remain unnoticed because all the dimensions fit.

We will follow a small example from beginning to end. All numbers and situations are hypothetical educational examples: they do not describe Atlas experiments, available robots or market results. The setting uses Forex observations and one prediction at the end of each window. The purpose is to learn how to specify and check the work of each block, rather than to propose an optimal configuration.

You should be comfortable reading a matrix and understand what training a model means. You do not need to know the complete LSTM equations. You do need to keep one question in view throughout: which transformation helps support a better decision, and how would we recognise that a block is unnecessary?

1. Begin with the output someone will actually use

Our research contract begins when an hourly observation closes. At that moment, we gather the latest 48 valid observations of one currency pair, calculate six variables and produce a number. To make the example concrete, that number attempts to estimate the probability that a defined reference price will be higher four observations later. The definition must identify the price, its timestamp and the treatment of missing observations.

This simplified label studies direction, not executable profit. A rise in the reference price does not mean that a purchase would cover the spread, slippage and other costs. If the eventual purpose requires another label, we must change it explicitly and investigate the experiment again. We should not alter its meaning when a chart looks disappointing.

The prediction unit is a window ending at a specific moment. The 32 windows we will process together form a computational batch. They do not necessarily represent 32 simultaneous positions, 32 independent markets or 32 consecutive hours. This detail may sound administrative, but it prevents confusion between how we use the computer and which observations support the investigation.

We also define when an action can occur. The closing price used to calculate variables does not automatically become a price at which an order could have been filled after those calculations. There is a sequence between information availability and execution that the simulation must preserve. The article on feature availability develops that part of the contract.

Before building layers, write down an example containing a timestamp, six values, a label and a permitted decision. Then write a case in which the prediction is not used because information is missing. That second case forces a choice: reject the window, wait for another observation or apply a previously defined policy for missing data.

A network does not resolve this ambiguity merely because it has memory. It receives numbers and optimises an objective. If two identical rows represent different operational situations that are absent from the input, demanding different answers creates a problem that increasing the number of units cannot clarify on its own.

2. Six variables with explicit units and availability

For our exercise, we choose six channels: a one-observation return, the relative candle range, the relative spread, a retrospective variability measure, the sine of the hour and the cosine of the hour. This is a teaching selection, not a recommendation of predictive variables. Each channel needs a definition that another person can calculate from the same authorised data.

The two hourly variables represent a cyclical coordinate. They do not add two market observations. The relative spread requires a defined quote and denominator; it cannot be reconstructed faithfully from just any candle file. The variability measure needs its own preceding history. Preparing 48 input rows may therefore require more than 48 original observations.

The shape of a matrix does not describe its meaning. Two matrices with identical dimensions might contain returns expressed as proportions or percentages, hours from different server time zones, or variables published after the decision. The model accepts all these possibilities without checking whether they match the intended experiment. The column dictionary and its units are part of a usable model.

Suppose a return of one tenth of a percentage point is stored as 0.001 during training and as 0.1 during a later test. The number of columns is still six, but that channel has changed scale by a factor of one hundred. A dimension check will not detect the difference. A reference example with expected values can.

Normalisation also needs a specific policy. Parameters learned from a training dataset are retained to transform later observations. If a rolling scale is used, its window and delays must be defined. Recalculating a scale from the entire available file can retrospectively change a prediction that was supposedly already issued.

A zero can be a valid return, an impossible spread under a particular definition, or a poorly documented marker for missing data. Those meanings should not merge silently. For this example, we will reject incomplete windows. Another policy would be possible, but adding missingness indicators would change our six channels and require updates to the dimensions and calculations that follow.

3. Convolution proposes a way to share the work

Imagine a filter that looks at three consecutive rows and combines their six channels. It then moves one row forward and applies the same coefficients to the next fragment. Instead of learning a different rule for every historical position, it reuses a local transformation. This reuse is a decision about which structure is worth looking for in the data.

We do not know beforehand whether the filter will identify acceleration, a change in range or a combination that is difficult to name. Calling it an opportunity detector before examining evidence would turn a possibility into a conclusion. We can describe precisely which numbers it can combine; assigning economic meaning to that combination requires additional work.

In the example, we use eight filters of length three, with no padding, stride one and no dilation. There will be 46 output positions: the first combines rows 1, 2 and 3; the last combines rows 46, 47 and 48. A subsequent activation, if included, transforms those results without adding parameters to our count.

A local filter does not automatically observe the entire window. Two successive layers of length three and stride one would expand the local dependency to five original rows. A recurrent layer afterwards can combine outputs that span a longer history. Being able to receive that history does not demonstrate that training uses it productively, however.

The choice of length affects what is shared. Three hourly observations describe a different timescale from three five-minute observations. Changing the frequency while retaining the same number of rows changes the meaning of the experiment, even if the code and number of parameters remain identical. It also changes the relationship with the label’s horizon.

It helps to state a testable expectation for this block: for example, that summarising local fragments makes a prediction easier to learn consistently than an isolated recurrent model manages under the chosen budget. That sentence does not anticipate the result. It defines a comparison and avoids justifying convolution simply because it appears in a familiar architecture.

4. Follow the axes before following the loss

The natural input in this exercise has shape (32, 48, 6): batch, time and variables. It contains 9,216 values. To use PyTorch Conv1d, we reorder it to (32, 6, 48). That layer’s contract places channels before length; changing axes preserves the values while changing their interpretation. The documentation specifies the shapes and the relationship between input and output length. Conv1d reference.

After our convolution, the result is (32, 8, 46). We reorder it to (32, 46, 8) so each sequence of eight-component vectors can enter an LSTM configured with the batch first. With twelve hidden units, one layer and one direction, its output at each position will have twelve components. We select only the last position to produce the window’s prediction.

Stage in the example Shape Interpretation
Prepared windows 32 × 48 × 6 Batch, observations, variables
Convolution input 32 × 6 × 48 Batch, channels, length
Convolution output 32 × 8 × 46 Eight filters, 46 positions
Recurrent input 32 × 46 × 8 Sequences of local vectors
Last recurrent output 32 × 12 One summary per window
Linear head 32 × 1 One logit per window
Dimensions traced from 32 windows of 48 rows and six variables to one logit per window.
Changing axes reorganises interpretation; convolution also changes the length and number of channels.

Reordering axes and reshaping a matrix are different operations. An indiscriminate reshape can redistribute elements without preserving the intended correspondence between time and variable. Having the required dimensions does not certify that every value is in the right place. The test must follow identifiable values as well as sizes.

Create a tiny matrix in which each cell encodes its row and column number. Then manually check which three rows reach the first filter. You do not need real prices for this test. Knowing the answer in advance is precisely what lets you detect a mistake that a plausible training curve could conceal.

The last step is a linear transformation from twelve components to one logit. Applying a sigmoid puts it between zero and one. That operation does not demonstrate that the number is calibrated as a probability. Nor does it determine a position size. Both decisions belong to additional contracts that require separate evaluation.

5. Causality depends on the moment each output represents

An operation can use information later than an internal position without using information later than the actual decision. This distinction matters especially in discussions of bidirectional networks. If an entire historical window is already available when one prediction is issued at its right edge, traversing it in both directions does not itself introduce data beyond that edge.

The problem arises when we assign an intermediate output to a decision that supposedly occurred before the rest of the window was known. A bidirectional network could have used observations later than that intermediate moment. The same calculation can be compatible or incompatible with the simulation depending on the temporal meaning assigned to its output.

The relevant boundary is the information available when deciding. Our example uses a unidirectional LSTM to keep the interpretation straightforward, but it does not establish a universal ban on bidirectionality. If another architecture is investigated, its correspondence with the specific contract must be demonstrated rather than inferred from its name alone.

A similar issue occurs with convolution padding. Keeping the length through same does not automatically express a causal constraint. Keras distinguishes that option from causal, which prevents a temporal output from depending on later inputs. Its documentation explicitly defines both behaviours. Conv1D options.

In our unpadded convolution, the first output uses rows 1 through 3. If we timestamp it as available at row 1, we bring information forward. If we timestamp it at the completion of row 3, we respect its availability. The last output uses rows 46 through 48 and becomes available at the completion of row 48, our decision boundary.

A window containing rows one through forty-eight ends at the decision; the first three-row filter is dated at row three, and future data remain outside.
A transformation's timestamp corresponds to the last input it needs, not necessarily to its first index.

A causality test must respect the output contract. For a model that promises an answer at every moment, change inputs after a cutoff and check that earlier answers remain unchanged. For our model with one answer per window, reconstruct the input using only data available at its close and verify that appending future data to the file changes neither that input nor its prediction.

6. Decide what keeping memory actually means

An LSTM maintains states that are updated as it processes a sequence. In our design, every window starts from defined initial states and is processed in full. The state used for the prediction is a computational summary of that window. It is neither a permanent memory of the market nor an explanation of the reasons for each price movement.

Another option exists: retain the state between observations and update it when a new row arrives. That alternative can be coherent, but it represents a different procedure. Its result also depends on how the sequence began, which interruptions occurred and what information was processed before the fragment we happen to be inspecting.

Independent windows and persistent state need an explicit protocol if combined. Consider two four-row windows: the first contains 1, 2, 3 and 4; the next contains 2, 3, 4 and 5. If you retain the first window’s final state and then feed in the entire second window, rows 2, 3 and 4 are processed twice within the accumulated history. You are not simply moving forward by one observation.

To reconstruct independent windows, reset the state and process all four rows in each. For a continuous sequence, retain the state and introduce only new information, with input preparation designed for that use. When convolution precedes the recurrent layer, its own required history must also be maintained correctly. Changing a single LSTM flag does not resolve the entire transition.

Two overlapping windows contain rows one to four and two to five; keeping state while replaying the whole second window duplicates rows two, three and four.
Reconstructing a history and updating a stream require different rules for state.

We must also define what happens when changing currency pairs, crossing a gap or restarting a process. A state from another instrument cannot silently travel into the next sample. With independent training windows, changing batch order should not change a particular window’s prediction when evaluating a deterministic model without operations that mix samples.

The operational test is to predict the same window alone and alongside other windows, keeping all evaluation settings fixed. An unexpected difference calls for inspection of shared state, normalisation and processing order. A tiny numerical difference may need a tolerance; a different decision requires an explanation before any performance is interpreted.

7. Count the capacity you actually built

Our example is deliberately small. The convolution has eight filters, each covering three positions and six channels: 8 × 3 × 6 = 144 coefficients. Add eight biases and the result is 152 parameters. The number of windows per batch does not enter this calculation because all windows reuse the same coefficients.

The example’s PyTorch LSTM receives eight components and has twelve hidden units, one layer, one direction, enabled biases and no projection. Its matrices contribute 4 × 12 × 8 = 384 and 4 × 12 × 12 = 576 parameters. Its two bias vectors contribute 48 each. The total is 384 + 576 + 48 + 48 = 1,056. The documented shapes allow this specific calculation to be checked. LSTM reference.

The linear head adds twelve weights and one bias: thirteen parameters. The total for this particular architecture is 152 + 1,056 + 13 = 1,221. It excludes trainable normalisation layers, projections, other heads and additional blocks. Changing implementations may change the representation of biases; this figure is not a universal formula for every LSTM.

Breakdown of 1221 parameters: 152 in convolution, 1056 in the LSTM and 13 in the linear head, with calculations that can be checked.
In this construction, the recurrent block contains most of the parameters.

Counting parameters helps interpret a comparison; it does not measure quality on its own. Two networks with the same total can impose different restrictions, require different amounts of time or respond differently to the optimiser. There is also no universal conversion from parameter count to a minimum number of historical trades that guarantees a reliable conclusion.

Another calculation concerns memory and computation time. A longer window can increase the work without changing the number of weights. Storing activations for training requires resources that do not appear in our sum. Parameter count, training duration and inference latency should be recorded as separate quantities, measured under identified conditions.

A capacity budget should be accompanied by a search budget. Comparing a network tuned through many trials with a rival trained once mixes architecture with selection effort. Record how many configurations and restarts you examined. This information helps establish what it really means when one alternative ends up with the best observed number.

8. Training involves decisions that may also explain an improvement

Architecture is one part of the procedure. The optimiser, variable scaling, training duration, batch size and rule for selecting a version of the weights all affect the result. If you change several of these elements while adding the LSTM, you cannot attribute every difference to the recurrent block.

Our directional objective requires decisions about how the loss is calculated and how classes are treated. Giving one class more weight changes the fitting problem. That may be deliberate, but it also changes the subsequent interpretation of the output. The action threshold and probability checks must acknowledge the choice.

A lower loss describes the objective you defined. It does not guarantee lower turnover, less exposure or a better distribution of net results. Nor does it certify that differences will survive other initialisations or reasonable changes in the available data. Every claim needs its own measurement, rather than turning one chart into evidence for all of them.

Overlapping windows require care when counting examples. With 48 observations of history and a one-observation step, two consecutive inputs share 47 rows. Processing them as different examples is computationally possible; treating each step as 48 new independent observations would exaggerate the diversity of information received. Independence does not appear when windows are stacked into a tensor.

A tiny artificial problem with a known answer can help diagnose the training mechanics, such as recognising whether the last input in one channel exceeds a fixed value. Solving it checks parts of the circuit; it does not demonstrate predictive ability in Forex. If the model cannot solve it, investigate labels, axes and optimisation before making the model larger.

Retain an evaluation case with fixed weights and fixed inputs as well. Stochastic operations used during training need an explicit evaluation policy. The aim is not to demand universal equality across machines, but to distinguish an implementation difference from a difference caused by new data or another model version.

9. Make each block compete for its place

An ablation compares procedures that differ in an identified part. For this investigation, we propose four: a simple reference without a deep network, convolution without recurrence, recurrence without convolution and the complete combination. Each procedure must receive the same meaning of input and address the same label. The initial reference can be built using the article on machine-learning baselines.

The convolution-only version needs a rule to summarise its positions. The recurrent-only version receives the six original channels directly. These choices must be documented before comparison, because removing a block requires adapting the interfaces. A damaged network that can no longer produce a valid output is not an informative competitor.

Variant Main question Adaptation to declare
Simple reference Is this deep representation needed? Variables and output rule
Convolution only Are local patterns and their summary enough? Temporal aggregation
Recurrence only Does the preceding filter actually help? Six-channel input
Hybrid Does the combination add anything? Interface between blocks
Matrix of four comparators separating the reference, convolution, recurrence and their combination, with shared input meaning, label and costs.
A useful comparison identifies what changes and which conditions make that change interpretable.

To compare architectures, we train each alternative again without the block. Setting part of an already trained network to zero answers a different question: how much that particular fitted model depends on the part. The remaining network had adapted to working with the removed block. An immediate deterioration does not prove that an alternative without that block, trained from the beginning, would be inferior.

You can compare under a similar training budget and also show the actual costs of each alternative. There is no need to pretend that matching parameter counts matches every aspect of capacity. It is more useful to state the comparison rule and acknowledge its limits. If one variant needs considerably more selection effort to become competitive, that effort also belongs in the result.

Multiple initialisations reveal sensitivity to the fitting procedure; they do not create new markets. Record the planned set of outcomes and avoid presenting only the best restart. If the difference between architectures is small compared with variation between runs, a reasonable conclusion may be that the protocol has not yet established a sufficiently stable preference.

10. Follow the prediction through to its economic consequence

Suppose we use a purely illustrative rule: buy one fixed unit when the output exceeds 0.60 and otherwise remain flat. Two models produce 0.52 and 0.58 for the same window. Their numbers differ, but both lead to no trade. If they produce 0.61 and 0.78, both lead to the same purchase at the same size under this rule.

The quality of those probabilities may differ and remain relevant for another use. In this example, however, the action is identical. Keep the complete chain: input, prediction, desired decision, position change and recorded result. That lets us locate where an economically relevant difference actually appears.

A model affects money through an action policy. A move from 0.59 to 0.61 can change the action in our example, whereas the larger move from 0.61 to 0.78 does not. This does not make 0.60 a recommended threshold. It shows why measuring only the size of changes in predictions can be insufficient.

If a position is already open, repeating a buy signal does not necessarily mean executing another order. The policy must say whether it maintains, increases, replaces or closes the exposure. Counting every positive prediction as a new trade can create costs or profits that belong to a simulation error rather than to the architecture.

Compare architectures using shared accounting and an identifiable policy. If each model is allowed its own threshold tuning, that tuning becomes part of the comparison and must be recorded. If thresholds remain fixed, you are evaluating that particular use. Both questions may be interesting, but they say different things about the combination of predictor and decision.

To investigate the transition from an output to a usable probability, continue with probability calibration. To study execution, retain prices and costs compatible with the available information. An architecture with good predictive behaviour may ultimately be uninteresting for the evaluated policy; it may also provide useful information without yet justifying real trades.

11. Build tests that can identify a particular failure

A good technical test narrows the space of explanations. Start with dimensions, units and column order. Continue with a matrix of identifiable values to check the axes. Add reconstruction of the window at its decision time. These tests cover different failures and cannot replace one another simply because each produces a green checkmark.

For recurrent state, compare an isolated window with the same window after another has been processed, using the intended reset. For the horizon, draw a short sequence by hand and verify which observation produces each label. For the local filter, change one cell and check which positions can depend on it before recurrence.

A visual explanation should correspond to a well-defined intervention. If hiding a channel changes the prediction, you have observed sensitivity to that modification. You must still ask whether the replacement value creates a plausible input. Replacing a spread with zero or an hour with an impossible combination may measure behaviour outside the domain under investigation.

It also matters to distinguish local sensitivity from usefulness during training. A variable may look unimportant when modified in isolation because another contains related information. Training again without that variable answers a different question. Describe the experiment you performed and avoid assigning it a broader conclusion simply because the chart looks intuitive.

Retain cases that produce abstention, inputs near the extremes of the intended domain and windows rejected as incomplete. Their purpose is not to find a flattering snapshot of the model. They help check whether the procedure follows explicit decisions when the data stop resembling the central case used during development.

If you ask an AI to help implement these checks, provide the contract and expected results for tiny examples. Ask it to explain which failure each test detects. A suite that merely reproduces the same transformation under a different name can agree with the code while sharing its mistake. The expected answer must come from an independent calculation or rule.

12. Read precedents without transferring their results

Published research can motivate comparisons between architecture families. Bai, Kolter and Koltun studied convolutional and recurrent networks across several sequence tasks and found results favouring their convolutional architecture on the problems examined. That work encourages keeping alternatives in consideration; it does not determine which network will work best with our Forex variables. Sequence-model evaluation.

DeepLOB, by Zhang, Zohren and Roberts, combined convolutional and LSTM components to predict movements using equity limit order books. It provides a precedent for combining architectures around a particular data structure. A currency candle file does not automatically contain that structure, nor does it inherit the paper’s results by using layers with the same names. DeepLOB paper.

What transfers is an idea worth testing. We can adopt the question of whether local relationships should be summarised before temporal dependencies are processed. We then have to define what local means in our own data. An order book may contain positions and levels with specific meanings; our matrix contains time and six heterogeneous channels.

Channel order also deserves attention when proposed operations exploit neighbourhood relationships between variables. Putting the spread next to the sine of the hour does not create a natural economic distance. Our temporal convolution combines all channels and moves through time; it does not assume that moving one column to the right represents the same kind of transition as advancing one hour.

When reading a result, ask about inputs, labels, sampling units and the comparison procedure before looking at a headline number. Then ask which part of the experiment you could reproduce with your permissions and resources. A superficial match in model names does not remove differences in information, frequency, costs or selection.

A published precedent justifies investigation, not an advance verdict. This discipline also protects the interpretation of negative results. If the hybrid does not improve on a reference under a particular protocol, you have learned something about that construction and use. You have not demonstrated that every recurrent network or every convolution is useless in every market.

13. Finish with a record that supports a decision

At the end of this exercise, you should be able to provide a concise input specification, a dimension trace, the state policy, the parameter count and a comparison explaining why each block remains. These pieces make the procedure reviewable without depending on the memory of the person who wrote the program.

Include an identified version of the weights and transformations, together with minimal input and output examples. An architecture drawn in a diagram is not enough to reconstruct a fitted model. A weights file is also insufficient if nobody retains the variable order, units and method for reconstructing each window.

As an exercise, change only the input length from 48 to 60. With our length-three unpadded filter, you will obtain 58 convolutional positions. The number of parameters remains 1,221 because channels, filters, units and head have not changed. There will be more positions to process and a different history available for the decision. Explain both consequences before training.

For a second exercise, try converting independent windows into a continuous stream. First write down which state you would retain, which new data you would introduce and how you would handle a gap. If you cannot describe that unambiguously, you do not yet have two equivalent implementations. You have a procedural change whose equivalence must be demonstrated or whose effect must be evaluated.

The reason to continue is useful evidence for the intended decision. The outcome may be to retain the hybrid, prefer a simpler alternative or suspend the comparison because of a data failure. Documenting that outcome is more valuable than adding another layer to avoid an uncomfortable conclusion. Complexity must justify its place within a reviewable system.

When studying a demo, ask whether the rules and code allow these decisions to be reconstructed. In the initial commercial scope, Forex is the reference market and the CSV is limited to the free demo; it should not be assumed to be included in the paid package. A useful prompt for your AI would request an audit of axes, timing and state using small examples, followed by an ablation plan. This work lets you study what you receive without turning an architecture’s name into a promise of profitability.

A historical window becomes local patterns, a recurrent state and an output that still needs a decision rule.
Every transformation has a function that can be checked; adding blocks also adds design decisions.
Back to the Blog