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.
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.