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

# Weather Data Analysis Project

> Analyze and visualize data from APIs

## Building on APIs

Let's take the weather API from the previous page and create something useful. We'll get weather data for the past 7 days, analyze it, visualize it, and save it.

This brings together everything you've learned: APIs, data processing, file handling, and visualization.

## Project Setup

Before writing any code, let's set up a clean, isolated project environment using `uv` and organize our files.

### 1. Initialize the Project

Create a new directory for your project and initialize it with `uv`:

```bash theme={null}
# Create and enter the project directory
mkdir weather-analysis
cd weather-analysis

# Initialize a new project with uv
uv init
```

### 2. Project Structure

A clean project structure helps keep your code, data, and output organized. Organize your folder structure like this:

```text theme={null}
weather-analysis/
├── data/               # For saving raw weather CSV files
├── src/                # For Python source files
│   └── main.py         # Main analysis and plotting script
├── pyproject.toml      # Project configuration and dependencies
└── .gitignore          # Ignored files (e.g. data/, .venv/)
```

Create the folders and move the default script using your terminal:

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

### 3. Install Dependencies

Install the required packages for API requests, data analysis, and plotting using `uv add`:

```bash theme={null}
uv add requests pandas matplotlib
```

This will automatically create a virtual environment (`.venv`) and lock exact versions in `uv.lock` for reproducibility.

## Get 7 days of weather

The Open-Meteo API can give us historical data:

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

# Calculate dates
today = datetime.now()
week_ago = today - timedelta(days=7)

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

# Get Paris weather for past week
url = f"https://api.open-meteo.com/v1/forecast?latitude=48.85&longitude=2.35&start_date={start_date}&end_date={end_date}&daily=temperature_2m_max,temperature_2m_min"

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

## Load into pandas

Now let's organize this data:

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

# Extract the daily data
daily_data = data['daily']

# Create a DataFrame
df = pd.DataFrame({
    'date': daily_data['time'],
    'max_temp': daily_data['temperature_2m_max'],
    'min_temp': daily_data['temperature_2m_min']
})

# Convert date strings to datetime
df['date'] = pd.to_datetime(df['date'])

print(df)
```

Output:

```
        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 simple line chart:

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

# Create the plot
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')

# Add labels and title
plt.xlabel('Date')
plt.ylabel('Temperature (°C)')
plt.title('Paris Weather - Past 7 Days')
plt.legend()

# Rotate x-axis labels for readability
plt.xticks(rotation=45)
plt.tight_layout()

# Save the plot
plt.savefig('weather_chart.png')
plt.show()
```

## Save to CSV

Let's save our data for later use:

```python theme={null}
import os

# Create data folder if it doesn't exist
if not os.path.exists('data'):
    os.makedirs('data')

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

## Complete example

Here's everything together:

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

# 1. Get weather data
today = datetime.now()
week_ago = today - timedelta(days=7)
start_date = week_ago.strftime("%Y-%m-%d")
end_date = today.strftime("%Y-%m-%d")

url = f"https://api.open-meteo.com/v1/forecast?latitude=48.85&longitude=2.35&start_date={start_date}&end_date={end_date}&daily=temperature_2m_max,temperature_2m_min"
response = requests.get(url)
data = response.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']
})

# 3. Calculate average
df['avg_temp'] = (df['max_temp'] + df['min_temp']) / 2

# 4. Create visualization
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()

# 5. Save everything
if not os.path.exists('data'):
    os.makedirs('data')

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")
```

## What you've accomplished

Look at what you just did:

* Connected to a real API
* Worked with dates and time
* Processed data with pandas
* Created a visualization
* Handled files and folders
* Saved your results

This is exactly how data analysis works in the real world!

<Tip>
  Try modifying the code to get weather for your city. Find your coordinates at [latlong.net](https://www.latlong.net/).
</Tip>

## What's next?

Now that you've built and organized your Python projects, let's learn how to build interactive web interfaces and chatbots in pure Python using Streamlit!

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