Akshayram1 commited on
Commit
e8d7188
·
verified ·
1 Parent(s): 243d786

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +157 -282
app.py CHANGED
@@ -6,319 +6,194 @@ import plotly.express as px
6
  from dateutil import parser
7
  import datetime
8
  import requests
9
- from transformers import AutoModelForSequenceClassification, AutoTokenizer, pipeline
10
- import torch
11
- import pytz
12
 
13
- # Page config
14
- st.set_page_config(
15
- page_title="Stock News Sentiment Analyzer",
16
- page_icon="📈",
17
- layout="wide",
18
- initial_sidebar_state="expanded"
19
- )
20
 
21
- # Custom CSS
22
- st.markdown("""
23
- <style>
24
- .stAlert {
25
- padding: 10px;
26
- margin-bottom: 20px;
27
- }
28
- .reportview-container {
29
- background: #f0f2f6
30
- }
31
- .main {
32
- padding: 2rem;
33
- }
34
- h1, h2, h3 {
35
- color: #1f77b4;
36
- }
37
- .stDataFrame {
38
- padding: 1rem;
39
- }
40
- </style>
41
- """, unsafe_allow_html=True)
42
-
43
- # Cache the model loading
44
  @st.cache_resource
45
- def load_finbert_model():
46
- try:
47
- model = AutoModelForSequenceClassification.from_pretrained("yiyanghkust/finbert-tone")
48
- tokenizer = AutoTokenizer.from_pretrained("yiyanghkust/finbert-tone")
49
- return pipeline("text-classification", model=model, tokenizer=tokenizer)
50
- except Exception as e:
51
- st.error(f"Error loading model: {str(e)}")
52
- return None
53
 
54
- # Load the model
55
- finbert = load_finbert_model()
56
 
57
- def verify_link(url, timeout=5, retries=2):
58
- """Verify if a URL is accessible."""
59
  for _ in range(retries):
60
  try:
61
  response = requests.head(url, timeout=timeout, allow_redirects=True)
62
- return 200 <= response.status_code < 300
 
63
  except requests.RequestException:
64
  continue
65
  return False
66
 
67
  def get_news(ticker):
68
- """Scrape news from FinViz for a given stock ticker."""
69
- try:
70
- finviz_url = f'https://finviz.com/quote.ashx?t={ticker}'
71
- headers = {
72
- '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'
73
- }
74
- req = Request(url=finviz_url, headers=headers)
75
- response = urlopen(req)
76
- html = BeautifulSoup(response, 'html.parser')
77
- news_table = html.find(id='news-table')
78
- if news_table is None:
79
- raise ValueError("No news table found - invalid ticker or website structure changed")
80
- return news_table
81
- except Exception as e:
82
- raise Exception(f"Error fetching news for {ticker}: {str(e)}")
83
 
84
  def parse_news(news_table):
85
- """Parse the news table and return a DataFrame."""
86
  parsed_news = []
87
 
88
- try:
89
- # Get timezone for EST (FinViz uses EST)
90
- est = pytz.timezone('US/Eastern')
91
-
92
- for row in news_table.findAll('tr'):
93
- title = row.a.get_text()
94
- link = row.a['href']
95
- date_data = row.td.text.strip().split()
96
-
97
- # Handle different date formats
98
- current_date = datetime.datetime.now(est)
99
 
100
- if len(date_data) == 1: # Time only
101
- time = date_data[0]
102
- date = current_date.strftime('%Y-%m-%d')
103
  else:
104
- if date_data[0] == 'Today':
105
- date = current_date.strftime('%Y-%m-%d')
106
- time = date_data[1]
107
- elif len(date_data[0]) <= 3: # Abbreviated month name
108
- month = current_date.strftime('%Y-') + date_data[0]
109
- date = parser.parse(month).strftime('%Y-%m-%d')
110
- time = date_data[1]
111
- else:
112
- date = date_data[0]
113
- time = date_data[1]
114
-
115
- # Convert time to 24-hour format
116
- try:
117
- if 'PM' in time or 'AM' in time:
118
- time_obj = datetime.datetime.strptime(time, '%I:%M%p')
119
- time = time_obj.strftime('%H:%M')
120
- except ValueError:
121
- time = current_date.strftime('%H:%M')
122
 
123
- # Parse the complete datetime
124
- try:
125
- parsed_date = parser.parse(f"{date} {time}")
126
- parsed_date = est.localize(parsed_date)
127
- except ValueError:
128
- parsed_date = current_date
129
 
130
- is_valid = verify_link(link)
131
- parsed_news.append([parsed_date, title, link, is_valid])
132
-
133
- # Create DataFrame and sort by datetime
134
- df = pd.DataFrame(parsed_news, columns=['datetime', 'headline', 'link', 'is_valid'])
135
- df = df.sort_values('datetime', ascending=False)
136
- return df
137
-
138
- except Exception as e:
139
- raise Exception(f"Error parsing news: {str(e)}")
140
 
141
- def analyze_sentiment(text):
142
- """Analyze sentiment of a single piece of text using FinBERT-tone."""
143
- try:
144
- result = finbert(text)[0]
145
- label = result['label']
146
- score = result['score']
147
-
148
- sentiment_score = {
149
- 'Positive': score,
150
- 'Negative': -score,
151
- 'Neutral': 0
152
- }.get(label, 0)
153
 
154
- return {
 
 
 
 
 
 
 
 
155
  'sentiment_score': sentiment_score,
156
- 'tone': label,
157
  'confidence': score
158
- }
159
- except Exception as e:
160
- st.error(f"Error analyzing sentiment: {str(e)}")
161
- return {'sentiment_score': 0, 'tone': 'Error', 'confidence': 0}
 
 
 
 
 
 
162
 
163
- def process_news_sentiment(parsed_news_df):
164
- """Process sentiment for all news headlines."""
165
- try:
166
- # Analyze sentiment for each headline
167
- sentiment_data = [analyze_sentiment(headline) for headline in parsed_news_df['headline']]
168
-
169
- # Convert to DataFrame
170
- sentiment_df = pd.DataFrame(sentiment_data)
171
-
172
- # Join with original news DataFrame
173
- result_df = parsed_news_df.join(sentiment_df)
174
- return result_df.set_index('datetime')
175
- except Exception as e:
176
- raise Exception(f"Error processing sentiments: {str(e)}")
 
 
177
 
178
- def plot_sentiment_timeline(df, ticker):
179
- """Create an hourly sentiment timeline plot."""
180
- try:
181
- hourly_sentiment = df['sentiment_score'].resample('H').mean()
182
-
183
- fig = px.bar(
184
- hourly_sentiment,
185
- title=f"{ticker} Hourly Sentiment Trend",
186
- color=hourly_sentiment.values,
187
- color_continuous_scale=['red', 'yellow', 'green'],
188
- range_color=[-1, 1]
189
- )
190
-
191
- fig.update_layout(
192
- xaxis_title="Time",
193
- yaxis_title="Sentiment Score",
194
- coloraxis_colorbar_title="Sentiment",
195
- showlegend=False,
196
- height=400
197
- )
198
-
199
- return fig
200
- except Exception as e:
201
- st.error(f"Error creating timeline plot: {str(e)}")
202
- return None
203
 
204
- def plot_sentiment_distribution(df, ticker):
205
- """Create a pie chart of sentiment distribution."""
206
- try:
207
- tone_counts = df['tone'].value_counts()
208
-
209
- fig = px.pie(
210
- values=tone_counts.values,
211
- names=tone_counts.index,
212
- title=f"{ticker} Sentiment Distribution",
213
- color=tone_counts.index,
214
- color_discrete_map={
215
- 'Positive': 'green',
216
- 'Neutral': 'yellow',
217
- 'Negative': 'red'
218
- }
219
- )
220
-
221
- fig.update_layout(height=400)
222
- return fig
223
- except Exception as e:
224
- st.error(f"Error creating distribution plot: {str(e)}")
225
- return None
226
 
227
- def generate_recommendation(df):
228
- """Generate trading recommendation based on sentiment analysis."""
229
- try:
230
- avg_sentiment = df['sentiment_score'].mean()
231
- tone_counts = df['tone'].value_counts()
232
- total_articles = len(df)
233
-
234
- positive_pct = tone_counts.get('Positive', 0) / total_articles * 100
235
- negative_pct = tone_counts.get('Negative', 0) / total_articles * 100
236
-
237
- if avg_sentiment >= 0.3 and positive_pct >= 50:
238
- return "🟢 STRONG BUY", f"Strong positive sentiment (Score: {avg_sentiment:.2f}, {positive_pct:.1f}% positive news). Recent news suggests a very favorable outlook."
239
- elif avg_sentiment >= 0.1:
240
- return "🟡 MODERATE BUY", f"Moderately positive sentiment (Score: {avg_sentiment:.2f}, {positive_pct:.1f}% positive news). Recent news leans positive."
241
- elif avg_sentiment <= -0.3 and negative_pct >= 50:
242
- return "🔴 STRONG SELL", f"Strong negative sentiment (Score: {avg_sentiment:.2f}, {negative_pct:.1f}% negative news). Recent news suggests significant caution."
243
- elif avg_sentiment <= -0.1:
244
- return "🟡 MODERATE SELL", f"Moderately negative sentiment (Score: {avg_sentiment:.2f}, {negative_pct:.1f}% negative news). Recent news leans negative."
245
- else:
246
- return "⚪ NEUTRAL", f"Neutral sentiment (Score: {avg_sentiment:.2f}). Recent news shows mixed or neutral signals."
247
- except Exception as e:
248
- st.error(f"Error generating recommendation: {str(e)}")
249
- return "⚠️ ERROR", "Unable to generate recommendation due to an error."
250
 
251
- def main():
252
- st.title("📈 Stock News Sentiment Analyzer")
253
- st.markdown("""
254
- This application analyzes the sentiment of recent news articles for any given stock ticker using the FinBERT-tone model,
255
- which is specifically trained for financial text analysis.
256
- """)
 
257
 
258
- # User input
259
- ticker = st.text_input('Enter Stock Ticker (e.g., AAPL, GOOGL)', '').upper()
 
260
 
261
- if ticker:
262
- try:
263
- with st.spinner('Fetching and analyzing news...'):
264
- # Get and process news
265
- news_table = get_news(ticker)
266
- parsed_news_df = parse_news(news_table)
267
- analyzed_news = process_news_sentiment(parsed_news_df)
268
-
269
- # Generate recommendation
270
- signal, explanation = generate_recommendation(analyzed_news)
271
-
272
- # Display recommendation
273
- st.header(f"Analysis Results for {ticker}")
274
- st.subheader(f"Signal: {signal}")
275
- st.write(explanation)
276
-
277
- # Display charts
278
- col1, col2 = st.columns(2)
279
-
280
- with col1:
281
- timeline_fig = plot_sentiment_timeline(analyzed_news, ticker)
282
- if timeline_fig:
283
- st.plotly_chart(timeline_fig, use_container_width=True)
284
-
285
- with col2:
286
- distribution_fig = plot_sentiment_distribution(analyzed_news, ticker)
287
- if distribution_fig:
288
- st.plotly_chart(distribution_fig, use_container_width=True)
289
-
290
- # Display news table
291
- st.subheader("Recent News Analysis")
292
-
293
- # Prepare display DataFrame
294
- display_df = analyzed_news.copy()
295
- display_df['link'] = display_df.apply(
296
- lambda row: f'<a href="{row["link"]}" target="_blank">{"🔗" if row["is_valid"] else "❌"}</a>',
297
- axis=1
298
- )
299
-
300
- # Format and display table
301
- display_df = display_df[['headline', 'tone', 'confidence', 'sentiment_score', 'link']]
302
- display_df = display_df.rename(columns={
303
- 'headline': 'Headline',
304
- 'tone': 'Sentiment',
305
- 'confidence': 'Confidence',
306
- 'sentiment_score': 'Score',
307
- 'link': 'Link'
308
- })
309
-
310
- st.write(display_df.to_html(escape=False), unsafe_allow_html=True)
311
-
312
- # Disclaimer
313
- st.markdown("""
314
- ---
315
- **Disclaimer:** This analysis is based on news sentiment only and should not be considered as financial advice.
316
- Always conduct thorough research and consult with financial professionals before making investment decisions.
317
- """)
318
 
319
- except Exception as e:
320
- st.error(f"Error processing {ticker}: {str(e)}")
321
- st.write("Please check the ticker symbol and try again.")
 
 
 
 
 
 
 
 
 
 
322
 
323
- if __name__ == "__main__":
324
- main()
 
 
 
 
 
 
6
  from dateutil import parser
7
  import datetime
8
  import requests
9
+ from transformers import pipeline
 
 
10
 
11
+ st.set_page_config(page_title="Stock News Sentiment Analyzer", layout="wide")
 
 
 
 
 
 
12
 
13
+ # Initialize FinBERT pipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  @st.cache_resource
15
+ def load_model():
16
+ return pipeline("text-classification", model="yiyanghkust/finbert-tone")
 
 
 
 
 
 
17
 
18
+ finbert = load_model()
 
19
 
20
+ def verify_link(url, timeout=10, retries=3):
 
21
  for _ in range(retries):
22
  try:
23
  response = requests.head(url, timeout=timeout, allow_redirects=True)
24
+ if 200 <= response.status_code < 300:
25
+ return True
26
  except requests.RequestException:
27
  continue
28
  return False
29
 
30
  def get_news(ticker):
31
+ finviz_url = 'https://finviz.com/quote.ashx?t='
32
+ url = finviz_url + ticker
33
+ req = Request(url=url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0'})
34
+ response = urlopen(req)
35
+ html = BeautifulSoup(response, 'html.parser')
36
+ news_table = html.find(id='news-table')
37
+ return news_table
 
 
 
 
 
 
 
 
38
 
39
  def parse_news(news_table):
 
40
  parsed_news = []
41
 
42
+ for x in news_table.findAll('tr'):
43
+ try:
44
+ text = x.a.get_text()
45
+ link = x.a['href']
46
+ date_scrape = x.td.text.strip().split()
 
 
 
 
 
 
47
 
48
+ if len(date_scrape) == 1:
49
+ date = datetime.datetime.today().strftime('%Y-%m-%d')
50
+ time = date_scrape[0]
51
  else:
52
+ date = date_scrape[0]
53
+ time = date_scrape[1]
54
+
55
+ datetime_str = f"{date} {time}"
56
+ datetime_parsed = parser.parse(datetime_str)
57
+
58
+ is_valid = verify_link(link)
 
 
 
 
 
 
 
 
 
 
 
59
 
60
+ parsed_news.append([datetime_parsed, text, link, is_valid])
 
 
 
 
 
61
 
62
+ except Exception as e:
63
+ print("Error parsing news:", e)
64
+ continue
65
+
66
+ columns = ['datetime', 'headline', 'link', 'is_valid']
67
+ parsed_news_df = pd.DataFrame(parsed_news, columns=columns)
68
+
69
+ return parsed_news_df
 
 
70
 
71
+ def score_news(parsed_news_df):
72
+ # Get FinBERT predictions
73
+ predictions = finbert(parsed_news_df['headline'].tolist())
74
+
75
+ # Convert predictions to sentiment scores
76
+ sentiment_scores = []
77
+ for pred in predictions:
78
+ label = pred['label']
79
+ score = pred['score']
 
 
 
80
 
81
+ # Convert to -1 to 1 scale
82
+ if label == 'positive':
83
+ sentiment_score = score
84
+ elif label == 'negative':
85
+ sentiment_score = -score
86
+ else: # neutral
87
+ sentiment_score = 0
88
+
89
+ sentiment_scores.append({
90
  'sentiment_score': sentiment_score,
91
+ 'label': label,
92
  'confidence': score
93
+ })
94
+
95
+ # Convert to DataFrame
96
+ scores_df = pd.DataFrame(sentiment_scores)
97
+
98
+ # Join with original news DataFrame
99
+ parsed_and_scored_news = parsed_news_df.join(scores_df)
100
+ parsed_and_scored_news = parsed_and_scored_news.set_index('datetime')
101
+
102
+ return parsed_and_scored_news
103
 
104
+ def plot_hourly_sentiment(parsed_and_scored_news, ticker):
105
+ mean_scores = parsed_and_scored_news['sentiment_score'].resample('h').mean()
106
+
107
+ fig = px.bar(mean_scores, x=mean_scores.index, y='sentiment_score',
108
+ title=f'{ticker} Hourly Sentiment Scores',
109
+ color='sentiment_score',
110
+ color_continuous_scale=['red', 'yellow', 'green'],
111
+ range_color=[-1, 1])
112
+
113
+ fig.update_layout(coloraxis_colorbar=dict(
114
+ title="Sentiment",
115
+ tickvals=[-1, 0, 1],
116
+ ticktext=["Negative", "Neutral", "Positive"],
117
+ ))
118
+
119
+ return fig
120
 
121
+ def plot_daily_sentiment(parsed_and_scored_news, ticker):
122
+ mean_scores = parsed_and_scored_news['sentiment_score'].resample('D').mean()
123
+
124
+ fig = px.bar(mean_scores, x=mean_scores.index, y='sentiment_score',
125
+ title=f'{ticker} Daily Sentiment Scores',
126
+ color='sentiment_score',
127
+ color_continuous_scale=['red', 'yellow', 'green'],
128
+ range_color=[-1, 1])
129
+
130
+ fig.update_layout(coloraxis_colorbar=dict(
131
+ title="Sentiment",
132
+ tickvals=[-1, 0, 1],
133
+ ticktext=["Negative", "Neutral", "Positive"],
134
+ ))
135
+
136
+ return fig
 
 
 
 
 
 
 
 
 
137
 
138
+ def get_recommendation(sentiment_scores):
139
+ avg_sentiment = sentiment_scores['sentiment_score'].mean()
140
+
141
+ if avg_sentiment >= 0.3:
142
+ return f"Positive sentiment (Score: {avg_sentiment:.2f}). The recent news suggests a favorable outlook for this stock. Consider buying or holding if you already own it."
143
+ elif avg_sentiment <= -0.3:
144
+ return f"Negative sentiment (Score: {avg_sentiment:.2f}). The recent news suggests caution. Consider selling or avoiding this stock for now."
145
+ else:
146
+ return f"Neutral sentiment (Score: {avg_sentiment:.2f}). The recent news doesn't show a strong bias. Consider holding if you own the stock, or watch for more definitive trends before making a decision."
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
+ st.header("Stock News Sentiment Analyzer (FinBERT)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
 
150
+ ticker = st.text_input('Enter Stock Ticker', '').upper()
151
+
152
+ try:
153
+ st.subheader(f"Sentiment Analysis and Recommendation for {ticker} Stock")
154
+ news_table = get_news(ticker)
155
+ parsed_news_df = parse_news(news_table)
156
+ parsed_and_scored_news = score_news(parsed_news_df)
157
 
158
+ # Generate and display recommendation
159
+ recommendation = get_recommendation(parsed_and_scored_news)
160
+ st.write(recommendation)
161
 
162
+ # Display a disclaimer
163
+ st.warning("Disclaimer: This recommendation is based solely on recent news sentiment and should not be considered as financial advice. Always do your own research and consult with a qualified financial advisor before making investment decisions.")
164
+
165
+ fig_hourly = plot_hourly_sentiment(parsed_and_scored_news, ticker)
166
+ fig_daily = plot_daily_sentiment(parsed_and_scored_news, ticker)
167
+
168
+ st.plotly_chart(fig_hourly)
169
+ st.plotly_chart(fig_daily)
170
+
171
+ description = f"""
172
+ The above charts average the sentiment scores of {ticker} stock hourly and daily.
173
+ The table below shows recent headlines with their sentiment scores and classifications.
174
+ The news headlines are obtained from the FinViz website.
175
+ Sentiments are analyzed using the ProsusAI/finbert model, which is specifically trained for financial text.
176
+ Links have been verified for validity.
177
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
+ st.write(description)
180
+
181
+ parsed_and_scored_news['link'] = parsed_and_scored_news.apply(
182
+ lambda row: f'<a href="{row["link"]}" target="_blank">{"Valid✅" if row["is_valid"] else "Invalid❌"} Link</a>',
183
+ axis=1
184
+ )
185
+
186
+ display_df = parsed_and_scored_news.drop(columns=['is_valid'])
187
+ st.write(display_df.to_html(escape=False), unsafe_allow_html=True)
188
+
189
+ except Exception as e:
190
+ print(str(e))
191
+ st.write("Enter a correct stock ticker, e.g. 'AAPL' above and hit Enter.")
192
 
193
+ hide_streamlit_style = """
194
+ <style>
195
+ #MainMenu {visibility: hidden;}
196
+ footer {visibility: hidden;}
197
+ </style>
198
+ """
199
+ st.markdown(hide_streamlit_style, unsafe_allow_html=True)