File size: 2,750 Bytes
d1388f2
b8f61f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6123045
b8f61f9
 
 
 
 
 
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

import torch
import numpy as np
import pandas as pd
from datetime import datetime
from newsapi import NewsApiClient
from transformers import pipeline
import plotly.graph_objects as go
import gradio as gr

# Initialize News API client with your API key
newsapi = NewsApiClient(api_key='381793b3d6834758918838bca0cf52ee')

# Define sentiment analyzer using FinBERT
sentiment_analyzer = pipeline("text-classification", model="ProsusAI/finbert")

# Function to fetch news, analyze sentiment, and create an interactive Plotly plot
def analyze_news_sentiment(company_name):
    # Fetch news articles related to the company
    news = newsapi.get_everything(q=company_name, language='en', sort_by='publishedAt')
    
    # Extract headlines from news articles
    headlines = [article['title'] for article in news['articles']]
    
    # Perform sentiment analysis on the headlines
    result = sentiment_analyzer(headlines)
    df = pd.DataFrame(result)
    
    # Map labels to numeric values
    label_mapping = {'positive': 1, 'neutral': 0, 'negative': -1}
    df['sentiment'] = df['label'].map(label_mapping)
    
    # Drop the 'label' column
    df.drop(columns=['label'], inplace=True)
    
    # Filter out neutral sentiment values
    positive_sentiment = df[df['sentiment'] == 1]['sentiment']
    negative_sentiment = df[df['sentiment'] == -1]['sentiment']

    # Create the interactive Plotly histogram
    fig = go.Figure()

    # Add Positive sentiment histogram
    fig.add_trace(go.Histogram(
        x=positive_sentiment,
        nbinsx=1,
        name='Positive',
        marker_color='purple',
        opacity=0.75
    ))

    # Add Negative sentiment histogram
    fig.add_trace(go.Histogram(
        x=negative_sentiment,
        nbinsx=1,
        name='Negative',
        marker_color='skyblue',
        opacity=0.75
    ))

    # Update layout for better visualization
    fig.update_layout(
        title=f'Sentiment Distribution for {company_name}',
        xaxis_title='Sentiment',
        yaxis_title='Count',
        barmode='overlay',
        plot_bgcolor='black',
        paper_bgcolor='black',
        font=dict(color='white'),
        xaxis=dict(tickvals=[-1, 1], ticktext=['Negative', 'Positive']),
        bargap=0.2,
    )

    return fig




# %%
# Create a Gradio interface
interface = gr.Interface(
    fn=analyze_news_sentiment,  # Function to run
    inputs=gr.Textbox(label="Enter Company Name"),  # Input: company name
    outputs=gr.Plot(label="Sentiment Distribution"),  # Output: Interactive Plotly chart
    title="Sentiment Analysis on News Headlines",
    description="Enter a company name to analyze the sentiment of the latest news related to that company."
)

# Launch the Gradio app
interface.launch()