Manasa1 commited on
Commit
f042f47
·
verified ·
1 Parent(s): adaac00

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +164 -55
app.py CHANGED
@@ -1,86 +1,195 @@
1
  import gradio as gr
2
  import yfinance as yf
3
  import pandas as pd
 
 
 
 
 
 
 
4
 
5
  # Mapping company names to their ticker symbols
6
- company_dict = {
7
  "Apple": "AAPL",
8
  "Google": "GOOGL",
9
  "Microsoft": "MSFT",
10
  "Amazon": "AMZN",
11
- "Tesla": "TSLA"
 
 
 
12
  }
13
 
14
- # Function to fetch ESG data for the selected company
15
- def fetch_esg_data(company_name):
16
- # Get the ticker symbol from the company name
17
- ticker = company_dict[company_name]
18
-
19
- # Fetch ESG data from Yahoo Finance
20
- stock = yf.Ticker(ticker)
21
- esg_data = stock.sustainability
22
 
23
- # If ESG data is available, process it into a DataFrame
24
- if esg_data is not None:
25
- esg_df = pd.DataFrame(esg_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
- # Extract only the relevant ESG scores and convert to a DataFrame
 
 
 
 
28
  esg_scores = esg_df.loc[["environmentScore", "socialScore", "governanceScore"], :].dropna().astype(float)
29
 
30
- # Prepare a DataFrame for plotting
31
  plot_df = pd.DataFrame({
32
  "ESG Category": ["Environment", "Social", "Governance"],
33
  "Score": esg_scores.squeeze().values
34
  })
35
 
36
- # Save the ESG data to a CSV file
37
  csv_filename = f"{ticker}_esg_data.csv"
38
  esg_df.to_csv(csv_filename)
39
- return plot_df, csv_filename, plot_df, plot_df
40
- else:
41
- # Return empty DataFrames and None if no data is available
42
- return pd.DataFrame(), None, pd.DataFrame(), pd.DataFrame()
 
 
 
 
 
 
 
43
 
44
- # Gradio interface with multiple tabs
45
- def app_interface():
46
- with gr.Blocks() as app:
47
- with gr.Tab("ESG Data Analysis"):
48
- # Dropdown to select company name
49
- company = gr.Dropdown(
50
- label="Select Company",
51
- choices=list(company_dict.keys()),
52
- value="Apple"
53
- )
54
-
55
- # Button to fetch and plot ESG data
56
- plot_button = gr.Button("Generate ESG Plot")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
- # LinePlot component for displaying the ESG data
59
- line_plot = gr.LinePlot(label="ESG Scores Line Plot", x="ESG Category", y="Score", overlay_point=True)
60
- # ScatterPlot component for displaying the ESG data
61
- scatter_plot = gr.ScatterPlot(plot_df, x="ESG Category", y="Score", overlay_point=True)
62
- # BarPlot component for displaying the ESG data
63
- bar_plot = gr.BarPlot(plot_df, x="ESG Category", y="Score")
 
 
 
 
 
 
64
 
65
- # File output for CSV download
66
- csv_output = gr.File(label="Download CSV")
67
 
68
- # Define the action when the "Generate ESG Plot" button is clicked
69
- plot_button.click(fn=fetch_esg_data, inputs=company, outputs=[line_plot, csv_output, scatter_plot, bar_plot])
70
-
71
- with gr.Tab("Tab 2"):
72
- gr.Markdown("This is Tab 2. You can add more content here.")
73
-
74
- with gr.Tab("Tab 3"):
75
- gr.Markdown("This is Tab 3. Add your custom functionality here.")
 
 
 
 
 
76
 
77
- with gr.Tab("Tab 4"):
78
- gr.Markdown("This is Tab 4. Add more features or visualization here.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
  return app
81
 
82
- # Launch the Gradio app
83
- app = app_interface()
84
  if __name__ == "__main__":
85
- app.launch()
86
-
 
1
  import gradio as gr
2
  import yfinance as yf
3
  import pandas as pd
4
+ import plotly.graph_objects as go
5
+ from typing import Tuple, Optional
6
+ import logging
7
+
8
+ # Set up logging
9
+ logging.basicConfig(level=logging.INFO)
10
+ logger = logging.getLogger(__name__)
11
 
12
  # Mapping company names to their ticker symbols
13
+ COMPANY_DICT = {
14
  "Apple": "AAPL",
15
  "Google": "GOOGL",
16
  "Microsoft": "MSFT",
17
  "Amazon": "AMZN",
18
+ "Tesla": "TSLA",
19
+ "Meta": "META",
20
+ "NVIDIA": "NVDA",
21
+ "Netflix": "NFLX"
22
  }
23
 
24
+ def fetch_esg_data(company_name: str) -> Tuple[pd.DataFrame, 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
+ - DataFrame with ESG scores
34
+ - Path to saved CSV file
35
+ - Three plotly figures for different visualizations
36
+ """
37
+ try:
38
+ # Get the ticker symbol
39
+ ticker = COMPANY_DICT[company_name]
40
+ logger.info(f"Fetching ESG data for {company_name} ({ticker})")
41
+
42
+ # Fetch ESG data
43
+ stock = yf.Ticker(ticker)
44
+ esg_data = stock.sustainability
45
 
46
+ if esg_data is None:
47
+ raise ValueError(f"No ESG data available for {company_name}")
48
+
49
+ # Process ESG data
50
+ esg_df = pd.DataFrame(esg_data)
51
  esg_scores = esg_df.loc[["environmentScore", "socialScore", "governanceScore"], :].dropna().astype(float)
52
 
53
+ # Create plotting DataFrame
54
  plot_df = pd.DataFrame({
55
  "ESG Category": ["Environment", "Social", "Governance"],
56
  "Score": esg_scores.squeeze().values
57
  })
58
 
59
+ # Save to CSV
60
  csv_filename = f"{ticker}_esg_data.csv"
61
  esg_df.to_csv(csv_filename)
62
+
63
+ # Create different plot types using plotly
64
+ line_fig = create_line_plot(plot_df)
65
+ scatter_fig = create_scatter_plot(plot_df)
66
+ bar_fig = create_bar_plot(plot_df)
67
+
68
+ return plot_df, csv_filename, line_fig, scatter_fig, bar_fig
69
+
70
+ except Exception as e:
71
+ logger.error(f"Error fetching ESG data: {str(e)}")
72
+ return pd.DataFrame(), None, {}, {}, {}
73
 
74
+ def create_line_plot(df: pd.DataFrame) -> dict:
75
+ """Create a line plot using plotly"""
76
+ fig = go.Figure()
77
+ fig.add_trace(go.Scatter(
78
+ x=df["ESG Category"],
79
+ y=df["Score"],
80
+ mode='lines+markers',
81
+ name='ESG Score'
82
+ ))
83
+ fig.update_layout(
84
+ title="ESG Scores Trend",
85
+ xaxis_title="ESG Category",
86
+ yaxis_title="Score",
87
+ yaxis_range=[0, 100]
88
+ )
89
+ return fig.to_dict()
90
+
91
+ def create_scatter_plot(df: pd.DataFrame) -> dict:
92
+ """Create a scatter plot using plotly"""
93
+ fig = go.Figure()
94
+ fig.add_trace(go.Scatter(
95
+ x=df["ESG Category"],
96
+ y=df["Score"],
97
+ mode='markers',
98
+ marker=dict(size=12),
99
+ name='ESG Score'
100
+ ))
101
+ fig.update_layout(
102
+ title="ESG Scores Distribution",
103
+ xaxis_title="ESG Category",
104
+ yaxis_title="Score",
105
+ yaxis_range=[0, 100]
106
+ )
107
+ return fig.to_dict()
108
+
109
+ def create_bar_plot(df: pd.DataFrame) -> dict:
110
+ """Create a bar plot using plotly"""
111
+ fig = go.Figure()
112
+ fig.add_trace(go.Bar(
113
+ x=df["ESG Category"],
114
+ y=df["Score"],
115
+ name='ESG Score'
116
+ ))
117
+ fig.update_layout(
118
+ title="ESG Scores Comparison",
119
+ xaxis_title="ESG Category",
120
+ yaxis_title="Score",
121
+ yaxis_range=[0, 100]
122
+ )
123
+ return fig.to_dict()
124
+
125
+ def create_interface() -> gr.Blocks:
126
+ """Create the Gradio interface"""
127
+ with gr.Blocks(theme=gr.themes.Soft()) as app:
128
+ gr.Markdown("# ESG Data Visualization Dashboard")
129
+ gr.Markdown("Analyze Environmental, Social, and Governance scores for major tech companies.")
130
+
131
+ with gr.Tab("ESG Analysis"):
132
+ with gr.Row():
133
+ with gr.Column():
134
+ company = gr.Dropdown(
135
+ label="Select Company",
136
+ choices=list(COMPANY_DICT.keys()),
137
+ value="Apple"
138
+ )
139
+ plot_button = gr.Button("Generate ESG Analysis", variant="primary")
140
+
141
+ with gr.Row():
142
+ csv_output = gr.File(label="Download Full ESG Data")
143
 
144
+ with gr.Row():
145
+ with gr.Column():
146
+ line_plot = gr.Plot(label="ESG Scores Trend")
147
+
148
+ with gr.Row():
149
+ with gr.Column():
150
+ scatter_plot = gr.Plot(label="ESG Score Distribution")
151
+ with gr.Column():
152
+ bar_plot = gr.Plot(label="ESG Score Comparison")
153
+
154
+ # Error message display
155
+ error_message = gr.Markdown(visible=False)
156
 
157
+ def handle_error(error):
158
+ return gr.Markdown.update(visible=True, value=f"⚠️ Error: {error}")
159
 
160
+ # Connect the button click to the fetch function
161
+ plot_button.click(
162
+ fn=fetch_esg_data,
163
+ inputs=company,
164
+ outputs=[
165
+ error_message,
166
+ csv_output,
167
+ line_plot,
168
+ scatter_plot,
169
+ bar_plot
170
+ ],
171
+ api_name="generate_esg_analysis"
172
+ )
173
 
174
+ with gr.Tab("About"):
175
+ gr.Markdown("""
176
+ ## About This Dashboard
177
+
178
+ This dashboard provides ESG (Environmental, Social, and Governance) data visualization for major technology companies. The data is sourced from Yahoo Finance and updated regularly.
179
+
180
+ ### How to Use
181
+ 1. Select a company from the dropdown menu
182
+ 2. Click 'Generate ESG Analysis' to view the visualizations
183
+ 3. Download the full ESG data as CSV for detailed analysis
184
+
185
+ ### Metrics Explained
186
+ - **Environmental Score**: Measures company's environmental impact and sustainability initiatives
187
+ - **Social Score**: Evaluates company's relationships with employees, suppliers, customers, and communities
188
+ - **Governance Score**: Assesses company's leadership, executive pay, audits, internal controls, and shareholder rights
189
+ """)
190
 
191
  return app
192
 
 
 
193
  if __name__ == "__main__":
194
+ app = create_interface()
195
+ app.launch(share=True, debug=True)