| title | app_file | sdk | sdk_version |
|---|---|---|---|
git_config_-global_credential.helper_store |
gradio_trends_mcp.py |
gradio |
5.32.0 |
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.
- ๐ 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
Python 3.8+
pip package manager-
Clone or download the
gradio_trends_mcp.pyfile -
Install dependencies:
pip install gradio pandas numpy plotly scipy scikit-learn- Run the application:
python gradio_trends_mcp.py- Access the interface:
- Open your browser to
http://localhost:7860 - The MCP server runs automatically in the background
- Open your browser to
-
Upload Data:
- Drag & drop CSV or Excel files
- Supported formats:
.csv,.xlsx,.xls
-
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 methodisolation: DBSCAN clustering approach
-
View Results:
- Comprehensive analysis report in Markdown
- 6 interactive visualizations
- Unique analysis ID for future reference
The application provides three main MCP functions accessible through the "MCP Functions" tab or external MCP clients:
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 */ }
}Retrieves a formatted report from a previous analysis.
Parameters:
{
"analysis_id": "analysis_20241201_143022"
}Returns: Markdown-formatted detailed report
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
}- 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
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
- 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
- Prominence-Based: Uses scipy's
find_peakswith prominence thresholds - Adaptive Filtering: Based on data standard deviation
- Comprehensive Counts: Tracks both peaks and valleys
- Linear Regression: Simple trend-based forecasting
- Confidence Intervals: 95% prediction bands
- Model Metrics: R-squared goodness of fit
- Trend Projection: Extrapolates historical trends
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- Support for
.xlsxand.xlsformats - First row should contain column headers
- Numeric data in the target column
- Automatic detection of
dateorfechacolumns - Supports various date formats
- Falls back to sequential indexing if no dates provided
The application generates 6 interactive Plotly charts:
- Original Time Series: Raw data with full interactivity
- Trend Analysis: Original vs. smoothed data
- Anomaly Detection: Highlighted anomalous points
- Peaks & Valleys: Marked extrema with symbols
- Forecasting: Historical data + predictions + confidence bands
- Distribution: Histogram of value distribution
All charts support:
- Zoom and pan
- Hover information
- Legend interaction
- Export capabilities
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
gradio>=5.0.0
pandas>=1.3.0
numpy>=1.21.0
plotly>=5.17.0
scipy>=1.7.0
scikit-learn>=1.0.0The 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.
- Upload a CSV file with sales data
- Set column name to "sales"
- Use default settings (window=7, method="zscore", periods=30)
- Click "Analyze Time Series"
- Review the 6-chart visualization and detailed report
# 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# 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"
}
)python gradio_trends_mcp.py
# Access at http://localhost:7860# 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
)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"]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
- Fork the repository
- Create a feature branch
- Implement changes with proper error handling
- Test with various data formats
- Submit pull request with description
MIT License - see LICENSE file for details.
- 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
Built with โค๏ธ for the data analysis community
For questions, issues, or feature requests, please open an issue in the repository.