QuantumLearner commited on
Commit
299003f
·
verified ·
1 Parent(s): 036413b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -81
app.py CHANGED
@@ -13,15 +13,16 @@ from datetime import datetime, timedelta
13
  nltk.download('vader_lexicon')
14
  from nltk.sentiment.vader import SentimentIntensityAnalyzer
15
 
16
- # Create a global VADER instance
17
  sia = SentimentIntensityAnalyzer()
18
 
19
- # Global constants (not exposed to the frontend)
20
  API_KEY = os.getenv("FMP_API_KEY")
21
 
22
- MAX_PAGES = 3 # Number of pages to fetch
 
23
 
24
- # Initialize session state variables if not already set
25
  if "all_run" not in st.session_state:
26
  st.session_state.all_run = False
27
  if "symbol_run" not in st.session_state:
@@ -38,10 +39,11 @@ if "selected_topics_symbol" not in st.session_state:
38
  #############################
39
  # Utility Functions
40
  #############################
 
41
  def process_press_releases_df(df: pd.DataFrame) -> pd.DataFrame:
42
  """
43
- Add a sentiment score (compound) using VADER.
44
- The full text is preserved.
45
  """
46
  if df.empty:
47
  return df
@@ -50,11 +52,11 @@ def process_press_releases_df(df: pd.DataFrame) -> pd.DataFrame:
50
 
51
  def generate_wordcloud(df: pd.DataFrame):
52
  """
53
- Generate and display a word cloud from the full 'text' column.
54
  """
55
  all_text = " ".join(df["text"].dropna().tolist())
56
  if not all_text:
57
- st.write("No text available for word cloud.")
58
  return
59
  wc = WordCloud(width=800, height=400, background_color="white").generate(all_text)
60
  fig, ax = plt.subplots(figsize=(10, 5))
@@ -64,14 +66,13 @@ def generate_wordcloud(df: pd.DataFrame):
64
 
65
  def run_topic_modeling(df: pd.DataFrame, n_topics=10, n_top_words=10):
66
  """
67
- Perform topic modeling using LDA and display the top words per topic.
68
- Uses an extended set of stop words to remove non-meaningful words.
69
  """
70
  texts = df["text"].dropna().tolist()
71
  if not texts:
72
  st.write("No text available for topic modeling.")
73
  return
74
- # Combine default English stop words with additional domain-specific words.
75
  custom_stop_words = list(ENGLISH_STOP_WORDS.union({
76
  "said", "reuters", "inc", "llc", "corp", "co", "company", "news", "press", "release"
77
  }))
@@ -79,30 +80,42 @@ def run_topic_modeling(df: pd.DataFrame, n_topics=10, n_top_words=10):
79
  X = vectorizer.fit_transform(texts)
80
  lda = LatentDirichletAllocation(n_components=n_topics, random_state=42)
81
  lda.fit(X)
 
 
82
  topics = {}
83
  for topic_idx, topic in enumerate(lda.components_):
84
  top_features_ind = topic.argsort()[:-n_top_words - 1:-1]
85
  top_features = [vectorizer.get_feature_names_out()[i] for i in top_features_ind]
86
  topics[f"Topic {topic_idx+1}"] = top_features
 
87
  st.write("### Topic Modeling Results")
88
- for topic, words in topics.items():
89
- st.write(f"**{topic}:** {', '.join(words)}")
90
 
91
  #############################
92
- # PAGE 1: Press Releases (All)
93
  #############################
 
94
  @st.cache_data(show_spinner=False)
95
  def fetch_press_releases_all() -> pd.DataFrame:
96
- """Fetch press releases from multiple pages."""
 
 
 
97
  frames = []
98
  for page in range(MAX_PAGES):
99
  url = f"https://financialmodelingprep.com/api/v3/press-releases?page={page}&apikey={API_KEY}"
100
- response = requests.get(url)
101
- response.raise_for_status()
102
- data = response.json()
103
- if not data:
104
- break
105
- frames.append(pd.DataFrame(data))
 
 
 
 
 
106
  if frames:
107
  df = pd.concat(frames, ignore_index=True)
108
  if "date" in df.columns:
@@ -111,36 +124,52 @@ def fetch_press_releases_all() -> pd.DataFrame:
111
  return pd.DataFrame()
112
 
113
  def run_all_press_releases():
 
114
  st.write(
115
- "This page retrieves press releases from various companies across multiple pages. "
116
- "The resulting DataFrame shows the company symbol, release date, title, full text, and a sentiment score computed by VADER."
 
117
  )
 
118
  df = fetch_press_releases_all()
119
  if df.empty:
120
  st.error("No press releases found.")
121
- else:
122
- df = process_press_releases_df(df)
123
- st.dataframe(df, use_container_width=True)
124
- st.subheader("Word Cloud")
125
- generate_wordcloud(df)
126
- st.subheader("Topic Modeling")
127
- run_topic_modeling(df, n_topics=st.session_state.selected_topics_all)
 
 
 
 
128
 
129
  #############################
130
- # PAGE 2: Press Releases By Symbol
131
  #############################
 
132
  @st.cache_data(show_spinner=False)
133
  def fetch_press_releases_by_symbol(symbol: str) -> pd.DataFrame:
134
- """Fetch press releases for a specific symbol over multiple pages."""
 
 
 
135
  frames = []
136
  for page in range(MAX_PAGES):
137
  url = f"https://financialmodelingprep.com/api/v3/press-releases/{symbol}?page={page}&apikey={API_KEY}"
138
- response = requests.get(url)
139
- response.raise_for_status()
140
- data = response.json()
141
- if not data:
142
- break
143
- frames.append(pd.DataFrame(data))
 
 
 
 
 
144
  if frames:
145
  df = pd.concat(frames, ignore_index=True)
146
  if "date" in df.columns:
@@ -149,86 +178,98 @@ def fetch_press_releases_by_symbol(symbol: str) -> pd.DataFrame:
149
  return pd.DataFrame()
150
 
151
  def run_symbol_press_releases(symbol: str, start_date, n_topics):
 
152
  st.write(
153
- f"This page retrieves press releases for the symbol **{symbol}** across {MAX_PAGES} pages. "
154
- "The DataFrame below contains the release date, title, full text, and the sentiment score computed by VADER. "
155
- f"Only press releases on or after **{start_date}** are shown."
156
  )
 
157
  df = fetch_press_releases_by_symbol(symbol)
158
  if df.empty:
159
- st.error(f"No press releases found for symbol {symbol}.")
160
- else:
161
- if "date" in df.columns:
162
- df = df[df["date"].dt.date >= start_date]
163
- df = process_press_releases_df(df)
164
- st.dataframe(df, use_container_width=True)
165
- st.subheader("Word Cloud")
166
- generate_wordcloud(df)
167
- st.subheader("Topic Modeling")
168
- run_topic_modeling(df, n_topics=n_topics)
 
 
 
 
 
 
169
 
170
  #############################
171
  # MAIN APP
172
  #############################
 
173
  def main():
174
- st.set_page_config(page_title="Press Releases Dashboard", layout="wide")
175
- st.title("Press Releases Dashboard")
176
  st.write(
177
- "This application provides access to press releases. "
178
- "Use the sidebar to select which endpoint you wish to view. "
179
- "The API key and number of pages are handled in the backend. "
180
- "Below the table you will find a word cloud and topic modeling results derived from the press release texts."
181
  )
182
-
183
- # Sidebar: Navigation and Options in an expander
184
  with st.sidebar.expander("Navigation and Options", expanded=True):
185
  page = st.radio(
186
  "Select Page",
187
- ("Press Releases (All)", "Press Releases By Symbol"),
188
- help="Choose whether to view all press releases or only those from a specific company."
189
  )
190
- if page == "Press Releases (All)":
 
191
  st.session_state.selected_topics_all = st.number_input(
192
- "Number of Topics (All)",
193
  value=st.session_state.selected_topics_all,
194
  min_value=1,
195
  max_value=20,
196
- help="Choose how many topics to display for topic modeling."
197
  )
198
- if st.button("Run All Press Releases"):
199
  st.session_state.all_run = True
200
- elif page == "Press Releases By Symbol":
 
201
  symbol = st.text_input(
202
  "Ticker Symbol",
203
  value=st.session_state.selected_symbol,
204
- help="Enter the ticker symbol for which to display press releases."
205
  )
206
  st.session_state.selected_symbol = symbol
 
207
  start_date = st.date_input(
208
- "From Date",
209
- value=datetime.now().date() - timedelta(days=30),
210
- help="Only press releases on or after this date will be shown."
211
  )
212
  st.session_state.selected_date = start_date
 
213
  st.session_state.selected_topics_symbol = st.number_input(
214
- "Number of Topics (By Symbol)",
215
  value=st.session_state.selected_topics_symbol,
216
  min_value=1,
217
  max_value=20,
218
- help="Choose how many topics to display for topic modeling."
219
  )
220
- if st.button("Run Press Releases By Symbol"):
221
  st.session_state.symbol_run = True
222
 
223
- # Main body: Display content based on page and run flag
224
- if page == "Press Releases (All)":
225
- st.header("All Press Releases")
226
  if st.session_state.all_run:
227
  run_all_press_releases()
228
  else:
229
- st.info("Select options in the sidebar and click 'Run All Press Releases'.")
230
- elif page == "Press Releases By Symbol":
231
- st.header("Press Releases By Symbol")
 
232
  if st.session_state.symbol_run:
233
  run_symbol_press_releases(
234
  st.session_state.selected_symbol,
@@ -236,12 +277,11 @@ def main():
236
  st.session_state.selected_topics_symbol
237
  )
238
  else:
239
- st.info("Enter a symbol, date, and topic count in the sidebar and click 'Run Press Releases By Symbol'.")
240
 
241
  if __name__ == "__main__":
242
  main()
243
 
244
-
245
  hide_streamlit_style = """
246
  <style>
247
  #MainMenu {visibility: hidden;}
 
13
  nltk.download('vader_lexicon')
14
  from nltk.sentiment.vader import SentimentIntensityAnalyzer
15
 
16
+ # Global VADER instance
17
  sia = SentimentIntensityAnalyzer()
18
 
19
+ # Environment variable for the API key
20
  API_KEY = os.getenv("FMP_API_KEY")
21
 
22
+ # Maximum pages to fetch
23
+ MAX_PAGES = 3
24
 
25
+ # Store stateful data
26
  if "all_run" not in st.session_state:
27
  st.session_state.all_run = False
28
  if "symbol_run" not in st.session_state:
 
39
  #############################
40
  # Utility Functions
41
  #############################
42
+
43
  def process_press_releases_df(df: pd.DataFrame) -> pd.DataFrame:
44
  """
45
+ Add a sentiment score using VADER for each press release row.
46
+ Returns the updated DataFrame.
47
  """
48
  if df.empty:
49
  return df
 
52
 
53
  def generate_wordcloud(df: pd.DataFrame):
54
  """
55
+ Generate and display a word cloud from the 'text' column.
56
  """
57
  all_text = " ".join(df["text"].dropna().tolist())
58
  if not all_text:
59
+ st.write("No text found for generating a word cloud.")
60
  return
61
  wc = WordCloud(width=800, height=400, background_color="white").generate(all_text)
62
  fig, ax = plt.subplots(figsize=(10, 5))
 
66
 
67
  def run_topic_modeling(df: pd.DataFrame, n_topics=10, n_top_words=10):
68
  """
69
+ Perform topic modeling using LDA. Display top words for each topic.
 
70
  """
71
  texts = df["text"].dropna().tolist()
72
  if not texts:
73
  st.write("No text available for topic modeling.")
74
  return
75
+ # Extend default English stop words with common press release terms.
76
  custom_stop_words = list(ENGLISH_STOP_WORDS.union({
77
  "said", "reuters", "inc", "llc", "corp", "co", "company", "news", "press", "release"
78
  }))
 
80
  X = vectorizer.fit_transform(texts)
81
  lda = LatentDirichletAllocation(n_components=n_topics, random_state=42)
82
  lda.fit(X)
83
+
84
+ # Build a dictionary of topic names -> top words
85
  topics = {}
86
  for topic_idx, topic in enumerate(lda.components_):
87
  top_features_ind = topic.argsort()[:-n_top_words - 1:-1]
88
  top_features = [vectorizer.get_feature_names_out()[i] for i in top_features_ind]
89
  topics[f"Topic {topic_idx+1}"] = top_features
90
+
91
  st.write("### Topic Modeling Results")
92
+ for topic_label, words in topics.items():
93
+ st.write(f"**{topic_label}:** {', '.join(words)}")
94
 
95
  #############################
96
+ # PAGE 1: Press Releases Live Feed
97
  #############################
98
+
99
  @st.cache_data(show_spinner=False)
100
  def fetch_press_releases_all() -> pd.DataFrame:
101
+ """
102
+ Fetch recent press releases from multiple companies across several pages.
103
+ Returns a combined DataFrame.
104
+ """
105
  frames = []
106
  for page in range(MAX_PAGES):
107
  url = f"https://financialmodelingprep.com/api/v3/press-releases?page={page}&apikey={API_KEY}"
108
+ try:
109
+ response = requests.get(url)
110
+ response.raise_for_status()
111
+ data = response.json()
112
+ if not data:
113
+ break
114
+ frames.append(pd.DataFrame(data))
115
+ except Exception:
116
+ # Fail gracefully without naming the data source
117
+ return pd.DataFrame()
118
+
119
  if frames:
120
  df = pd.concat(frames, ignore_index=True)
121
  if "date" in df.columns:
 
124
  return pd.DataFrame()
125
 
126
  def run_all_press_releases():
127
+ st.write("**Press Releases Live Feed**")
128
  st.write(
129
+ "Here, you will see the latest press releases aggregated from various companies. "
130
+ "Explore the table for publication dates, text content, and automated sentiment. "
131
+ "Use the Word Cloud and Topic Modeling below to uncover common themes."
132
  )
133
+
134
  df = fetch_press_releases_all()
135
  if df.empty:
136
  st.error("No press releases found.")
137
+ return
138
+
139
+ # Process text for sentiment
140
+ df = process_press_releases_df(df)
141
+ st.dataframe(df, use_container_width=True)
142
+
143
+ st.subheader("Word Cloud")
144
+ generate_wordcloud(df)
145
+
146
+ st.subheader("Topic Modeling")
147
+ run_topic_modeling(df, n_topics=st.session_state.selected_topics_all)
148
 
149
  #############################
150
+ # PAGE 2: Press Releases by Company
151
  #############################
152
+
153
  @st.cache_data(show_spinner=False)
154
  def fetch_press_releases_by_symbol(symbol: str) -> pd.DataFrame:
155
+ """
156
+ Fetch recent press releases for a single company symbol across several pages.
157
+ Returns a combined DataFrame.
158
+ """
159
  frames = []
160
  for page in range(MAX_PAGES):
161
  url = f"https://financialmodelingprep.com/api/v3/press-releases/{symbol}?page={page}&apikey={API_KEY}"
162
+ try:
163
+ response = requests.get(url)
164
+ response.raise_for_status()
165
+ data = response.json()
166
+ if not data:
167
+ break
168
+ frames.append(pd.DataFrame(data))
169
+ except Exception:
170
+ # Fail gracefully without naming the data source
171
+ return pd.DataFrame()
172
+
173
  if frames:
174
  df = pd.concat(frames, ignore_index=True)
175
  if "date" in df.columns:
 
178
  return pd.DataFrame()
179
 
180
  def run_symbol_press_releases(symbol: str, start_date, n_topics):
181
+ st.write("**Press Releases by Company**")
182
  st.write(
183
+ f"Browse recent press releases for **{symbol}**, starting from {start_date}. "
184
+ "View release text, publication dates, and sentiment analysis. "
185
+ "Below, discover prevalent words and recurring topics for these press releases."
186
  )
187
+
188
  df = fetch_press_releases_by_symbol(symbol)
189
  if df.empty:
190
+ st.error(f"No press releases found for {symbol}.")
191
+ return
192
+
193
+ # Filter by user-chosen date
194
+ if "date" in df.columns:
195
+ df = df[df["date"].dt.date >= start_date]
196
+
197
+ # Process text for sentiment
198
+ df = process_press_releases_df(df)
199
+ st.dataframe(df, use_container_width=True)
200
+
201
+ st.subheader("Word Cloud")
202
+ generate_wordcloud(df)
203
+
204
+ st.subheader("Topic Modeling")
205
+ run_topic_modeling(df, n_topics=n_topics)
206
 
207
  #############################
208
  # MAIN APP
209
  #############################
210
+
211
  def main():
212
+ st.set_page_config(page_title="Press Releases", layout="wide")
213
+ st.title("Press Releases Analysis")
214
  st.write(
215
+ "Explore recent press releases from multiple companies or focus on a single company. "
216
+ "Each page provides a table of press releases, sentiment analysis, a word cloud, and topic modeling."
 
 
217
  )
218
+
219
+ # Sidebar navigation
220
  with st.sidebar.expander("Navigation and Options", expanded=True):
221
  page = st.radio(
222
  "Select Page",
223
+ ("Press Releases Live Feed", "Press Releases by Company"),
224
+ help="Choose between a broad overview or a single company's releases."
225
  )
226
+
227
+ if page == "Press Releases Live Feed":
228
  st.session_state.selected_topics_all = st.number_input(
229
+ "Number of Topics for Live Feed",
230
  value=st.session_state.selected_topics_all,
231
  min_value=1,
232
  max_value=20,
233
+ help="Choose how many topics you want to see."
234
  )
235
+ if st.button("Run Press Releases Live Feed"):
236
  st.session_state.all_run = True
237
+
238
+ elif page == "Press Releases by Company":
239
  symbol = st.text_input(
240
  "Ticker Symbol",
241
  value=st.session_state.selected_symbol,
242
+ help="Type the company's ticker symbol."
243
  )
244
  st.session_state.selected_symbol = symbol
245
+
246
  start_date = st.date_input(
247
+ "Start Date",
248
+ value=st.session_state.selected_date,
249
+ help="Only press releases on or after this date will appear."
250
  )
251
  st.session_state.selected_date = start_date
252
+
253
  st.session_state.selected_topics_symbol = st.number_input(
254
+ "Number of Topics for Company",
255
  value=st.session_state.selected_topics_symbol,
256
  min_value=1,
257
  max_value=20,
258
+ help="Choose how many topics you want to see."
259
  )
260
+ if st.button("Run Press Releases by Company"):
261
  st.session_state.symbol_run = True
262
 
263
+ # Main body content
264
+ if page == "Press Releases Live Feed":
265
+ st.header("Press Releases Live Feed")
266
  if st.session_state.all_run:
267
  run_all_press_releases()
268
  else:
269
+ st.info("Pick how many topics to show, then click 'Run Press Releases Live Feed'.")
270
+
271
+ elif page == "Press Releases by Company":
272
+ st.header("Press Releases by Company")
273
  if st.session_state.symbol_run:
274
  run_symbol_press_releases(
275
  st.session_state.selected_symbol,
 
277
  st.session_state.selected_topics_symbol
278
  )
279
  else:
280
+ st.info("Enter a ticker symbol, date, and number of topics, then click 'Run Press Releases by Company'.")
281
 
282
  if __name__ == "__main__":
283
  main()
284
 
 
285
  hide_streamlit_style = """
286
  <style>
287
  #MainMenu {visibility: hidden;}