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

# %matplotlib inline
from matplotlib import style
style.use('fivethirtyeight')
import matplotlib.pyplot as plt

import numpy as np
import pandas as pd

import datetime as dt

# # Reflect Tables into SQLAlchemy ORM

# Python SQL toolkit and Object Relational Mapper
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func, inspect

engine = create_engine("sqlite:///Resources/hawaii.sqlite")
inspector = inspect(engine)

# reflect an existing database into a new model
Base = automap_base()

# reflect the tables
Base.prepare(engine,reflect = True)

# We can view all of the classes that automap found
Base.classes.keys()

columns = inspector.get_columns('measurement')
for column in columns:
    print(column["name"], column["type"])

columns = inspector.get_columns('station')
for column in columns:
    print(column["name"], column["type"])

# Save references to each table
Station = Base.classes.station

Measurement = Base.classes.measurement

# Create our session (link) from Python to the DB
Session = Session(engine)

# # Exploratory Climate Analysis

# Calculate the date 1 year ago from the last data point in the database
last_twelve_months = dt.date(2017,8,23)-dt.timedelta(days=365)
last_twelve_months

# Design a query to retrieve the last 12 months of precipitation data and plot the results
results = Session.query(Measurement.date, Measurement.prcp).filter(Measurement.date>=last_twelve_months).all()
#results

# Save the query results as a Pandas DataFrame and set the index to the date column
measurements = pd.DataFrame(results) 
measurements = measurements.rename(columns={"date": "Date","prcp": "Precipitation"})
measurements.set_index(measurements["Date"], inplace=True)
del measurements["Date"]
measurements.head(5)

# Sort the dataframe by date
measurements = measurements.sort_values("Date")
measurements

# Use Pandas Plotting with Matplotlib to plot the data
precipitation_plot = measurements.plot(figsize = (15,8), color = 'navy', rot=45)
plt.tight_layout()
plt.ylabel("Precipitation", size=15)
plt.title("Last 12 Months of Precipitation", size=25)
plt.savefig("Last_12_Months_of_Precipitation.png")

# Use Pandas to calculate the summary statistics for the precipitation data
measurements.describe()

# Design a query to show how many stations are available in this dataset?
no_stations = Session.query(func.count(Station.station)).all()
print(f'There are {no_stations} stations available')

# What are the most active stations? (i.e. what stations have the most rows)?
# Choose the station with the highest number of temperature observations.
# List the stations and the counts in descending order.
active_stations= Session.query(Measurement.station,func.count(Measurement.station)).group_by(Measurement.station).\
    order_by(func.count(Measurement.station).desc()).all()
active_stations

# Using the station id from the previous query, calculate the lowest temperature recorded, 
lowest_temp = Session.query(func.min(Measurement.tobs),func.max(Measurement.tobs),func.avg(Measurement.tobs)).\
    filter(Measurement.station=="USC00519281").all()
lowest_temp

# Query the last 12 months of temperature observation data for this station and plot the results as a histogram
last_twelve_months = dt.date(2017,8,23)-dt.timedelta(days=365)
station_9281 = Session.query(Measurement.tobs).filter(Measurement.station == "USC00519281").\
    filter(Measurement.date>=last_twelve_months).all()


station_9281_df = pd.DataFrame(station_9281, columns = ["tobs"])
station_9281_df = station_9281_df.rename(columns = {"tobs": "Temperature"})
station_9281_df.head(10)

station_9281_df.plot.hist(bins=12)
plt.title("Temperature Past 12 Months")
plt.xlabel("Temperature")
plt.tight_layout()
plt.savefig("Temperature_Past_12_Months")


# ## Bonus Challenge Assignment

# +
# This function called `calc_temps` will accept start date and end date in the format '%Y-%m-%d' 
# and return the minimum, average, and maximum temperatures for that range of dates
def calc_temps(start_date, end_date):
    """TMIN, TAVG, and TMAX for a list of dates.
    
    Args:
        start_date (string): A date string in the format %Y-%m-%d
        end_date (string): A date string in the format %Y-%m-%d
        
    Returns:
        TMIN, TAVE, and TMAX
    """
    
    return session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\
        filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).all()

# function usage example
print(calc_temps('2012-02-28', '2012-03-05'))
# -

# Use your previous function `calc_temps` to calculate the tmin, tavg, and tmax 
# for your trip using the previous year's data for those same dates.


# Plot the results from your previous query as a bar chart. 
# Use "Trip Avg Temp" as your Title
# Use the average temperature for the y value
# Use the peak-to-peak (tmax-tmin) value as the y error bar (yerr)


# +
# Calculate the total amount of rainfall per weather station for your trip dates using the previous year's matching dates.
# Sort this in descending order by precipitation amount and list the station, name, latitude, longitude, and elevation



# +
# Create a query that will calculate the daily normals 
# (i.e. the averages for tmin, tmax, and tavg for all historic data matching a specific month and day)

def daily_normals(date):
    """Daily Normals.
    
    Args:
        date (str): A date string in the format '%m-%d'
        
    Returns:
        A list of tuples containing the daily normals, tmin, tavg, and tmax
    
    """
    
    sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)]
    return session.query(*sel).filter(func.strftime("%m-%d", Measurement.date) == date).all()
    
daily_normals("01-01")

# +
# calculate the daily normals for your trip
# push each tuple of calculations into a list called `normals`

# Set the start and end date of the trip

# Use the start and end date to create a range of dates

# Stip off the year and save a list of %m-%d strings

# Loop through the list of %m-%d strings and calculate the normals for each date

# -

# Load the previous query results into a Pandas DataFrame and add the `trip_dates` range as the `date` index


# Plot the daily normals as an area plot with `stacked=False`


StarcoderdataJupyterScriptsDedupFiltered