import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import IsolationForest
# ==========================================
# 1. Generate Synthetic Time-Series Data
# ==========================================
def generate_data(n=200):
np.random.seed(42)
# Create a time range
time_steps = pd.date_range(start='2023-01-01', periods=n, freq='D')
# Generate a sine wave with some noise (Seasonality + Noise)
values = np.sin(np.linspace(0, 20, n)) + np.random.normal(scale=0.2, size=n)
# Create a DataFrame
df = pd.DataFrame({'timestamp': time_steps, 'value': values})
# Inject artificial anomalies (Spikes and Dips)
df.loc[40, 'value'] = 3.5 # High spike
df.loc[150, 'value'] = -3.0 # Low dip
df.loc[160:163, 'value'] = 2.5 # Clustered anomalies
return df.set_index('timestamp')
# ==========================================
# 2. Method A: Statistical (Rolling Z-Score)
# ==========================================
def statistical_anomaly_detection(df, window=10, threshold=3.0):
"""
Detects anomalies based on deviation from a moving average.
If a point is 'threshold' standard deviations away from the rolling mean, it is an anomaly.
"""
# Calculate rolling mean and standard deviation
rolling_mean = df['value'].rolling(window=window).mean()
rolling_std = df['value'].rolling(window=window).std()
# Calculate Z-Score
# Note: We fill NaN created by rolling window with 0 to avoid errors at the start
df['z_score'] = (df['value'] - rolling_mean) / rolling_std
# Flag anomalies
df['stat_anomaly'] = df['z_score'].abs() > threshold
return df
# ==========================================
# 3. Method B: Machine Learning (Isolation Forest)
# ==========================================
def ml_anomaly_detection(df, contamination=0.05):
"""
Uses an ensemble method (Isolation Forest) to isolate anomalies.
Good for multidimensional or non-gaussian data.
"""
# Prepare data (sklearn expects 2D array)
data = df[['value']].values
# Initialize model
# contamination: expected proportion of outliers in the dataset
model = IsolationForest(contamination=contamination, random_state=42)
# Fit and predict (-1 is anomaly, 1 is normal)
df['ml_pred'] = model.fit_predict(data)
# Convert to boolean (True if anomaly)
df['ml_anomaly'] = df['ml_pred'] == -1
return df
# ==========================================
# 4. Main Execution and Visualization
# ==========================================
if __name__ == "__main__":
# Generate Data
df = generate_data()
# Apply Detection
df = statistical_anomaly_detection(df, window=7, threshold=2.5)
df = ml_anomaly_detection(df, contamination=0.04)
# Plotting
fig, ax = plt.subplots(2, 1, figsize=(12, 10), sharex=True)
# Plot 1: Statistical Method
ax[0].plot(df.index, df['value'], label='Data', color='blue', alpha=0.6)
# Highlight Statistical Anomalies
anomalies_stat = df[df['stat_anomaly']]
ax[0].scatter(anomalies_stat.index, anomalies_stat['value'], color='red', label='Anomaly', zorder=5)
ax[0].set_title('Method 1: Statistical (Rolling Z-Score)')
ax[0].legend()
ax[0].grid(True, linestyle='--', alpha=0.6)
# Plot 2: Machine Learning Method
ax[1].plot(df.index, df['value'], label='Data', color='green', alpha=0.6)
# Highlight ML Anomalies
anomalies_ml = df[df['ml_anomaly']]
ax[1].scatter(anomalies_ml.index, anomalies_ml['value'], color='red', label='Anomaly', zorder=5)
ax[1].set_title('Method 2: Machine Learning (Isolation Forest)')
ax[1].legend()
ax[1].grid(True, linestyle='--', alpha=0.6)
plt.show()
# Print identified anomalies
print("Statistical Anomalies Found:")
print(anomalies_stat[['value']])
print("\nMachine Learning Anomalies Found:")
print(anomalies_ml[['value']])