> ## Documentation Index
> Fetch the complete documentation index at: https://fastapi2day.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Weather Data Analysis Project with APIs and Python

> Build a complete Python project that fetches 7 days of weather data from a real API, analyzes it with pandas, and visualizes it with matplotlib.

Everything you've learned so far — APIs, pandas, matplotlib, project structure, virtual environments — comes together in this project. You'll fetch a full week of historical weather data from the Open-Meteo API (free, no key required), load it into a DataFrame, compute statistics, produce a visualization, and save both the chart and the raw data to disk. This is exactly the kind of end-to-end data analysis workflow you'll use in real-world Python and AI projects.

## Project setup

Before writing any analysis code, you'll create a clean, isolated project environment using `uv`.

<Steps>
  <Step title="Initialize the project">
    ```bash theme={null}
    mkdir weather-analysis
    cd weather-analysis
    uv init
    ```
  </Step>

  <Step title="Create the folder structure">
    A clean layout keeps your source code, data files, and outputs organized:

    ```text theme={null}
    weather-analysis/
    ├── data/               # Raw weather CSV files
    ├── src/                # Python source files
    │   └── main.py         # Main analysis script
    ├── pyproject.toml      # Project config and dependencies
    └── .gitignore          # Ignored files (data/, .venv/, etc.)
    ```

    Create the folders and move the default script:

    ```bash theme={null}
    mkdir data src
    mv main.py src/
    ```
  </Step>

  <Step title="Install dependencies">
    ```bash theme={null}
    uv add requests pandas matplotlib
    ```

    This creates `.venv` automatically and locks exact package versions in `uv.lock` for reproducibility.
  </Step>
</Steps>

## Fetch 7 days of weather data

The Open-Meteo API provides historical weather data with no authentication required. The following code calculates the date range and builds the request URL dynamically:

```python theme={null}
import requests
from datetime import datetime, timedelta

# Calculate the date range
today    = datetime.now()
week_ago = today - timedelta(days=7)

# Format dates as required by the API (YYYY-MM-DD)
start_date = week_ago.strftime("%Y-%m-%d")
end_date   = today.strftime("%Y-%m-%d")

# Request daily max and min temperatures for Paris
url = (
    f"https://api.open-meteo.com/v1/forecast"
    f"?latitude=48.85&longitude=2.35"
    f"&start_date={start_date}&end_date={end_date}"
    f"&daily=temperature_2m_max,temperature_2m_min"
)

response = requests.get(url)
data = response.json()
print(data)
```

## Load the data into pandas

Organize the API response into a structured DataFrame:

```python theme={null}
import pandas as pd

# Extract the daily section of the response
daily = data["daily"]

# Build the DataFrame
df = pd.DataFrame({
    "date":     daily["time"],
    "max_temp": daily["temperature_2m_max"],
    "min_temp": daily["temperature_2m_min"],
})

# Convert date strings to proper datetime objects
df["date"] = pd.to_datetime(df["date"])

print(df)
```

You'll see output like:

```text theme={null}
        date  max_temp  min_temp
0 2024-01-08      12.3       5.1
1 2024-01-09      11.8       4.2
2 2024-01-10      13.5       6.0
...
```

## Visualize the data

Create a line chart showing max, min, and average temperature over the week:

```python theme={null}
import matplotlib.pyplot as plt

plt.figure(figsize=(10, 6))
plt.plot(df["date"], df["max_temp"], marker="o", label="Max Temp")
plt.plot(df["date"], df["min_temp"], marker="o", label="Min Temp")

plt.xlabel("Date")
plt.ylabel("Temperature (°C)")
plt.title("Paris Weather — Past 7 Days")
plt.legend()
plt.xticks(rotation=45)
plt.tight_layout()

plt.savefig("data/weather_chart.png")
plt.show()
```

## Save the data to CSV

```python theme={null}
import os

# Ensure the data folder exists
os.makedirs("data", exist_ok=True)

# Save the DataFrame
df.to_csv("data/paris_weather.csv", index=False)
print("Data saved to data/paris_weather.csv")
```

## Complete example

Here's the full script in one place, ready to run from the `src/` directory:

```python theme={null}
# src/main.py
import requests
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
import os

# ── 1. Fetch weather data ─────────────────────────────────────────────────────
today    = datetime.now()
week_ago = today - timedelta(days=7)

url = (
    f"https://api.open-meteo.com/v1/forecast"
    f"?latitude=48.85&longitude=2.35"
    f"&start_date={week_ago.strftime('%Y-%m-%d')}"
    f"&end_date={today.strftime('%Y-%m-%d')}"
    f"&daily=temperature_2m_max,temperature_2m_min"
)

data = requests.get(url).json()

# ── 2. Process with pandas ────────────────────────────────────────────────────
df = pd.DataFrame({
    "date":     pd.to_datetime(data["daily"]["time"]),
    "max_temp": data["daily"]["temperature_2m_max"],
    "min_temp": data["daily"]["temperature_2m_min"],
})

df["avg_temp"] = (df["max_temp"] + df["min_temp"]) / 2

# ── 3. Visualize ──────────────────────────────────────────────────────────────
plt.figure(figsize=(10, 6))
plt.plot(df["date"], df["max_temp"], "r-o", label="Max")
plt.plot(df["date"], df["min_temp"], "b-o", label="Min")
plt.plot(df["date"], df["avg_temp"], "g--",  label="Average")

plt.xlabel("Date")
plt.ylabel("Temperature (°C)")
plt.title("Paris Weather — Past Week")
plt.legend()
plt.grid(True, alpha=0.3)
plt.xticks(rotation=45)
plt.tight_layout()

# ── 4. Save results ───────────────────────────────────────────────────────────
os.makedirs("data", exist_ok=True)

plt.savefig("data/weather_chart.png")
df.to_csv("data/paris_weather.csv", index=False)

print(f"Average temperature: {df['avg_temp'].mean():.1f}°C")
print("Files saved in 'data/' folder")
```

Run the script from the project root:

```bash theme={null}
uv run python src/main.py
```

## What you've accomplished

Look at what this project brings together:

* **Real API integration** — fetching live data from a public HTTP endpoint
* **Date arithmetic** — computing dynamic date ranges with `datetime` and `timedelta`
* **Data processing** — reshaping and enriching a DataFrame with pandas
* **Visualization** — producing a multi-series chart with matplotlib
* **File handling** — creating directories and saving CSV and image files
* **Project structure** — organized folders, a virtual environment, and locked dependencies

This is exactly how data analysis and AI projects work in the real world.

<Tip>
  Try modifying the script to fetch weather for your own city. Look up your coordinates at [latlong.net](https://www.latlong.net/) and update the `latitude` and `longitude` values in the URL.
</Tip>

## What's next?

Now that you've built and organized a complete Python project, the next step is creating interactive web interfaces and AI dashboards using Streamlit.

<Card title="Building UIs with Streamlit" icon="arrow-right" href="/streamlit/intro">
  Create interactive web applications and AI dashboards
</Card>
