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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import streamlit as st
|
| 3 |
+
import requests
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import nltk
|
| 6 |
+
from wordcloud import WordCloud
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
from sklearn.feature_extraction.text import CountVectorizer, ENGLISH_STOP_WORDS
|
| 9 |
+
from sklearn.decomposition import LatentDirichletAllocation
|
| 10 |
+
from datetime import datetime, timedelta
|
| 11 |
+
|
| 12 |
+
# Download VADER lexicon (if not already downloaded)
|
| 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:
|
| 28 |
+
st.session_state.symbol_run = False
|
| 29 |
+
if "selected_symbol" not in st.session_state:
|
| 30 |
+
st.session_state.selected_symbol = "AAPL"
|
| 31 |
+
if "selected_date" not in st.session_state:
|
| 32 |
+
st.session_state.selected_date = datetime.now().date() - timedelta(days=30)
|
| 33 |
+
if "selected_topics_all" not in st.session_state:
|
| 34 |
+
st.session_state.selected_topics_all = 10
|
| 35 |
+
if "selected_topics_symbol" not in st.session_state:
|
| 36 |
+
st.session_state.selected_topics_symbol = 10
|
| 37 |
+
|
| 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
|
| 48 |
+
df["sentiment"] = df["text"].apply(lambda x: sia.polarity_scores(x)["compound"])
|
| 49 |
+
return df
|
| 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))
|
| 61 |
+
ax.imshow(wc, interpolation="bilinear")
|
| 62 |
+
ax.axis("off")
|
| 63 |
+
st.pyplot(fig)
|
| 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 |
+
}))
|
| 78 |
+
vectorizer = CountVectorizer(stop_words=custom_stop_words)
|
| 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:
|
| 109 |
+
df["date"] = pd.to_datetime(df["date"])
|
| 110 |
+
return df
|
| 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:
|
| 147 |
+
df["date"] = pd.to_datetime(df["date"])
|
| 148 |
+
return df
|
| 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,
|
| 235 |
+
st.session_state.selected_date,
|
| 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;}
|
| 248 |
+
footer {visibility: hidden;}
|
| 249 |
+
</style>
|
| 250 |
+
"""
|
| 251 |
+
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
|