A real-time weather forecasting system with intelligent alerts for rain, heat, wind, and UV conditions
Built with Python, FastAPI, SQLite, and Open-Meteo API
- Overview
- Features
- Tech Stack
- Quick Start
- Installation
- Usage
- API Documentation
- Project Structure
- Alert Rules
- Simulation Mode
- Examples
- Contributing
- License
The Weather Forecast & Alert Application is a comprehensive system that:
✅ Fetches real-time weather data from free APIs (Open-Meteo)
✅ Analyzes forecasts to identify risk conditions
✅ Generates intelligent alerts (rain, heat, wind, UV, fog, thunderstorms)
✅ Stores weather history and alert logs
✅ Serves data via REST API
✅ Provides CLI interface for easy interaction
✅ Exports reports as CSV files
- 🌾 Agriculture - Irrigation planning, frost warnings
- 🚚 Logistics - Route optimization during storms
- ⛑️ Event Planning - Rescheduling outdoor events
✈️ Travel - Pre-trip weather checks- 🏥 Healthcare - Heat wave preparedness
- ⚡ Energy - Solar/wind forecast coordination
- 🌊 Emergency Management - Storm warnings
- 📍 Multi-location Tracking - Monitor any city worldwide
- 🔄 Real-time Data - Fresh weather every 3 hours (configurable)
- 🚨 12+ Alert Rules - Comprehensive condition detection
- 📊 Hourly & Daily Forecasts - 48h hourly + 7d daily
- 💾 Historical Storage - Track weather trends
- 🎮 Simulation Mode - Test without API calls
- 📋 CSV Reports - Export forecasts for analysis
- 🌐 REST API - FastAPI with Swagger documentation
| Alert | Condition | Severity |
|---|---|---|
| 🌧️ Rain Soon | Precip prob ≥ 60% | |
| 🌧️ Heavy Rain | Rainfall ≥ 10mm | 🔴 Critical |
| 🔥 Heat Wave | Max temp ≥ 40°C | 🔴 Critical |
| 🥶 Cold Snap | Min temp ≤ 0°C | |
| 💨 High Wind | Gusts ≥ 15 m/s | |
| ☀️ UV High | UV index ≥ 8 | |
| 🌫️ Fog | Visibility < 1 km | |
| ⛈️ Thunderstorm | Humidity + rain + wind | 🔴 Critical |
| + 4 more custom rules |
- Python 3.9+ - Core language
- FastAPI - REST API framework with auto-docs
- SQLite3 - File-based relational database
- httpx - Async HTTP client
- Pydantic - Data validation
- Open-Meteo - Free weather API (no key required)
- Optional: Telegram - Alert notifications
- Optional: SMTP - Email alerts
- Git - Version control
- GitHub - Repository hosting
- Virtual Environment - Python isolation
- Python 3.8 or higher
- pip package manager
- Git (optional)
# 1. Clone repository
git clone https://github.com/yourusername/Weather-Forecast-Alert.git
cd Weather-Forecast-Alert
# 2. Create virtual environment
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
# 3. Install dependencies
pip install -r requirements.txt
# 4. Initialize database
python main.py
# Select option 1: Initialize Database
# 5. Add locations to track
python main.py
# Select option 2: Add Location
# Example: Delhi, India (28.7041, 77.1025)
# 6. Fetch real weather data
python main.py
# Select option 3: Fetch Real Weather Data
# 7. View forecast & alerts
python main.py
# Select option 6: Get Forecast & Alerts# Check Python version
python --version # Should be 3.8+
# Install Git (optional but recommended)
# Visit: https://git-scm.com/downloads# Using Git
git clone https://github.com/yourusername/Weather-Forecast-Alert.git
cd Weather-Forecast-Alert
# OR download ZIP and extract manually# Windows
python -m venv venv
venv\Scripts\activate
# Mac/Linux
python3 -m venv venv
source venv/bin/activate
# Verify activation (prompt should show (venv))pip install --upgrade pip
pip install -r requirements.txt
# Verify installation
python -c "import fastapi; import httpx; print('✓ Installation OK')"# Copy template
cp .env.example .env
# Edit .env (optional, defaults work fine)
# Set USE_SIMULATION=true to test without APIpython -c "from src.database import init_database; init_database('db/weather.db'); print('✓ Database initialized')"
# Or use interactive menu
python main.py # Option 1# Check database exists
ls -la db/weather.db
# Test imports
python -c "from src.ingest import fetch_open_meteo; from src.rules import evaluate; print('✓ All OK')"python main.pyMenu Options:
1. Initialize Database - Create/reset database
2. Add Location - Add city to track
3. Fetch Real Weather Data - Get data from API
4. Load Simulation Scenario - Generate test data
5. View Locations - List all tracked cities
6. Get Forecast & Alerts - View weather predictions
7. Generate Report - Export to CSV
8. View Alert Scenarios - Show available test scenarios
9. Exit
# Start server
uvicorn api.app:app --reload --port 8000
# Access:
# - API: http://localhost:8000
# - Docs: http://localhost:8000/docs
# - ReDoc: http://localhost:8000/redocfrom src.database import init_database, query_all
from src.ingest import add_location, fetch_open_meteo, persist_raw, upsert_series
from src.rules import evaluate
# Initialize
init_database("db/weather.db")
# Add location
loc_id = add_location("db/weather.db", "Delhi, India", 28.7041, 77.1025, "Asia/Kolkata")
# Fetch weather
payload = fetch_open_meteo(28.7041, 77.1025, "Asia/Kolkata")
persist_raw("db/weather.db", loc_id, payload, "full")
upsert_series("db/weather.db", loc_id, payload)
# Get forecast
hourly = query_all("db/weather.db",
"SELECT * FROM weather_hourly WHERE location_id = ? LIMIT 24", (loc_id,))
# Evaluate alerts
alerts = evaluate(hourly_tuples, daily_tuples)
print(f"Found {len(alerts)} active alerts")http://localhost:8000
GET /locationsResponse:
{
"count": 2,
"locations": [
{
"id": 1,
"name": "Delhi, India",
"lat": 28.7041,
"lon": 77.1025,
"tz": "Asia/Kolkata"
}
]
}GET /forecast/{location_id}?hours=24&days=7Response:
{
"location": {...},
"hourly": {
"count": 24,
"data": [
{
"ts": "2024-01-15T10:00",
"temp_c": 22.5,
"humidity": 65.2,
"wind_ms": 8.2,
"precip_mm": 0.5,
"precip_prob": 40.0
}
]
},
"daily": {...}
}GET /alerts/{location_id}Response:
{
"location": {...},
"count": 2,
"alerts": [
{
"code": "RAIN_SOON",
"label": "Rain likely in next 12 hours",
"severity": "warn",
"description": "Precipitation probability >= 60%"
}
]
}GET /current/{location_id}GET /statistics/{location_id}Full Swagger Docs: http://localhost:8000/docs
Weather-Forecast-Alert-Application/
│
├── 📄 README.md # This file
├── 📄 main.py # CLI entry point
├── 📄 requirements.txt # Python dependencies
├── 📄 .env.example # Config template
├── 📄 .gitignore # Git exclusions
│
├── src/ # 🐍 Source modules
│ ├── __init__.py
│ ├── ingest.py # Fetch from APIs
│ ├── rules.py # Alert rules
│ ├── simulation.py # Test scenarios
│ └── database.py # DB utilities
│
├── api/ # 🌐 REST API
│ └── app.py # FastAPI application
│
├── jobs/ # ⏰ Background jobs
│ └── refresh.py # Scheduled refresh
│
├── db/ # 💾 Database
│ ├── schema.sql # Table definitions
│ └── weather.db # SQLite file (created)
│
├── reports/ # 📋 Generated CSVs
├── outputs/ # 📁 Generated outputs
├── images/ # 📸 Screenshots
├── data/ # 📊 Sample data
└── docs/ # 📚 Documentation
└── PROJECT_EXPLANATION.md # Detailed guide
| # | Rule | Condition | Severity |
|---|---|---|---|
| 1 | RAIN_SOON | Precip prob ≥ 60% (12h) | |
| 2 | RAIN_HEAVY | Rainfall ≥ 10mm (24h) | 🔴 |
| 3 | HEAT_WAVE | Max temp ≥ 40°C | 🔴 |
| 4 | EXTREME_HEAT | Max temp ≥ 43°C | 🔴 |
| 5 | COLD_SNAP | Min temp ≤ 0°C | |
| 6 | WIND_HIGH | Gusts ≥ 15 m/s | |
| 7 | WIND_EXTREME | Gusts ≥ 20 m/s | 🔴 |
| 8 | UV_HIGH | UV ≥ 8 | |
| 9 | UV_EXTREME | UV ≥ 11 | 🔴 |
| 10 | HUMIDITY_HIGH | Humidity ≥ 80% | ℹ️ |
| 11 | FOG_EXPECTED | Visibility < 1 km | |
| 12 | THUNDERSTORM_RISK | Humidity + rain + wind | 🔴 |
- 🔵 INFO - Informational (nice to know)
- 🟡 WARN - Action recommended
- 🔴 CRITICAL - Urgent attention needed
# In src/rules.py
from src.rules import AlertRule
new_rule = AlertRule(
code="HAIL_RISK",
label="Hail storm possible",
description="Temperature drop + high precipitation",
condition=lambda ctx: (
ctx.get("tmin_tomorrow", 999) < 5 and
any((x or 0) >= 70 for x in ctx.get("precip_prob_next_12h", []))
),
severity="critical"
)python main.py
# Option 4: Load Simulation ScenarioScenarios:
- normal_weather - Clear, 25°C, 60% humidity
- monsoon_heavy_rain - 25mm rain, 85% probability
- heat_wave - 42°C+, dry conditions
- cold_snap - -2°C, frost risk
- thunderstorm - Severe: 95% rain, 18 m/s winds
- foggy_morning - 95% humidity, 0.5km visibility
- high_wind_event - 20 m/s winds
✓ No API calls needed
✓ Reproducible results
✓ Test specific scenarios
✓ Verify alerts work correctly
✓ Demo without dependencies
$ python main.py
Select option (1-9): 2
📍 ADD NEW LOCATION
Enter location name (e.g., 'Delhi, India'): New York, USA
Enter latitude: 40.7128
Enter longitude: -74.0060
Enter timezone (default: UTC, e.g., 'Asia/Kolkata'): America/New_York
✓ Location added! (ID=2)Select option (1-9): 6
Select location: 1 (Delhi, India)
══════════════════════════════════════════════════════════════════
FORECAST FOR: Delhi, India
══════════════════════════════════════════════════════════════════
📈 NEXT 24 HOURS:
Time Temp(°C) Humidity(%) Wind(m/s)
──────────────────────────────────────────────────────────────
2024-01-15T10:00 22.5 65.2 8.2
2024-01-15T11:00 23.1 63.8 7.8
...
WEATHER ALERTS (2 active):
══════════════════════════════════════════════════════════════════
⚠️ RAIN_SOON
Rain likely in next 12 hours
Severity: WARN
⚠️ HIGH_WIND
Strong winds: Gusts >= 15 m/s
Severity: WARN
✓ Report generated: reports/forecast_Delhi_20240115_101530.csv# Start server
uvicorn api.app:app --reload
# Fetch alerts for location 1
curl http://localhost:8000/alerts/1
# Response:
{
"location": {"id": 1, "name": "Delhi, India"},
"count": 2,
"alerts": [
{
"code": "RAIN_SOON",
"label": "Rain likely in next 12 hours",
"severity": "warn"
}
]
}- Query Time: < 100ms for typical queries
- Data Storage: ~5MB for 30 days of data (5 locations)
- Indexes: Optimized with composite primary keys
- Scalability: Supports 1000+ locations before optimization needed
- Locations: < 10ms
- Forecast: < 50ms
- Alerts: < 100ms
✓ API Keys: Never commit .env files
✓ Secrets: Use environment variables
✓ Passwords: Use system keyring
✓ HTTPS: Enable in production
✓ Rate Limiting: Implement API quotas
✓ Input Validation: Pydantic models
# ❌ WRONG - Never do this
API_KEY = "abc123xyz" # Hardcoded
# ✓ RIGHT - Use environment variables
import os
API_KEY = os.getenv("API_KEY")Contributions welcome! Here's how:
# 1. Fork repository
# 2. Create feature branch
git checkout -b feature/amazing-feature
# 3. Commit changes
git commit -m "Add amazing feature"
# 4. Push to branch
git push origin feature/amazing-feature
# 5. Open Pull Request- Code follows style guide (PEP 8)
- Tests pass locally
- No hardcoded secrets
- Documentation updated
- Commit messages are clear
# Solution: Ensure venv is activated and install dependencies
source venv/bin/activate # or venv\Scripts\activate on Windows
pip install -r requirements.txt# Solution: Check folder permissions and disk space
ls -la db/
chmod 755 db/# Solution: Check internet connection or switch to simulation mode
USE_SIMULATION=true python main.py- PROJECT_EXPLANATION.md - Detailed project guide
- API_REFERENCE.md - Complete API docs
- ARCHITECTURE.md - System design
- DEPLOYMENT.md - Production deployment
- Code Lines: ~2000 (excluding docs)
- Alert Rules: 12 configurable
- API Endpoints: 8
- Database Tables: 5
- Test Scenarios: 7
- Development Time: ~20-30 hours (including documentation)
✅ API integration with httpx
✅ Database design with SQLite
✅ REST API development with FastAPI
✅ Rule engine implementation
✅ Alert/notification systems
✅ Data visualization (CSV export)
✅ CLI application design
✅ Environment configuration
✅ Git version control
✅ Production deployment patterns
Q: Do I need an API key?
A: No! Open-Meteo is free and doesn't require authentication.
Q: Can I use this commercially?
A: Yes, it's MIT licensed. Just provide attribution.
Q: How often is data updated?
A: Every 3 hours by default (configurable in .env).
Q: Can I deploy on free platforms?
A: Yes! Heroku Free, Render, Railway, or PythonAnywhere.
- 📧 Email: your.email@example.com
- 🐙 GitHub: @yourusername
- 💼 LinkedIn: Your Profile
This project is licensed under the MIT License - see LICENSE file for details.
MIT License
Copyright (c) 2024 [Your Name]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
- Open-Meteo - Free weather API (https://open-meteo.com/)
- FastAPI - Modern Python web framework
- SQLite - Lightweight database engine
- Community - All contributors and users
- Add more alert rules
- Improve forecast accuracy
- Add user preferences
- Mobile app (React Native)
- Multi-provider support
- Machine learning predictions
- Real-time notifications
- Geospatial queries
- Calendar integration
- AQI integration
- SaaS platform
⭐ If you find this useful, please star the repository!
🌦️ Developed an AI-Powered Weather Forecast & Alert Application using Python, Streamlit, SQLite, and real-time weather APIs. The system provides live forecasts, smart weather alerts, analytics dashboards, and interactive visualizations with a modern UI for enhanced weather monitoring and decision-making. 🚀
02edfde90e93d56a6977fb9906ebd2ae95a7a3a7