Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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 |
-
#
|
| 17 |
sia = SentimentIntensityAnalyzer()
|
| 18 |
|
| 19 |
-
#
|
| 20 |
API_KEY = os.getenv("FMP_API_KEY")
|
| 21 |
|
| 22 |
-
|
|
|
|
| 23 |
|
| 24 |
-
#
|
| 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
|
| 44 |
-
|
| 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
|
| 54 |
"""
|
| 55 |
all_text = " ".join(df["text"].dropna().tolist())
|
| 56 |
if not all_text:
|
| 57 |
-
st.write("No text
|
| 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
|
| 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 |
-
#
|
| 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
|
| 89 |
-
st.write(f"**{
|
| 90 |
|
| 91 |
#############################
|
| 92 |
-
# PAGE 1: Press Releases
|
| 93 |
#############################
|
|
|
|
| 94 |
@st.cache_data(show_spinner=False)
|
| 95 |
def fetch_press_releases_all() -> pd.DataFrame:
|
| 96 |
-
"""
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
"
|
| 116 |
-
"
|
|
|
|
| 117 |
)
|
|
|
|
| 118 |
df = fetch_press_releases_all()
|
| 119 |
if df.empty:
|
| 120 |
st.error("No press releases found.")
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
#############################
|
| 130 |
-
# PAGE 2: Press Releases
|
| 131 |
#############################
|
|
|
|
| 132 |
@st.cache_data(show_spinner=False)
|
| 133 |
def fetch_press_releases_by_symbol(symbol: str) -> pd.DataFrame:
|
| 134 |
-
"""
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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"
|
| 154 |
-
"
|
| 155 |
-
|
| 156 |
)
|
|
|
|
| 157 |
df = fetch_press_releases_by_symbol(symbol)
|
| 158 |
if df.empty:
|
| 159 |
-
st.error(f"No press releases found for
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
#############################
|
| 171 |
# MAIN APP
|
| 172 |
#############################
|
|
|
|
| 173 |
def main():
|
| 174 |
-
st.set_page_config(page_title="Press Releases
|
| 175 |
-
st.title("Press Releases
|
| 176 |
st.write(
|
| 177 |
-
"
|
| 178 |
-
"
|
| 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
|
| 184 |
with st.sidebar.expander("Navigation and Options", expanded=True):
|
| 185 |
page = st.radio(
|
| 186 |
"Select Page",
|
| 187 |
-
("Press Releases
|
| 188 |
-
help="Choose
|
| 189 |
)
|
| 190 |
-
|
|
|
|
| 191 |
st.session_state.selected_topics_all = st.number_input(
|
| 192 |
-
"Number of Topics
|
| 193 |
value=st.session_state.selected_topics_all,
|
| 194 |
min_value=1,
|
| 195 |
max_value=20,
|
| 196 |
-
help="Choose how many topics
|
| 197 |
)
|
| 198 |
-
if st.button("Run
|
| 199 |
st.session_state.all_run = True
|
| 200 |
-
|
|
|
|
| 201 |
symbol = st.text_input(
|
| 202 |
"Ticker Symbol",
|
| 203 |
value=st.session_state.selected_symbol,
|
| 204 |
-
help="
|
| 205 |
)
|
| 206 |
st.session_state.selected_symbol = symbol
|
|
|
|
| 207 |
start_date = st.date_input(
|
| 208 |
-
"
|
| 209 |
-
value=
|
| 210 |
-
help="Only press releases on or after this date will
|
| 211 |
)
|
| 212 |
st.session_state.selected_date = start_date
|
|
|
|
| 213 |
st.session_state.selected_topics_symbol = st.number_input(
|
| 214 |
-
"Number of Topics
|
| 215 |
value=st.session_state.selected_topics_symbol,
|
| 216 |
min_value=1,
|
| 217 |
max_value=20,
|
| 218 |
-
help="Choose how many topics
|
| 219 |
)
|
| 220 |
-
if st.button("Run Press Releases
|
| 221 |
st.session_state.symbol_run = True
|
| 222 |
|
| 223 |
-
# Main body
|
| 224 |
-
if page == "Press Releases
|
| 225 |
-
st.header("
|
| 226 |
if st.session_state.all_run:
|
| 227 |
run_all_press_releases()
|
| 228 |
else:
|
| 229 |
-
st.info("
|
| 230 |
-
|
| 231 |
-
|
|
|
|
| 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
|
| 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;}
|