Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -12,7 +12,6 @@ from io import BytesIO
|
|
| 12 |
import numpy as np
|
| 13 |
from sklearn.linear_model import LinearRegression
|
| 14 |
import plotly.graph_objects as go
|
| 15 |
-
import os
|
| 16 |
|
| 17 |
# --------------------------
|
| 18 |
# CONFIG
|
|
@@ -30,6 +29,7 @@ def load_models():
|
|
| 30 |
vader = SentimentIntensityAnalyzer()
|
| 31 |
return bert_model, vader
|
| 32 |
|
|
|
|
| 33 |
def analyze_text(text, bert_model, vader):
|
| 34 |
if not text.strip():
|
| 35 |
return 0
|
|
@@ -47,38 +47,49 @@ def analyze_text(text, bert_model, vader):
|
|
| 47 |
bert_score = label_map.get(bert_result["label"], 0)
|
| 48 |
return np.mean([vader_score, textblob_score, bert_score])
|
| 49 |
|
|
|
|
| 50 |
@st.cache_data(ttl=3600)
|
| 51 |
-
def fetch_financial_news(keyword, days=7
|
| 52 |
-
"""ดึงข่าวย้อนหลังจาก NewsAPI.org"""
|
| 53 |
to_date = datetime.now().strftime('%Y-%m-%d')
|
| 54 |
from_date = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
-
if data.get("status") != "ok":
|
| 68 |
-
st.error(f"API Error: {data}")
|
| 69 |
-
return pd.DataFrame()
|
| 70 |
-
|
| 71 |
-
articles = []
|
| 72 |
-
for a in data["articles"]:
|
| 73 |
-
if a["description"]:
|
| 74 |
-
articles.append({
|
| 75 |
-
"date": pd.to_datetime(a["publishedAt"]),
|
| 76 |
-
"text": f"{a['title']} {a['description']}",
|
| 77 |
-
"source": a["source"]["name"],
|
| 78 |
-
"url": a["url"]
|
| 79 |
-
})
|
| 80 |
-
|
| 81 |
-
return pd.DataFrame(articles)
|
| 82 |
|
| 83 |
def generate_wordcloud(text):
|
| 84 |
stopwords = nltk.corpus.stopwords.words('english')
|
|
@@ -87,17 +98,18 @@ def generate_wordcloud(text):
|
|
| 87 |
wordcloud.to_image().save(buf, format="PNG")
|
| 88 |
return base64.b64encode(buf.getvalue()).decode()
|
| 89 |
|
|
|
|
| 90 |
# --------------------------
|
| 91 |
# MAIN APP
|
| 92 |
# --------------------------
|
| 93 |
def main():
|
| 94 |
st.title("📰 SentimentSync NewsAI")
|
| 95 |
-
st.markdown("
|
| 96 |
|
| 97 |
# Sidebar
|
| 98 |
with st.sidebar:
|
| 99 |
keyword = st.text_input("ค้นหาคำ (เช่น Tesla, Bitcoin, Inflation):", "")
|
| 100 |
-
|
| 101 |
analyze_btn = st.button("วิเคราะห์เลย")
|
| 102 |
|
| 103 |
if not analyze_btn:
|
|
@@ -107,10 +119,10 @@ def main():
|
|
| 107 |
bert_model, vader = load_models()
|
| 108 |
|
| 109 |
# ดึงข่าว
|
| 110 |
-
st.info(f"
|
| 111 |
-
news_df = fetch_financial_news(keyword,
|
| 112 |
if news_df.empty:
|
| 113 |
-
st.warning("
|
| 114 |
return
|
| 115 |
|
| 116 |
# วิเคราะห์ sentiment
|
|
@@ -153,21 +165,18 @@ def main():
|
|
| 153 |
# Plot both actual + prediction
|
| 154 |
fig = go.Figure()
|
| 155 |
|
| 156 |
-
# Actual data
|
| 157 |
fig.add_trace(go.Scatter(
|
| 158 |
x=df_sorted["date"], y=df_sorted["sentiment"],
|
| 159 |
mode="lines+markers", name="Actual Sentiment",
|
| 160 |
line=dict(color="blue")
|
| 161 |
))
|
| 162 |
|
| 163 |
-
# Prediction line
|
| 164 |
fig.add_trace(go.Scatter(
|
| 165 |
x=future_dates, y=future_preds,
|
| 166 |
mode="lines+markers", name="Predicted Sentiment (7-day Forecast)",
|
| 167 |
line=dict(color="orange", dash="dash")
|
| 168 |
))
|
| 169 |
|
| 170 |
-
# Confidence range (±0.1)
|
| 171 |
fig.add_trace(go.Scatter(
|
| 172 |
x=future_dates + future_dates[::-1],
|
| 173 |
y=list(future_preds + 0.1) + list((future_preds - 0.1)[::-1]),
|
|
@@ -186,10 +195,10 @@ def main():
|
|
| 186 |
)
|
| 187 |
st.plotly_chart(fig, use_container_width=True)
|
| 188 |
|
| 189 |
-
# ตารางข่าว (optional)
|
| 190 |
st.subheader("📰 รายการข่าว")
|
| 191 |
st.dataframe(news_df[["date", "source", "text", "sentiment", "url"]], use_container_width=True)
|
| 192 |
|
|
|
|
| 193 |
if __name__ == "__main__":
|
| 194 |
nltk.download("stopwords", quiet=True)
|
| 195 |
main()
|
|
|
|
| 12 |
import numpy as np
|
| 13 |
from sklearn.linear_model import LinearRegression
|
| 14 |
import plotly.graph_objects as go
|
|
|
|
| 15 |
|
| 16 |
# --------------------------
|
| 17 |
# CONFIG
|
|
|
|
| 29 |
vader = SentimentIntensityAnalyzer()
|
| 30 |
return bert_model, vader
|
| 31 |
|
| 32 |
+
|
| 33 |
def analyze_text(text, bert_model, vader):
|
| 34 |
if not text.strip():
|
| 35 |
return 0
|
|
|
|
| 47 |
bert_score = label_map.get(bert_result["label"], 0)
|
| 48 |
return np.mean([vader_score, textblob_score, bert_score])
|
| 49 |
|
| 50 |
+
|
| 51 |
@st.cache_data(ttl=3600)
|
| 52 |
+
def fetch_financial_news(keyword, days=7):
|
| 53 |
+
"""ดึงข่าวย้อนหลังจาก NewsAPI.org ตามจำนวนวัน"""
|
| 54 |
to_date = datetime.now().strftime('%Y-%m-%d')
|
| 55 |
from_date = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
|
| 56 |
|
| 57 |
+
all_articles = []
|
| 58 |
+
page = 1
|
| 59 |
+
while True:
|
| 60 |
+
url = (
|
| 61 |
+
f"https://newsapi.org/v2/everything?"
|
| 62 |
+
f"q={keyword}+finance+stock&"
|
| 63 |
+
f"from={from_date}&to={to_date}&"
|
| 64 |
+
f"language=en&sortBy=publishedAt&"
|
| 65 |
+
f"pageSize=100&page={page}&apiKey={API_KEY}"
|
| 66 |
+
)
|
| 67 |
+
r = requests.get(url)
|
| 68 |
+
data = r.json()
|
| 69 |
+
|
| 70 |
+
if data.get("status") != "ok":
|
| 71 |
+
st.error(f"API Error: {data}")
|
| 72 |
+
break
|
| 73 |
+
|
| 74 |
+
articles = data.get("articles", [])
|
| 75 |
+
if not articles:
|
| 76 |
+
break
|
| 77 |
+
|
| 78 |
+
for a in articles:
|
| 79 |
+
if a["description"]:
|
| 80 |
+
all_articles.append({
|
| 81 |
+
"date": pd.to_datetime(a["publishedAt"]),
|
| 82 |
+
"text": f"{a['title']} {a['description']}",
|
| 83 |
+
"source": a["source"]["name"],
|
| 84 |
+
"url": a["url"]
|
| 85 |
+
})
|
| 86 |
+
|
| 87 |
+
if len(articles) < 100:
|
| 88 |
+
break # หมดแล้ว
|
| 89 |
+
page += 1
|
| 90 |
+
|
| 91 |
+
return pd.DataFrame(all_articles)
|
| 92 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
def generate_wordcloud(text):
|
| 95 |
stopwords = nltk.corpus.stopwords.words('english')
|
|
|
|
| 98 |
wordcloud.to_image().save(buf, format="PNG")
|
| 99 |
return base64.b64encode(buf.getvalue()).decode()
|
| 100 |
|
| 101 |
+
|
| 102 |
# --------------------------
|
| 103 |
# MAIN APP
|
| 104 |
# --------------------------
|
| 105 |
def main():
|
| 106 |
st.title("📰 SentimentSync NewsAI")
|
| 107 |
+
st.markdown("วิเคราะห์แนวโน้มอารมณ์ของข่าวการเงินย้อนหลังตามจำนวนวันที่เลือก พร้อมพยากรณ์ในอนาคต")
|
| 108 |
|
| 109 |
# Sidebar
|
| 110 |
with st.sidebar:
|
| 111 |
keyword = st.text_input("ค้นหาคำ (เช่น Tesla, Bitcoin, Inflation):", "")
|
| 112 |
+
days = st.slider("จำนวนวันย้อนหลัง:", 7, 30, 7)
|
| 113 |
analyze_btn = st.button("วิเคราะห์เลย")
|
| 114 |
|
| 115 |
if not analyze_btn:
|
|
|
|
| 119 |
bert_model, vader = load_models()
|
| 120 |
|
| 121 |
# ดึงข่าว
|
| 122 |
+
st.info(f"กำลังดึงข่าวย้อนหลัง {days} วัน จาก NewsAPI.org สำหรับ '{keyword}' ...")
|
| 123 |
+
news_df = fetch_financial_news(keyword, days=days)
|
| 124 |
if news_df.empty:
|
| 125 |
+
st.warning("ไม่พบบทความข่าวในช่วงเวลาที่เลือก")
|
| 126 |
return
|
| 127 |
|
| 128 |
# วิเคราะห์ sentiment
|
|
|
|
| 165 |
# Plot both actual + prediction
|
| 166 |
fig = go.Figure()
|
| 167 |
|
|
|
|
| 168 |
fig.add_trace(go.Scatter(
|
| 169 |
x=df_sorted["date"], y=df_sorted["sentiment"],
|
| 170 |
mode="lines+markers", name="Actual Sentiment",
|
| 171 |
line=dict(color="blue")
|
| 172 |
))
|
| 173 |
|
|
|
|
| 174 |
fig.add_trace(go.Scatter(
|
| 175 |
x=future_dates, y=future_preds,
|
| 176 |
mode="lines+markers", name="Predicted Sentiment (7-day Forecast)",
|
| 177 |
line=dict(color="orange", dash="dash")
|
| 178 |
))
|
| 179 |
|
|
|
|
| 180 |
fig.add_trace(go.Scatter(
|
| 181 |
x=future_dates + future_dates[::-1],
|
| 182 |
y=list(future_preds + 0.1) + list((future_preds - 0.1)[::-1]),
|
|
|
|
| 195 |
)
|
| 196 |
st.plotly_chart(fig, use_container_width=True)
|
| 197 |
|
|
|
|
| 198 |
st.subheader("📰 รายการข่าว")
|
| 199 |
st.dataframe(news_df[["date", "source", "text", "sentiment", "url"]], use_container_width=True)
|
| 200 |
|
| 201 |
+
|
| 202 |
if __name__ == "__main__":
|
| 203 |
nltk.download("stopwords", quiet=True)
|
| 204 |
main()
|