Manasa1 commited on
Commit
631a049
·
verified ·
1 Parent(s): 0e731dc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -103
app.py CHANGED
@@ -21,56 +21,7 @@ COMPANY_DICT = {
21
  "Netflix": "NFLX"
22
  }
23
 
24
- def fetch_esg_data(company_name: str) -> Tuple[Optional[str], dict, dict, dict]:
25
- """
26
- Fetch and process ESG data for the selected company.
27
-
28
- Args:
29
- company_name (str): Name of the company to fetch ESG data for
30
-
31
- Returns:
32
- Tuple containing:
33
- - Path to saved CSV file
34
- - Three plotly figures for different visualizations
35
- """
36
- try:
37
- # Get the ticker symbol
38
- ticker = COMPANY_DICT[company_name]
39
- logger.info(f"Fetching ESG data for {company_name} ({ticker})")
40
-
41
- # Fetch ESG data
42
- stock = yf.Ticker(ticker)
43
- esg_data = stock.sustainability
44
-
45
- if esg_data is None:
46
- return None, None, None, None
47
-
48
- # Process ESG data
49
- esg_df = pd.DataFrame(esg_data)
50
- esg_scores = esg_df.loc[["environmentScore", "socialScore", "governanceScore"], :].dropna().astype(float)
51
-
52
- # Create plotting DataFrame
53
- plot_df = pd.DataFrame({
54
- "ESG Category": ["Environment", "Social", "Governance"],
55
- "Score": esg_scores.squeeze().values
56
- })
57
-
58
- # Save to CSV
59
- csv_filename = f"{ticker}_esg_data.csv"
60
- esg_df.to_csv(csv_filename)
61
-
62
- # Create different plot types using plotly
63
- line_fig = create_line_plot(plot_df)
64
- scatter_fig = create_scatter_plot(plot_df)
65
- bar_fig = create_bar_plot(plot_df)
66
-
67
- return csv_filename, line_fig, scatter_fig, bar_fig
68
-
69
- except Exception as e:
70
- logger.error(f"Error fetching ESG data: {str(e)}")
71
- return None, None, None, None
72
-
73
- def create_line_plot(df: pd.DataFrame) -> dict:
74
  """Create a line plot using plotly"""
75
  fig = go.Figure()
76
  fig.add_trace(go.Scatter(
@@ -85,9 +36,9 @@ def create_line_plot(df: pd.DataFrame) -> dict:
85
  yaxis_title="Score",
86
  yaxis_range=[0, 100]
87
  )
88
- return fig.to_dict()
89
 
90
- def create_scatter_plot(df: pd.DataFrame) -> dict:
91
  """Create a scatter plot using plotly"""
92
  fig = go.Figure()
93
  fig.add_trace(go.Scatter(
@@ -103,9 +54,9 @@ def create_scatter_plot(df: pd.DataFrame) -> dict:
103
  yaxis_title="Score",
104
  yaxis_range=[0, 100]
105
  )
106
- return fig.to_dict()
107
 
108
- def create_bar_plot(df: pd.DataFrame) -> dict:
109
  """Create a bar plot using plotly"""
110
  fig = go.Figure()
111
  fig.add_trace(go.Bar(
@@ -119,7 +70,51 @@ def create_bar_plot(df: pd.DataFrame) -> dict:
119
  yaxis_title="Score",
120
  yaxis_range=[0, 100]
121
  )
122
- return fig.to_dict()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
 
124
  def create_interface() -> gr.Blocks:
125
  """Create the Gradio interface"""
@@ -136,60 +131,61 @@ def create_interface() -> gr.Blocks:
136
  value="Apple"
137
  )
138
  plot_button = gr.Button("Generate ESG Analysis", variant="primary")
139
-
140
- with gr.Row():
141
- csv_output = gr.File(label="Download Full ESG Data")
 
 
142
 
143
  with gr.Row():
144
  with gr.Column():
145
- line_plot = gr.Plot(label="ESG Scores Trend")
146
-
147
- with gr.Row():
148
- with gr.Column():
149
- scatter_plot = gr.Plot(label="ESG Score Distribution")
150
- with gr.Column():
151
- bar_plot = gr.Plot(label="ESG Score Comparison")
152
-
153
- status_message = gr.Textbox(
154
- label="Status",
155
- interactive=False,
156
- visible=True
157
- )
158
 
159
- def process_esg_data(company_name):
160
- try:
161
- csv_file, line, scatter, bar = fetch_esg_data(company_name)
162
-
163
- if csv_file is None:
164
- return (
165
- None,
166
- None,
167
- None,
168
- None,
169
- f"No ESG data available for {company_name}"
170
- )
171
-
172
- return (
173
- csv_file,
174
- line,
175
- scatter,
176
- bar,
177
- f"Successfully generated ESG analysis for {company_name}"
178
  )
179
- except Exception as e:
180
- return None, None, None, None, f"Error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
 
182
  # Connect the button click to the process function
183
  plot_button.click(
184
- fn=process_esg_data,
185
  inputs=company,
186
- outputs=[
187
- csv_output,
188
- line_plot,
189
- scatter_plot,
190
- bar_plot,
191
- status_message
192
- ],
193
  api_name="generate_esg_analysis"
194
  )
195
 
@@ -201,8 +197,8 @@ def create_interface() -> gr.Blocks:
201
 
202
  ### How to Use
203
  1. Select a company from the dropdown menu
204
- 2. Click 'Generate ESG Analysis' to view the visualizations
205
- 3. Download the full ESG data as CSV for detailed analysis
206
 
207
  ### Metrics Explained
208
  - **Environmental Score**: Measures company's environmental impact and sustainability initiatives
@@ -214,4 +210,4 @@ def create_interface() -> gr.Blocks:
214
 
215
  if __name__ == "__main__":
216
  app = create_interface()
217
- app.launch(share=True, debug=True)
 
21
  "Netflix": "NFLX"
22
  }
23
 
24
+ def create_line_plot(df: pd.DataFrame) -> go.Figure:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  """Create a line plot using plotly"""
26
  fig = go.Figure()
27
  fig.add_trace(go.Scatter(
 
36
  yaxis_title="Score",
37
  yaxis_range=[0, 100]
38
  )
39
+ return fig
40
 
41
+ def create_scatter_plot(df: pd.DataFrame) -> go.Figure:
42
  """Create a scatter plot using plotly"""
43
  fig = go.Figure()
44
  fig.add_trace(go.Scatter(
 
54
  yaxis_title="Score",
55
  yaxis_range=[0, 100]
56
  )
57
+ return fig
58
 
59
+ def create_bar_plot(df: pd.DataFrame) -> go.Figure:
60
  """Create a bar plot using plotly"""
61
  fig = go.Figure()
62
  fig.add_trace(go.Bar(
 
70
  yaxis_title="Score",
71
  yaxis_range=[0, 100]
72
  )
73
+ return fig
74
+
75
+ def fetch_esg_data(company_name: str) -> Tuple[Optional[str], str]:
76
+ """
77
+ Fetch and process ESG data for the selected company.
78
+
79
+ Args:
80
+ company_name (str): Name of the company to fetch ESG data for
81
+
82
+ Returns:
83
+ Tuple containing:
84
+ - DataFrame with processed data
85
+ - Status message
86
+ """
87
+ try:
88
+ # Get the ticker symbol
89
+ ticker = COMPANY_DICT[company_name]
90
+ logger.info(f"Fetching ESG data for {company_name} ({ticker})")
91
+
92
+ # Fetch ESG data
93
+ stock = yf.Ticker(ticker)
94
+ esg_data = stock.sustainability
95
+
96
+ if esg_data is None:
97
+ return None, f"No ESG data available for {company_name}"
98
+
99
+ # Process ESG data
100
+ esg_df = pd.DataFrame(esg_data)
101
+ esg_scores = esg_df.loc[["environmentScore", "socialScore", "governanceScore"], :].dropna().astype(float)
102
+
103
+ # Create plotting DataFrame
104
+ plot_df = pd.DataFrame({
105
+ "ESG Category": ["Environment", "Social", "Governance"],
106
+ "Score": esg_scores.squeeze().values
107
+ })
108
+
109
+ # Save to CSV
110
+ csv_filename = f"{ticker}_esg_data.csv"
111
+ esg_df.to_csv(csv_filename)
112
+
113
+ return plot_df, f"Successfully fetched ESG data for {company_name}"
114
+
115
+ except Exception as e:
116
+ logger.error(f"Error fetching ESG data: {str(e)}")
117
+ return None, f"Error fetching ESG data: {str(e)}"
118
 
119
  def create_interface() -> gr.Blocks:
120
  """Create the Gradio interface"""
 
131
  value="Apple"
132
  )
133
  plot_button = gr.Button("Generate ESG Analysis", variant="primary")
134
+ status_message = gr.Textbox(
135
+ label="Status",
136
+ interactive=False,
137
+ visible=True
138
+ )
139
 
140
  with gr.Row():
141
  with gr.Column():
142
+ plot = gr.Plot(label="ESG Scores Analysis")
 
 
 
 
 
 
 
 
 
 
 
 
143
 
144
+ def process_esg_request(company_name: str) -> Tuple[go.Figure, str]:
145
+ # Fetch the data
146
+ plot_df, status = fetch_esg_data(company_name)
147
+
148
+ if plot_df is None:
149
+ # Create an empty figure with an error message
150
+ fig = go.Figure()
151
+ fig.add_annotation(
152
+ text=status,
153
+ xref="paper",
154
+ yref="paper",
155
+ x=0.5,
156
+ y=0.5,
157
+ showarrow=False
 
 
 
 
 
158
  )
159
+ return fig, status
160
+
161
+ # Create a combined figure with subplots
162
+ fig = go.Figure()
163
+
164
+ # Add bar chart
165
+ fig.add_trace(go.Bar(
166
+ x=plot_df["ESG Category"],
167
+ y=plot_df["Score"],
168
+ name="Score",
169
+ marker_color="rgb(55, 83, 109)"
170
+ ))
171
+
172
+ # Update layout
173
+ fig.update_layout(
174
+ title=f"ESG Analysis for {company_name}",
175
+ xaxis_title="ESG Category",
176
+ yaxis_title="Score",
177
+ yaxis_range=[0, 100],
178
+ showlegend=True,
179
+ height=500
180
+ )
181
+
182
+ return fig, status
183
 
184
  # Connect the button click to the process function
185
  plot_button.click(
186
+ fn=process_esg_request,
187
  inputs=company,
188
+ outputs=[plot, status_message],
 
 
 
 
 
 
189
  api_name="generate_esg_analysis"
190
  )
191
 
 
197
 
198
  ### How to Use
199
  1. Select a company from the dropdown menu
200
+ 2. Click 'Generate ESG Analysis' to view the visualization
201
+ 3. The plot shows the Environmental, Social, and Governance scores for the selected company
202
 
203
  ### Metrics Explained
204
  - **Environmental Score**: Measures company's environmental impact and sustainability initiatives
 
210
 
211
  if __name__ == "__main__":
212
  app = create_interface()
213
+ app.launch(share=True, debug=True)