Run an AI Weather Forecast Yourself
Compare ECMWF AI and physics weather forecasts with Python, APIs, and charts.
Introduction
30 Second Summary
Weather forecasts can look certain until two models predict different temperatures for the same place. The useful question is which forecast comes closer to what actually happens.
In this project, you will use Claude Code to build a Python workflow that compares AI and physics weather forecasts for a city you choose.
What You'll Build
You will demo an attributed seven-day chart for your city beside a terminal scorecard that reveals which model came closer to the historical temperatures.
By the end of this project, you'll have:
- A city search that presents five matches before saving your chosen location's coordinates and time zone.
- An AI-versus-physics comparison that prints tomorrow's temperatures every six hours before opening a labelled seven-day chart with the required credit.
- A six-day scorecard that shows each model's mean absolute error against historical weather before naming the closer model.
- Secret Mission: Read nearest-city temperatures from matched-run AIFS and IFS GRIB files downloaded directly from ECMWF.
Are there any prerequisites?
You need internet access on a Mac running macOS 13.0+. You also need a Claude Pro, Max, Ultra, Team, Enterprise, or Console account.
No coding knowledge is required.
Before We Start
This is your moment to commit to a city before the hands-on work begins. Your reason for comparing its ECMWF AIFS AI forecast with its ECMWF IFS physics forecast will anchor every result that follows.
Install Python and Claude Code
Plain-English requests become runnable forecast scripts only when a verified Python runtime is ready. An authenticated Claude Code session completes the toolchain.
macOS Terminal gives both tools one shared place to work. By the end, two Terminal windows will point at the empty ai-weather folder.
In this step, get ready to:
- Install Python 3.11 or later. Terminal reports a supported version.
- Install Claude Code. An eligible paid account is authenticated. The version check succeeds.
- Create the empty ai-weather folder. Claude Code confirms that Python works. A second Terminal window is ready in the same folder.
Install and verify Python
Python runs every weather script in this project. Version 3.15.2 is the preferred release. Any supported version from 3.11 onward works.
- Open Terminal on your Mac.
- Press Cmd+Space to open Spotlight.
- Type Terminal into the search field.
Spotlight should highlight the Terminal app.
- Press Return to open Terminal.
You'll see a prompt where you can enter commands.
- Open the official Python downloads page.
- Download the current macOS installer for Python 3.15.2.
- Find the Python 3.15.2 release on the downloads page.
- Select its macOS installer download.
You'll see a .pkg installer in your browser's downloads.
The installer adds the Python runtime that Terminal uses. It also creates a certificate helper for secure internet connections.
- Install Python 3.15.2 with the downloaded .pkg installer.
- Open the downloaded .pkg file.
- Continue through the macOS installation prompts.
- Approve the installation with your Mac administrator credentials if macOS asks.
- Complete the installation.
The installer should report that Python installed successfully.
Finding the certificate helper can be fiddly because it sits inside the versioned Python application folder. Running it prevents secure package downloads from failing later.
- Double-click Install Certificates.command inside /Applications/Python 3.15/.
- Open Finder.
- Open the Applications folder.
- Open the Python 3.15 folder.
- Double-click Install Certificates.command.
You'll see Successfully installed certifi followed by update complete in the helper window.
Before you check the runtime, which Python version do you expect Terminal to report?
- Check the installed Python version by running this command:
python3 --version
What Does This Command Do?
The python3 executable starts Python 3 on macOS. The version option prints the release that Terminal currently finds.
Terminal should report Python 3.15.2 or another supported version of 3.11 or later.
✔️ I see version 3.11 or higher
Your Python runtime is supported. Continue to the Claude Code installation.
ⓧ I see an older version
Terminal is still finding an older Python runtime. Install Python 3.15.2 from the official macOS installer.
- Return to the official Python downloads page.
- Download the macOS installer for Python 3.15.2.
- Complete the installation.
- Close the current Terminal window.
- Open a new Terminal window.
- Repeat the version check by running this command:
python3 --version
What Does This Command Do?
A fresh Terminal session reloads the available command paths. This check shows which Python 3 release the new session finds.
ⓧ Command not found
Terminal cannot find a Python 3 installation. Install Python 3.15.2 before continuing.
- Open the official Python downloads page.
- Download the macOS installer for Python 3.15.2.
- Complete the installation.
- Close the current Terminal window.
- Open a new Terminal window.
- Check the installation by running this command:
python3 --version
What Does This Command Do?
The command asks the newly installed Python 3 runtime for its version. A version response confirms that Terminal can find it.
Install and verify Claude Code
Claude Code turns your plain-English requests into local project files. Its native installer adds the command-line tool to your Mac.
Claude Code requires an eligible paid account. Eligible access comes from Pro, Max, Ultra, Team, Enterprise, or Console accounts.
- Install Claude Code by running this command in Terminal:
curl -fsSL https://claude.ai/install.sh | bash
What Does This Command Do?
The command downloads Claude Code's official macOS installation script. The shell runs that script to install the command-line tool.
The installer should finish with Claude Code installed on your Mac.
Installer Did Not Finish?
- Check that your Mac still has an internet connection.
- Rerun the installation command above.
- Ask for targeted help with troubleshooting the Claude Code installation.
- Close the current Terminal window.
- Open a new Terminal window.
- Press Cmd+Space to open Spotlight.
- Type Terminal into the search field.
- Press Return to open a fresh Terminal session.
- Check the Claude Code installation by running this command:
claude --version
What Does This Command Do?
The command asks the installed Claude Code executable for its version. A version response confirms that the new Terminal session can find it.
Terminal should print the installed Claude Code version.
✔️ I see a version number
Claude Code is installed. You can create the local project workspace.
ⓧ The version check fails
A Terminal session opened before installation can keep an outdated command path. Start with a fresh session.
- Close every Terminal window.
- Open a new Terminal window through Spotlight.
- Run the diagnostic check before retrying the version check:
claude doctor
claude --version
What Do These Commands Do?
- The first line runs Claude Code's documented diagnostic checks.
- The second line retries the installed version check.
Create the project workspace
A dedicated folder keeps every generated script beside its input data. Both Terminal windows need the same current folder so Claude Code and Python work on one project.
- Move to your Desktop by running this command:
cd ~/Desktop
What Does This Command Do?
The cd command changes Terminal's current folder. The tilde represents your macOS home folder.
- Create the ai-weather folder and move into it by running these commands:
mkdir ai-weather
cd ai-weather
What Do These Commands Do?
- The first line creates the empty ai-weather folder on your Desktop.
- The second line makes that folder the current Terminal location.
Your Terminal prompt should now end with ai-weather.
Signing in can feel sensitive. Claude Code moves authentication into your browser.
Starting an unauthenticated session opens browser login prompts. Keep this Terminal window open while you complete them.
- Start Claude Code inside ai-weather by running this command:
claude
What Does This Command Do?
The command starts an interactive Claude Code session in the current folder. Files created through the session will belong to ai-weather.
You'll see browser login prompts if this Mac has not authenticated Claude Code yet.
- Authenticate Claude Code through the browser prompts with your eligible paid account.
- Continue through the browser sign-in flow.
- Return to Terminal after the browser confirms access.
You'll see the Claude Code prompt in Terminal.
- Ask Claude Code to verify Python by pasting this exact prompt:
Check that Python works here and tell me which version I have.
What Does This Prompt Do?
Claude Code checks the Python runtime available inside the current project environment. Its response confirms whether scripts can run from this folder.
Claude Code should report Python 3.11 or later.
That is the hardest setup complete. Claude Code can now use Python inside your weather project.
- Open a second Terminal window.
- Press Cmd+N while Terminal is active.
You'll see a separate Terminal prompt while Claude Code keeps running in the first window.
- Move the second Terminal window into ai-weather by running these commands:
cd ~/Desktop
cd ai-weather
What Do These Commands Do?
The first line moves the second Terminal session to your Desktop. The second line enters the existing ai-weather folder.
The second Terminal prompt should now end with ai-weather.
Before you run the final checks, which two version reports do you expect to see?
- Verify both tools from the second Terminal window by running these commands:
python3 --version
claude --version
What Do These Commands Do?
- The first line prints the Python version available to project scripts.
- The second line prints the installed Claude Code version.
You'll see Python 3.11 or later followed by a Claude Code version. The first Terminal window remains inside Claude Code. The second window remains ready inside the empty ai-weather folder.
Your local weather workspace is ready. Next, you'll turn a city name into reusable coordinates and a time zone.
Find Your City
You proved that Claude Code can reach Python from your ai-weather folder. Now you will use that plain-English workflow to create the first reusable project data.
This step turns an ambiguous city name into the coordinates and time zone required by forecast APIs.
In this step, get ready to:
- Install Requests 2.34.2 plus Matplotlib 3.11.2 for your verified Python environment.
- Create find_city.py through Claude Code.
- Run the city finder until city.json contains your selected location details.
Ask Claude Code to build the city finder
The Open-Meteo geocoding API converts a city search into locations with coordinates and time zones. Showing several matches helps you distinguish places that share the same name.
- Paste this exact request into the Claude Code session from the previous step:
Install requests and matplotlib. Then write find_city.py. It asks me for my city, looks it up with the Open-Meteo geocoding API, shows the first 5 matches with their country, lets me pick one, and saves the name, latitude, longitude and timezone to city.json. Then tell me the command to run it.
What Does This Prompt Do?
The request asks Claude Code to install the project libraries. It also asks Claude Code to create an interactive city search in find_city.py.
The selected result is saved in city.json. That file gives every later script one consistent location.
- Approve Claude Code's dependency installation for Requests 2.34.2 plus Matplotlib 3.11.2.
Claude Code should complete the installation for your verified Python environment.
- Approve Claude Code's request to create find_city.py.
Claude Code should confirm that find_city.py exists. It should also provide the command for running the script.
Create your city record
The script presents several possible locations before saving anything. Your selection controls the coordinates and time zone used throughout the forecast comparison.
- Switch back to the second Terminal window from earlier.
Before you run the script, consider which city details you expect it to preserve.
- Start the city finder by running this command:
python3 find_city.py
What Does This Command Do?
The python3 command starts your verified Python interpreter. It executes the instructions inside find_city.py.
You should see the Enter your city: prompt in the second Terminal window.
- Enter the city you plan to compare.
You should see a numbered list of up to five matching locations with country details.
- Enter the number beside your correct location at the Enter 1-5: prompt.
You should see Saved city.json: followed by your selected name, latitude, longitude, and time zone.
That is your first live data artifact complete. The new city.json file gives every later script one exact location.
No City Matches?
Check the spelling of the city before running the search again. If several places share the name, use the country details to choose the correct result.
Ask for targeted help with troubleshooting the city search.
Ask Claude Code to explain the city record
JSON stores labelled values in a format that scripts can read. In city.json, each label identifies one part of the location selected through the city finder.
- Return to the Claude Code session from earlier.
- Paste this exact request into Claude Code:
Open city.json and explain each line to me.
What Does This Prompt Do?
The request makes Claude Code inspect the generated file. Its explanation connects each saved value to the location you selected.
Claude Code should explain the selected name, latitude, longitude, and timezone values.
The reference below gives you a final checkpoint for the file Claude Code created.
✔️ Awesome, I've got everything!
Your find_city.py file matches the project workflow. Your generated city.json contains the location you selected.
ⓧ I'd like to double check the full code
- Compare find_city.py with the reference below.
import json
import requests
GEOCODING_URL = "https://geocoding-api.open-meteo.com/v1/search"
def main():
city_query = input("Enter your city: ").strip()
response = requests.get(
GEOCODING_URL,
params={"name": city_query, "count": 5, "format": "json", "language": "en"},
timeout=30,
)
response.raise_for_status()
matches = response.json().get("results", [])
if not matches:
raise SystemExit("No matches found. Check the spelling and try again.")
print("\nChoose your city:")
for index, match in enumerate(matches, start=1):
country = match.get("country", "Unknown country")
admin1 = match.get("admin1")
place = f"{match['name']}, {country}"
if admin1:
place += f" ({admin1})"
print(f"{index}. {place}")
while True:
try:
choice = int(input("Enter 1-5: "))
selected = matches[choice - 1]
break
except (ValueError, IndexError):
print(f"Enter a number from 1 to {len(matches)}.")
city = {
"name": selected["name"],
"latitude": selected["latitude"],
"longitude": selected["longitude"],
"timezone": selected["timezone"],
}
with open("city.json", "w", encoding="utf-8") as file:
json.dump(city, file, indent=2)
print("\nSaved city.json:")
print(json.dumps(city, indent=2))
if __name__ == "__main__":
main()
Your terminal output and Claude Code's explanation should show the same selected name, latitude, longitude, and time zone.
Your project now knows where to forecast. Next, you will pull the AI and physics temperature predictions for that location.
Pull the AI and Physics Forecasts
Your selected city is now stored in city.json with its coordinates and time zone. Next, you will use those values to request matching AIFS and IFS temperatures from Open-Meteo.
The raw response is difficult to compare because it spreads both models across long column names and hourly values.
In this step, get ready to:
- Create get_forecast.py. It saves a seven-day response in forecast.json.
- Run the script. It prints tomorrow's AIFS and IFS temperatures at six-hour intervals.
- Check your 1 degree prediction against the explained model columns and printed differences.
Predict the model agreement
AIFS is the AI forecast in this project. IFS is the physics forecast.
A prediction gives you something concrete to test when tomorrow's values appear.
Create the forecast script
Claude Code can turn one precise request into the script that fetches both forecasts. The request fixes the endpoint and model identifiers used throughout the project.
- Ask Claude Code to create the forecast script by pasting this exact request:
- Switch to the Terminal window that already shows the Claude Code prompt.
Write get_forecast.py. It reads city.json and calls https://api.open-meteo.com/v1/forecast with hourly=temperature_2m, models=ecmwf_aifs025_single,ecmwf_ifs025, forecast_days=7 and timezone=auto. It saves the response to forecast.json and prints tomorrow every 6 hours as a table: time, AI (AIFS), physics (IFS), difference.
What Does This Request Do?
- It tells Claude Code to reuse the coordinates and time zone saved in city.json.
- It requests seven days of hourly temperatures from both ECMWF models.
- It keeps the full response in forecast.json while printing a smaller table for tomorrow.
- Approve the creation of get_forecast.py when Claude Code asks.
The approval prompt appears in the same Terminal window beneath Claude Code's proposed change.
You should see get_forecast.py appear inside the existing ai-weather folder.
✔️ Awesome, I've got everything!
Your file matches the requested forecast flow. It is ready to run with the selected city.
ⓧ I'd like to double check the full code
The complete get_forecast.py file should match this reference.
- Replace the contents of get_forecast.py with this reference if Claude Code produced a different version.
import json
from datetime import date, datetime, timedelta
import requests
FORECAST_URL = "https://api.open-meteo.com/v1/forecast"
AI_KEY = "temperature_2m_ecmwf_aifs025_single"
PHYSICS_KEY = "temperature_2m_ecmwf_ifs025"
def main():
with open("city.json", encoding="utf-8") as file:
city = json.load(file)
response = requests.get(
FORECAST_URL,
params={
"latitude": city["latitude"],
"longitude": city["longitude"],
"hourly": "temperature_2m",
"models": "ecmwf_aifs025_single,ecmwf_ifs025",
"forecast_days": 7,
"timezone": "auto",
},
timeout=30,
)
response.raise_for_status()
forecast = response.json()
with open("forecast.json", "w", encoding="utf-8") as file:
json.dump(forecast, file, indent=2)
hourly = forecast["hourly"]
times = hourly["time"]
ai_values = hourly[AI_KEY]
physics_values = hourly[PHYSICS_KEY]
tomorrow = date.fromisoformat(times[0][:10]) + timedelta(days=1)
print(f"Tomorrow in {city['name']}")
print(f"{'Time':<8} {'AI (AIFS)':>10} {'Physics (IFS)':>14} {'Difference':>12}")
for timestamp, ai, physics in zip(times, ai_values, physics_values):
moment = datetime.fromisoformat(timestamp)
if moment.date() == tomorrow and moment.hour % 6 == 0:
print(f"{moment:%H:%M} {ai:>10.1f} {physics:>14.1f} {abs(ai - physics):>12.1f}")
print("\nSaved forecast.json")
if __name__ == "__main__":
main()
Run and inspect both forecasts
The script requests both models in one call. Shared timestamps make each printed difference a direct comparison.
Before you run the script, do you think every printed difference will stay within 1 degree?
- Run the forecast script in the second Terminal window by running this command:
python3 get_forecast.py
What Does This Command Do?
The python3 command runs get_forecast.py with your verified Python environment. The script reads city.json before requesting the forecast.
You'll see Tomorrow in followed by your city. The table should include Time, AI (AIFS), Physics (IFS), and Difference columns.
The final line should say Saved forecast.json. The saved response should contain temperature_2m_ecmwf_aifs025_single and temperature_2m_ecmwf_ifs025.
That is the comparison running. Your city now has a saved seven-day forecast plus a readable view of tomorrow.
The saved response also exposes the intended limitation. A full week of hourly values under long model keys is cumbersome to inspect directly.
Forecast Script Did Not Complete?
- Compare get_forecast.py with the full reference if the printed times are hours off. Confirm that the request includes timezone=auto.
- Rerun the command if the API reports an error mentioning overloaded.
- Ask for targeted help with troubleshooting the forecast request.
- Ask Claude Code to explain the model columns by pasting this exact request:
- Switch back to the Terminal window that is running Claude Code.
What do the two long column names in forecast.json mean?
What Does This Request Do?
This asks Claude Code to read the generated JSON response. It interprets both model-specific temperature keys without changing your files.
Claude Code should identify temperature_2m_ecmwf_aifs025_single as the AIFS temperature column. It should identify temperature_2m_ecmwf_ifs025 as the IFS temperature column.
- Compare the terminal's Difference values with the prediction you recorded.
You'll be able to tell whether the two forecasts stayed within 1 degree at every printed time.
This result belongs to one city and one forecast day. It gives you a concrete comparison without claiming that either model always stays closer.
Your AI and physics forecasts are aligned and saved. Next, you will turn the full week into a two-line chart that makes the largest disagreements visible.
Chart the Next 7 Days
Your six-hour table proved that both ECMWF forecasts are available for your city. Claude Code can now turn those hourly points into a week-long view.
A two-line chart exposes the week's largest model disagreement hidden inside the table and JSON's timestamp-by-timestamp view.
In this step, get ready to:
- Create make_chart.py to read the existing city and forecast data.
- Generate forecast.png with two labelled seven-day forecast lines and the required attribution.
- Identify the day where the AI and physics forecasts are furthest apart.
Ask Claude Code to build the chart
The chart script uses Matplotlib to plot both model columns on the same axes. It saves the finished visual as a reusable image.
- Ask Claude Code to create the chart by pasting this exact request:
- Switch back to the Claude Code session in ai-weather.
Write make_chart.py. It reads forecast.json and city.json and saves forecast.png: temperature over the next 7 days, one line for "AI forecast (ECMWF AIFS)" and one for "Physics forecast (ECMWF IFS)", the city name and today's date in the title, days on the x axis, and the credit "Weather data by Open-Meteo.com, forecasts by ECMWF (CC BY 4.0)" at the bottom.
What Does This Prompt Do?
This request tells Claude Code to reuse your existing JSON files.
The required labels make the two models distinguishable.
The attribution keeps the image ready to share.
- Approve the creation of make_chart.py when Claude Code asks.
- Review the proposed make_chart.py file in Claude Code.
- Choose the option shown by Claude Code that allows this file creation.
Claude Code should confirm that it created make_chart.py inside ai-weather.
This checkpoint shows the full working version of make_chart.py.
✔️ Awesome, I've got everything!
Great. Your chart script is ready for its first run.
ⓧ I'd like to double check the full code
The complete working file is shown below for comparison.
import json
from datetime import datetime
from zoneinfo import ZoneInfo
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
AI_KEY = "temperature_2m_ecmwf_aifs025_single"
PHYSICS_KEY = "temperature_2m_ecmwf_ifs025"
CREDIT = "Weather data by Open-Meteo.com, forecasts by ECMWF (CC BY 4.0)"
def main():
with open("city.json", encoding="utf-8") as file:
city = json.load(file)
with open("forecast.json", encoding="utf-8") as file:
forecast = json.load(file)
hourly = forecast["hourly"]
times = [datetime.fromisoformat(value) for value in hourly["time"]]
today = datetime.now(ZoneInfo(city["timezone"])).date()
figure, axes = plt.subplots(figsize=(12, 6))
axes.plot(times, hourly[AI_KEY], label="AI forecast (ECMWF AIFS)", linewidth=2)
axes.plot(times, hourly[PHYSICS_KEY], label="Physics forecast (ECMWF IFS)", linewidth=2)
axes.set_title(f"7-day temperature forecast for {city['name']} | {today}")
axes.set_xlabel("Day")
axes.set_ylabel("Temperature (°C)")
axes.xaxis.set_major_locator(mdates.DayLocator())
axes.xaxis.set_major_formatter(mdates.DateFormatter("%a\n%b %d"))
axes.grid(alpha=0.3)
axes.legend()
figure.text(0.5, 0.02, CREDIT, ha="center", fontsize=9)
figure.tight_layout(rect=(0, 0.05, 1, 1))
figure.savefig("forecast.png", dpi=150, bbox_inches="tight")
print("Saved forecast.png")
if __name__ == "__main__":
main()
Generate the PNG
Running the script converts the live forecast values into a PNG file. The terminal message confirms that the image was saved.
- Generate forecast.png in the second Terminal window from earlier by running this command:
python3 make_chart.py
What Does This Command Do?
Python runs make_chart.py inside the current ai-weather folder. The script reads the two JSON files before saving the chart.
You should see Saved forecast.png in the terminal. Good progress. Your model comparison now exists as a shareable image.
Chart File Was Not Created?
Check that city.json and forecast.json are still inside ai-weather.
Confirm that make_chart.py uses temperature_2m_ecmwf_aifs025_single and temperature_2m_ecmwf_ifs025 exactly.
Ask for focused help with diagnosing why the chart script did not create forecast.png.
Inspect the largest disagreement
The vertical distance between the two lines shows how far apart the models are at each timestamp. The widest gap reveals the largest disagreement in this forecast.
Before you open the chart, which day do you expect to show the widest gap?
- Open the generated chart by running this command in the second Terminal window:
open forecast.png
What Does This Command Do?
The macOS open command launches forecast.png in the default image viewer.
You should see AI forecast (ECMWF AIFS) and Physics forecast (ECMWF IFS) as two temperature lines across seven daily x-axis positions.
The title should show your selected city with the local date.
The bottom should show Weather data by Open-Meteo.com, forecasts by ECMWF (CC BY 4.0).
- Identify the day where the two forecast lines are furthest apart.
You should be able to name one day by finding the widest vertical gap between the lines.
You have now pinpointed where the AI and physics forecasts diverge most.
Your week-long comparison is ready. Next, you will test both models against historical temperatures.
Score the Models
Your seven-day chart made the largest gap between AIFS and IFS visible. Now you can test both models against completed days.
Accuracy requires comparing three-day-ahead forecasts with historical temperatures from completed days.
In this step, get ready to:
- Create score.py with Claude Code so it compares aligned forecasts with historical temperatures.
- Run score.py in your second Terminal window. Its scorecard shows the six sample dates, both mean absolute errors, and the closer model.
- Confirm that AIFS starts from initial conditions produced through physics-based data assimilation.
Create the scoring script
The Open-Meteo Previous Runs API returns values predicted 72 hours before each valid time. The Historical Weather API supplies reanalysis values for the matching hours.
Matching those timestamps lets mean absolute error summarize the average size of each model's misses.
- Switch back to the Claude Code session from earlier.
- Paste this exact request into Claude Code:
Write score.py. For the 6 days that ended 5 days ago, get what each model forecast 3 days ahead from the Open-Meteo Previous Runs API (hourly=temperature_2m_previous_day3, models=ecmwf_aifs025_single,ecmwf_ifs025), and what actually happened from the Historical Weather API (hourly=temperature_2m), for my city with timezone=auto. Print each model's average miss in degrees, and which one was closer.
What Does This Prompt Do?
- The six-day window ends five days ago so historical reanalysis is available for every date.
- The previous-runs request retrieves temperatures predicted three days before each matching timestamp.
- The historical request retrieves the comparison temperatures for those timestamps.
- The final calculation averages the absolute temperature misses for each model.
- Approve creation of score.py when Claude Code asks.
- Select the approval control shown beside the score.py proposal.
Claude Code should confirm that it created score.py inside ai-weather.
Your generated file should contain the complete scoring workflow shown in the reference tab.
✔️ Awesome, I've got everything!
Great. Confirm that score.py is saved inside ai-weather.
ⓧ I'd like to double check the full code
import json
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
import requests
PREVIOUS_RUNS_URL = "https://previous-runs-api.open-meteo.com/v1/forecast"
HISTORICAL_URL = "https://archive-api.open-meteo.com/v1/archive"
AI_KEY = "temperature_2m_previous_day3_ecmwf_aifs025_single"
PHYSICS_KEY = "temperature_2m_previous_day3_ecmwf_ifs025"
def get_json(url, params):
response = requests.get(url, params=params, timeout=30)
response.raise_for_status()
return response.json()
def mean_absolute_error(times, forecasts, actual_by_time):
errors = []
for timestamp, forecast in zip(times, forecasts):
actual = actual_by_time.get(timestamp)
if forecast is not None and actual is not None:
errors.append(abs(forecast - actual))
if not errors:
raise ValueError("No matching forecast and historical values were returned.")
return sum(errors) / len(errors)
def main():
with open("city.json", encoding="utf-8") as file:
city = json.load(file)
today = datetime.now(ZoneInfo(city["timezone"])).date()
end_date = today - timedelta(days=5)
start_date = end_date - timedelta(days=5)
common_params = {
"latitude": city["latitude"],
"longitude": city["longitude"],
"start_date": start_date.isoformat(),
"end_date": end_date.isoformat(),
"timezone": "auto",
}
previous = get_json(
PREVIOUS_RUNS_URL,
{**common_params, "hourly": "temperature_2m_previous_day3", "models": "ecmwf_aifs025_single,ecmwf_ifs025"},
)
historical = get_json(HISTORICAL_URL, {**common_params, "hourly": "temperature_2m"})
actual_by_time = dict(zip(historical["hourly"]["time"], historical["hourly"]["temperature_2m"]))
times = previous["hourly"]["time"]
ai_error = mean_absolute_error(times, previous["hourly"][AI_KEY], actual_by_time)
physics_error = mean_absolute_error(times, previous["hourly"][PHYSICS_KEY], actual_by_time)
if ai_error < physics_error:
winner = "AI (AIFS)"
elif physics_error < ai_error:
winner = "Physics (IFS)"
else:
winner = "Tie"
print(f"Forecast scorecard for {city['name']}")
print(f"Dates: {start_date} to {end_date}")
print(f"AI (AIFS) average miss: {ai_error:.2f}°C")
print(f"Physics (IFS) average miss: {physics_error:.2f}°C")
print(f"Closer model: {winner}")
if __name__ == "__main__":
main()
Run the six-day scorecard
Mean absolute error measures how far forecast temperatures were from the historical values on average. A smaller result means the model came closer during this specific six-day sample.
Before you run the scorecard, which model do you expect to have the smaller average miss?
- Run the scorecard in the second Terminal window by running this command:
python3 score.py
What Does This Command Do?
Python runs score.py using the selected city from city.json.
The script requests both datasets. It aligns their hourly timestamps before calculating each average miss.
You'll see the selected city followed by six inclusive dates ending five days ago.
You'll also see an average miss in Celsius for each model followed by Closer model.
You now have a working scorecard that tests both forecasting approaches against the same historical sample.
Scorecard Missing Values?
- Check that end_date remains five days before today in score.py.
- Confirm that your Mac has an active internet connection before retrying the script.
- Ask for targeted help with diagnosing missing scorecard values.
- Treat this six-day result as a local experiment for one city.
A different city or date range can produce a different closer model. A broad ranking needs a much larger evaluation.
Confirm where the AI forecast starts
Every forecast needs a starting description of the atmosphere. The source of that starting state explains why an AI forecast still depends on a physics-based forecasting system.
Before you ask, do you think AIFS starts from raw observations alone or from processed starting conditions?
- Switch back to the Claude Code session from earlier.
- Paste this exact question into Claude Code:
Why does the AI still need the physics model to run first?
What Does This Prompt Check?
The question checks whether the scorecard result means the AI model operates independently. It focuses on how AIFS receives the atmospheric starting conditions needed for a forecast.
Claude Code should explain that AIFS uses initial conditions produced through physics-based data assimilation.
Secret mission
Read Raw ECMWF Forecast Files
Download one AIFS file and one IFS file from the same UTC run. Decode their nearest-city temperatures from GRIB2 and compare them with your API results.
Clean Up Your Resources
Clean Up Your Resources
Everything you created lives in the local ai-weather folder, so there are no cloud resources to shut down. Keeping it creates no incremental API charges beyond your existing Claude subscription.
Resources you used:
- The local ai-weather folder containing every script and generated file from this project.
- The optional raw_ecmwf.py script with its matched-run aifs-single.grib2 and ifs.grib2 downloads inside ai-weather.
Keep everything running
No action needed. Choose this if you want to rerun the forecast comparison or scorecard later.
- Keep the ai-weather folder intact on your Mac.
- Keep forecast.png as your screenshot-ready comparison.
- Keep aifs-single.grib2 and ifs.grib2 if you want to inspect the raw forecast files again.
Your scripts and generated files remain ready to use. Keeping them creates no incremental API charges.
Pause - I'll come back to this later
Close the active sessions to free your Terminal windows. Every project file remains available on your Mac.
- Close the Terminal window running Claude Code.
- Close the second Terminal window used to run the Python scripts.
- Leave the ai-weather folder unchanged on your Mac.
Both Terminal sessions are closed. Your chart, scorecard script, and raw forecast files remain stored inside ai-weather.
Delete - I don't want to use this again
Deleting the folder is permanent. The removal only affects the local project files inside ai-weather.
- Close the Terminal window running Claude Code.
- Close the second Terminal window from earlier.
- Search for the ai-weather folder in Finder.
- Select the ai-weather folder in the search results.
- Move the selected folder to Trash.
- Open Trash.
- Remove the ai-weather folder from Trash.
The ai-weather folder no longer appears in Finder or Trash. No cloud resource or API key needs cleanup.
Nice Work!
Nice Work!
You did it! Your weather project now delivers a screenshot-ready seven-day comparison of AI and physics forecasts, backed by a six-day accuracy scorecard.
You've learned how to:
- Use Claude Code to turn exact plain-English requests into four runnable Python scripts for your selected city.
- Compare ECMWF AIFS with ECMWF IFS in a six-hour table plus an attributed seven-day chart saved as forecast.png.
- Evaluate both forecasts against Open-Meteo historical reanalysis with a six-day mean absolute error scorecard.
- Secret Mission: Download matched-run GRIB files from ECMWF for one shared UTC run. Decode nearest-city temperatures from aifs-single.grib2 and ifs.grib2 in Celsius.
Ready to quiz yourself?