Anomaly Detection in Python
Bekhruz (Bex) Tuychiev
Kaggle Master, Data Science Content Creator

from statsmodels.tsa.seasonal import seasonal_decompose
results = seasonal_decompose(google['Open'], period=365)
print(results)
<statsmodels.tsa.seasonal.DecomposeResult object at 0x7f0a67fac820>
results.seasonal.plot(color="red", figsize=(12, 4))



results.trend.plot(color="red", figsize=(12, 4))


results.resid.plot(color="red", figsize=(12, 4))

figure = results.plot()
figure.set_figwidth(12)
figure.set_figheight(8)

# Extract and reshape residuals results = seasonal_decompose(google['Volume'], period=365) residuals = results.resid residuals = residuals.values.reshape(-1, 1)# Fit MAD mad = MAD().fit(residuals)# Find the outliers is_outlier = mad.labels_ == 1 outliers = google[is_outlier] print(len(outliers))
81
Anomaly Detection in Python