13.Analyze weather data collected from the Open-Meteo API and visualize temperature and humidity trends using bar charts and perform statistical analysis.

Input : https://api.open-meteo.com/v1/forecast?latitude=9.93&longitude=76.27&
current=temperature_2m,relative_humidity_2m,wind_speed_10m

pip install requests pandas plotly streamlit

streamlit

app.py:


import requests
import pandas as pd
import plotly.express as px
import streamlit as st

# Open-Meteo hourly weather API
URL = (
    "https://api.open-meteo.com/v1/forecast"
    "?latitude=9.93&longitude=76.27"
    "&hourly=temperature_2m,relative_humidity_2m"
    "&forecast_days=1&timezone=auto"
)

st.set_page_config(
    page_title="Weather Data Analysis",
    page_icon="🌤️",
    layout="wide"
)

st.title("Open-Meteo Weather Data Analysis")
st.write("Hourly temperature and humidity analysis for Kochi")

# Fetch weather data
@st.cache_data(ttl=900)
def get_weather_data():
    response = requests.get(URL, timeout=20)
    response.raise_for_status()
    return response.json()

try:
    data = get_weather_data()

    # Extract hourly data
    hourly = data["hourly"]

    df = pd.DataFrame({
        "Time": pd.to_datetime(hourly["time"]),
        "Temperature (°C)": hourly["temperature_2m"],
        "Humidity (%)": hourly["relative_humidity_2m"]
    })

    # Display raw data
    st.subheader("Hourly Weather Data")
    st.dataframe(df, use_container_width=True)

    # Statistical analysis
    st.subheader("Statistical Analysis")

    stats = df[["Temperature (°C)", "Humidity (%)"]].describe()
    st.dataframe(stats, use_container_width=True)

    col1, col2 = st.columns(2)

    with col1:
        st.metric(
            "Average Temperature",
            f"{df['Temperature (°C)'].mean():.2f} °C"
        )
        st.metric(
            "Maximum Temperature",
            f"{df['Temperature (°C)'].max():.2f} °C"
        )

    with col2:
        st.metric(
            "Average Humidity",
            f"{df['Humidity (%)'].mean():.2f}%"
        )
        st.metric(
            "Maximum Humidity",
            f"{df['Humidity (%)'].max():.2f}%"
        )

    # Temperature bar chart
    st.subheader("Temperature Trend")

    fig_temp = px.bar(
        df,
        x="Time",
        y="Temperature (°C)",
        title="Hourly Temperature",
        labels={"Time": "Time"}
    )

    st.plotly_chart(fig_temp, use_container_width=True)

    # Humidity bar chart
    st.subheader("Humidity Trend")

    fig_humidity = px.bar(
        df,
        x="Time",
        y="Humidity (%)",
        title="Hourly Relative Humidity",
        labels={"Time": "Time"}
    )

    st.plotly_chart(fig_humidity, use_container_width=True)

    # Download data
    csv = df.to_csv(index=False).encode("utf-8")

    st.download_button(
        "Download Weather Data as CSV",
        data=csv,
        file_name="weather_data.csv",
        mime="text/csv"
    )

except requests.exceptions.RequestException as e:
    st.error(f"API connection error: {e}")

except (KeyError, ValueError) as e:
    st.error(f"Error processing weather data: {e}")

