Spaces:
Runtime error
Runtime error
Update app.py
Browse files11 unmodified lines1213141515161711 unmodified lines2930313233343511 unmodified lines474849505151525253545556575859565758596061626364656061626364656667686970717273747576777879808182838485868788899091926768697071727374757677787980819394952 unmodified lines9899100101102103104105106951071081091101111001121131141153 unmodified lines11912012111011112212312411312512612712836 unmodified lines16516616715616816917017117217316317417517617717817917018018118212 unmodified lines19519619718919819920020120220320411 unmodified linesimport numpy as npfrom sklearn.linear_model import LinearRegressionimport plotly.graph_objects as goimport os
# --------------------------# CONFIG11 unmodified lines vader = SentimentIntensityAnalyzer() return bert_model, vader
def analyze_text(text, bert_model, vader): if not text.strip(): return 011 unmodified lines bert_score = label_map.get(bert_result["label"], 0) return np.mean([vader_score, textblob_score, bert_score])
@st.cache_data(ttl=3600)def fetch_financial_news(keyword, days=7, limit=50): """ดึงข่าวย้อนหลังจาก NewsAPI.org"""def fetch_financial_news(keyword, days=7): """ดึงข่าวย้อนหลังจาก NewsAPI.org ตามจำนวนวัน""" to_date = datetime.now().strftime('%Y-%m-%d') from_date = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
all_articles = [] page = 1 while True: url = ( f"https://newsapi.org/v2/everything?" f"q={keyword}+finance+stock&" f"from={from_date}&to={to_date}&" f"language=en&sortBy=publishedAt&" f"pageSize={limit}&apiKey={API_KEY}" )
r = requests.get(url) data = r.json() url = ( f"https://newsapi.org/v2/everything?" f"q={keyword}+finance+stock&" f"from={from_date}&to={to_date}&" f"language=en&sortBy=publishedAt&" f"pageSize=100&page={page}&apiKey={API_KEY}" ) r = requests.get(url) data = r.json()
if data.get("status") != "ok": st.error(f"API Error: {data}") break
articles = data.get("articles", []) if not articles: break
for a in articles: if a["description"]: all_articles.append({ "date": pd.to_datetime(a["publishedAt"]), "text": f"{a['title']} {a['description']}", "source": a["source"]["name"], "url": a["url"] })
if len(articles) < 100: break # หมดแล้ว page += 1
return pd.DataFrame(all_articles)
if data.get("status") != "ok": st.error(f"API Error: {data}") return pd.DataFrame()
articles = [] for a in data["articles"]: if a["description"]: articles.append({ "date": pd.to_datetime(a["publishedAt"]), "text": f"{a['title']} {a['description']}", "source": a["source"]["name"], "url": a["url"] })
return pd.DataFrame(articles)
def generate_wordcloud(text): stopwords = nltk.corpus.stopwords.words('english')2 unmodified lines wordcloud.to_image().save(buf, format="PNG") return base64.b64encode(buf.getvalue()).decode()
# --------------------------# MAIN APP# --------------------------def main(): st.title("📰 SentimentSync NewsAI") st.markdown("วิเคราะห์แนวโน้มอารมณ์ของข่าวการเงินย้อนหลัง 7 วัน พร้อมพยากรณ์ในอนาคต") st.markdown("วิเคราะห์แนวโน้มอารมณ์ของข่าวการเงินย้อนหลังตามจำนวนวันที่เลือก พร้อมพยากรณ์ในอนาคต")
# Sidebar with st.sidebar: keyword = st.text_input("ค้นหาคำ (เช่น Tesla, Bitcoin, Inflation):", "") limit = st.slider("จำนวนข่าวที่ดึง:", 10, 100, 40) days = st.slider("จำนวนวันย้อนหลัง:", 7, 30, 7) analyze_btn = st.button("วิเคราะห์เลย")
if not analyze_btn:3 unmodified lines bert_model, vader = load_models()
# ดึงข่าว st.info(f"กำลังดึงข่าวจาก NewsAPI.org สำหรับ '{keyword}' ...") news_df = fetch_financial_news(keyword, limit=limit) st.info(f"กำลังดึงข่าวย้อนหลัง {days} วัน จาก NewsAPI.org สำหรับ '{keyword}' ...") news_df = fetch_financial_news(keyword, days=days) if news_df.empty: st.warning("ไม่พบบทความข่าวในช่วง 7 วันที่ผ่านมา") st.warning("ไม่พบบทความข่าวในช่วงเวลาที่เลือก") return
# วิเคราะห์ sentiment36 unmodified lines # Plot both actual + prediction fig = go.Figure()
# Actual data fig.add_trace(go.Scatter( x=df_sorted["date"], y=df_sorted["sentiment"], mode="lines+markers", name="Actual Sentiment", line=dict(color="blue") ))
# Prediction line fig.add_trace(go.Scatter( x=future_dates, y=future_preds, mode="lines+markers", name="Predicted Sentiment (7-day Forecast)", line=dict(color="orange", dash="dash") ))
# Confidence range (±0.1) fig.add_trace(go.Scatter( x=future_dates + future_dates[::-1], y=list(future_preds + 0.1) + list((future_preds - 0.1)[::-1]),12 unmodified lines ) st.plotly_chart(fig, use_container_width=True)
# ตารางข่าว (optional) st.subheader("📰 รายการข่าว") st.dataframe(news_df[["date", "source", "text", "sentiment", "url"]], use_container_width=True)
if __name__ == "__main__": nltk.download("stopwords", quiet=True) main()app.py+46-37