Lightweight Network Anomaly Detector

import numpy as np

class AnomalyDetector:
    def __init__(self, window=50, threshold=3.0):
        self.window = window
        self.threshold = threshold
        self.history = []

    def update(self, value):
        self.history.append(value)
        if len(self.history) < self.window:
            return False, 0.0  # not enough data yet

        window_data = np.array(self.history[-self.window:])
        mean = window_data.mean()
        std = window_data.std() + 1e-6

        z = (value - mean) / std
        alert = abs(z) > self.threshold
        return alert, z

if __name__ == "__main__":
    detector = AnomalyDetector()

    # fake inbound traffic samples
    import random
    for i in range(200):
        v = random.gauss(100, 5)
        if i == 150:
            v = 180  # simulated attack spike

        alert, score = detector.update(v)
        if alert:
            print(f"ALERT: t={i}, traffic={v}, z={score:.2f}")

Leave a Reply

Your email address will not be published. Required fields are marked *