File size: 2,670 Bytes
29e42d5
78c1fff
 
6af8332
908b282
 
 
 
 
 
 
29e42d5
78c1fff
 
 
 
 
 
 
ef3e3f0
78c1fff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29e42d5
6af8332
78c1fff
29e42d5
78c1fff
 
822643b
78c1fff
 
 
6af8332
78c1fff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import requests
from bs4 import BeautifulSoup
from transformers import pipeline
from transformers import AutoTokenizer, AutoModelForSequenceClassification

model_id = "LinkLinkWu/Boss_Stock_News_Analysis"

# Load tokenizer & Model
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForSequenceClassification.from_pretrained(model_id)

# Initialize sentiment analysis pipeline
sentiment_pipeline = pipeline("sentiment-analysis")

# Function to fetch top 3 news articles from FinViz
def fetch_news(ticker):
    try:
        url = f"https://finviz.com/quote.ashx?t={ticker}"
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}
        response = requests.get(url, headers=headers)
        soup = BeautifulSoup(response.text, 'html.parser')
        news_table = soup.find(id='news-table')
        news = []
        for row in news_table.findAll('tr')[:3]:  # Limit to top 3
            title = row.a.get_text()
            link = row.a['href']
            news.append({'title': title, 'link': link})
        return news
    except Exception as e:
        st.error(f"Failed to fetch news for {ticker}: {e}")
        return []

# Function to analyze sentiment of news title
def analyze_sentiment(text):
    try:
        result = sentiment_pipeline(text)[0]
        return "Positive" if result['label'] == 'POSITIVE' else "Negative"
    except Exception as e:
        st.error(f"Sentiment analysis failed: {e}")
        return "Unknown"

# Streamlit UI
st.title("Stock News Sentiment Analysis")

# Input field for stock tickers
tickers_input = st.text_input("Enter five stock tickers separated by commas (e.g., AAPL, MSFT, GOOGL, AMZN, TSLA):")

if st.button("Get News and Sentiment"):
    if tickers_input:
        tickers = [ticker.strip().upper() for ticker in tickers_input.split(',')]
        
        # Validate input
        if len(tickers) != 5:
            st.error("Please enter exactly five stock tickers.")
        else:
            # Process each ticker
            for ticker in tickers:
                st.subheader(f"Top 3 News Articles for {ticker}")
                news_list = fetch_news(ticker)
                
                if news_list:
                    for i, news in enumerate(news_list, 1):
                        sentiment = analyze_sentiment(news['title'])
                        st.markdown(f"{i}. [{news['title']}]({news['link']}) - **{sentiment}**")
                else:
                    st.write("No news available for this ticker.")
    else:
        st.warning("Please enter stock tickers.")