#!/usr/bin/env python3
"""Auto-generated by AGI Loop cycle #1043
Task: Write a Python function that generates random timeseries data and detects anomalies using z-score
Generated: 2026-02-12T18:03:26.832715
"""

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import zscore

def generate_and_analyze_timeseries(length=100, anomaly_points=3):
    # Generate random time series data
    np.random.seed(42)
    data = np.random.normal(loc=10, scale=2, size=length)
    
    # Introduce anomalies
    anomaly_indices = np.random.choice(length, size=anomaly_points, replace=False)
    for idx in anomaly_indices:
        data[idx] += 10  # Add a big jump as an anomaly
    
    # Compute z-scores
    z_scores = zscore(data)
    
    # Detect anomalies using z-score threshold (e.g., |z| > 2)
    threshold = 2
    anomalies = np.where(np.abs(z_scores) > threshold)[0]
    
    # Plot data with anomalies highlighted
    plt.figure(figsize=(12, 6))
    plt.plot(data, label='Time Series')
    plt.scatter(anomalies, data[anomalies], color='red', label='Anomalies')
    plt.axhline(y=threshold, color='green', linestyle='--', label='Z-score threshold')
    plt.axhline(y=-threshold, color='green', linestyle='--')
    plt.title('Time Series with Anomalies Detected using Z-score')
    plt.legend()
    plt.show()
    
    # Print detected anomalies
    print(f"Detected anomalies at indices: {anomalies}")
    print(f"Anomaly values: {data[anomalies]}")
    print(f"Z-scores of anomalies: {z_scores[anomalies]}")

if __name__ == '__main__':
    generate_and_analyze_timeseries(length=100, anomaly_points=3)