Skip to content

carperca23/time_series_analysis

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

2 Commits
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

title app_file sdk sdk_version
git_config_-global_credential.helper_store
gradio_trends_mcp.py
gradio
5.32.0

๐Ÿ“ˆ Gradio MCP Time Series Trends Analyzer

Python Gradio MCP Plotly License

A comprehensive Gradio 5 web application with integrated Model Context Protocol (MCP) capabilities for advanced time series analysis. Features automatic trend detection, anomaly identification, seasonal pattern analysis, and forecasting with interactive visualizations.

๐ŸŒŸ Key Features

  • ๐ŸŒ Web Interface: Interactive Gradio 5 dashboard with file upload
  • ๐Ÿค– MCP Integration: Built-in MCP server functions for programmatic access
  • ๐Ÿ“Š Advanced Analysis:
    • Trend detection with configurable smoothing
    • Multi-method anomaly detection (Z-score, IQR, DBSCAN)
    • Seasonal pattern recognition
    • Peak and valley identification
    • Linear forecasting with confidence intervals
  • ๐Ÿ“ˆ Rich Visualizations: 6 interactive Plotly charts in a single view
  • ๐Ÿ“ File Support: CSV and Excel file processing
  • ๐Ÿ” Real-time Analysis: Instant results with detailed reports

๐Ÿš€ Quick Start

Prerequisites

Python 3.8+
pip package manager

Installation

  1. Clone or download the gradio_trends_mcp.py file

  2. Install dependencies:

pip install gradio pandas numpy plotly scipy scikit-learn
  1. Run the application:
python gradio_trends_mcp.py
  1. Access the interface:
    • Open your browser to http://localhost:7860
    • The MCP server runs automatically in the background

๐ŸŽฏ Usage Guide

๐Ÿ“Š Web Interface Analysis

  1. Upload Data:

    • Drag & drop CSV or Excel files
    • Supported formats: .csv, .xlsx, .xls
  2. Configure Analysis:

    • Column Name: Specify which column to analyze (e.g., "sales", "temperature")
    • Trend Window: Set smoothing window (3-30 periods)
    • Forecast Periods: Number of future periods to predict (5-100)
    • Anomaly Method: Choose detection algorithm:
      • zscore: Standard deviation based (default)
      • iqr: Interquartile range method
      • isolation: DBSCAN clustering approach
  3. View Results:

    • Comprehensive analysis report in Markdown
    • 6 interactive visualizations
    • Unique analysis ID for future reference

๐Ÿค– MCP Functions

The application provides three main MCP functions accessible through the "MCP Functions" tab or external MCP clients:

1. analyze_trends

Performs comprehensive time series analysis.

Parameters:

{
  "data": [100, 105, 98, 110, 115, 102, 120],
  "dates": ["2024-01-01", "2024-01-02", ...],  // optional
  "window": 7,
  "anomaly_method": "zscore"
}

Returns:

{
  "analysis_id": "mcp_analysis_20241201_143022",
  "summary": {
    "total_points": 100,
    "anomalies_detected": 5,
    "peaks_count": 12,
    "valleys_count": 8,
    "trend_strength": 0.0245
  },
  "results": { /* detailed analysis results */ }
}

2. get_analysis_report

Retrieves a formatted report from a previous analysis.

Parameters:

{
  "analysis_id": "analysis_20241201_143022"
}

Returns: Markdown-formatted detailed report

3. forecast_series

Generates forecasts with confidence intervals.

Parameters:

{
  "data": [100, 105, 98, 110, 115],
  "periods": 30
}

Returns:

{
  "forecast_values": [118.2, 121.5, 124.8, ...],
  "confidence_upper": [125.1, 128.9, 132.7, ...],
  "confidence_lower": [111.3, 114.1, 116.9, ...],
  "r_squared": 0.85,
  "trend_slope": 3.2
}

๐Ÿ“Š Analysis Capabilities

๐Ÿ” Trend Detection

  • Moving Average Smoothing: Configurable window size (3-30 periods)
  • Slope Analysis: Calculates trend strength and direction
  • Classification: Categorizes periods as increasing, decreasing, or stable
  • Trend Strength: Quantifies overall trend consistency

โš ๏ธ Anomaly Detection

Z-Score Method (Default):

  • Identifies points >2.5 standard deviations from mean
  • Best for normally distributed data

IQR Method:

  • Uses interquartile range (Q1-1.5ร—IQR, Q3+1.5ร—IQR)
  • Robust against outliers

Isolation Method:

  • DBSCAN clustering to identify outliers
  • Effective for complex patterns

๐Ÿ“… Seasonality Analysis

  • Multiple Periods: Tests for 7, 30, and 365-period cycles
  • Autocorrelation: Measures periodic strength
  • Pattern Detection: Identifies recurring seasonal patterns
  • Strength Quantification: Measures seasonal influence

๐Ÿ“ˆ Peak & Valley Detection

  • Prominence-Based: Uses scipy's find_peaks with prominence thresholds
  • Adaptive Filtering: Based on data standard deviation
  • Comprehensive Counts: Tracks both peaks and valleys

๐Ÿ”ฎ Forecasting

  • Linear Regression: Simple trend-based forecasting
  • Confidence Intervals: 95% prediction bands
  • Model Metrics: R-squared goodness of fit
  • Trend Projection: Extrapolates historical trends

๐Ÿ“ Data Format Requirements

CSV Files

date,sales,temperature,traffic
2024-01-01,1000,25.5,150
2024-01-02,1050,26.1,175
2024-01-03,980,24.8,145

Excel Files

  • Support for .xlsx and .xls formats
  • First row should contain column headers
  • Numeric data in the target column

Date Handling

  • Automatic detection of date or fecha columns
  • Supports various date formats
  • Falls back to sequential indexing if no dates provided

๐ŸŽจ Visualization Features

The application generates 6 interactive Plotly charts:

  1. Original Time Series: Raw data with full interactivity
  2. Trend Analysis: Original vs. smoothed data
  3. Anomaly Detection: Highlighted anomalous points
  4. Peaks & Valleys: Marked extrema with symbols
  5. Forecasting: Historical data + predictions + confidence bands
  6. Distribution: Histogram of value distribution

All charts support:

  • Zoom and pan
  • Hover information
  • Legend interaction
  • Export capabilities

๐Ÿ”ง Technical Implementation

Core Components

TrendsAnalyzer Class:

class TrendsAnalyzer:
    def detect_trends(self, data, window=7)
    def detect_anomalies(self, data, method="zscore")
    def detect_seasonality(self, data, periods=[7,30,365])
    def find_peaks_valleys(self, data)
    def generate_forecast(self, data, periods=30)

Global Analysis Store:

  • In-memory storage for analysis results
  • Unique ID generation for session tracking
  • Enables report retrieval and result persistence

MCP Integration:

  • Built-in MCP server capabilities with Gradio 5
  • Programmatic access to all analysis functions
  • JSON-based parameter passing and result return

Dependencies

gradio>=5.0.0
pandas>=1.3.0
numpy>=1.21.0
plotly>=5.17.0
scipy>=1.7.0
scikit-learn>=1.0.0

๐Ÿšจ Error Handling

The application includes comprehensive error handling for:

  • File Format Issues: Unsupported file types, corrupted files
  • Column Validation: Missing or invalid column names
  • Data Quality: Insufficient data points, all-NaN series
  • Analysis Errors: Invalid parameters, calculation failures
  • MCP Errors: JSON parsing issues, parameter validation

Error messages are user-friendly and provide actionable guidance.

๐Ÿ” Usage Examples

Basic Web Analysis

  1. Upload a CSV file with sales data
  2. Set column name to "sales"
  3. Use default settings (window=7, method="zscore", periods=30)
  4. Click "Analyze Time Series"
  5. Review the 6-chart visualization and detailed report

MCP Function Usage

# Through the web interface MCP tab
data_input = '[100, 105, 98, 110, 115, 102, 120, 130, 125, 135]'
# Returns comprehensive analysis with ID

# Get detailed report
analysis_id = 'mcp_analysis_20241201_143022'
# Returns formatted Markdown report

# Generate forecast
forecast_data = '[120, 125, 130, 135, 140]'
periods = 10
# Returns forecast with confidence intervals

Integration with External MCP Clients

# Example with Claude or other MCP clients
response = await mcp_client.call_function(
    "analyze_trends",
    {
        "data": [1000, 1050, 980, 1100, 1150],
        "window": 5,
        "anomaly_method": "iqr"
    }
)

๐Ÿš€ Deployment Options

Local Development

python gradio_trends_mcp.py
# Access at http://localhost:7860

Production Deployment

# With custom port and host
GRADIO_SERVER_PORT=8080 python gradio_trends_mcp.py

# Or modify the launch parameters in main()
interface.launch(
    server_port=8080,
    server_name="0.0.0.0",
    share=True  # For temporary public access
)

Docker Deployment

FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY gradio_trends_mcp.py .
EXPOSE 7860
CMD ["python", "gradio_trends_mcp.py"]

๐Ÿค Contributing

Contributions are welcome! Areas for enhancement:

  • Additional forecasting models (ARIMA, Prophet, LSTM)
  • More anomaly detection algorithms
  • Export functionality (PDF reports, CSV results)
  • Database connectivity options
  • Advanced statistical tests
  • Multi-variate time series support
  • Real-time data streaming
  • Custom visualization themes

Development Workflow

  1. Fork the repository
  2. Create a feature branch
  3. Implement changes with proper error handling
  4. Test with various data formats
  5. Submit pull request with description

๐Ÿ“„ License

MIT License - see LICENSE file for details.

๐Ÿ™ Acknowledgments

  • Gradio Team - Amazing web interface framework
  • Plotly - Interactive visualization library
  • MCP Community - Model Context Protocol development
  • SciPy/NumPy - Scientific computing foundations
  • scikit-learn - Machine learning algorithms

๐Ÿ”— Related Resources


Built with โค๏ธ for the data analysis community

For questions, issues, or feature requests, please open an issue in the repository.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages