dibend commited on
Commit
d137217
·
verified ·
1 Parent(s): 8c6c990

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +156 -0
app.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ import pandas as pd
4
+ import plotly.express as px
5
+ import gradio as gr
6
+ from sklearn.preprocessing import StandardScaler
7
+
8
+ # Fetch the FRED API key from environment variables
9
+ API_KEY = os.getenv("FRED_API_KEY")
10
+
11
+ def fetch_data(series_id, frequency="m", adjustment="sa"):
12
+ """
13
+ Fetch data from FRED API based on the provided series ID, frequency, and adjustment type.
14
+ """
15
+ if not API_KEY:
16
+ raise ValueError("FRED API key not set. Please set the FRED_API_KEY environment variable.")
17
+
18
+ url = "https://api.stlouisfed.org/fred/series/observations"
19
+ params = {
20
+ 'api_key': API_KEY,
21
+ 'series_id': series_id,
22
+ 'file_type': 'json',
23
+ 'frequency': frequency,
24
+ 'seasonal_adjustment': adjustment,
25
+ }
26
+ try:
27
+ response = requests.get(url, params=params)
28
+ response.raise_for_status()
29
+ data = response.json()
30
+ return data
31
+ except requests.exceptions.RequestException as e:
32
+ print(f"Error fetching data for {series_id}: {e}")
33
+ return {}
34
+
35
+ def process_data(data):
36
+ """
37
+ Process the FRED data into a pandas DataFrame.
38
+ """
39
+ if 'observations' not in data:
40
+ print("No observations found in data.")
41
+ return pd.DataFrame()
42
+
43
+ df = pd.DataFrame(data['observations'])
44
+ df['date'] = pd.to_datetime(df['date'])
45
+ df['value'] = pd.to_numeric(df['value'], errors='coerce')
46
+ return df
47
+
48
+ def standardize_series(df):
49
+ """
50
+ Standardize the 'value' column in the dataframe using Z-scores.
51
+ """
52
+ scaler = StandardScaler()
53
+ df['standardized_value'] = scaler.fit_transform(df[['value']])
54
+ return df
55
+
56
+ def create_combined_2d_visualization(dataframes, labels):
57
+ """
58
+ Generate a combined 2D line plot using Plotly.
59
+ Each dataframe will be plotted on the same axes.
60
+ """
61
+ combined_df = pd.concat(dataframes, keys=labels, names=['series', 'index']).reset_index(level='series')
62
+ fig = px.line(
63
+ combined_df,
64
+ x='date',
65
+ y='standardized_value',
66
+ color='series',
67
+ title="Combined Economic Data 2D Visualization",
68
+ labels={"standardized_value": "Standardized Value", "date": "Date", "series": "Data Type"}
69
+ )
70
+ fig.update_layout(
71
+ width=1200,
72
+ height=600,
73
+ xaxis_title="Date",
74
+ yaxis_title="Standardized Value",
75
+ legend_title="Data Type"
76
+ )
77
+ return fig
78
+
79
+ def visualize_multiple_series(series_names):
80
+ """
81
+ Fetch, standardize, and combine multiple datasets for visualization.
82
+ """
83
+ dataframes = []
84
+ labels = []
85
+ for series_name in series_names:
86
+ series_id = series_options.get(series_name)
87
+ frequency = default_frequencies.get(series_id, "m")
88
+ adjustment = default_adjustments.get(series_id, "sa")
89
+ data = fetch_data(series_id, frequency, adjustment)
90
+ df = process_data(data)
91
+ if not df.empty:
92
+ standardized_df = standardize_series(df)
93
+ dataframes.append(standardized_df)
94
+ labels.append(series_name)
95
+
96
+ if not dataframes:
97
+ raise ValueError("No valid data to visualize.")
98
+ return create_combined_2d_visualization(dataframes, labels)
99
+
100
+ # Define default frequencies and adjustments
101
+ default_frequencies = {
102
+ "GDP": "q",
103
+ "UNRATE": "m",
104
+ "CPIAUCSL": "m",
105
+ "FEDFUNDS": "m",
106
+ "MORTGAGE30US": "w"
107
+ }
108
+
109
+ default_adjustments = {
110
+ "GDP": "sa",
111
+ "UNRATE": "sa",
112
+ "CPIAUCSL": "sa",
113
+ "FEDFUNDS": "nsa",
114
+ "MORTGAGE30US": "nsa"
115
+ }
116
+
117
+ # Define options for each dropdown
118
+ series_options = {
119
+ "Gross Domestic Product (GDP)": "GDP",
120
+ "Unemployment Rate (UNRATE)": "UNRATE",
121
+ "Consumer Price Index (CPI - All Urban Consumers)": "CPIAUCSL",
122
+ "Federal Funds Rate": "FEDFUNDS",
123
+ "30-Year Fixed Mortgage Rate": "MORTGAGE30US"
124
+ }
125
+
126
+ # Gradio Interface using Blocks
127
+ with gr.Blocks() as demo:
128
+ gr.Markdown("# FRED Combined Data 2D Visualizer")
129
+ gr.Markdown("Choose multiple economic indicators to visualize them together in a 2D space.")
130
+
131
+ with gr.Row():
132
+ series_dropdown = gr.CheckboxGroup(
133
+ choices=list(series_options.keys()),
134
+ label="Select Economic Indicators to Compare"
135
+ )
136
+
137
+ plot_output = gr.Plot()
138
+
139
+ # Explanation Section
140
+ with gr.Accordion("Color Coding Explanation", open=True):
141
+ gr.Markdown("""
142
+ - **Gross Domestic Product (GDP)**: Displayed in **blue**.
143
+ - **Unemployment Rate (UNRATE)**: Displayed in **green**.
144
+ - **Consumer Price Index (CPI - All Urban Consumers)**: Displayed in **red**.
145
+ - **Federal Funds Rate**: Displayed in **purple**.
146
+ - **30-Year Fixed Mortgage Rate**: Displayed in **orange**.
147
+ """)
148
+
149
+ # Define interaction
150
+ series_dropdown.change(
151
+ visualize_multiple_series,
152
+ inputs=[series_dropdown],
153
+ outputs=[plot_output]
154
+ )
155
+
156
+ demo.launch(debug=True)