A small decision tree you can explain all the way down
Trace a hypothetical depth-two trading classifier from closed-bar inputs to leaf counts, export checks, and a comparison with a simpler rule.

Two printouts sit beside the same hypothetical research record. Its closed five-minute bar spans exactly 8.00 pips. One printout says ranges at most 8.00 pips go to a second question. The other says ranges below 8.00 pips go there. Both carry the same model name. On this particular record the first sends the case to a leaf with twenty-four positives out of thirty-six. The second sends it to a leaf with ten out of forty. Somebody can give a fluent explanation for either answer.
A useful audit starts by asking which comparison the system actually evaluated. Once that is settled, a different question remains. What would justify trusting the distinction between the two groups on future observations? A correct drawing can settle the first question if it expresses the full input and routing contract. To address the second, the researcher needs evidence about how the rule was selected and how it behaves when time moves forward.
This article follows an invented three-leaf classifier through both questions. The numbers are teaching examples throughout, including the later simulation totals. The rule’s role is to score an opportunity to study a long entry. That narrow job gives us room to follow a row from its timestamp to its terminal count, then decide whether anything ought to be done with the result.
The decision starts with a clock
Imagine five-minute bars for a hypothetical currency pair with a pip size of 0.0001. We timestamp each bar by its end and separately record when the completed record became available. A bar ending at 10:00 and received shortly afterwards can inform a decision after receipt. Set the schedule in advance. If the bar misses the decision cutoff, record a missing input at that time. A feed correction arriving later can improve the historical archive while leaving the original decision record intact.
The first feature is that bar’s high minus its low, expressed in pips. The second is the close minus the open of the same bar, also in pips. The signed second feature distinguishes a bar that ended above its open from one that ended below it. For this exercise the data contract represents prices as integer quote ticks of 0.000001, or one hundredth of a pip. It subtracts those integers before expressing the result in pips for people to read. The 8.00 and 2.00 thresholds are therefore 800 and 200 quote ticks in the comparison.
Define a positive label as an increase in the midpoint from a prescribed post-decision snapshot to a snapshot fifteen minutes later. The midpoint is halfway between bid and ask. A flat or declining midpoint is class zero. Specify a maximum permitted delay for both snapshots and reject a label if either is unavailable. Store the actual observation times. The future snapshot goes in the outcome record and becomes available for training only after the horizon has elapsed and the snapshot has arrived.
Consider a decision after the bar ending at 10:00 and a hypothetical first midpoint snapshot at 10:01. Its corresponding endpoint is at 10:16 under a schedule that allows those snapshots. A later decision can already be on the books before 10:16. The feature record and the maturing outcome record therefore have different clocks even when the dataset eventually stores them on the same line. Reconstruct the row as it was known at decision time. The same discipline applies when checking feature availability in a pipeline that fills gaps or revises raw data.
Walk a row from root to leaf
The root node asks whether the range is less than or equal to 8.00 pips. On the right, range greater than 8.00 ends the evaluation at leaf C. On the left, a second node asks about the signed body, the close minus the open. A body greater than 2.00 leads to A and a body less than or equal to 2.00 leads to B. The deepest route takes two comparisons, which is why this three-leaf example has depth two. C takes just one comparison.
Suppose the hypothetical bar opens at 1.10308, closes at 1.10330, reaches a high of 1.10356 and a low of 1.10276. Its range is 8.00 pips and its signed body is 2.20 pips. The first comparison takes the equality branch and the second takes the greater-than branch. The ordered sequence of visited nodes and comparisons is the decision path. A is the terminal region, or leaf, shared by every valid row that satisfies those two comparisons.
The leaf’s output stays constant within its region. Moving the body from 2.20 to 3.00 pips keeps this row at A while the range stays fixed. Reducing it to 2.00 pips changes the output to B. The scikit-learn tree guide describes piecewise-constant predictions, and its tree structure example shows how to retrieve visited nodes and terminal leaves.
The teaching rule puts validation before the root. If either input is missing or invalid, the output is “no score” with a reason, even if a present range would have been enough to route to C. Some implementations support routing missing values. A researcher using that feature would have to export and test those routes too. Here the validator checks known price relationships. The high must cover the open and close, the low must sit at or below both, and the absolute body cannot exceed the range. The drawing starts where these checks end.
Count evidence at the leaf
Suppose our invented fitting sample has one hundred unweighted rows. A contains 24 positives and 12 negatives. B contains 6 positives and 18 negatives. C contains 10 positives and 30 negatives. The raw positive fractions are about 66.7%, 25%, and 25%. A and C are close in size, yet their fractions are far apart. B and C have identical fractions despite a difference of sixteen rows and different routes into the leaves.
An explanation of A should include its denominator. A score of roughly two thirds based on 24 out of 36 tells the reader how many recorded positives share it. It also gives them a handle for auditing provenance. If twenty of the thirty-six A rows come from one morning, ask whether they came from distinct episodes or from adjacent, overlapping opportunities during the same movement. Repeated observations of that morning cannot replace observations across mornings. Counting dates and inspecting episodes are useful complements to counting rows.
Look at the base rate too. Forty of the hundred fitting rows are positive, so a classifier that always predicts class zero gets sixty correct. Using the majority class within each leaf gives 24 correct in A, 18 in B and 30 in C, or seventy-two correct on those same fitting rows. Fitting accuracy rewards agreement on the sample the rule saw. It also gives each error the same influence. If the actual research policy considers only A, sample coverage, precision within A, and the economic outcomes of that proposed action measure different things from accuracy across A, B and C.
The frequency is an observed proportion among rows that arrived at that leaf during fitting. Calling it a forecast of two chances in three requires more evidence. Even a high proportion may be pushed upward by choosing a split that maximizes separation on the same sample. If reliable later observations assign scores near two thirds to groups whose outcomes are positive much less often, the score has a calibration problem. A separate guide to probability calibration discusses comparing predicted levels with subsequent frequencies. With three leaves, a table with each leaf’s later count and observed fraction can already expose an important discrepancy.
What made the split look good
One way a fitting algorithm can rank binary splits is to use Gini impurity. For two classes with proportions p and 1 minus p, subtract the sum of their squared proportions from one. A node containing only one class has impurity zero. A node divided evenly between two classes has impurity one half. The measure scores how mixed the classes are. The algorithm can compare the parent’s mixture with the size-weighted mixtures of the candidate children.
Here the root contains 40 positives and 60 negatives, so its impurity is 0.48. Its at-most-eight branch contains 30 positives and 30 negatives, for impurity 0.50. The greater-than-eight branch contains 10 positives and 30 negatives, for impurity 0.375. The children’s weighted impurity is 0.60 times 0.50 plus 0.40 times 0.375, or 0.45. The reduction is 0.03. One child is more mixed than its parent even though the weighted mixture decreases overall.
Within the left child, A has impurity about 0.4444 and B has impurity 0.375. Those groups account for 36 and 24 of the sixty rows. The weighted mixture is about 0.4167, a local reduction of about 0.0833. Expressed relative to all one hundred rows, the contribution is 0.60 times that difference, or 0.05. Together with the root’s 0.03, that yields a total fitting impurity reduction of 0.08. These figures describe the stipulated split. Without the candidate feature values there is no basis for declaring either cut optimal among all possible cuts.
A research log could display the best and second-best candidate reductions at each node and describe which alternatives reached nearly the same value. Nearby thresholds may split precisely the same fitting rows if no values lie between them. They can still disagree on later rows that land in that gap. A different feature can also isolate almost the same observations during one period. A split helps establish which rows the algorithm found useful to group together. Changing the observed range by intervention, if such an intervention could even be defined, is a different question from selecting rows by their existing range. A clock-time concentration could account for some apparent separation.
The horizon and weighting can change the tree
Suppose we move the endpoint from fifteen minutes to five. Features for the same decision may remain identical while labels change. A hypothetical midpoint could rise by one pip in five minutes and fall to two pips below the original snapshot by fifteen. That row contributes a positive in the first task and a negative in the second. If the tree changes when the horizon changes, first check whether it is answering a materially different question. The planned time in the market should inform the label definition before the results are compared.
Changing a horizon also changes how labels overlap. Decision snapshots five minutes apart at a fifteen-minute horizon will share part of the move they measure. When a direction persists across that stretch, several labels can reflect it. Retaining all scheduled rows can be appropriate if that is how decisions arrive, while counting contiguous episodes separately helps describe where the evidence came from. If the policy allows only one open position, distinguish scheduled rows from decisions actually eligible under that policy.
Weights change what the fitting criterion pays attention to. In a separate hypothetical calculation on the same memberships, give every positive row weight two and every negative row weight one. A then has positive weight 48 and total weight 60, yielding a weighted fraction of 80%, alongside the unweighted 24 of 36. Across the root, total weight rises from 100 to 140 and positive weight is 80. A new fit with these weights can choose different thresholds and memberships. The calculation with memberships held fixed shows the change in the score alone.
Weighting can express a preference to notice an infrequent outcome, or reduce the influence of densely sampled periods if that is the defined objective. Record the reason and show raw counts next to total weights and weighted positive amounts. If the intended forecast is for the original decision stream, assess it on that stream’s natural frequency or on an explicitly defined target population. Preserve the distinction between a count and the influence assigned to it. A report containing only weighted fractions can make a small number of heavily weighted cases look like a broad empirical base.
From score to an executable rule
Say a hypothetical research policy sends only A cases to a cost and eligibility check. The tree reports a score and a leaf identifier. The policy needs a schedule, an entry convention, an exit convention, and rules for overlapping signals. It must decide what happens when quotes are stale or missing and when the simulation is already carrying exposure. The label defined earlier asks whether the midpoint rose. The executable question concerns prices available to the prospective buyer and seller at the specified times.
Consider a separate hypothetical set of ten fills with seven midpoint gains of one pip and three midpoint losses of two pips. Gross midpoint movement sums to one pip across the ten cases, or 0.10 pip per case. If an all-in round-trip friction of 0.40 pip applies to each case, net performance sums to minus three pips, or minus 0.30 pip per case. The positive frequency is 70%, while size and cost govern the average. This arithmetic describes these invented fills only.
For a long entry simulated at the ask and an exit at the bid, spread is already embedded in those prices. If the cost test starts with mids, it needs to account for the entry and exit spread portions explicitly. Commission, slippage relative to an agreed reference, and other modeled fees should follow the same convention for every candidate. The bid and ask walkthrough goes into the price-side distinction. Store both gross and net quantities so a change in the cost model can be audited independently of a change in tree routing.
A policy rejection should have its own reason even when the classifier produced a valid score. Imagine two A rows with the same score, one during a normal quote and the other during a wide quote. If only the first meets a predeclared cost cap, the different actions come from policy. A score log can still keep both rows for studying calibration, with the eventual outcomes attached under the common label definition where available. A trade log counts only fills. Those records distinguish three denominators: opportunities scored, opportunities admitted, and entries simulated. Losing that distinction can make a cost filter appear to improve the classifier merely by changing which rows are visible in the report.
Export the precise questions
An export contract should specify the input type and feature names, their order where positional access is used, the instrument’s tick and pip conventions, the clock and cutoff, and the origin of each price. It should capture the tree version, branching operators and thresholds, ordering of classes, leaf counts and score convention, and the version of the separately evaluated action policy. Attach a few reference inputs and expected paths so a reader can test the artifact. A rendered tree is an index into that contract.
The hypothetical contract uses integer quote ticks. A human may print 8.00 pips, and a runtime comparing the range with 800 ticks will agree on 800. If somebody preprocesses to one decimal pip for a summary and passes that summary into the rule, a raw 8.01 can become 8.0. With a body of 2.20 the correct route is C, while the rounded route is A. A second failure comes from passing 8.01 into an interface expecting 801. Type validation can reject the non-integer. A plausible integer in the wrong unit can evade type checks, which is why provenance and reference fixtures matter.
In a fitted model that uses floating-point features, keep the actual comparison representation used by the prediction routine. Readable display precision can be separate. An export that silently reduces precision creates a different rule around a threshold. If deliberate quantization is needed, define it as part of preprocessing and evaluate the rule with that representation. The display can document when printed numbers have been rounded.
Record the value and operator that decided the branch. For an individual case, a useful decision trace contains the raw source identity, decision time, normalized feature value, threshold representation, comparison result, next node and terminal identifier. When reproducing yesterday’s route, use the relevant model version and the inputs seen yesterday. If all you retain is the leaf score, B and C in this example both emit 25%, and a change from one leaf to the other can escape a parity check. A later investigator needs the path to see whether a data revision, bad conversion, or comparison change caused the divergence.
Try to make the implementations disagree
Start a parity test with six hypothetical valid feature pairs. At a fixed body of 2.20, the ranges 7.99, 8.00 and 8.01 route to A, A and C. At a fixed range of 8.00, the bodies 1.99, 2.00 and 2.01 route to B, B and A. On the teaching grid these examples sit one quote tick away from equality in either direction. Hand-derived expectations are useful here because the test can catch an exporter and a test oracle that would otherwise copy the same incorrect comparison.
Probe the surrounding data contract too. For a missing body and a valid 9.00 range, expect no score before routing. For a range of 2.00 paired with a body of 2.01, expect rejection on the physical relationship between the two features. For a bar that arrives after its cutoff, expect the missing-input outcome for that decision time, even if a replay tomorrow finds the historical record. For a valid range above 8.00, varying the body within its admissible bounds should leave the terminal leaf unchanged. These tests demonstrate that upstream checks run even on rows that would take a short path.
Use reference examples for ordinary and awkward inputs, then compare the whole output across research and export. That means rejection reason or validity, feature values, visited nodes, terminal identity and score. Add the policy result in a separate comparison once the quotes and eligibility data have been fixed. A string in place of an integer, a non-finite number, a stale bar and an unexpected instrument identifier are reasonable offline fixtures. They can reveal accidental coercion or fallback before it becomes part of the research results.
After finding a mismatch, shrink it to one observation and one transformation. If one version routes to C and the other to A on the 8.01 case, inspect the value just before the root. A 800 versus 801 mismatch points toward conversion or rounding. Identical values with different paths point toward operator or threshold differences. The choice of test case helps locate the failed contract as well as detect the discrepancy.
Limit complexity and account for the search
A depth cap limits comparisons along any path. A minimum leaf size prevents a split from creating a tiny terminal node under the chosen counting rule. Pruning permits a branch to disappear after a larger tree has been considered. The classifier reference documents max_depth, min_samples_leaf and the cost-complexity parameter ccp_alpha. Those are controls on the fitted structure. A simple output can still be selected from a broad search.
Imagine a researcher tries five horizons, four definitions of bar movement and three policies for when sessions begin. That is sixty combinations before trying tree settings, costs or alternate calendars. The final report might show a tidy two-question diagram, but the alternatives that competed to produce it help explain how surprisingly good an in-sample result could look. Keep a search log that records discarded combinations and describes how outcomes informed later decisions. The discussion of manual search and selection bias covers why informal trials belong in that history.
With pruning, pay attention to what changes for decision rows. If the left branch in the teaching tree is collapsed, A and B merge into a 30-of-60 leaf. This changes coverage if the old policy admitted only A. A pruned policy must define how to deal with the merged leaf. In a comparison based on a score threshold, the merged 50% may fail to qualify. Assess the whole policy with the new branch structure and the same execution conventions.
One way to reduce research discretion is to write a compact candidate set with a reason for each option. For example, allow either a one-question range filter or the same filter with a body subdivision, and choose among them on development periods using predefined criteria. Keep an account of changes to that candidate set. You can add a better feature when an exploratory result suggests it, while treating the period that suggested it as development evidence. The more often you read a nominally untouched block and adjust the procedure in response, the more that block participates in selection. Scikit-learn’s guide also notes that small data changes can yield different trees.
Evaluate on a sequence you could have lived through
Use chronological cuts that reflect when models and labels would actually have been available. A decision made a few minutes before the fitting cutoff can have a label that only becomes observable after it. If the model is supposed to be fitted at the cutoff, hold that row out of fitting until its label matures. Use actual endpoint and availability times when deciding which rows qualify. Removing the rows near the boundary whose label horizons cross it also keeps those measurements from straddling the transition.
One procedure is to create development blocks for choosing depth, features, policy thresholds and costs, then freeze these choices before an untouched evaluation block. If the intended routine refits periodically, freeze the refitting schedule and selection procedure. The training and preprocessing data at each refit should reflect what would have been available then. Inspect results by evaluation block with support and coverage. A block where A appears twice poses a different question from a block where A accounts for most scheduled decisions.
Preserve the order of signals and label endpoints. If a handful of overlapping episodes contributes most of the net result, show the concentration. Durations matter too. Twenty simulated trades from one day and twenty spanning different weeks expose the rule to different conditions. Multiple evaluations can cover distinct periods, but a forward evaluation opened repeatedly for tweaking becomes a source of design feedback. The next genuine test then needs a later block or fresh prospective observations.
The unchanged candidate can encounter a different mix of conditions. Compare the distribution of inputs and routes as well as the positive fractions within leaves. If A’s coverage drops, two possibilities are fewer qualifying bars and fewer valid feature records. These can be separated by counting validation failures before examining paths on the remaining rows. If A’s fraction drops with similar coverage, inspect episode concentration and endpoint quality as well as changed market conditions. Give label maturity and decision availability equal billing in the timeline. That record helps tell whether a small sample came from the clock, the feature supply, or the substance of the policy.
A smaller rival puts the second question to work
The natural rival is a one-question policy that considers all complete bars with ranges at or below 8.00 pips. It admits both regions called A and B before any shared cost or eligibility checks. Compare it with the A-only policy under the same schedule, label, friction, missing-value treatment and position rules. Keep a record of overlapping and exclusive opportunities. If a prior action blocks a later one, two individually identical eligible rows can contribute differently to each policy’s fills.
Take three hypothetical periods P1, P2 and P3. The tree policy produces 12, 7 and 9 simulated fills with net totals of +8, −6 and +2 pips. The rival produces 20, 18 and 19 fills with +6, −3 and +4 pips. The tree sums to +4 over 28 fills, or about +0.14 pip per fill. The rival sums to +7 over 57 fills, or about +0.12. The totals, averages and individual periods tell different stories. A fair assessment includes discrepancies in exposure and feasible fill counts alongside uncertainty in either estimate.
An average per fill is informative about admitted cases. Total net movement under the schedule captures how often the strategy found usable cases at the specified size. Treat each period as paired evidence because both policies see the same environment. Ask whether the additional body question removes a cluster of costly opportunities or merely removes enough cases to make the remaining average sensitive to one or two observations. Period totals can guide that investigation. A decision-level ledger locates the actual differences.
Look at the marginal decisions before attributing the difference to the body feature. Suppose, in a separate hypothetical replay, the range-only policy enters on a B case and remains in that position when an A case arrives five minutes later. The tree policy passes on B and is free to take A. The difference between the policies includes the B fill and the opportunity it displaced. Comparing every observed B outcome with every observed A outcome would miss that dependency.
Replay both policies on the same ordered stream and retain, for each rejected signal, whether a previous fill made it ineligible. A reviewer can then identify periods where the second split changed exposure primarily by moving entries through the day. That mechanism is observable in the ledger even when the aggregated totals are too sparse for a confident comparison.
There is a further distinction between policy stability and structural stability. A refitted tree might choose 7.90 in place of 8.00 yet route nearly every row the same way in a reference set. Another might print an identical root threshold while changing a downstream cut that moves most candidate actions. Compare agreement on leaf regions and eligible decisions on shared reference rows, paying attention to where the disagreements occur. A root label by itself gives little indication of the operational effect of a refit.
Leave room for a decision to wait
Suppose the predeclared review standard calls for eligible A cases across distinct episodes and enough later observations for a cost-sensitive comparison with the rival. The seven hypothetical fills from P2 could all cluster around one movement. Treat that concentration as a reason to continue collecting evidence offline. Name the condition in concrete terms and distinguish a thin estimate from a well-measured adverse result.
An abstention decision can happen before scoring, after scoring or at research review. Before scoring it could reflect incomplete inputs. After scoring it might follow from a cost or exposure cap. At review a team may decline to advance the whole candidate because the observed support is weak or the additional branch has yet to justify its complexity. Persist the specific reason at each stage. A future review can then distinguish a need for better input monitoring from a need to see more independent episodes.
For an inspectable handoff, include the feature and label specification, routing contract, search history, reference input traces, and a ledger linking scored opportunities to eventual labels and any simulated fills. Include statistics by period and by leaf even when the application is only being used for research. A colleague should be able to start with the 8.00-pip record, recover the equality branch, find the A count, and see where the cost policy would decide eligibility. They should then be able to read the paired evaluation and establish which rows arrived after the rules had been chosen.
The two printed rules from the opening can now be distinguished by a boundary test and by an artifact that keeps equality visible. Advancing the resulting candidate takes a different kind of support. With the illustrative figures above, keeping both policies available for study and withholding a deployment decision is a defensible outcome. The outstanding question can be named precisely. Does the body subdivision earn its place once the opportunity set, the costs and the time order are respected?
The Forex demo provides material for study and testing. Use it to practise tracing an input through a rule and recording where the evidence runs out.



