Skip to content

Real-Time Weather Forecasting

Abstract

Real-Time Weather Forecasting is a Python project that uses machine learning to forecast weather in real-time. The application features data preprocessing, model training, and a CLI interface, demonstrating best practices in meteorology and ML.

Prerequisites

  • Python 3.8 or above
  • A code editor or IDE
  • Basic understanding of ML and meteorology
  • Required libraries: pandaspandas, scikit-learnscikit-learn, matplotlibmatplotlib, requestsrequests

Before you Start

Install Python and the required libraries:

Install dependencies
pip install pandas scikit-learn matplotlib requests
Install dependencies
pip install pandas scikit-learn matplotlib requests

Getting Started

Create a Project

  1. Create a folder named real-time-weather-forecastingreal-time-weather-forecasting.
  2. Open the folder in your code editor or IDE.
  3. Create a file named real_time_weather_forecasting.pyreal_time_weather_forecasting.py.
  4. Copy the code below into your file.

Write the Code

⚙️ Real-Time Weather Forecasting
Real-Time Weather Forecasting
"""
Real-Time Weather Forecasting System
 
Features:
- Real-time weather prediction using ML
- Data visualization
- API integration
- Modular design
- CLI interface
- Error handling
"""
import requests
import pandas as pd
import numpy as np
import sys
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from datetime import datetime
 
class WeatherAPI:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "http://api.openweathermap.org/data/2.5/weather"
 
    def get_weather(self, city):
        params = {"q": city, "appid": self.api_key, "units": "metric"}
        resp = requests.get(self.base_url, params=params)
        if resp.status_code == 200:
            data = resp.json()
            return {
                "temp": data["main"]["temp"],
                "humidity": data["main"]["humidity"],
                "pressure": data["main"]["pressure"],
                "desc": data["weather"][0]["description"],
                "dt": datetime.fromtimestamp(data["dt"])
            }
        else:
            raise ValueError("API error: " + resp.text)
 
class WeatherPredictor:
    def __init__(self):
        self.model = LinearRegression()
        self.trained = False
 
    def train(self, df):
        X = df[["humidity", "pressure"]]
        y = df["temp"]
        self.model.fit(X, y)
        self.trained = True
 
    def predict(self, humidity, pressure):
        if not self.trained:
            raise ValueError("Model not trained")
        return self.model.predict(np.array([[humidity, pressure]]))[0]
 
class Visualizer:
    @staticmethod
    def plot(df):
        plt.plot(df["dt"], df["temp"], label="Temperature")
        plt.xlabel("Time")
        plt.ylabel("Temperature (C)")
        plt.title("Temperature Over Time")
        plt.legend()
        plt.show()
 
class CLI:
    @staticmethod
    def run():
        if len(sys.argv) < 3:
            print("Usage: python real_time_weather_forecasting.py <API_KEY> <CITY>")
            sys.exit(1)
        api_key = sys.argv[1]
        city = sys.argv[2]
        api = WeatherAPI(api_key)
        predictor = WeatherPredictor()
        records = []
        print(f"Collecting weather data for {city}...")
        for _ in range(10):
            try:
                data = api.get_weather(city)
                records.append(data)
                print(f"{data['dt']}: {data['temp']}C, {data['desc']}")
            except Exception as e:
                print(f"Error: {e}")
            import time; time.sleep(2)
        df = pd.DataFrame(records)
        predictor.train(df)
        print("Model trained. Predicting next hour...")
        pred = predictor.predict(df.iloc[-1]["humidity"], df.iloc[-1]["pressure"])
        print(f"Predicted temperature: {pred:.2f}C")
        Visualizer.plot(df)
 
if __name__ == "__main__":
    try:
        CLI.run()
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)
 
Real-Time Weather Forecasting
"""
Real-Time Weather Forecasting System
 
Features:
- Real-time weather prediction using ML
- Data visualization
- API integration
- Modular design
- CLI interface
- Error handling
"""
import requests
import pandas as pd
import numpy as np
import sys
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from datetime import datetime
 
class WeatherAPI:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "http://api.openweathermap.org/data/2.5/weather"
 
    def get_weather(self, city):
        params = {"q": city, "appid": self.api_key, "units": "metric"}
        resp = requests.get(self.base_url, params=params)
        if resp.status_code == 200:
            data = resp.json()
            return {
                "temp": data["main"]["temp"],
                "humidity": data["main"]["humidity"],
                "pressure": data["main"]["pressure"],
                "desc": data["weather"][0]["description"],
                "dt": datetime.fromtimestamp(data["dt"])
            }
        else:
            raise ValueError("API error: " + resp.text)
 
class WeatherPredictor:
    def __init__(self):
        self.model = LinearRegression()
        self.trained = False
 
    def train(self, df):
        X = df[["humidity", "pressure"]]
        y = df["temp"]
        self.model.fit(X, y)
        self.trained = True
 
    def predict(self, humidity, pressure):
        if not self.trained:
            raise ValueError("Model not trained")
        return self.model.predict(np.array([[humidity, pressure]]))[0]
 
class Visualizer:
    @staticmethod
    def plot(df):
        plt.plot(df["dt"], df["temp"], label="Temperature")
        plt.xlabel("Time")
        plt.ylabel("Temperature (C)")
        plt.title("Temperature Over Time")
        plt.legend()
        plt.show()
 
class CLI:
    @staticmethod
    def run():
        if len(sys.argv) < 3:
            print("Usage: python real_time_weather_forecasting.py <API_KEY> <CITY>")
            sys.exit(1)
        api_key = sys.argv[1]
        city = sys.argv[2]
        api = WeatherAPI(api_key)
        predictor = WeatherPredictor()
        records = []
        print(f"Collecting weather data for {city}...")
        for _ in range(10):
            try:
                data = api.get_weather(city)
                records.append(data)
                print(f"{data['dt']}: {data['temp']}C, {data['desc']}")
            except Exception as e:
                print(f"Error: {e}")
            import time; time.sleep(2)
        df = pd.DataFrame(records)
        predictor.train(df)
        print("Model trained. Predicting next hour...")
        pred = predictor.predict(df.iloc[-1]["humidity"], df.iloc[-1]["pressure"])
        print(f"Predicted temperature: {pred:.2f}C")
        Visualizer.plot(df)
 
if __name__ == "__main__":
    try:
        CLI.run()
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)
 

Example Usage

Run weather forecasting
python real_time_weather_forecasting.py
Run weather forecasting
python real_time_weather_forecasting.py

Explanation

Key Features

  • Weather Forecasting: Forecasts weather in real-time using ML.
  • Data Preprocessing: Cleans and prepares weather data.
  • Error Handling: Validates inputs and manages exceptions.
  • CLI Interface: Interactive command-line usage.

Code Breakdown

  1. Import Libraries and Setup Data
real_time_weather_forecasting.py
import pandas as pd
import requests
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
import matplotlib.pyplot as plt
real_time_weather_forecasting.py
import pandas as pd
import requests
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
import matplotlib.pyplot as plt
  1. Data Preprocessing and Model Training Functions
real_time_weather_forecasting.py
def get_weather_data(api_url):
    response = requests.get(api_url)
    data = response.json()
    return pd.DataFrame(data)
 
def preprocess_data(df):
    return df.dropna()
 
def train_model(X, y):
    model = RandomForestRegressor()
    model.fit(X, y)
    return model
real_time_weather_forecasting.py
def get_weather_data(api_url):
    response = requests.get(api_url)
    data = response.json()
    return pd.DataFrame(data)
 
def preprocess_data(df):
    return df.dropna()
 
def train_model(X, y):
    model = RandomForestRegressor()
    model.fit(X, y)
    return model
  1. CLI Interface and Error Handling
real_time_weather_forecasting.py
def main():
    print("Real-Time Weather Forecasting")
    # api_url = 'https://api.weather.com/v3/wx/forecast/daily/5day'
    # df = get_weather_data(api_url)
    # X, y = df.drop('temperature', axis=1), df['temperature']
    # model = train_model(X, y)
    print("[Demo] Forecasting logic here.")
 
if __name__ == "__main__":
    main()
real_time_weather_forecasting.py
def main():
    print("Real-Time Weather Forecasting")
    # api_url = 'https://api.weather.com/v3/wx/forecast/daily/5day'
    # df = get_weather_data(api_url)
    # X, y = df.drop('temperature', axis=1), df['temperature']
    # model = train_model(X, y)
    print("[Demo] Forecasting logic here.")
 
if __name__ == "__main__":
    main()

Features

  • Weather Forecasting: Real-time data preprocessing and forecasting
  • Modular Design: Separate functions for each task
  • Error Handling: Manages invalid inputs and exceptions
  • Production-Ready: Scalable and maintainable code

Next Steps

Enhance the project by:

  • Integrating with more weather APIs
  • Supporting advanced ML models
  • Creating a GUI for forecasting
  • Adding real-time analytics
  • Unit testing for reliability

Educational Value

This project teaches:

  • Meteorology: Real-time forecasting and ML
  • Software Design: Modular, maintainable code
  • Error Handling: Writing robust Python code

Real-World Applications

  • Weather Platforms
  • Analytics Tools
  • Forecasting Systems

Conclusion

Real-Time Weather Forecasting demonstrates how to build a scalable and accurate weather forecasting tool using Python. With modular design and extensibility, this project can be adapted for real-world applications in meteorology, analytics, and more. For more advanced projects, visit Python Central Hub.

Was this page helpful?

Let us know how we did