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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -65
app.py CHANGED
@@ -21,95 +21,114 @@ COMPANY_DICT = {
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(
28
  x=df["ESG Category"],
29
  y=df["Score"],
30
  mode='lines+markers',
31
- name='ESG Score'
 
 
32
  ))
33
  fig.update_layout(
34
- title="ESG Scores Trend",
35
  xaxis_title="ESG Category",
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(
45
  x=df["ESG Category"],
46
  y=df["Score"],
47
  mode='markers',
48
- marker=dict(size=12),
 
 
 
 
 
 
 
49
  name='ESG Score'
50
  ))
51
  fig.update_layout(
52
- title="ESG Scores Distribution",
53
  xaxis_title="ESG Category",
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(
63
  x=df["ESG Category"],
64
  y=df["Score"],
 
65
  name='ESG Score'
66
  ))
67
  fig.update_layout(
68
- title="ESG Scores Comparison",
69
  xaxis_title="ESG Category",
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:
@@ -137,55 +156,35 @@ def create_interface() -> gr.Blocks:
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,8 +196,10 @@ def create_interface() -> gr.Blocks:
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
 
21
  "Netflix": "NFLX"
22
  }
23
 
24
+ def create_line_plot(df: pd.DataFrame, company_name: str) -> go.Figure:
25
  """Create a line plot using plotly"""
26
  fig = go.Figure()
27
  fig.add_trace(go.Scatter(
28
  x=df["ESG Category"],
29
  y=df["Score"],
30
  mode='lines+markers',
31
+ name='ESG Score',
32
+ line=dict(color='rgb(55, 83, 109)', width=2),
33
+ marker=dict(size=10)
34
  ))
35
  fig.update_layout(
36
+ title=f"ESG Scores Trend for {company_name}",
37
  xaxis_title="ESG Category",
38
  yaxis_title="Score",
39
+ yaxis_range=[0, 100],
40
+ height=400,
41
+ template='plotly_white'
42
  )
43
  return fig
44
 
45
+ def create_scatter_plot(df: pd.DataFrame, company_name: str) -> go.Figure:
46
  """Create a scatter plot using plotly"""
47
  fig = go.Figure()
48
  fig.add_trace(go.Scatter(
49
  x=df["ESG Category"],
50
  y=df["Score"],
51
  mode='markers',
52
+ marker=dict(
53
+ size=15,
54
+ color='rgb(55, 83, 109)',
55
+ line=dict(
56
+ color='rgb(8,48,107)',
57
+ width=2
58
+ )
59
+ ),
60
  name='ESG Score'
61
  ))
62
  fig.update_layout(
63
+ title=f"ESG Score Distribution for {company_name}",
64
  xaxis_title="ESG Category",
65
  yaxis_title="Score",
66
+ yaxis_range=[0, 100],
67
+ height=400,
68
+ template='plotly_white'
69
  )
70
  return fig
71
 
72
+ def create_bar_plot(df: pd.DataFrame, company_name: str) -> go.Figure:
73
  """Create a bar plot using plotly"""
74
  fig = go.Figure()
75
  fig.add_trace(go.Bar(
76
  x=df["ESG Category"],
77
  y=df["Score"],
78
+ marker_color='rgb(55, 83, 109)',
79
  name='ESG Score'
80
  ))
81
  fig.update_layout(
82
+ title=f"ESG Scores Comparison for {company_name}",
83
  xaxis_title="ESG Category",
84
  yaxis_title="Score",
85
+ yaxis_range=[0, 100],
86
+ height=400,
87
+ template='plotly_white'
88
  )
89
  return fig
90
 
91
+ def create_empty_plot(message: str) -> go.Figure:
92
+ """Create an empty plot with an error message"""
93
+ fig = go.Figure()
94
+ fig.add_annotation(
95
+ text=message,
96
+ xref="paper",
97
+ yref="paper",
98
+ x=0.5,
99
+ y=0.5,
100
+ showarrow=False,
101
+ font=dict(size=14)
102
+ )
103
+ fig.update_layout(
104
+ xaxis_visible=False,
105
+ yaxis_visible=False,
106
+ height=400
107
+ )
108
+ return fig
109
+
110
+ def fetch_esg_data(company_name: str) -> Tuple[Optional[pd.DataFrame], str]:
111
  """
112
  Fetch and process ESG data for the selected company.
 
 
 
 
 
 
 
 
113
  """
114
  try:
 
115
  ticker = COMPANY_DICT[company_name]
116
  logger.info(f"Fetching ESG data for {company_name} ({ticker})")
117
 
 
118
  stock = yf.Ticker(ticker)
119
  esg_data = stock.sustainability
120
 
121
  if esg_data is None:
122
  return None, f"No ESG data available for {company_name}"
123
 
 
124
  esg_df = pd.DataFrame(esg_data)
125
  esg_scores = esg_df.loc[["environmentScore", "socialScore", "governanceScore"], :].dropna().astype(float)
126
 
 
127
  plot_df = pd.DataFrame({
128
  "ESG Category": ["Environment", "Social", "Governance"],
129
  "Score": esg_scores.squeeze().values
130
  })
131
 
 
 
 
 
132
  return plot_df, f"Successfully fetched ESG data for {company_name}"
133
 
134
  except Exception as e:
 
156
  visible=True
157
  )
158
 
159
+ with gr.Row():
160
+ line_plot = gr.Plot(label="Trend Analysis")
161
+
162
  with gr.Row():
163
  with gr.Column():
164
+ scatter_plot = gr.Plot(label="Distribution Analysis")
165
+ with gr.Column():
166
+ bar_plot = gr.Plot(label="Comparison Analysis")
167
 
168
+ def process_esg_request(company_name: str) -> Tuple[go.Figure, go.Figure, go.Figure, str]:
169
  # Fetch the data
170
  plot_df, status = fetch_esg_data(company_name)
171
 
172
  if plot_df is None:
173
+ empty_plot = create_empty_plot(status)
174
+ return empty_plot, empty_plot, empty_plot, status
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
 
176
+ # Create all three plots
177
+ line = create_line_plot(plot_df, company_name)
178
+ scatter = create_scatter_plot(plot_df, company_name)
179
+ bar = create_bar_plot(plot_df, company_name)
 
 
 
 
 
180
 
181
+ return line, scatter, bar, status
182
 
183
  # Connect the button click to the process function
184
  plot_button.click(
185
  fn=process_esg_request,
186
  inputs=company,
187
+ outputs=[line_plot, scatter_plot, bar_plot, status_message],
188
  api_name="generate_esg_analysis"
189
  )
190
 
 
196
 
197
  ### How to Use
198
  1. Select a company from the dropdown menu
199
+ 2. Click 'Generate ESG Analysis' to view multiple visualizations:
200
+ - Trend Analysis: Shows the progression across ESG categories
201
+ - Distribution Analysis: Displays the spread of ESG scores
202
+ - Comparison Analysis: Compares ESG scores side by side
203
 
204
  ### Metrics Explained
205
  - **Environmental Score**: Measures company's environmental impact and sustainability initiatives