Szeyu commited on
Commit
47ffeb1
·
verified ·
1 Parent(s): 72f2309

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -48
app.py CHANGED
@@ -5,16 +5,36 @@ from transformers import pipeline
5
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
6
  import time
7
 
8
- model_id = "LinkLinkWu/Boss_Stock_News_Analysis"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- # Load tokenizer & Model
 
11
  tokenizer = AutoTokenizer.from_pretrained(model_id)
12
  model = AutoModelForSequenceClassification.from_pretrained(model_id)
13
-
14
- # Initialize sentiment analysis pipeline
15
  sentiment_pipeline = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
16
 
17
- # Function to fetch top 50 news articles from FinViz
18
  def fetch_news(ticker):
19
  try:
20
  url = f"https://finviz.com/quote.ashx?t={ticker}"
@@ -32,7 +52,6 @@ def fetch_news(ticker):
32
  st.error(f"Failed to fetch news for {ticker}: {e}")
33
  return []
34
 
35
- # Function to analyze sentiment of news title
36
  def analyze_sentiment(text):
37
  try:
38
  result = sentiment_pipeline(text)[0]
@@ -41,51 +60,59 @@ def analyze_sentiment(text):
41
  st.error(f"Sentiment analysis failed: {e}")
42
  return "Unknown"
43
 
44
- # Streamlit UI
45
- st.title("Stock News Sentiment Analysis")
 
 
 
 
 
46
 
47
  # Input field for stock tickers
48
- tickers_input = st.text_input("Enter five stock tickers separated by commas (e.g., AAPL, MSFT, GOOGL, AMZN, TSLA):")
49
 
 
 
 
 
 
 
 
 
 
50
  if st.button("Get News and Sentiment"):
51
- if tickers_input:
52
- tickers = [ticker.strip().upper() for ticker in tickers_input.split(',')]
53
-
54
- # Validate input
55
- if len(tickers) != 5:
56
- st.error("Please enter exactly five stock tickers.")
57
- else:
58
- progress_bar = st.progress(0)
59
- total_stocks = len(tickers)
60
- for idx, ticker in enumerate(tickers):
61
- st.subheader(f"Analyzing {ticker}...")
62
- news_list = fetch_news(ticker)
 
 
 
63
 
64
- if news_list:
65
- # Analyze sentiment for all news articles (up to 50)
66
- sentiments = []
67
- for news in news_list:
68
- sentiment = analyze_sentiment(news['title'])
69
- sentiments.append(sentiment)
70
-
71
- # Determine overall sentiment based on majority
72
- positive_count = sentiments.count("Positive")
73
- negative_count = sentiments.count("Negative")
74
- overall_sentiment = "Positive" if positive_count > negative_count else "Negative"
75
-
76
- # Display top 3 news articles with sentiment
77
- st.write(f"**Top 3 News Articles for {ticker}**")
78
- for i, news in enumerate(news_list[:3], 1):
79
- sentiment = sentiments[i-1]
80
- st.markdown(f"{i}. [{news['title']}]({news['link']}) - **{sentiment}**")
81
-
82
- # Display overall sentiment
83
- st.write(f"**Overall Sentiment for {ticker}: {overall_sentiment}**")
84
- else:
85
- st.write(f"No news available for {ticker}.")
86
 
87
- # Update progress bar
88
- progress_bar.progress((idx + 1) / total_stocks)
89
- time.sleep(0.1) # Simulate processing time
90
- else:
91
- st.warning("Please enter stock tickers.")
 
 
 
 
 
 
 
 
 
 
5
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
6
  import time
7
 
8
+ # ----------- Page Layout & Custom Styling -----------
9
+ st.set_page_config(page_title="Stock News Sentiment Analysis", layout="centered")
10
+
11
+ st.markdown("""
12
+ <style>
13
+ .main { background-color: #f9fbfc; }
14
+ .stTextInput>div>div>input {
15
+ font-size: 16px;
16
+ padding: 0.5rem;
17
+ }
18
+ .stButton>button {
19
+ background-color: #4CAF50;
20
+ color: white;
21
+ font-size: 16px;
22
+ padding: 0.5rem 1rem;
23
+ border-radius: 8px;
24
+ }
25
+ .stButton>button:hover {
26
+ background-color: #45a049;
27
+ }
28
+ </style>
29
+ """, unsafe_allow_html=True)
30
 
31
+ # ----------- Model Setup -----------
32
+ model_id = "LinkLinkWu/Boss_Stock_News_Analysis"
33
  tokenizer = AutoTokenizer.from_pretrained(model_id)
34
  model = AutoModelForSequenceClassification.from_pretrained(model_id)
 
 
35
  sentiment_pipeline = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
36
 
37
+ # ----------- Function Definitions -----------
38
  def fetch_news(ticker):
39
  try:
40
  url = f"https://finviz.com/quote.ashx?t={ticker}"
 
52
  st.error(f"Failed to fetch news for {ticker}: {e}")
53
  return []
54
 
 
55
  def analyze_sentiment(text):
56
  try:
57
  result = sentiment_pipeline(text)[0]
 
60
  st.error(f"Sentiment analysis failed: {e}")
61
  return "Unknown"
62
 
63
+ # ----------- Streamlit UI -----------
64
+ st.title("📊 Stock News Sentiment Analysis")
65
+ st.markdown("""
66
+ This tool parses stock tickers and analyzes the sentiment of related news articles.
67
+
68
+ 💡 *Example input:* `META, NVDA, AAPL, NTES, NCTY`
69
+ """)
70
 
71
  # Input field for stock tickers
72
+ tickers_input = st.text_input("Enter stock tickers separated by commas:", "META, NVDA, AAPL, NTES, NCTY")
73
 
74
+ # Parse and display cleaned tickers in real-time
75
+ if tickers_input:
76
+ tickers = [ticker.strip().upper() for ticker in tickers_input.split(",") if ticker.strip()]
77
+ cleaned_input = ", ".join(tickers)
78
+ st.markdown(f"🔎 **Parsed Tickers:** `{cleaned_input}`")
79
+ else:
80
+ tickers = []
81
+
82
+ # Button to trigger sentiment analysis
83
  if st.button("Get News and Sentiment"):
84
+ if not tickers:
85
+ st.warning("Please enter at least one stock ticker.")
86
+ else:
87
+ progress_bar = st.progress(0)
88
+ total_stocks = len(tickers)
89
+ for idx, ticker in enumerate(tickers):
90
+ st.subheader(f"Analyzing {ticker}...")
91
+ news_list = fetch_news(ticker)
92
+
93
+ if news_list:
94
+ # Analyze sentiment for all news articles (up to 50)
95
+ sentiments = []
96
+ for news in news_list:
97
+ sentiment = analyze_sentiment(news['title'])
98
+ sentiments.append(sentiment)
99
 
100
+ # Determine overall sentiment based on majority
101
+ positive_count = sentiments.count("Positive")
102
+ negative_count = sentiments.count("Negative")
103
+ overall_sentiment = "Positive" if positive_count > negative_count else "Negative"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
+ # Display top 3 news articles with sentiment
106
+ st.write(f"**Top 3 News Articles for {ticker}**")
107
+ for i, news in enumerate(news_list[:3], 1):
108
+ sentiment = sentiments[i-1]
109
+ st.markdown(f"{i}. [{news['title']}]({news['link']}) - **{sentiment}**")
110
+
111
+ # Display overall sentiment
112
+ st.write(f"**Overall Sentiment for {ticker}: {overall_sentiment}**")
113
+ else:
114
+ st.write(f"No news available for {ticker}.")
115
+
116
+ # Update progress bar
117
+ progress_bar.progress((idx + 1) / total_stocks)
118
+ time.sleep(0.1) # Simulate processing time