How does an isolation forest flag unusual trades?

Fit an isolation forest to trades, rank them by their anomaly scores with nsmallest, and see what the contamination setting changes.

After this lesson, you can score trades with an isolation forest and pick the most unusual ones for review.

How does an isolation forest score a trade?

An isolation forest splits the trades again and again at random values of random features, and a trade that ends up alone after few splits gets a low anomaly score. Among ten made-up trades, row 9, with a spread of 35 basis points, scores lowest at −0.7303, and row 8, with 900 shares, next at −0.6923.

A split at a size of 500 shares would put row 8 alone on one side, and a split at a spread of 10 basis points would do the same for row 9. A trade in the middle of the others needs many splits. The method needs no examples of known unusual trades.

IsolationForest(random_state=7, contamination=0.1) creates the model with a fixed seed, so the random splits repeat. .fit() builds the trees on the two features, and .score_samples() gives each trade its score, lower for more unusual.

The following box builds the trades and scores them.

import pandas as pd
from sklearn.ensemble import IsolationForest

trades = pd.DataFrame({
    "ticker": ["AAA", "BBB", "CCC", "AAA", "BBB", "CCC", "AAA", "BBB", "CCC", "AAA"],
    "size": [100, 120, 90, 110, 130, 95, 115, 100, 900, 150],
    "spread_bps": [2, 3, 2, 4, 3, 2, 3, 4, 3, 35],
})
features = trades[["size", "spread_bps"]]
model = IsolationForest(random_state=7, contamination=0.1).fit(features)
trades["score"] = model.score_samples(features)
print(trades.round(4))
  ticker  size  spread_bps   score
0    AAA   100           2 -0.4081
1    BBB   120           3 -0.3818
2    CCC    90           2 -0.4465
3    AAA   110           4 -0.4169
4    BBB   130           3 -0.4159
5    CCC    95           2 -0.4033
6    AAA   115           3 -0.3743
7    BBB   100           4 -0.4215
8    CCC   900           3 -0.6923
9    AAA   150          35 -0.7303

A score ranks the trades and is not a probability of misconduct. The forest scores the trades it was fitted on, which suits a review of past trades, and a live screen fits on an earlier period.

How do I pick the trades to review?

.nsmallest(3, "score") returns the three trades with the lowest scores, here rows 9, 8 and 2, which suits a fixed review budget. .predict() instead flags each trade with −1 or 1 by a threshold that contamination sets, so 0.1 flags row 9 only and 0.3 flags rows 2, 8 and 9, with the same scores.

The following box prints the review list and the flags of both settings.

print(trades.nsmallest(3, "score").round(4))
wider = IsolationForest(random_state=7, contamination=0.3).fit(features)
print(pd.DataFrame({"ticker": trades["ticker"], "flag_10": model.predict(features), "flag_30": wider.predict(features)}))
  ticker  size  spread_bps   score
9    AAA   150          35 -0.7303
8    CCC   900           3 -0.6923
2    CCC    90           2 -0.4465
  ticker  flag_10  flag_30
0    AAA        1        1
1    BBB        1        1
2    CCC        1       -1
3    AAA        1        1
4    BBB        1        1
5    CCC        1        1
6    AAA        1        1
7    BBB        1        1
8    CCC        1       -1
9    AAA       -1       -1

A contamination of 0.3 does not mean that 30% of the trades are suspicious. It is a setting of the threshold.

Your turn

Print the ticker, size and spread of the two most unusual trades. You should see AAA’s trade with the wide spread, then CCC’s trade of 900 shares.

.nsmallest(2, "score") keeps the two lowest scores in order.

print(trades.nsmallest(2, "score")[["ticker", "size", "spread_bps"]])
  ticker  size  spread_bps
9    AAA   150          35
8    CCC   900           3