Artificial intelligenceIntermediate23 min read

The model is almost always right because almost nothing happens

Evaluate rare market events without confusing accuracy, sampling balance and trading value. Work through labels, confusion matrices and realistic review costs.

A single blue glass marble among many pale ceramic marbles on a cream surface
Conceptual photograph: rarity changes what a successful count appears to mean.

The reassuring number on the first screen

The dashboard reports 99% accuracy. Before celebrating, Leila opens the prediction file and discovers that every row contains the same answer: no event. Her model has learned to stay silent. There is no mysterious numerical failure. In the invented sample she is examining, only one observation in a hundred belongs to the event class. A machine that ignores every input can therefore produce the headline on the screen.

Leila wants an alert for unusually expensive trading conditions, not a directional forecast. Her hypothetical robot normally evaluates an entry every five minutes. She is considering a model that would ask the research process to inspect an observation more closely when the subsequent execution window is expensive. This article uses deliberately invented counts and costs to explain the investigation. They are not measurements of TradeAndRoll robots, recommendations to trade a particular rule or estimates of future performance.

The first decision is about the question. A classifier describes a labelled event; a trading system chooses an action. The event might be a large price move, a spread threshold, an order rejection or a combination. Each definition creates a different population and a different imbalance. Calling them all opportunities would conceal the distinctions needed to evaluate them.

By the end of the exercise, Leila needs more than a replacement headline metric. She needs a label that can be reconstructed, a sample representing the intended use, a way to count mistakes, and a statement of what changes when an alert occurs. Without these pieces, balancing the dataset could make the training graph prettier while making the actual decision less understandable.

Define the event before counting its rarity

Suppose the event means that a specified executable spread exceeds a fixed threshold during the next five minutes. That sentence still contains unresolved choices. Does any quote above the threshold qualify, or must the condition persist? Which quote stream is relevant to the order size? Is the label based on the largest spread, the average spread or the spread observed at a fixed delay? These alternatives can produce very different class counts from exactly the same raw observations.

Leila writes a narrow educational definition: at each eligible five-minute boundary, observe the spread for a stated reference size at a stated venue exactly thirty seconds later. Label one if that spread exceeds the chosen threshold, otherwise zero. If the necessary quote is unavailable, the label is missing. Missing is not the same as normal. Treating unavailable quotes as zero would make a failing feed look like a quiet market and could reward the model for recognizing outages.

A label also has an availability time. The features must be available at the boundary, whereas the thirty-second outcome becomes available afterward. The evaluation therefore retains both instants. A variable calculated from the entire following five-minute candle is not a legitimate input merely because its row is placed beside the boundary timestamp. The apparent ability to detect rare events can otherwise be a simple consequence of seeing part of the answer.

The threshold itself should have a reason. A fixed price distance may describe a very different practical condition across instruments or quote conventions. A normalized threshold creates other assumptions, including how its normalization is estimated. Leila records the units and origin of the threshold before comparing models. The class proportion is an output of a definition, not an instruction to manufacture equal groups.

The denominator belongs to the intended decision

Leila’s first export contains every five-minute boundary, including nights when the robot would not consider an entry. Her intended use is narrower: inspect only boundaries at which the existing entry rule is eligible. A classifier evaluated on the wider calendar could look strong because it recognizes hours that the strategy already excludes. That does not demonstrate incremental usefulness for the actual decision.

She therefore distinguishes three counts: all calendar boundaries, boundaries with usable data, and boundaries where a decision could occur. The proportion of expensive outcomes can differ across these sets. None is automatically the correct denominator for every purpose. The broad set can help investigate market conditions; the eligible set answers the operational question. Write the population beside every metric, especially when two teams use the same event name.

Instrument aggregation creates another trap. Imagine that one pair contributes 9,000 observations and another contributes 1,000. A pooled metric is dominated by the first pair even if the second produces most alerts. A report that shows only the total hides the allocation of both evidence and work. Leila adds separate counts by instrument and by the eligibility condition already fixed in her protocol. She does not search for whichever subgroup makes the model look best.

Repeated observations also complicate the word sample. Ten adjacent boundaries during one prolonged disturbance may generate ten positive labels. They are ten decisions under the stated schedule, but they are not necessarily ten independent disturbances. Keeping an episode identifier makes this distinction inspectable. Later, the report can show both observation-level performance and the number of distinct episodes encountered, without pretending that one number replaces the other.

An illustrative population of 10,000 eligible observations contains 100 events and 9,900 normal outcomes
The denominator is 10,000 eligible observations in this invented example. It does not represent every timestamp in a market file.

Read four cells before choosing a score

Use the invented evaluation sample of 10,000 eligible observations: 100 events and 9,900 normal outcomes. Model A raises 200 alerts. Sixty coincide with events; 140 do not. It misses forty events and correctly leaves 9,760 normal observations unflagged. Its accuracy is 98.2%, below the silent model’s 99%. The lower headline does not settle which model is more useful.

The four cells answer concrete questions. Sixty true positives describe events found. Forty false negatives describe events missed. One hundred and forty false positives describe unnecessary alerts under this label definition. The 9,760 true negatives describe normal observations left alone. Calling a false positive a losing trade would be incorrect: the classifier predicts a condition, and the trading consequence still depends on the action taken.

For A, recall is 60 divided by 100, or 60%. Precision is 60 divided by 200, or 30%. The false-positive rate is 140 divided by 9,900, approximately 1.41%. Thus a seemingly small false-positive rate can coexist with a majority of alerts being false. The arithmetic follows from the large number of normal observations. The rare-event problem lives in the denominators, not in a failure of percentages to add up.

Balanced accuracy averages the recall of the classes; this definition is documented in scikit-learn’s balanced accuracy reference. For A, the two recalls are 60% and approximately 98.59%, giving about 79.29%. That offers a useful view of class-wise recognition, but it does not assign an economic value to an avoided event or a false alarm. Leila keeps the four cells in the report even when a summary score is needed.

Put an action behind an alert

The next question is what an alert changes. It could postpone an entry, reduce an assumed research order size, request a manual check or merely create a log entry. These actions have different consequences. A model that is acceptable for an informational dashboard may be unacceptable as an automatic gate. Conversely, an imperfect alert can be useful when it directs a small amount of attention toward a costly problem.

For a transparent illustration, suppose each successfully detected event permits an action that saves twenty cost units. Suppose each false alert sacrifices four units of value. Assume missed events and true negatives are unchanged relative to a baseline that never alerts. Model A then contributes 60 times twenty, minus 140 times four: 640 units before operating costs. This is a conditional accounting exercise, not a profit forecast. It assumes that the proposed response really produces those effects.

Now consider Model B: eighty events found, twenty missed, and four hundred false alerts. Under the same assumptions, B contributes eighty times twenty minus four hundred times four, which is zero. Its higher recall does not make it the better decision rule in this example. If the avoided-event value were forty instead of twenty, the comparison would change. The chosen values therefore deserve investigation rather than being hidden in a score name.

The model must also pay for itself operationally. If an alert requires three minutes of review, A’s two hundred alerts consume ten hours, while B’s four hundred and eighty alerts consume twenty-four hours. These are sample-period workloads, not annual estimates. A review process with only six available hours cannot implement either proposal as described. An alert is useful only through an action that the workflow can actually perform.

Two illustrative confusion matrices compare Model A with 60 events found and 140 false alerts, and Model B with 80 events found and 400 false alerts
Higher recall and lower workload are different objectives. Keep the cells visible before converting them into one decision score.

Resampling changes the training question

The team proposes retaining every positive observation and selecting an equal number of negative observations for training. That can be a reasonable experimental choice. It does not mean that events now occur half the time in the environment. The training sample and the use population have become different distributions, and the evaluation needs to acknowledge the change. The imbalanced-learn guidance on sampling pitfalls specifically warns against altering the test distribution and resampling before the train-test separation.

There are several ways to influence a model’s attention. One can duplicate rare examples, subsample common examples or assign unequal loss weights. These methods are not interchangeable. Duplicating an observation gives it more influence but does not create a new market episode. Removing normal observations reduces computational work but can discard important variation. Weighting changes the objective and may interact with regularization or model capacity. Keep the unmodified evaluation population so that the consequences remain measurable.

The distinction is especially important when synthetic examples are proposed. A synthetic point between two positive rows is not automatically an economically possible observation. The rows might belong to different instruments, sessions or quote regimes. Combining their fields can create a state that no real decision could encounter. Leila requires a description of which relationships the synthetic construction preserves and which it deliberately ignores.

She also asks whether rarity is a data problem or a reality of the task. If the target condition is truly uncommon, no resampling algorithm can provide independent historical episodes that were never observed. The model may benefit computationally from balanced training while remaining scientifically constrained by a small number of distinct events. The correct response can be a narrower conclusion, a simpler model or a different question, rather than a larger artificial dataset.

A probability from a balanced sample needs interpretation

Imagine a simplified case where examples were sampled solely according to their class, and the relation between features and class within each group stayed unchanged. The training sample has a fifty-fifty class mix, while the intended population has a one-percent event rate. A model output of fifty percent in the balanced sample does not automatically mean a fifty-percent event probability in the use population.

Under these strong assumptions, prior odds provide a useful algebraic illustration. Population odds equal sample odds multiplied by the population prior odds divided by the sample prior odds. A sample probability of one half has odds of one. Multiplying by 0.01 divided by 0.99 gives population odds of approximately 0.010101, which correspond to a one-percent probability. The feature pattern in this constructed example has not improved on the population prior.

For a sample probability of 0.9, sample odds are nine. The adjusted odds become approximately 0.090909, giving a probability of about 8.33%. That is substantially above one percent, but far below ninety percent. The calculation is not a universal calibration recipe. It relies on class-dependent sampling and stable conditional distributions, assumptions that can fail when a temporal subsample removes particular sessions or when the market changes.

Leila uses the arithmetic to prevent a category error, then evaluates probabilities on appropriately separated observations with the intended prevalence. She checks reliability in ranges relevant to the proposed decision, with counts visible. A bin containing two alerts cannot support the same confidence as one containing two hundred. The existing guide to probability calibration develops that separate question; the key here is to record how training sampling changed what the output initially represents.

Training is shown with equal event and normal groups while evaluation retains the original one-percent event prevalence
A balanced training experiment does not authorize balancing the evaluation set and then presenting its precision as an operating result.

Choose thresholds without spending the final test

A classifier often produces a score rather than a hard alert. Changing the threshold changes the number of events found, false alerts and reviews required. There is no reason to assume that 0.5 is the right boundary, particularly after weighted training. But choosing the best threshold on the final evaluation period would use that period to develop the rule.

Leila writes a selection procedure before inspecting the final period. On the development validation window, she compares a small, declared set of thresholds. Each must satisfy a workload limit and a minimum number of observed events sufficient for the intended descriptive report. She chooses according to an explicitly stated objective and locks the resulting rule. The subsequent period evaluates that entire procedure, including the selected threshold, not an imaginary model that knew the best boundary in advance.

Precision-recall displays can help inspect the tradeoff, but their points are not independent experiments. They usually summarize thresholds applied to the same observations. Choosing an attractive corner after trying many label definitions, models and response rules adds another layer of selection. Count the choices that produced the curve, rather than describing the final graph as if it were the only analysis performed.

Capacity constraints can also suggest a different policy: review only the highest-ranked eligible observations until a fixed daily quota is reached. That is a ranking-and-allocation rule, not a fixed probability threshold. It needs its own evaluation, including what happens on days with no useful candidates and days with many events. A quota should not force meaningless alerts simply to keep an operator busy. The policy must be reproducible from information available at each decision time.

Time can make balancing quietly leak information

Randomly selecting a balanced sample across the entire history can put adjacent parts of the same event into training and evaluation. A prolonged spread disturbance might contribute some boundaries to one set and neighboring boundaries to another. A model that recognizes the episode can appear to generalize even when the real task is to recognize a future episode it has never encountered.

Leila first separates the intended time periods, then fits preprocessing and any training-only sampling within the appropriate development data. If labels cover future intervals, she accounts for overlap near boundaries. The event identity remains available for diagnostics. The sampling method must respect the evaluation boundary, not merely produce the desired class ratio in a spreadsheet.

Another subtle leak comes from identifying unusual events with statistics computed over the full history. A threshold defined as the top one percent of all future spreads has used the evaluation distribution to decide which outcomes count as unusual. That may be acceptable for a clearly retrospective description, but it does not reproduce a rule a researcher could have fixed beforehand. A production-like experiment needs a threshold obtained from prior information or an explicit updating mechanism.

The same principle applies to missing-value handling and normalization. If the rare class is concentrated during a period of broken observations, filling values with statistics from later data can make the class easier to identify. Balancing does not repair that causal problem. It can amplify it by repeatedly presenting the contaminated examples during training. Leila traces a few positive and negative rows from raw observations to final inputs before spending time comparing sophisticated classifiers.

Prevalence changes the meaning of a stable detector

Return to Model A’s event recall of sixty percent and false-positive rate of about 1.41%. Suppose these rates remained unchanged in a new hypothetical population with five hundred events among ten thousand observations. The model would find about three hundred events and falsely flag about 134 of the 9,500 normal observations. Precision would rise to roughly 69%, even though the conditional detection rates were unchanged.

The reverse can happen when events become rarer. With fifty events among ten thousand observations, sixty-percent recall gives thirty detections. Applying the same false-positive rate to 9,950 normal observations gives about 141 false alerts. Precision falls to roughly 18%. These approximate calculations isolate a prevalence effect; they do not claim that a real model’s conditional rates would stay constant while the environment changed.

The operational lesson is to monitor several quantities together. A falling precision can reflect a changed event frequency, a deteriorating detector, a changed label pipeline or some combination. One aggregate metric cannot identify the cause. Leila stores event counts, eligible-observation counts, score distributions and the four confusion cells for predefined reporting windows. She also tracks label delay so that an incomplete recent period is not compared with a fully observed older one.

When outcomes arrive late, the dashboard should show how much of a window has matured. An apparent run of false alerts may simply include alerts whose future label cannot yet be calculated. Conversely, deleting unresolved observations can bias the report if difficult market conditions are also the ones with slow or missing data. The review distinguishes provisional monitoring from completed evaluation and records unresolved cases rather than silently classifying them as failures or successes.

Rare labels are sometimes the wrong target

A binary event label can simplify a decision, but it may discard information that matters. Two spreads just below and just above a threshold could be practically indistinguishable, while two observations both labelled one could have very different magnitudes. If the proposed action depends on expected cost rather than threshold crossing, estimating a continuous quantity might be more aligned with the task.

That alternative brings its own difficulties. A regression model can be dominated by a few extreme observations, and an average prediction can conceal a broad range of possible outcomes. Quantile estimates, interval estimates or a deliberately simple ranking may be useful comparisons, but none should be added merely because the classifier produced disappointing results. Leila asks which output can support the action with the least unnecessary complexity.

There may also be multiple kinds of rare event. A wide spread during a scheduled announcement, an absent quote and a rejected order are not necessarily manifestations of one mechanism. Combining them into a single positive class can produce a detector that finds the easiest type while missing the one the researcher actually cares about. Inspect the composition of the positive group, with categories specified from operational meaning rather than chosen after inspecting model errors.

Sometimes the best first version is a transparent rule that directly checks data freshness or quote availability. A predictive model is not required to recognize a condition already observable at decision time. Keeping the observable control separate from the forecast clarifies what the model adds. It also makes failures easier to explain: the system can distinguish an unavailable input from an uncertain prediction instead of converting both into an unexplained confidence score.

Count repeated warnings as work, not new discoveries

An event can remain active long enough to generate several alerts. Suppose the model raises an alert at 10:00, another at 10:05 and another at 10:10 during the same expensive episode. If each alert counts as a separate success, the report may give the impression of three independent discoveries. If each triggers the same manual investigation, the operator may instead experience one discovery followed by duplicated work. The label definition alone does not determine which interpretation is appropriate.

Leila adds an explicit alert state to the proposed workflow. An observation can open a review, update an already open review or do nothing. Closing the review requires a declared condition, such as a completed check or a return to specified normal conditions. These are workflow choices, not changes to the classifier’s historical predictions. They should be evaluated on the same recorded score sequence so that reduced alert volume is not mistaken for improved predictive skill.

For example, twelve positive observations might belong to four episodes. The classifier could identify nine observations but touch only two episodes, repeatedly recognizing the longest disturbances while missing two short ones. Another model could identify six observations across all four episodes. Which pattern matters depends on the response: avoiding the first expensive entry may require early episode detection, whereas controlling every eligible entry requires continuing observation-level decisions. Report the timing of the first useful warning, not only the number of positive rows.

The protocol therefore distinguishes observation recall, episode coverage and review openings. A quiet-period rule can reduce repeated warnings but also delay recognition of a genuinely new event. Leila records the exact rule and checks examples where episodes occur close together. A smaller alert count can come from suppression rather than from better discrimination. The difference matters when someone later changes the notification policy while leaving the model untouched.

Separate a corrected label from a better model

During a manual review, Leila discovers that several supposed false positives were calculated with an outdated quote-size convention. Correcting those labels improves the displayed precision. It would be misleading to present that movement as a model improvement: the predictions did not change. The definition of their evaluated outcome did. The repaired report needs a versioned label specification and a comparison explaining which observations were affected.

This is also a reason to preserve the original evaluation extract. A reproducible investigation keeps both the earlier label file and the corrected version, along with a small machine-readable list of affected row identifiers. It does not silently overwrite the evidence and leave an old chart circulating without context. The purpose is to make the correction inspectable, not to punish the team for discovering a mistake.

Some corrections are unambiguous: a unit conversion was wrong or a timestamp was shifted. Others change the research question, such as deciding that an expensive spread must persist for longer. The latter requires a new label version even if the change seems more sensible. Reusing the same performance number across both definitions would compare different targets without telling the reader.

Finally, the team records whether seeing model errors motivated the revised definition. If it did, the revised target has been developed using those observations. It can still be worthwhile, but those observations no longer provide a clean independent test of the revised design. Data repair and target redesign deserve different records. That distinction allows a later reviewer to understand whether the next evaluation is checking a corrected implementation or a newly selected idea.

Build a small review packet before a large experiment

Leila’s first deliverable is a packet containing a handful of fully traced observations. It includes a correctly detected event, a missed event, a false alert, an ordinary observation, a missing label and two neighboring boundaries from one prolonged episode. For each, the packet shows the eligible decision time, input availability, label rule, outcome time, model score and proposed response.

The packet is intentionally small enough to inspect by hand. Its purpose is not to estimate performance from six examples. It tests whether the evaluation objects mean what the team thinks they mean. If a reader cannot explain why one row is positive and another is missing, a million-row report will not resolve the ambiguity. Scale the computation after the semantics are stable.

Next comes a locked report layout. It contains the population definition, temporal partition, sampling method, model version, threshold rule, event and episode counts, confusion cells, workload and a sensitivity table for the assumed action consequences. The sensitivity table varies values used in the decision calculation, not historical outcomes that are inconvenient. It reveals whether the proposal remains useful only under a narrow, optimistic assumption about avoided costs.

An AI assistant can help identify inconsistencies in that packet. A productive prompt asks it to reconstruct denominators, verify the numerical examples and list fields whose availability time is unclear. It should not be asked to certify a trading edge from a confusion matrix. The human reviewer still needs to check the cited sources, inspect the original records and decide which uncertainties matter before moving toward any executable adaptation.

A review sequence separates defining eligible observations, training-only sampling, chronological evaluation and measuring the alert action
The investigation has four different objects: population, learning sample, evaluation and action. Their boundaries prevent a balanced table from becoming an unsupported trading claim.

What would justify another round of work?

Leila does not end by declaring the classifier ready. She writes the next decision in observable terms. If the label cannot be reconstructed, the next task is data repair. If the model adds no useful distinction among eligible observations, a more complex response policy is premature. If the detector has promising separation but creates too much review work, the next experiment concerns allocation or the response action rather than another resampling technique.

An inconclusive result can still narrow the project. Discovering that almost all positive labels belong to one malfunctioning feed is useful because it redirects attention toward a data-quality control. Discovering that a rare event has only three independent historical episodes is useful because it limits what can honestly be claimed. Neither finding needs to be dressed as a successful predictive model to justify the investigation.

The final report uses ordinary language: which event was studied, which decisions were eligible, what the model found, what it missed, how much work it created and which consequence assumptions drive the comparison. Rarity makes the accounting more important, not less. A high accuracy number is easy to obtain when nothing happens. A useful decision requires showing what happens when the rare case does appear, and what the proposed response costs on all the other occasions.

To practise that style of investigation, start with a small, inspectable system and trace its rules before adding a classifier. The TradeAndRoll demo provides ten Forex robots with rules, source code, market CSVs and prompt ideas for research. Use the material to formulate a specific test and verify any adaptation in your own environment. The value of the exercise is the evidence you can inspect; a model score does not promise returns.

Back to the Blog