Spaces:
Sleeping
Sleeping
| title: TS_Analysis | |
| app_file: app.py | |
| sdk: gradio | |
| sdk_version: 5.32.0 | |
| tag: mcp-server-track | |
| # 📈 Gradio MCP Time Series Trends Analyzer | |
| [](https://python.org) | |
| [](https://gradio.app) | |
| [](https://modelcontextprotocol.io) | |
| [](https://plotly.com) | |
| [](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 | |
| ## Demostration Video | |
| [Demo](https://youtu.be/tKOnjcp--cI) | |
| ## 🚀 Quick Start | |
| ### Prerequisites | |
| ```bash | |
| Python 3.8+ | |
| pip package manager | |
| ``` | |
| ### Installation | |
| 1. **Clone or download** the `gradio_trends_mcp.py` file | |
| 2. **Install dependencies**: | |
| ```bash | |
| pip install gradio pandas numpy plotly scipy scikit-learn | |
| ``` | |
| 3. **Run the application**: | |
| ```bash | |
| python gradio_trends_mcp.py | |
| ``` | |
| 4. **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:** | |
| ```json | |
| { | |
| "data": [100, 105, 98, 110, 115, 102, 120], | |
| "dates": ["2024-01-01", "2024-01-02", ...], // optional | |
| "window": 7, | |
| "anomaly_method": "zscore" | |
| } | |
| ``` | |
| **Returns:** | |
| ```json | |
| { | |
| "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:** | |
| ```json | |
| { | |
| "analysis_id": "analysis_20241201_143022" | |
| } | |
| ``` | |
| **Returns:** Markdown-formatted detailed report | |
| #### 3. `forecast_series` | |
| Generates forecasts with confidence intervals. | |
| **Parameters:** | |
| ```json | |
| { | |
| "data": [100, 105, 98, 110, 115], | |
| "periods": 30 | |
| } | |
| ``` | |
| **Returns:** | |
| ```json | |
| { | |
| "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 | |
| ```csv | |
| 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**: | |
| ```python | |
| 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 | |
| ```txt | |
| 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 | |
| ```python | |
| # 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 | |
| ```python | |
| # 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 | |
| ```bash | |
| python gradio_trends_mcp.py | |
| # Access at http://localhost:7860 | |
| ``` | |
| ### Production Deployment | |
| ```bash | |
| # 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 | |
| ```dockerfile | |
| 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 | |
| - [Gradio Documentation](https://gradio.app/docs) | |
| - [MCP Specification](https://modelcontextprotocol.io) | |
| - [Plotly Python](https://plotly.com/python/) | |
| - [Time Series Analysis Guide](https://www.statsmodels.org/stable/tsa.html) | |
| --- | |
| **Built with ❤️ for the data analysis community** | |
| For questions, issues, or feature requests, please open an issue in the repository. |