# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # Analysis

# 1. The peak of the temperature trend seems to be around 25 degrees latitude.
# 2. There seems to be a high degree of humidity at a majority of points near the equator.
# 3. Wind speeds seem to be the highest between -25 and 75 degrees latitude.

# +
#Import dependencies 
import pandas as pd
import numpy as np
import random
import requests
import json
import csv
import openweathermapy.core as owm
import matplotlib.pyplot as plt
from datetime import datetime

from citipy import citipy
#Importing personal API key from own config file
from config import api_key
# -

# # Generating a list of cities

#Making an empty list to store randomly generated longitude and latitude data
longi = []
latit = []
for i in range(1500):
    longi.append(float(random.uniform(-180.00,180.00)))
    latit.append(float(random.uniform(-90.00,90.00)))
#Creating empty lists to store the cities and their names
cities = []
city_names = []
#Finding the nearest city given the random coordinates
for i in range(len(longi)):
    cities.append(citipy.nearest_city(latit[i],longi[i]))
#Finding the city info and appending to empty list
for city in cities:
    city_names.append(city.city_name)
#Inputting the city name, lat, and lon into a dataframe
city_df = pd.DataFrame({"City": city_names,
                        "Latitude": latit,
                        "Longitude": longi})
#Dropping any duplicate cities 
unique_city_df = city_df.drop_duplicates(subset = ["City"])
unique_city_df.head()
#print(len(unique_city_df))
print(len(unique_city_df))

# # Grabbing city weather data

#Grabbing data using API
url = "http://api.openweathermap.org/data/2.5/weather?"
units = "imperial"
target_cities = city_df["City"]
country = []
date = []
max_temp = []
humidity = []
cloudiness = []
wind_speed = []
for target_city in target_cities:
    query_url = f"{url}appid={api_key}&units={units}&q="
    response_url = query_url + target_city
    print(f"Processing record for {target_city}: {response_url}")
    try:
        weather_data = requests.get(query_url + target_city).json()
        country_data = weather_data["sys"]["country"]
        date_data = weather_data["dt"]
        temperature = weather_data["main"]["temp_max"]
        humidity_data = weather_data["main"]["humidity"]
        cloudiness_data = weather_data["clouds"]["all"]
        wind_data = weather_data["wind"]["speed"]
    except KeyError: 
        print("Pull was unsuccessful")
    country.append(country_data)
    date.append(date_data)
    max_temp.append(temperature)
    humidity.append(humidity_data)
    cloudiness.append(cloudiness_data)
    wind_speed.append(wind_data)
weather_dict = {"City": target_cities,
                "Cloudiness": cloudiness,
                "Country": country,
                "Date": date,
                "Humidity": humidity,
                "Lat": latit,
                "Lon": longi,
                "Max Temp": max_temp,
                "Wind Speed": wind_speed}


#Putting the weather dictionary into a dataframe
weather_df = pd.DataFrame(weather_dict)
weather_df = weather_df.drop_duplicates(subset="City")
weather_df = weather_df.dropna(how="any",inplace=False)
weather_df.head()

# # Temperature (F) vs. Latitude

plt.scatter(weather_df["Lat"],weather_df["Max Temp"],c="Blue", alpha=0.75)
cur_date = datetime.now()
cur_date = cur_date.strftime("%Y-%m-%d")
plt.xlim(-95,95)
plt.ylim(0,100)
plt.title(f"City Latitude vs. Max Temperature {cur_date}")
plt.xlabel("Latitude")
plt.ylabel("Max Temperature (F)")
plt.grid(True)
plt.savefig("./Images/temp_vs_lat.jpg")
plt.show()

# # Humidity (%) vs. Latitude

plt.scatter(weather_df["Lat"],weather_df["Humidity"],c="Blue", alpha=0.75)
cur_date = datetime.now()
cur_date = cur_date.strftime("%Y-%m-%d")
plt.xlim(-95,95)
plt.ylim(0,110)
plt.title(f"City Latitude vs. Humidity {cur_date}")
plt.xlabel("Latitude")
plt.ylabel("Humidity (%)")
plt.grid(True)
plt.savefig("./Images/humidity_vs_lat.jpg")
plt.show()

# # Cloudiness (%) vs. Latitude

plt.scatter(weather_df["Lat"],weather_df["Cloudiness"],c="Blue", alpha=0.75)
cur_date = datetime.now()
cur_date = cur_date.strftime("%Y-%m-%d")
plt.xlim(-95,95)
plt.ylim(-10,120)
plt.title(f"City Latitude vs. Cloudiness {cur_date}")
plt.xlabel("Latitude")
plt.ylabel("Cloudiness (%)")
plt.grid(True)
plt.savefig("./Images/cloudiness_vs_lat.jpg")
plt.show()

# # Wind Speed (mph) vs. Latitude

plt.scatter(weather_df["Lat"],weather_df["Wind Speed"],c="Blue", alpha=0.75)
cur_date = datetime.now()
cur_date = cur_date.strftime("%Y-%m-%d")
plt.xlim(-95,95)
plt.ylim(-5,50)
plt.title(f"City Latitude vs. Wind Speed {cur_date}")
plt.xlabel("Latitude")
plt.ylabel("Wind Speed (mph)")
plt.grid(True)
plt.savefig("./Images/windspeed_vs_lat.jpg")
plt.show()



StarcoderdataJupyterScriptsDedupFiltered