import numpy as np # arrays and random number generation
import pandas as pd # tabular containers for clean reporting
from scipy.optimize import minimize # numerical optimiser for maximum likelihood
# The steps below draw from the generator numpy keeps by default, so fixing its seed here
# gives the same numbers on every render.
np.random.seed(42)Detection-controlled estimation in Python: the frequency of market crimes

I show how you can try to infer how much market crime there is in the data, given that in truth you never know. I use some of the characteristics of each announcement to infer a suggestive number, and it is important to say that the number is only suggestive.
So I code Detection-Controlled Estimation (DCE) in Python and test it on data I simulate. Prosecutions say 5%, DCE says 22.9%, and the truth is 25.3%.
Why prosecutions are not enough
Each announcement has two unobserved probabilities, \(P(\text{crime})\) and \(P(\text{detection} \mid \text{crime})\).
You observe only the joint outcome:
\[P(\text{prosecution}) = P(\text{crime}) \times P(\text{detection} \mid \text{crime})\]
A 5% prosecution rate can come from many combinations of crime rate and detection rate:
| Crime rate | Detection rate | Prosecution rate |
|---|---|---|
| 5% | 100% | 5% |
| 10% | 50% | 5% |
| 25% | 20% | 5% |
| 50% | 10% | 5% |
So prosecution counts alone cannot tell you how much market crime there is.
What DCE adds
DCE uses two equations that are estimated simultaneously, one about how insiders trade and one about how they are detected and prosecuted.
The model needs variables that affect only one side, the exclusion restrictions.
Step 1. Simulating the data
I simulate the data to keep it simple, because getting a lot of prosecution data takes time, at least in the US. There are 10,000 announcements and five features.
The features come from two unobserved factors, so some of them are correlated, as real features would be.
Each feature is a weighted sum of an unobserved factor \(F_i\) and the feature’s own noise \(u_i\), rescaled to a mean of 0 and a standard deviation of 1,
\[x_i = \operatorname{standardise}(a\,F_i + b\,u_i),\]
where a and b are weights that differ by feature.
N = 10000 # number of announcements
def standardise(feature):
"""Rescale one feature to mean 0 and standard deviation 1.
An array with mean 4 and standard deviation 2 comes back with mean 0 and standard
deviation 1. Putting every feature on the same scale makes the coefficients chosen below
comparable with each other. Without it, each coefficient would depend on the units
of its raw feature.
"""
centred = feature - feature.mean()
return centred / feature.std()
# Two latent factors that nobody observes. Building every feature partly out of one of them
# gives the five features realistic correlations.
firm_size_factor = np.random.normal(0, 1, N) # bigger firms: bigger deals, more liquidity
detection_era_factor = np.random.normal(0, 1, N) # periods of stronger enforcement
# Each feature is a share of its latent factor plus its own private noise, and the two
# weights set how much of each. Numbers leave the generator in the order these lines run,
# so reordering these lines changes which draws the features receive.
# Crime side, correlated with firm size
raw_info_value = 0.7 * firm_size_factor + 0.7 * np.random.normal(0, 1, N)
raw_leakage = 0.6 * firm_size_factor + 0.8 * np.random.normal(0, 1, N)
# Detection side, correlated with the enforcement era
raw_surveillance_signal = 0.7 * detection_era_factor + 0.7 * np.random.normal(0, 1, N)
raw_reg_resources = 0.8 * detection_era_factor + 0.6 * np.random.normal(0, 1, N)
# Both sides, correlated with firm size
raw_liquidity = 0.5 * firm_size_factor + 0.9 * np.random.normal(0, 1, N)
info_value = standardise(raw_info_value)
leakage = standardise(raw_leakage)
surveillance_signal = standardise(raw_surveillance_signal)
reg_resources = standardise(raw_reg_resources)
liquidity = standardise(raw_liquidity)The crime and detection scores are weighted sums of the features,
\[s_{Ci} = -1.5 + 0.9\,\text{info}_i + 0.6\,\text{leak}_i + 0.4\,\text{liq}_i, \qquad s_{Di} = -1.8 + 1.2\,\text{surv}_i + 0.7\,\text{reg}_i - 0.3\,\text{liq}_i,\]
and the logistic function turns each score into a probability,
\[\sigma(s) = \frac{1}{1 + e^{-s}}, \qquad p_i = \sigma(s_{Ci}), \qquad d_i = \sigma(s_{Di}),\]
where \(p_i\) is the probability of a crime and \(d_i\) is the probability that a crime, if it happened, is detected and prosecuted.
# The true coefficients, which DCE is never given. Changing one of them changes
# the crime rate, the detection rate, or both.
crime_intercept = -1.5 # the crime score at average features
crime_weight_info_value = 0.9
crime_weight_leakage = 0.6
crime_weight_liquidity = 0.4
detection_intercept = -1.8 # the detection score at average features
detection_weight_surveillance = 1.2
detection_weight_reg_resources = 0.7
detection_weight_liquidity = -0.3 # negative: harder to spot in liquid markets
def sigmoid(score):
"""Turn any number into a probability between 0 and 1.
sigmoid(0) is 0.5, sigmoid(-4) is about 0.02, and sigmoid(4) is about 0.98. The sigmoid
makes a weighted sum of features readable as a probability.
"""
return 1.0 / (1.0 + np.exp(-score))
# A weighted sum of the features, one number per announcement, before the sigmoid runs.
crime_score = (crime_intercept
+ crime_weight_info_value * info_value
+ crime_weight_leakage * leakage
+ crime_weight_liquidity * liquidity)
detection_score = (detection_intercept
+ detection_weight_surveillance * surveillance_signal
+ detection_weight_reg_resources * reg_resources
+ detection_weight_liquidity * liquidity)
true_crime_probability = sigmoid(crime_score)
true_detection_probability = sigmoid(detection_score)
# A Bernoulli draw: take a random number between 0 and 1 and call the event a 1 whenever
# the number is below the probability, which happens exactly that often in the long run.
crime_random_number = np.random.uniform(0, 1, N)
detection_random_number = np.random.uniform(0, 1, N)
# 1 = a crime happened here
C = (crime_random_number < true_crime_probability).astype(int)
# 1 = it would be detected, if a crime happened here
D_if_crime = (detection_random_number < true_detection_probability).astype(int)
# 1 = prosecution. Of the three columns, A is the only one DCE is allowed to read.
A = C * D_if_crime
print("TRUTH (not given to DCE):")
print(f" mean P(crime) = {true_crime_probability.mean():.2%}")
print(f" mean P(detection | crime) = {true_detection_probability.mean():.2%}")
print()
print("OBSERVED (the only input to DCE, alongside the features):")
print(f" P(prosecution) = {A.mean():.2%}")
print(f" P(no prosecution) = {1 - A.mean():.2%}")TRUTH (not given to DCE):
mean P(crime) = 25.30%
mean P(detection | crime) = 22.93%
OBSERVED (the only input to DCE, alongside the features):
P(prosecution) = 4.97%
P(no prosecution) = 95.03%
So most crimes are never detected, with a true crime rate of about 25% and a prosecution rate of about 5%.
Step 2. Writing the likelihood
A prosecution needs both a crime and its detection,
\[P(A = 1) = p \cdot d.\]
and everything else has the leftover probability,
\[P(A = 0) = 1 - p \cdot d.\]
The log of their product across announcements is the log-likelihood,
\[\log L = \sum_{i:\,A_i = 1} \log(p_i d_i) \;+\; \sum_{i:\,A_i = 0} \log(1 - p_i d_i).\]
# One row per announcement, one column per coefficient. crime_features is X1 in the formula
# above and detection_features is X2. The leading column of ones is the intercept, so one
# matrix multiplication covers the intercept and the slopes together.
#
# The next two lines impose the exclusion restrictions: surveillance_signal and
# reg_resources are absent from the crime side, info_value and leakage are absent from the
# detection side.
crime_features = np.column_stack([np.ones(N), info_value, leakage, liquidity])
detection_features = np.column_stack([np.ones(N), surveillance_signal, reg_resources, liquidity])
n_crime_coefficients = crime_features.shape[1] # shape is (rows, columns)
n_detection_coefficients = detection_features.shape[1]
def dce_negative_log_likelihood(params):
"""How badly one candidate set of coefficients explains the prosecutions we observe.
minimize takes a single flat array, so params holds both coefficient vectors end
to end: the first n_crime_coefficients entries belong to the crime equation and the
rest to the detection equation. Lower is better, because this is the log-likelihood
with its sign flipped, and minimize searches for the lowest value.
"""
crime_coefficients = params[:n_crime_coefficients]
detection_coefficients = params[n_crime_coefficients:]
# @ is matrix multiplication, so every row of features meets the coefficients once.
crime_probability = sigmoid(crime_features @ crime_coefficients)
detection_probability = sigmoid(detection_features @ detection_coefficients)
# A prosecution needs the crime and its detection, so its probability is the product.
prosecution_probability = crime_probability * detection_probability
# np.log(0) is minus infinity and would stall the optimiser, so hold the probability a
# hair inside 0 and 1.
guarded_probability = np.clip(prosecution_probability, 1e-12, 1 - 1e-12)
# A is 1 or 0, so each announcement contributes exactly one of these two terms.
prosecuted_terms = A * np.log(guarded_probability)
not_prosecuted_terms = (1 - A) * np.log(1 - guarded_probability)
return -np.sum(prosecuted_terms + not_prosecuted_terms)I fit both equations simultaneously using maximum likelihood.
Step 3. Fitting the model and comparing with the truth
# The optimiser has to start somewhere. Every slope starts at zero, and both intercepts
# start at -1.0, which is a low crime rate and a low detection rate. Starting the two
# intercepts below zero starts the search at a prosecution rate closer to the one in the data.
starting_values = np.zeros(n_crime_coefficients + n_detection_coefficients)
starting_values[0] = -1.0 # position 0 is the crime intercept
starting_values[n_crime_coefficients] = -1.0 # the detection intercept opens the second half
# L-BFGS-B walks downhill on the negative log-likelihood until it stops improving.
fit = minimize(dce_negative_log_likelihood, starting_values, method='L-BFGS-B',
options={'maxiter': 2000, 'ftol': 1e-10})
# fit.x is the flat array the optimiser settled on, split exactly as params was.
estimated_crime_coefficients = fit.x[:n_crime_coefficients]
estimated_detection_coefficients = fit.x[n_crime_coefficients:]
estimated_crime_probability = sigmoid(crime_features @ estimated_crime_coefficients)
estimated_detection_probability = sigmoid(detection_features @ estimated_detection_coefficients)
# A prosecution needs both, on the true side and on the estimated side alike.
true_prosecution_probability = true_crime_probability * true_detection_probability
estimated_prosecution_probability = estimated_crime_probability * estimated_detection_probability
not_observed = "n/a" # n/a marks a quantity real data never reveals
result = pd.DataFrame({
"Quantity": ["mean P(crime)", "mean P(detection | crime)", "mean P(prosecution)"],
"TRUE (unobserved)": [f"{true_crime_probability.mean():.2%}",
f"{true_detection_probability.mean():.2%}",
f"{true_prosecution_probability.mean():.2%}"],
"OBSERVED (data)": [not_observed, not_observed, f"{A.mean():.2%}"],
"DCE estimate": [f"{estimated_crime_probability.mean():.2%}",
f"{estimated_detection_probability.mean():.2%}",
f"{estimated_prosecution_probability.mean():.2%}"],
})
print(result.to_string(index=False)) Quantity TRUE (unobserved) OBSERVED (data) DCE estimate
mean P(crime) 25.30% n/a 22.86%
mean P(detection | crime) 22.93% n/a 24.04%
mean P(prosecution) 5.35% 4.97% 5.00%
DCE matches the observed prosecution rate (5.00% vs. 4.97%), and its crime and detection rates can be compared with the truth.
Results
In this data, DCE does well compared to the truth. Counting prosecutions would put market crimes at about 5% of announcements, while DCE estimates 22.9%, against a true 25.3%, and a detection rate of 24.0%, against a true 22.9%.
import matplotlib.pyplot as plt
RED, TEAL, GREY = "#C0392B", "#17868A", "#888888"
# The site's chart colours, in order: the cream background, the text, the light grid lines,
# the pale frame and the axis labels, the same on every chart of the site.
BG, INK, GRID, SPINE, AXIS_TEXT = "#FCEFE3", "#1f1f1f", "#EADCCC", "#D5C6B4", "#4a4a4a"
def style_chart(figure, axis):
"""Give a finished chart the site's cream background, light grid and pale frame."""
figure.patch.set_facecolor(BG)
axis.set_facecolor(BG)
axis.grid(True, axis="y", color=GRID, lw=1.0)
axis.set_axisbelow(True)
for side in ("top", "right"):
axis.spines[side].set_visible(False)
for side in ("left", "bottom"):
axis.spines[side].set_color(SPINE)
axis.tick_params(axis="both", length=0, colors=INK, pad=6)
axis.xaxis.label.set_color(AXIS_TEXT)
axis.yaxis.label.set_color(AXIS_TEXT)
axis.title.set_color(INK)
# Write each legend entry in the colour of what it labels: a line's colour or a bar's fill
# colour. get_legend() returns None when the chart has no legend.
legend = axis.get_legend()
if legend is not None:
for text, handle in zip(legend.get_texts(), legend.legend_handles):
if hasattr(handle, "get_color"):
text.set_color(handle.get_color())
else:
text.set_color(handle.get_facecolor())
# The three crime rates, in percent of the 10,000 announcements: the share that was prosecuted,
# the average crime probability that DCE estimates, and the average true crime probability,
# which DCE never sees. \n in a label starts a second line.
bar_labels = ["counted from\nprosecutions", "DCE estimate", "true crime rate"]
bar_heights = [100 * A.mean(),
100 * estimated_crime_probability.mean(),
100 * true_crime_probability.mean()]
# plt.subplots creates the figure and its one chart, axis; figsize is the figure's width and
# height in inches.
figure, axis = plt.subplots(figsize=(7, 4.5))
bars = axis.bar(bar_labels, bar_heights, color=[RED, TEAL, GREY])
# bar_label writes each bar's height above it, 3 points up: %.1f writes one decimal and %% a
# percent sign
axis.bar_label(bars, fmt="%.1f%%", padding=3, color=INK)
axis.set_ylim(0, 30)
axis.set_ylabel("Share of announcements (%)")
axis.set_title("The crime rate from prosecutions, from DCE and in truth")
style_chart(figure, axis)
# tight_layout() fits the labels inside the figure. savefig writes the chart to a PNG file:
# dpi=140 sets its resolution, bbox_inches="tight" trims the empty margin, and facecolor=BG
# keeps the cream background. show() displays the chart.
plt.tight_layout()
plt.savefig("dce_crime_rates.png", dpi=140, bbox_inches="tight", facecolor=BG)
plt.show()
The prosecution rate is about a fifth of the true crime rate, and the DCE estimate is nine tenths of it.
Limitations
This is simulated data, so you can never know exactly whether DCE does what it is supposed to do in real data.
The exclusion restrictions are true here only by construction, and in real data you can never know whether they hold.
The restrictions can also fail, and then the split between crime and detection can be biased.
So the conclusion is that I provide this methodology with Python code, so that a reader who has the data can try it and see what suggestive number they get for market crimes.
References
Comerton-Forde, C., & Putniņš, T. J. (2014). Stock price manipulation: Prevalence and determinants. Review of Finance, 18(1), 23–66. https://doi.org/10.1093/rof/rfs040
Feinstein, J. S. (1990). Detection controlled estimation. The Journal of Law and Economics, 33(1), 233–276. https://doi.org/10.1086/467205
Patel, V., & Putniņš, T. J. (2020). How much insider trading happens in stock markets? SSRN. https://doi.org/10.2139/ssrn.3764192
Disclaimer: a synthetic illustration of an estimation method, for discussion purposes only. The probabilities recovered here describe data I generated. They do not describe any real market or any real party. Not investment advice.