YAML Metadata Warning:empty or missing yaml metadata in repo card
Check out the documentation for more information.
- TradeNest AI
- π― Core Philosophy
- ποΈ Architecture
- π Visualization Pipeline
- π Quick Start
- π¨ Beautiful Gradio Interface
- π‘ API Endpoints
- π Response Format (MANDATORY)
- π Visualization Details
- π§ Explainability Rules
- π Data Handling
- π οΈ Development
- π Example Usage
- π¨ Visualization Pipeline Flow
- β οΈ Important Notes
- π Dependencies
- π¦ Status
- π License
- π― Core Philosophy
TradeNest AI
Production-Ready AI Trade Intelligence Platform
TradeNest AI is a standalone AI trade intelligence platform that provides predictive analytics, clear business explanations, and visual insights (charts and graphs) for every analysis.
π― Core Philosophy
Every analytical response MUST return:
- β Structured explanation (text)
- β At least one graph
- β At least one pie or distribution chart (when applicable)
No prediction is valid without visual support.
ποΈ Architecture
TradeNest AI
β
βββ api/
β βββ routes.py # API endpoints
βββ core/
βββ models/
βββ preprocessing/
βββ schemas/
β βββ request_schemas.py # Request validation
β βββ response_schemas.py # Response models
βββ services/
β βββ prediction_service.py # ML predictions
β βββ explanation_service.py # Business explanations
β βββ visualization_service.py # Chart orchestration
β βββ web_data_service.py # Optional web/data enrichment
βββ visualizations/
β βββ line_charts.py # Line chart generation
β βββ bar_charts.py # Bar chart generation
β βββ pie_charts.py # Pie chart generation
βββ storage/
βββ utils/
βββ main.py # FastAPI application
π Visualization Pipeline
Technology Stack
- Matplotlib: Production-safe, backend-friendly visualization library
- Base64 Encoding: Charts returned as Base64 strings in JSON responses
- Non-interactive Backend: Uses
Aggbackend for server environments
Chart Types by Analysis
1οΈβ£ Demand Forecasting
- Line Graph: Historical sales vs predicted demand
- Pie Chart: Demand distribution by time period
2οΈβ£ Pricing Optimization
- Line Graph: Price vs sales volume (dual-axis)
- Pie Chart: Revenue contribution by price range
3οΈβ£ Sales Trend Analysis
- Bar Chart: Sales trend over time
- Pie Chart: Sales contribution by period or category
π Quick Start
Installation
# Install dependencies
pip install -r requirements.txt
Run the Application
Option 1: FastAPI Backend Only
# Start the server
python main.py
# Or using uvicorn directly
uvicorn main:app --host 0.0.0.0 --port 8000
Option 2: Full Platform (FastAPI + Gradio)
# Run both backend and beautiful frontend
python run_platform.py
The applications will be available at:
- API:
http://localhost:8000 - Gradio UI:
http://localhost:7860 - API Docs:
http://localhost:8000/docs
API Documentation
Interactive API documentation:
- Swagger UI:
http://localhost:8000/docs - ReDoc:
http://localhost:8000/redoc
π¨ Beautiful Gradio Interface
TradeNest AI features a stunning, user-friendly web interface built with Gradio:
Key Features
- π Business Forecasting Dashboard: Interactive forecasting with visual charts
- π Country Intelligence: Detailed country information and analysis
- π’ Trade Analytics: Trade data visualization between countries
- πΉ Economic Indicators: IMF data integration with time-series charts
- π¨ Modern UI: Gradient backgrounds, responsive cards, and professional styling
Interface Components
Business Forecasting Tab
- Select business type (retail, manufacturing, tech, etc.)
- Enter historical revenue data
- Configure forecast horizon
- View comprehensive forecasts with growth charts
- Get business insights, risks, and opportunities
Country Intelligence Tab
- Search by country code
- View detailed country information
- See flag and geographic data
Trade Analytics Tab
- Analyze trade flows between countries
- Filter by commodity and time period
- View trade value and volume metrics
Economic Indicators Tab
- Access IMF economic data
- View time-series charts
- Analyze GDP, inflation, unemployment, and more
π‘ API Endpoints
POST /api/predict/demand
Forecast demand with visualizations.
Request:
{
"historical_values": [100, 120, 110, 130, 125],
"historical_dates": ["2024-01", "2024-02", "2024-03", "2024-04", "2024-05"],
"periods_ahead": 4,
"method": "moving_average"
}
Response:
{
"insight_summary": "Strong growth expected: 15.2% increase in average demand",
"explanation": "The line chart shows...",
"predictions": {
"values": [135.5, 138.2, 140.9, 143.6],
"range": "135.50 - 143.60"
},
"confidence_level": "High",
"visuals": {
"line_chart": "base64_encoded_image...",
"pie_chart": "base64_encoded_image..."
}
}
POST /api/predict/price
Optimize price with visualizations.
Request:
{
"prices": [10.0, 12.0, 11.0, 13.0, 12.5],
"volumes": [1000, 800, 900, 700, 850],
"target": "revenue"
}
Response:
{
"insight_summary": "Optimal price identified: $12.00 for maximum revenue",
"explanation": "The line chart displays the relationship...",
"predictions": {
"optimal_price": 12.0,
"expected_volume": 800,
"expected_revenue": 9600.0,
"price_elasticity": 0.75,
"recommendation": "Set price at $12.00 for maximum revenue"
},
"confidence_level": "Medium",
"visuals": {
"line_chart": "base64_encoded_image...",
"pie_chart": "base64_encoded_image..."
}
}
POST /api/analyze/trend
Analyze sales trend with visualizations.
Request:
{
"values": [5000, 5500, 5200, 6000, 5800, 6200],
"periods": ["Q1", "Q2", "Q3", "Q4", "Q5", "Q6"]
}
Response:
{
"insight_summary": "Strong upward trend: 12.5% growth detected in sales performance",
"explanation": "The trend chart provides a clear visual representation...",
"predictions": {
"trend_direction": "increasing",
"growth_rate": 24.0,
"trend_percentage": 12.5,
"average": 5616.67,
"volatility": 0.08,
"range": "5000.00 - 6200.00"
},
"confidence_level": "High",
"visuals": {
"line_chart": "base64_encoded_image...",
"pie_chart": "base64_encoded_image..."
}
}
POST /api/country/info
Get detailed country information from Country API.
Request:
{
"country_code": "TZ"
}
POST /api/country/search
Search for countries by name.
Request:
{
"name": "Tanzania"
}
POST /api/trade/data
Get trade data between two countries.
Request:
{
"reporter_code": "842",
"partner_code": "156",
"year": "2023",
"commodity_code": "TOTAL",
"trade_flow": "export"
}
POST /api/imf/indicator
Get IMF economic indicator data.
Request:
{
"country_code": "US",
"indicator": "NGDP_RPCH",
"dataset": "IFS",
"start_year": "2020",
"end_year": "2024"
}
POST /api/forecast/business
Comprehensive business performance forecasting.
Request:
{
"business_type": "retail",
"country_code": "US",
"historical_revenue": [100000, 120000, 115000, 130000, 140000, 135000],
"forecast_horizon_months": 12,
"include_external_factors": true
}
Response:
{
"business_type": "retail",
"country_code": "US",
"country_name": "United States",
"forecast_horizon_months": 12,
"forecast": {
"values": [145000, 150000, 155000, ...],
"growth_rates": [5.2, 3.4, 3.3, ...],
"cumulative_growth": 25.8
},
"insights": [
"π Strong growth expected: Average monthly growth of 4.2%",
"π Favorable macroeconomic environment: Country GDP growing at 2.1%"
],
"risk_assessment": [
"Moderate inflation creating cost pressures"
],
"opportunities": [
"E-commerce adoption still growing in emerging markets"
]
}
π Response Format (MANDATORY)
Every endpoint returns JSON with this structure:
{
"insight_summary": "Short business conclusion",
"explanation": "Clear explanation referencing visible charts",
"predictions": {
"values": [...],
"range": "numeric range"
},
"confidence_level": "High | Medium | Low",
"visuals": {
"line_chart": "base64_encoded_image",
"pie_chart": "base64_encoded_image"
}
}
No visuals β response is invalid.
π Visualization Details
Chart Generation Process
- Data Validation: Input data is validated before chart generation
- Chart Creation: Matplotlib generates charts with professional styling
- Base64 Encoding: Charts are encoded as Base64 strings
- Response Integration: Visuals are embedded in JSON responses
Chart Features
- Professional Styling: Seaborn-inspired color schemes
- High Resolution: 150 DPI for crisp visuals
- Clear Labels: Bold titles, axis labels, and legends
- Value Annotations: Data points labeled on charts
- Grid Lines: Subtle grid for easy reading
π§ Explainability Rules
Explanations must:
- β Reference what is visible in the charts
- β Use business language (growth, decline, contribution)
- β Avoid technical ML jargon
- β Be quote-ready and structured
Example:
"The line chart shows consistent week-over-week growth, while the pie chart confirms that 60% of sales come from peak weeks."
π Data Handling
- Strict Validation: Inputs validated using Pydantic schemas
- Error Handling: Clear error messages for insufficient data
- No Fabrication: Missing values are not fabricated
- Real Data Only: Charts reflect actual input data
π οΈ Development
Project Structure
- Services: Business logic and orchestration
- Visualizations: Chart generation utilities
- Schemas: Request/response validation
- API: FastAPI route handlers
Adding New Visualizations
- Create chart function in appropriate module (
line_charts.py,bar_charts.py, orpie_charts.py) - Add method to
VisualizationService - Integrate into API endpoint
- Update response schema if needed
π Example Usage
Python Client
import requests
import json
import base64
from PIL import Image
from io import BytesIO
# Make request
response = requests.post(
"http://localhost:8000/api/predict/demand",
json={
"historical_values": [100, 120, 110, 130, 125],
"periods_ahead": 4
}
)
data = response.json()
# Decode and save charts
line_chart = base64.b64decode(data['visuals']['line_chart'])
pie_chart = base64.b64decode(data['visuals']['pie_chart'])
# Save images
with open('line_chart.png', 'wb') as f:
f.write(line_chart)
with open('pie_chart.png', 'wb') as f:
f.write(pie_chart)
print(data['insight_summary'])
print(data['explanation'])
cURL Example
curl -X POST "http://localhost:8000/api/predict/demand" \
-H "Content-Type: application/json" \
-d '{
"historical_values": [100, 120, 110, 130, 125],
"periods_ahead": 4
}'
π¨ Visualization Pipeline Flow
Input Data
β
Validation (Pydantic)
β
Prediction Service
β
Visualization Service
β
Chart Generation (Matplotlib)
β
Base64 Encoding
β
Explanation Service
β
JSON Response (with visuals)
β οΈ Important Notes
- Visuals are Mandatory: Every response includes charts
- No Notebooks: All code is production-ready Python
- Backend-Safe: Uses non-interactive Matplotlib backend
- Business Language: Explanations avoid technical jargon
- Real Data Only: No synthetic data generation
π Dependencies
fastapi: Web frameworkuvicorn: ASGI serverpydantic: Data validationmatplotlib: Visualizationnumpy: Numerical operationsgradio: Beautiful web interfacerequests: API clientpandas: Data manipulation
π¦ Status
β All core features implemented β Visualization pipeline complete β API endpoints functional β Beautiful Gradio interface ready β Country API integration β Trade API integration β IMF API integration β Business forecasting engine β Documentation ready
π License
MIT License
TradeNest AI shows its intelligence, not just says it.