ESG_Dashboard / app.py
Manasa1's picture
Update app.py
f042f47 verified
raw
history blame
6.61 kB
import gradio as gr
import yfinance as yf
import pandas as pd
import plotly.graph_objects as go
from typing import Tuple, Optional
import logging
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Mapping company names to their ticker symbols
COMPANY_DICT = {
"Apple": "AAPL",
"Google": "GOOGL",
"Microsoft": "MSFT",
"Amazon": "AMZN",
"Tesla": "TSLA",
"Meta": "META",
"NVIDIA": "NVDA",
"Netflix": "NFLX"
}
def fetch_esg_data(company_name: str) -> Tuple[pd.DataFrame, Optional[str], dict, dict, dict]:
"""
Fetch and process ESG data for the selected company.
Args:
company_name (str): Name of the company to fetch ESG data for
Returns:
Tuple containing:
- DataFrame with ESG scores
- Path to saved CSV file
- Three plotly figures for different visualizations
"""
try:
# Get the ticker symbol
ticker = COMPANY_DICT[company_name]
logger.info(f"Fetching ESG data for {company_name} ({ticker})")
# Fetch ESG data
stock = yf.Ticker(ticker)
esg_data = stock.sustainability
if esg_data is None:
raise ValueError(f"No ESG data available for {company_name}")
# Process ESG data
esg_df = pd.DataFrame(esg_data)
esg_scores = esg_df.loc[["environmentScore", "socialScore", "governanceScore"], :].dropna().astype(float)
# Create plotting DataFrame
plot_df = pd.DataFrame({
"ESG Category": ["Environment", "Social", "Governance"],
"Score": esg_scores.squeeze().values
})
# Save to CSV
csv_filename = f"{ticker}_esg_data.csv"
esg_df.to_csv(csv_filename)
# Create different plot types using plotly
line_fig = create_line_plot(plot_df)
scatter_fig = create_scatter_plot(plot_df)
bar_fig = create_bar_plot(plot_df)
return plot_df, csv_filename, line_fig, scatter_fig, bar_fig
except Exception as e:
logger.error(f"Error fetching ESG data: {str(e)}")
return pd.DataFrame(), None, {}, {}, {}
def create_line_plot(df: pd.DataFrame) -> dict:
"""Create a line plot using plotly"""
fig = go.Figure()
fig.add_trace(go.Scatter(
x=df["ESG Category"],
y=df["Score"],
mode='lines+markers',
name='ESG Score'
))
fig.update_layout(
title="ESG Scores Trend",
xaxis_title="ESG Category",
yaxis_title="Score",
yaxis_range=[0, 100]
)
return fig.to_dict()
def create_scatter_plot(df: pd.DataFrame) -> dict:
"""Create a scatter plot using plotly"""
fig = go.Figure()
fig.add_trace(go.Scatter(
x=df["ESG Category"],
y=df["Score"],
mode='markers',
marker=dict(size=12),
name='ESG Score'
))
fig.update_layout(
title="ESG Scores Distribution",
xaxis_title="ESG Category",
yaxis_title="Score",
yaxis_range=[0, 100]
)
return fig.to_dict()
def create_bar_plot(df: pd.DataFrame) -> dict:
"""Create a bar plot using plotly"""
fig = go.Figure()
fig.add_trace(go.Bar(
x=df["ESG Category"],
y=df["Score"],
name='ESG Score'
))
fig.update_layout(
title="ESG Scores Comparison",
xaxis_title="ESG Category",
yaxis_title="Score",
yaxis_range=[0, 100]
)
return fig.to_dict()
def create_interface() -> gr.Blocks:
"""Create the Gradio interface"""
with gr.Blocks(theme=gr.themes.Soft()) as app:
gr.Markdown("# ESG Data Visualization Dashboard")
gr.Markdown("Analyze Environmental, Social, and Governance scores for major tech companies.")
with gr.Tab("ESG Analysis"):
with gr.Row():
with gr.Column():
company = gr.Dropdown(
label="Select Company",
choices=list(COMPANY_DICT.keys()),
value="Apple"
)
plot_button = gr.Button("Generate ESG Analysis", variant="primary")
with gr.Row():
csv_output = gr.File(label="Download Full ESG Data")
with gr.Row():
with gr.Column():
line_plot = gr.Plot(label="ESG Scores Trend")
with gr.Row():
with gr.Column():
scatter_plot = gr.Plot(label="ESG Score Distribution")
with gr.Column():
bar_plot = gr.Plot(label="ESG Score Comparison")
# Error message display
error_message = gr.Markdown(visible=False)
def handle_error(error):
return gr.Markdown.update(visible=True, value=f"⚠️ Error: {error}")
# Connect the button click to the fetch function
plot_button.click(
fn=fetch_esg_data,
inputs=company,
outputs=[
error_message,
csv_output,
line_plot,
scatter_plot,
bar_plot
],
api_name="generate_esg_analysis"
)
with gr.Tab("About"):
gr.Markdown("""
## About This Dashboard
This dashboard provides ESG (Environmental, Social, and Governance) data visualization for major technology companies. The data is sourced from Yahoo Finance and updated regularly.
### How to Use
1. Select a company from the dropdown menu
2. Click 'Generate ESG Analysis' to view the visualizations
3. Download the full ESG data as CSV for detailed analysis
### Metrics Explained
- **Environmental Score**: Measures company's environmental impact and sustainability initiatives
- **Social Score**: Evaluates company's relationships with employees, suppliers, customers, and communities
- **Governance Score**: Assesses company's leadership, executive pay, audits, internal controls, and shareholder rights
""")
return app
if __name__ == "__main__":
app = create_interface()
app.launch(share=True, debug=True)