Created
February 12, 2025 11:41
-
-
Save cavedave/81046a6c94b7ce899ee22af9f36faa86 to your computer and use it in GitHub Desktop.
usa egg prices
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import pandas as pd | |
def download_data(url, filename): | |
"""Downloads data from a given URL and saves it as a CSV file. | |
Args: | |
url: The URL of the data to download. | |
filename: The name of the CSV file to save the data to. | |
""" | |
try: | |
response = requests.get(url) | |
response.raise_for_status() # Raise an exception for bad status codes | |
with open(filename, 'wb') as f: | |
f.write(response.content) | |
print(f"Data downloaded successfully and saved to {filename}") | |
except requests.exceptions.RequestException as e: | |
print(f"Error downloading data: {e}") | |
except Exception as e: | |
print(f"An unexpected error occurred: {e}") | |
# Example usage: | |
url = "https://fred.stlouisfed.org/graph/fredgraph.csv?bgcolor=%23ebf3fb&chart_type=line&drp=0&fo=open%20sans&graph_bgcolor=%23ffffff&height=450&mode=fred&recession_bars=on&txtcolor=%23444444&ts=12&tts=12&width=1140&nt=0&thu=0&trc=0&show_legend=yes&show_axis_titles=yes&show_tooltip=yes&id=APU0000708111&scale=left&cosd=1980-01-01&coed=2024-12-01&line_color=%230073e6&link_values=false&line_style=solid&mark_type=none&mw=3&lw=3&ost=-99999&oet=99999&mma=0&fml=a&fq=Monthly&fam=avg&fgst=lin&fgsnd=2020-02-01&line_index=1&transformation=lin&vintage_date=2025-02-12&revision_date=2025-02-12&nd=1980-01-01" | |
filename = "eggs.csv" | |
download_data(url, filename) | |
import matplotlib.pyplot as plt | |
import pandas as pd | |
# Assuming eggs.csv is in the current working directory of the notebook. | |
# If it's in a different location, adjust the filepath accordingly. | |
try: | |
eggs = pd.read_csv('eggs.csv') | |
# Convert 'observation_date' to datetime objects | |
eggs['observation_date'] = pd.to_datetime(eggs['observation_date']) | |
# eggs['12M_MA'] = eggs['APU0000708111'].rolling(window=12).mean() | |
# plt.plot(eggs['observation_date'], eggs['12M_MA'], label="12-Month Moving Avg", linestyle="dashed", color="red") | |
annotate_date = pd.to_datetime("2022-06-01") | |
# Create the line plot | |
plt.figure(figsize=(10, 6)) # Adjust figure size as needed | |
plt.plot(eggs['observation_date'], eggs['APU0000708111']) | |
plt.xlabel('Year') | |
plt.ylabel('Price in Dollars') | |
plt.title('Egg Price Over Time') | |
# Add Annotation | |
plt.annotate( | |
'Bird Flu Outbreak', | |
xy=(annotate_date, 2.50), # Arrow still points to the actual event | |
xytext=(pd.to_datetime("2010-01-01"), 4.00), # Move text to x=2010, y=4 | |
arrowprops=dict(facecolor='black', shrink=0.05), | |
fontsize=12, | |
bbox=dict(boxstyle="round,pad=0.3", edgecolor="black", facecolor="white") | |
) | |
plt.grid(True) # Add gridlines for better readability | |
plt.xticks(rotation=45) # Rotate x-axis labels for better visibility if needed | |
plt.tight_layout() # Adjust layout to prevent labels from overlapping | |
# Save the plot as a PNG file | |
plt.savefig('egg_price_plot.png') | |
plt.show() | |
except FileNotFoundError: | |
print("Error: eggs.csv not found in the current directory.") | |
except pd.errors.ParserError: | |
print("Error: Could not parse eggs.csv. Please check file format.") | |
except KeyError as e: | |
print(f"Error: Column '{e}' not found in the DataFrame. Check your column name.") | |
except Exception as e: | |
print(f"An unexpected error occurred: {e}") | |
Author
cavedave
commented
Feb 12, 2025
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment