File size: 6,612 Bytes
76ba4f4
2086e56
 
f042f47
 
 
 
 
 
 
a8a3333
76ba4f4
f042f47
a8a3333
 
76ba4f4
a8a3333
f042f47
 
 
 
a8a3333
 
f042f47
 
 
8e4352d
f042f47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
090fb84
f042f47
 
 
 
 
ac0650f
8e4352d
f042f47
ac0650f
 
 
 
8e4352d
f042f47
0919ad9
 
f042f47
 
 
 
 
 
 
 
 
 
 
76ba4f4
f042f47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73fc605
f042f47
 
 
 
 
 
 
 
 
 
 
 
e03238f
f042f47
 
090fb84
f042f47
 
 
 
 
 
 
 
 
 
 
 
 
090fb84
f042f47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
090fb84
76ba4f4
 
090fb84
f042f47
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
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)