Python Central HubSign in

Python Projects / Advanced

Real-Time Weather Forecasting

A Python application for forecasting weather in real-time using machine learning, featuring data preprocessing, model training, and a CLI interface.

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: pandas, scikit-learn, matplotlib, requests

Before you Start

Install Python and the required libraries:

Shell
pip install pandas scikit-learn matplotlib requests

Getting Started

Create a Project

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

Write the Code

Real-Time Weather ForecastingSource
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.savefig("real_time_weather_forecasting.png", dpi=120, bbox_inches="tight")
        print("saved real_time_weather_forecasting.png")
        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

Shell
python real_time_weather_forecasting.py

How it fits together

Read from the top: this is what runs when you execute the file, and which function calls which. It is generated from the code, so it cannot drift from it.

diagram Diagram mermaid

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. What it imports (lines 12–18)
Python
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
  1. WeatherAPI — the class (lines 20–38)
Python
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)
  1. WeatherPredictor — the class (lines 40–54)
Python
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]
  1. Visualizer — the class (lines 56–66)
Python
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.savefig("real_time_weather_forecasting.png", dpi=120, bbox_inches="tight")
        print("saved real_time_weather_forecasting.png")
        plt.show()
  1. CLI — the class (lines 68–93)
Python
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)

The file defines 4 top-level symbols in all; the whole thing is above under Write the Code.

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

Checkpoint exercise

This checkpoint practises forecasting the next temperature from lag features with least squares.

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

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