Anomaly Detection in Delphi: An Open Source Library to Detect the Unexpected
📦 TL;DR: The Delphi Anomaly Detection Library is a free open source library implementing 7 algorithms for detecting anomalies in data: Three Sigma, Sliding Window, EMA, Adaptive, Isolation Forest, DBSCAN, and LOF. It identifies fraud, errors, failures, and anomalous behaviors in Delphi applications. Production-ready, thread-safe, supports both real-time and batch analysis. GitHub Repository.
Introduction
“Prevention is better than cure” - this ancient saying applies perfectly to the world of software development and business systems. Too often we find ourselves chasing problems we could have intercepted before they caused damage: suspicious order amounts, fraudulent transactions, malfunctioning sensors, anomalous traffic spikes, data entry errors.
If your application handles data, anomalies are not a matter of "if" but "when."
Every system that processes user inputs, sensor readings, financial transactions, or any form of real-world data will eventually encounter values that don't fit the expected pattern. The question isn't whether anomalies will occur - they will. The question is whether your system will detect them in time to act, or discover them only after the damage is done.
Anomaly detection isn't an optional feature for edge cases; it's a fundamental layer of protection that every data-driven application should have.
Anomaly detection is the branch of data science that deals with identifying unexpected patterns, outliers, and anomalous behaviors in data. Techniques that until a few years ago were the exclusive domain of data scientists and researchers can now be integrated directly into our business applications, making them smarter, safer, and more reliable.
This is exactly what I talked about in my talk “Building Applications That Prevent Their Own Disasters” at ITDevCon 2025, the main annual event for the European Delphi community, held on November 6-7 in Milan. I also presented a shorter Italian version of the same talk at ITDevCon Bites in Padua in October 2025. The response was extraordinary: dozens of developers approached me telling stories of scenarios where these techniques could have saved critical situations or prevented significant economic losses.
From that presentation came the idea to release a complete, ready-to-use open source library that would allow the Delphi community to easily integrate anomaly detection into their projects. Today I’m happy to announce that this library is available on GitHub.
The Library: Delphi Anomaly Detection Algorithms
The Delphi Anomaly Detection Library is a complete library that implements 7 different algorithms for anomaly detection, covering scenarios ranging from classical statistical analysis to advanced machine learning.
🔗 GitHub Repository: github.com/danieleteti/delphi-anomalies-detectors
Key Features
- 7 Detection Algorithms - From simple statistical methods to advanced ML techniques
- Production Ready - Thread-safe, memory-efficient, 100% tested
- Real-time & Batch - Supports both streaming data and historical analysis
- Simple Integration - Modular architecture, zero external dependencies
- Performance Monitoring - Integrated metrics and benchmarking
- Hyperparameter Tuning - Grid search and random search with cross-validation
- Factory Patterns - Pre-configured detectors for common use cases
The Algorithms: Which One to Use and When
The library implements 7 different algorithms, each optimized for specific scenarios. Here’s a quick overview:
| Algorithm | Type | Primary Use Case | Performance |
|---|---|---|---|
| Three Sigma | Statistical | Quality control, normal data | ~100k/sec |
| Sliding Window | Statistical | Real-time sensor monitoring | ~80k/sec |
| EMA | Statistical | Trading, high-frequency data | ~100k/sec |
| Adaptive | Statistical | Seasonal systems, variable patterns | ~60k/sec |
| Isolation Forest | ML | Multidimensional fraud detection | ~20k/sec |
| DBSCAN | ML | Behavioral clustering | ~25k/sec |
| LOF | ML | Churn prediction, local outliers | ~20k/sec |
Let’s look at them in detail.
Three Sigma Detector - Statistical Process Control
The problem: In a manufacturing production line, every component must meet precise tolerances. A bearing with a diameter of 100mm ± 0.5mm is acceptable; one at 105mm is a defect that can cause cascading failures. Operators can’t manually measure every piece, and defects slip through until they cause problems in assembly or, worse, at the customer’s site.
The solution: Three Sigma is the most classic and intuitive algorithm. It calculates mean and standard deviation of historical data, then considers anything that deviates more than 3σ (sigma) from the mean as anomalous. It’s the foundation of industrial quality control used for decades.
var
Detector: TThreeSigmaDetector;
Result: TAnomalyResult;
begin
Detector := TThreeSigmaDetector.Create;
try
// Add historical production data (diameters in mm)
Detector.AddValues([100.2, 99.8, 100.5, 99.9, 100.1, 100.3, 99.7]);
Detector.Build;
// Verify a new measurement
Result := Detector.Detect(105.5);
if Result.IsAnomaly then
ShowMessage('Production anomaly detected!');
finally
Detector.Free;
end;
end;
Sliding Window Detector - Real-time Monitoring
The problem: Your data center hosts critical servers. The ambient temperature must stay between 18°C and 24°C. An air conditioner that fails at night can cause the temperature to rise gradually - and by the time you notice the next morning, the servers have already shut down for thermal protection. You need to detect anomalies in real-time, on a continuous stream of sensor data.
The solution: The Sliding Window Detector maintains a sliding window of fixed size (e.g., last 100 values) and recalculates statistics in real-time. It consumes constant memory and naturally adapts to gradual changes (like day/night transitions).
var
Detector: TSlidingWindowDetector;
Value: Double;
begin
Detector := TSlidingWindowDetector.Create(100); // Window of 100 values
try
// Initialize with baseline
Detector.InitializeWindow([21.5, 21.8, 22.0, 21.7, 21.9, 22.1, 21.6]);
// Process continuous stream from sensor
while HasIncomingData do
begin
Value := GetNextSensorReading;
if Detector.Detect(Value).IsAnomaly then
TriggerAlert('Temperature out of range: ' + Value.ToString + '°C');
Detector.AddValue(Value); // Update window
end;
finally
Detector.Free;
end;
end;
EMA Detector - Rapid Adaptation
The problem: You manage a trading platform. Stock prices change every millisecond and you need to detect anomalous movements instantly - a flash crash, a sudden spike, market manipulation. You can’t afford to keep millions of historical values in memory, and “normality” patterns change continuously throughout the day.
The solution: The Exponential Moving Average gives more weight to recent values, gradually forgetting the past. It consumes constant O(1) memory - literally a few bytes - and is extremely fast (~100k detections/sec). Perfect for ultra-high-frequency scenarios.
var
Detector: TEMAAnomalyDetector;
Price: Double;
begin
Detector := TEMAAnomalyDetector.Create(0.1); // Alpha = sensitivity
try
// Warm-up with normal data
Detector.WarmUp([50.2, 50.5, 49.8, 50.1, 50.3]);
// Monitor stock prices in real-time
for Price in StockPrices do
begin
if Detector.Detect(Price).IsAnomaly then
begin
if Price > Detector.CurrentMean then
LogAlert('Spike detected: ' + Price.ToString)
else
LogAlert('Crash detected: ' + Price.ToString);
end;
Detector.AddValue(Price);
end;
finally
Detector.Free;
end;
end;
Adaptive Detector - Learning Systems
The problem: Your e-commerce site has traffic patterns that change over time. In December the load is 10x compared to February. Black Friday is an anomaly… but it’s an expected anomaly! If the system flags every seasonal spike as anomalous, operators will start ignoring alerts - and when a real problem comes, nobody will notice.
The solution: The Adaptive Detector gradually adapts to new patterns, learning from user feedback. When it flags an anomaly, the operator can confirm “yes, it’s anomalous” or “no, it’s normal” - and the detector learns. Over time it becomes increasingly accurate for your specific context.
var
Detector: TAdaptiveAnomalyDetector;
CPUUsage: Double;
begin
Detector := TAdaptiveAnomalyDetector.Create(30, 0.05); // 30-day window
try
Detector.InitializeWithNormalData([45, 52, 48, 55, 50, 47, 53]);
for var Day := 1 to 365 do
begin
CPUUsage := GetServerCPU;
if Detector.Detect(CPUUsage).IsAnomaly then
begin
if UserConfirms('High CPU: ' + CPUUsage.ToString + '% - Is this normal?') then
Detector.UpdateNormal(CPUUsage) // Teach the detector
else
InvestigateCPUSpike;
end
else
Detector.UpdateNormal(CPUUsage); // Learn automatically
end;
finally
Detector.Free;
end;
end;
Isolation Forest - Multidimensional Machine Learning
The problem: You need to detect credit card fraud. Is a €5,000 transaction suspicious? It depends. If it’s a premium customer who often buys jewelry, no. If it’s a customer who usually spends €50 at the supermarket, yes. And if that transaction happens at 3 AM from a foreign country? “Normality” depends on multiple combined variables - amount, time, location, category, customer history.
The solution: Isolation Forest is an unsupervised machine learning algorithm that identifies anomalies in multidimensional spaces. It builds “isolation trees” that separate points: anomalies, being rare and different, get isolated quickly. It doesn’t require defining rules - it learns from data.
var
Detector: TIsolationForestDetector;
Transaction: TArray<Double>;
begin
Detector := TIsolationForestDetector.Create(100, 256, 5); // 100 trees, 5 features
try
// Training on normal transactions
for var i := 1 to 1000 do
begin
SetLength(Transaction, 5);
Transaction[0] := RandomAmount; // Amount
Transaction[1] := RandomHour; // Hour of day
Transaction[2] := RandomDay; // Day of week
Transaction[3] := RandomCategory; // Category
Transaction[4] := RandomAge; // Customer age
Detector.AddTrainingData(Transaction);
end;
Detector.Train; // Build the model
// Detect suspicious transaction
Transaction := [5000, 3, 2, 5, 35]; // €5000 at 3 AM
if Detector.DetectMultiDimensional(Transaction).IsAnomaly then
FlagForFraudReview('High fraud score!');
finally
Detector.Free;
end;
end;
DBSCAN - Density-Based Clustering
The problem: You manage a retail chain with dozens of registers and cashiers. Internal theft is hard to detect: a dishonest cashier can make fictitious refunds, apply unauthorized discounts, or void items after the customer has paid. You can’t define rigid rules (“never more than 5 refunds per day”) because patterns vary by store, shift, and season. You need a system that learns what’s “normal” for each context.
The solution: DBSCAN (Density-Based Spatial Clustering of Applications with Noise) automatically groups similar behaviors into clusters. Cashiers with normal operating patterns form dense groups; those with anomalous behaviors - too many refunds, excessive discounts, suspicious timing patterns - end up isolated as “noise” and get flagged for review.
var
Detector: TDBSCANDetector;
CashierBehavior: TArray<Double>;
begin
Detector := TDBSCANDetector.Create(
0.3, // Epsilon: neighborhood radius
10 // MinPoints: minimum points to form a cluster
);
try
// Training on historical cashier behaviors
// [refunds_day, avg_discount_%, voided_receipts, avg_amount]
for var i := 1 to 5000 do
begin
CashierBehavior := [
Random(5), // 0-5 refunds/day is normal
Random(8), // 0-8% average discount
Random(3), // 0-3 voided receipts
50 + Random(150) // €50-€200 average amount
];
Detector.AddTrainingData(CashierBehavior);
end;
Detector.Train;
// Analyze a suspicious cashier's behavior
CashierBehavior := [12, 15, 8, 35]; // Too many refunds, high discounts, many voids, low amount
if Detector.DetectMultiDimensional(CashierBehavior).IsAnomaly then
FlagForAudit('Cashier with anomalous operating pattern - verify');
finally
Detector.Free;
end;
end;
Another classic example: supplier orders in an ERP system. Orders follow patterns related to seasonality, typical quantities, and regular suppliers. An order for material never purchased before, to a supplier just added to the database, with unusual amounts and quantities, automatically emerges as an anomaly - a potential sign of procurement fraud or data entry error.
LOF - Local Outlier Factor
The problem: You want to prevent premium customer churn. A customer who buys little is normal if they’re an occasional customer. But if a customer who used to spend €500/month suddenly drops to €50/month, it’s an alarm signal - they’re about to leave you. The problem is that “little” and “a lot” are relative to the customer segment.
The solution: LOF (Local Outlier Factor) compares each point with its “neighbors” in the dataset. A premium customer behaving like an occasional customer has a high LOF - they’re anomalous relative to their reference group, even if their behavior would be normal for other customers.
var
Detector: TLOFDetector;
CustomerBehavior: TArray<Double>;
begin
Detector := TLOFDetector.Create(20); // k=20 neighbors
try
// Training on customer behaviors: [purchases_month, avg_value, login_frequency]
for var i := 1 to 5000 do
begin
CustomerBehavior := [
GetRandomPurchases, // 1-50 purchases/month
GetRandomAvgValue, // €10-€500 average value
GetRandomLoginFreq // 1-30 logins/month
];
Detector.AddTrainingData(CustomerBehavior);
end;
Detector.Train;
// Premium customer suddenly behaving like an occasional one
CustomerBehavior := [2, 450, 1]; // Few purchases but high value, rare login
if Detector.DetectMultiDimensional(CustomerBehavior).IsAnomaly then
FlagForChurnRisk('Possible premium customer churn');
finally
Detector.Free;
end;
end;
Real Use Cases in Business Applications
Let’s look at concrete scenarios where this library can make a difference.
Production Quality Control
In a manufacturing production line, every component must meet precise tolerances. The Three Sigma detector automatically identifies out-of-spec pieces:
type
TQualityController = class
private
FDiameterDetector: TThreeSigmaDetector;
FWeightDetector: TThreeSigmaDetector;
public
procedure CheckComponent(Diameter, Weight: Double);
end;
procedure TQualityController.CheckComponent(Diameter, Weight: Double);
begin
if FDiameterDetector.Detect(Diameter).IsAnomaly then
begin
RejectComponent('Diameter out of tolerance: ' + Diameter.ToString + 'mm');
NotifyQualityTeam;
end;
if FWeightDetector.Detect(Weight).IsAnomaly then
begin
RejectComponent('Weight out of range: ' + Weight.ToString + 'g');
NotifyQualityTeam;
end;
end;
Result: Intercept defects before they reach assembly or the end customer.
Data Center Temperature Monitoring
Critical servers must operate within controlled temperature ranges. The Sliding Window detector monitors sensors in real-time:
type
TDataCenterMonitor = class
private
FSensors: TDictionary<string, TSlidingWindowDetector>;
public
procedure ProcessReading(SensorID: string; Temperature: Double);
end;
procedure TDataCenterMonitor.ProcessReading(SensorID: string; Temperature: Double);
var
Detector: TSlidingWindowDetector;
begin
if not FSensors.TryGetValue(SensorID, Detector) then
begin
Detector := TSlidingWindowDetector.Create(100);
FSensors.Add(SensorID, Detector);
end;
if Detector.Detect(Temperature).IsAnomaly then
begin
TriggerAlert(Format('Sensor %s: anomalous temperature %.1f°C', [SensorID, Temperature]));
if Temperature > 28 then
ActivateEmergencyCooling;
end;
Detector.AddValue(Temperature);
end;
Result: Prevent thermal shutdowns and hardware damage before it’s too late.
Credit Card Fraud Detection
Fraudulent transactions often have anomalous multidimensional patterns. Isolation Forest simultaneously analyzes amount, time, location, and historical behavior:
type
TFraudDetector = class
private
FDetector: TIsolationForestDetector;
public
function CheckTransaction(Amount, Hour, DayOfWeek, Category,
CustomerAge: Double): Boolean;
end;
function TFraudDetector.CheckTransaction(Amount, Hour, DayOfWeek,
Category, CustomerAge: Double): Boolean;
var
Features: TArray<Double>;
begin
Features := [Amount, Hour, DayOfWeek, Category, CustomerAge];
if FDetector.DetectMultiDimensional(Features).IsAnomaly then
begin
Result := False; // Block transaction
FlagForManualReview('Suspicious transaction - high fraud score');
NotifyFraudTeam;
end
else
Result := True;
end;
Result: Block fraud in real-time without impacting legitimate customers.
Retail Cashier Control
Internal theft is hard to detect with fixed rules. DBSCAN automatically identifies cashiers with anomalous operating patterns:
type
TCashierAudit = class
private
FDetector: TDBSCANDetector;
public
procedure AnalyzeCashier(RefundsPerDay, AvgDiscountPct,
VoidedReceipts, AvgTransactionAmount: Double);
end;
procedure TCashierAudit.AnalyzeCashier(RefundsPerDay, AvgDiscountPct,
VoidedReceipts, AvgTransactionAmount: Double);
var
Behavior: TArray<Double>;
begin
Behavior := [RefundsPerDay, AvgDiscountPct, VoidedReceipts, AvgTransactionAmount];
if FDetector.DetectMultiDimensional(Behavior).IsAnomaly then
begin
FlagForAudit('Anomalous operating pattern detected');
GenerateDetailedReport(Behavior);
end;
end;
Result: Detect internal fraud and suspicious behaviors that would escape traditional controls.
Supplier Order Anomalies (ERP)
Purchase orders follow predictable patterns. An anomalous order can indicate fraud, error, or need for verification:
type
TPurchaseOrderValidator = class
private
FDetector: TDBSCANDetector;
public
function ValidateOrder(Amount, Quantity: Double;
SupplierAge, CategoryCode: Integer): Boolean;
end;
function TPurchaseOrderValidator.ValidateOrder(Amount, Quantity: Double;
SupplierAge, CategoryCode: Integer): Boolean;
var
OrderFeatures: TArray<Double>;
begin
// [amount, quantity, supplier_age, merchandise_category]
OrderFeatures := [Amount, Quantity, SupplierAge, CategoryCode];
if FDetector.DetectMultiDimensional(OrderFeatures).IsAnomaly then
begin
Result := MessageDlg(
'Order with unusual characteristics:' + sLineBreak +
Format('Amount: €%.2f, Quantity: %.0f', [Amount, Quantity]) + sLineBreak +
'Requires manual approval. Proceed?',
mtWarning, [mbYes, mbNo], 0) = mrYes;
if not Result then
LogSuspiciousOrder(OrderFeatures);
end
else
Result := True;
end;
Result: Intercept fraudulent orders, data entry errors, and situations requiring verification.
Premium Customer Churn Prevention
Premium customers who change behavior are at risk of leaving. LOF compares each customer with their reference group:
type
TChurnPredictor = class
private
FDetector: TLOFDetector;
public
procedure AnalyzeCustomer(PurchasesPerMonth, AvgOrderValue,
LoginFrequency: Double; CustomerID: Integer);
end;
procedure TChurnPredictor.AnalyzeCustomer(PurchasesPerMonth, AvgOrderValue,
LoginFrequency: Double; CustomerID: Integer);
var
Behavior: TArray<Double>;
begin
Behavior := [PurchasesPerMonth, AvgOrderValue, LoginFrequency];
if FDetector.DetectMultiDimensional(Behavior).IsAnomaly then
begin
// Premium customer with occasional customer behavior
FlagChurnRisk(CustomerID, 'High churn risk');
TriggerRetentionCampaign(CustomerID);
NotifyAccountManager(CustomerID);
end;
end;
Result: Intervene proactively before valuable customers leave.
High-Frequency Trading Monitoring
Trading systems must detect anomalies in milliseconds. The EMA detector is optimized for ultra-high-frequency scenarios:
type
TTradingMonitor = class
private
FPriceDetector: TEMAAnomalyDetector;
FVolumeDetector: TEMAAnomalyDetector;
public
procedure CheckMarketData(Price, Volume: Double);
end;
procedure TTradingMonitor.CheckMarketData(Price, Volume: Double);
begin
if FPriceDetector.Detect(Price).IsAnomaly then
begin
if Price > FPriceDetector.CurrentMean * 1.1 then
LogAlert('SPIKE: price +10% in one tick')
else if Price < FPriceDetector.CurrentMean * 0.9 then
LogAlert('CRASH: price -10% in one tick');
PauseAutomatedTrading; // Protection
end;
if FVolumeDetector.Detect(Volume).IsAnomaly then
LogAlert('Anomalous volume: possible manipulation');
FPriceDetector.AddValue(Price);
FVolumeDetector.AddValue(Volume);
end;
Result: Protect your algorithms from flash crashes and market manipulation.
E-commerce Seasonal Adaptation
E-commerce traffic varies drastically throughout the year. The Adaptive detector learns seasonal patterns:
type
TEcommerceMonitor = class
private
FTrafficDetector: TAdaptiveAnomalyDetector;
public
procedure ProcessDailyTraffic(Visitors: Integer);
end;
procedure TEcommerceMonitor.ProcessDailyTraffic(Visitors: Integer);
begin
if FTrafficDetector.Detect(Visitors).IsAnomaly then
begin
// Ask operator for confirmation
if IsExpectedPeak then // Black Friday, Christmas, etc.
begin
FTrafficDetector.UpdateNormal(Visitors); // Learn
LogInfo('Expected peak confirmed');
end
else
begin
InvestigateTrafficAnomaly;
LogWarning('Unexpected traffic anomaly');
end;
end
else
FTrafficDetector.UpdateNormal(Visitors);
end;
Result: The system learns your seasonal patterns and stops flagging false positives.
Data Entry Validation - Preventing Human Errors
Imagine a business system where operators enter invoices. With anomaly detection you can alert them in real-time about suspicious amounts:
type
TInvoiceValidator = class
private
FDetectors: TDictionary<string, TSlidingWindowDetector>;
public
function ValidateAmount(SupplierCode: string; Amount: Double): Boolean;
end;
function TInvoiceValidator.ValidateAmount(SupplierCode: string;
Amount: Double): Boolean;
var
Detector: TSlidingWindowDetector;
begin
// One detector per supplier
if not FDetectors.TryGetValue(SupplierCode, Detector) then
begin
Detector := TSlidingWindowDetector.Create(50);
FDetectors.Add(SupplierCode, Detector);
end;
if Detector.Detect(Amount).IsAnomaly then
begin
Result := MessageDlg(
Format('Unusual amount for %s: €%.2f' + sLineBreak +
'Confirm entry?', [SupplierCode, Amount]),
mtWarning, [mbYes, mbNo], 0) = mrYes;
end
else
Result := True;
if Result then
Detector.AddValue(Amount); // Learn
end;
Result: Reduce typos (€10,000 instead of €1,000), duplicate amounts, price anomalies.
DDoS Alert System
Protect your web services from distributed attacks:
var
TrafficDetector: TSlidingWindowDetector;
begin
TrafficDetector := TSlidingWindowDetector.Create(60); // 1 minute
while ServiceRunning do
begin
RequestsPerSecond := GetCurrentRPS;
if TrafficDetector.Detect(RequestsPerSecond).IsAnomaly then
begin
LogSecurity('Possible DDoS: ' + RequestsPerSecond.ToString + ' req/s');
EnableRateLimiting;
NotifySecurityTeam;
end;
TrafficDetector.AddValue(RequestsPerSecond);
Sleep(1000);
end;
end;
Knight Capital Scenario - The 440 Million Dollar Lesson
In my ITDevCon talk I told the story of Knight Capital Group (2012): a software bug generated anomalous orders for 45 minutes, causing a loss of 440 million dollars and the company’s bankruptcy.
With anomaly detection this disaster would have been avoidable:
var
OrderVolumeDetector: TEMAAnomalyDetector;
OrderFrequencyDetector: TSlidingWindowDetector;
begin
OrderVolumeDetector := TEMAAnomalyDetector.Create(0.05);
OrderFrequencyDetector := TSlidingWindowDetector.Create(100);
// Before every order
if OrderVolumeDetector.IsAnomaly(OrderVolume) or
OrderFrequencyDetector.IsAnomaly(OrdersPerSecond) then
begin
LogCritical('TRADING ANOMALY DETECTED!');
HaltTradingSystem;
NotifyRiskManagement;
Exit; // Block the order
end;
// Process normal order...
end;
A simple check would have saved the company.
IoT Monitoring and Predictive Maintenance
Industrial sensors that predict failures before they happen:
type
TSensorMonitor = class
private
FTempDetector: TEMAAnomalyDetector;
FVibrationDetector: TAdaptiveAnomalyDetector;
FPressureDetector: TSlidingWindowDetector;
public
procedure ProcessSensorData(Temp, Vibration, Pressure: Double);
end;
procedure TSensorMonitor.ProcessSensorData(Temp, Vibration, Pressure: Double);
begin
if FTempDetector.IsAnomaly(Temp) then
ScheduleMaintenance('Anomalous motor temperature');
if FVibrationDetector.IsAnomaly(Vibration) then
ScheduleMaintenance('Excessive bearing vibrations');
if FPressureDetector.IsAnomaly(Pressure) then
ScheduleMaintenance('Hydraulic pressure out of range');
// Update models
FTempDetector.AddValue(Temp);
FVibrationDetector.UpdateNormal(Vibration);
FPressureDetector.AddValue(Pressure);
end;
Result: Reduce machine downtime, prevent catastrophic failures, optimize maintenance.
Evaluation and Optimization
The library includes a complete framework for evaluating detector accuracy and automatically optimizing parameters.
Evaluation Framework
If you have labeled data (you know which are real anomalies), you can measure performance:
uses AnomalyDetection.Evaluation;
var
Dataset: TLabeledDataset;
Evaluator: TAnomalyDetectorEvaluator;
Result: TEvaluationResult;
begin
Dataset := TLabeledDataset.Create('Test Production Data');
Dataset.LoadFromCSV('sensor_data.csv', 0, 1, True);
Detector := TSlidingWindowDetector.Create(100);
Evaluator := TAnomalyDetectorEvaluator.Create(Detector, Dataset);
try
Result := Evaluator.Evaluate;
WriteLn('Accuracy: ', Result.ConfusionMatrix.GetAccuracy:0:3);
WriteLn('Precision: ', Result.ConfusionMatrix.GetPrecision:0:3);
WriteLn('Recall: ', Result.ConfusionMatrix.GetRecall:0:3);
WriteLn('F1-Score: ', Result.ConfusionMatrix.GetF1Score:0:3);
finally
Evaluator.Free;
end;
end;
Automatic Hyperparameter Tuning
Automatically find optimal parameters:
var
Tuner: THyperparameterTuner;
BestConfig: TTuningResult;
begin
Tuner := THyperparameterTuner.Create(adtThreeSigma, Dataset);
try
Tuner.OptimizationMetric := 'F1';
// Test all combinations
BestConfig := Tuner.GridSearch(
[2.0, 2.5, 3.0, 3.5], // Sigma values to test
nil, nil, nil
);
ShowMessage(Format('Best sigma: %.2f (F1: %.3f)',
[BestConfig.Config.SigmaMultiplier, BestConfig.Score]));
finally
Tuner.Free;
end;
end;
The library automatically tests dozens of combinations and tells you which is best for your data.
Getting Started
Clone the repository:
git clone https://github.com/danieleteti/delphi-anomalies-detectors.git
Add the units to your project and use the factory pattern to get started immediately:
uses
AnomalyDetection.Types, AnomalyDetection.Factory;
var
Detector: IAnomalyDetector;
begin
// Factory pre-configured for your scenario
Detector := Factory.CreateForFinancialData; // Financial data
// Detector := Factory.CreateForWebTrafficMonitoring; // Web security
// Detector := Factory.CreateForIoTSensors; // IoT sensors
Detector.AddValues([100, 105, 98, 102, 107, 99, 103]);
Detector.Build;
if Detector.IsAnomaly(150) then
ShowMessage('Anomaly detected!');
end;
The repository includes complete demos for each algorithm in the Samples\ folder, a suite of 84 DUnitX tests with 100% coverage, and follows SOLID principles for maximum extensibility. All detectors are thread-safe and optimized for production environments (~20k to ~100k detections/sec depending on the algorithm).
Conclusions
Anomaly detection is no longer the exclusive domain of data scientists and large corporations. With this library you can integrate intelligence into your Delphi applications in minutes, preventing errors, fraud, failures, and critical situations.
The library is the result of months of work, literature research, implementation, and testing. It was designed to be production-ready from day one: thread-safe, performant, tested, and documented.
Whether you’re developing an ERP, an industrial monitoring system, a financial platform, or an IoT application, anomaly detection can make the difference between a reactive system (that discovers problems afterward) and a proactive one (that prevents them).
The library is open source and free (Apache 2.0 license). 🎓 A dedicated course is in preparation on how to use the library and apply anomaly detection algorithms in your projects. 📄 Additionally, an exclusive Paper for AllAccess+ supporters on Patreon will be released soon, with technical deep-dives, algorithm comparisons, and advanced guides.
🏢 For business needs - training, workshops, consulting, or enterprise support - bit Time Professionals offers training and consulting services in Italian, English, and Spanish: professionals@bittime.it | www.bittimeprofessionals.com
Frequently Asked Questions (FAQ)
What is anomaly detection?
Anomaly detection is a set of techniques that automatically identify data, events, or behaviors that deviate significantly from the normal pattern. It’s used to detect fraud, failures, data entry errors, security intrusions, and any “out of the ordinary” situation.
What anomaly detection algorithms are available in the Delphi library?
The library implements 7 algorithms:
- Three Sigma - Classic statistical control based on mean and standard deviation
- Sliding Window - Real-time monitoring with sliding window
- EMA (Exponential Moving Average) - Rapid adaptation for high-frequency data
- Adaptive Detector - System that learns from user feedback
- Isolation Forest - Machine learning for multidimensional anomalies
- DBSCAN - Density-based clustering for complex patterns
- LOF (Local Outlier Factor) - Comparison with local neighbors in the dataset
Which anomaly detection algorithm should I use?
The choice depends on the scenario:
- Three Sigma: Quality control, normally distributed data
- Sliding Window: Sensor monitoring, continuous data streams
- EMA: High-frequency trading, rapidly changing data
- Adaptive: Systems with seasonality, evolving patterns
- Isolation Forest: Fraud detection, multi-variable transactions
- DBSCAN: Behavioral clustering, cashier/user analysis
- LOF: Churn prediction, comparison between customer groups
Is the library free?
Yes, the Delphi Anomaly Detection Library is completely open source and free under the Apache 2.0 license. You can use it in commercial projects without restrictions.
Can anomaly detection be used in real-time?
Yes. The Sliding Window, EMA, and Adaptive algorithms are optimized for real-time processing on data streams. They support throughput from 20,000 to 100,000 detections per second.
Do I need machine learning knowledge to use the library?
No. The library includes pre-configured factories for common scenarios (financial data, IoT sensors, web traffic) that allow you to start without knowing the algorithm details. For those who want to dive deeper, complete documentation and a dedicated course are available.
In which industries is anomaly detection used?
The most common use cases include:
- Finance: Credit card fraud, anomalous trading
- Retail: Internal theft, suspicious cashier behavior
- Manufacturing: Quality control, predictive maintenance
- IT: Security (DDoS, intrusions), server monitoring
- Healthcare: Anomalous vital signs, dosage errors
- ERP: Data entry validation, suspicious orders
🔗 GitHub Repository: github.com/danieleteti/delphi-anomalies-detectors
📖 Complete documentation available in the repository
💬 Questions? Open an issue on GitHub
Daniele Teti
Comments
comments powered by Disqus