import streamlit as st import requests import pandas as pd from datetime import datetime, timedelta from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer from textblob import TextBlob import nltk from wordcloud import WordCloud import base64 # (แก้ไข Typo) from io import BytesIO import numpy as np from sklearn.linear_model import LinearRegression import plotly.graph_objects as go from plotly.subplots import make_subplots import yfinance as yf # -------------------------- # CONFIG # -------------------------- st.set_page_config(page_title="📰 SentimentSync NewsAI", layout="wide") API_KEY = "88bc396d4eab4be494a4b86ec842db47" # -------------------------- # UTILITIES # -------------------------- def analyze_text(text, vader): if not text.strip(): return 0 vader_score = vader.polarity_scores(text)["compound"] textblob_score = TextBlob(text).sentiment.polarity return np.mean([vader_score, textblob_score]) def generate_wordcloud(text): stopwords = nltk.corpus.stopwords.words('english') wordcloud = WordCloud(width=800, height=400, background_color="white", stopwords=stopwords).generate(text) buf = BytesIO() wordcloud.to_image().save(buf, format="PNG") return base64.b64encode(buf.getvalue()).decode() # (แก้ไข Typo) # -------------------------- # แปลงชื่อ/ตัวย่อ → (Company Name, Symbol) # -------------------------- def resolve_company_symbol(keyword: str): keyword = keyword.strip() ticker = None name = None try: data = yf.Ticker(keyword) info = data.info if "symbol" in info and info["symbol"]: ticker = info["symbol"] name = info.get("longName", info.get("shortName", keyword)) else: url = f"https://query2.finance.yahoo.com/v1/finance/search?q={keyword}" res = requests.get(url).json() if "quotes" in res and len(res["quotes"]) > 0: q = res["quotes"][0] ticker = q.get("symbol") name = q.get("longname", q.get("shortname", keyword)) except Exception as e: print("Lookup failed:", e) if not ticker: ticker = keyword.upper() if not name: name = keyword.capitalize() return name, ticker # -------------------------- # ดึงข่าว 7 วัน สำหรับ Company + Symbol # -------------------------- @st.cache_data(ttl=3600) def fetch_financial_news(keyword): company, symbol = resolve_company_symbol(keyword) to_date = datetime.now().strftime('%Y-%m-%d') from_date = (datetime.now() - timedelta(days=7)).strftime('%Y-%m-%d') query_keyword = f"({company} OR {symbol}) finance stock" all_articles = [] page = 1 while True: url = ( f"https://newsapi.org/v2/everything?" f"q={query_keyword}&" 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) # -------------------------- # ดึงราคาหุ้นตามช่วงเวลาที่กำหนด # -------------------------- @st.cache_data(ttl=3600) def fetch_stock_price(symbol, start_date, end_date): try: start_str = (start_date - timedelta(days=2)).strftime('%Y-%m-%d') end_str = (end_date + timedelta(days=1)).strftime('%Y-%m-%d') df = yf.download(symbol, start=start_str, end=end_str, interval="1d") if df.empty: st.warning("ไม่พบข้อมูลราคาหุ้นในช่วงเวลานี้") return pd.DataFrame() df = df.reset_index()[["Date", "Close"]] df.rename(columns={"Date": "date", "Close": "price"}, inplace=True) df["date"] = pd.to_datetime(df["date"].dt.date) return df except Exception as e: st.warning(f"ไม่สามารถดึงราคาหุ้นได้: {e}") return pd.DataFrame() # -------------------------- # MAIN APP # -------------------------- def main(): st.title("📰 SentimentSync NewsAI") st.markdown("วิเคราะห์แนวโน้มอารมณ์ของข่าวย้อนหลัง 7 วัน พร้อมราคาหุ้น") # Sidebar with st.sidebar: keyword = st.text_input("ค้นหาคำ / ตัวย่อหุ้น (เช่น Tesla หรือ TSLA):", "") analyze_btn = st.button("วิเคราะห์เลย") if not analyze_btn: st.info("กรอกคำค้นแล้วกด 'วิเคราะห์เลย' เพื่อเริ่มต้น") return vader = SentimentIntensityAnalyzer() # ดึงข่าว st.info(f"กำลังดึงข่าวย้อนหลัง 7 วันสำหรับ '{keyword}' ...") news_df = fetch_financial_news(keyword) if news_df.empty: st.warning("ไม่พบบทความข่าวในช่วง 7 วันที่ผ่านมา") return # วิเคราะห์ sentiment st.info("กำลังวิเคราะห์อารมณ์ของข่าว...") news_df["sentiment"] = news_df["text"].apply(lambda x: analyze_text(x, vader)) news_df["date"] = pd.to_datetime(news_df["date"]) # แสดง Metric avg_sentiment = news_df["sentiment"].mean() pos_pct = (news_df["sentiment"] > 0.1).mean() * 100 neg_pct = (news_df["sentiment"] < -0.1).mean() * 100 col1, col2, col3 = st.columns(3) col1.metric("ค่าเฉลี่ยอารมณ์ข่าว", f"{avg_sentiment:.2f}", "Positive" if avg_sentiment > 0 else "Negative" if avg_sentiment < 0 else "Neutral") col2.metric("ข่าวเชิงบวก", f"{pos_pct:.1f}%") col3.metric("ข่าวเชิงลบ", f"{neg_pct:.1f}%") # Wordcloud st.subheader("☁️ Word Cloud ของข่าว") all_text = " ".join(news_df["text"].tolist()) img = generate_wordcloud(all_text) st.image(f"data:image/png;base64,{img}", use_column_width=True) # ----------------------------------------------------------------- # กราฟไฮบริด (Ref1 + Prediction) # ----------------------------------------------------------------- st.subheader("📈 แนวโน้มอารมณ์ของข่าว & ราคาหุ้น") # 1. รวบรวมข้อมูลข่าวเป็นรายวัน (Daily Aggregation) news_df["date_day"] = pd.to_datetime(news_df["date"].dt.date) def sentiment_type(score): if score > 0.1: return "positive" if score < -0.1: return "negative" return "neutral" news_df["sentiment_type"] = news_df["sentiment"].apply(sentiment_type) daily_avg_sentiment = news_df.groupby("date_day").agg( avg_sentiment=('sentiment', 'mean') ).reset_index() daily_counts = news_df.groupby(["date_day", "sentiment_type"]).size().unstack(fill_value=0).reset_index() daily_data = pd.merge(daily_avg_sentiment, daily_counts, on="date_day", how="left").fillna(0) for col in ['positive', 'negative', 'neutral']: if col not in daily_data.columns: daily_data[col] = 0 df_sorted = daily_data.sort_values("date_day").copy() if len(df_sorted) < 2: st.warning("มีข้อมูลข่าวไม่เพียงพอที่จะสร้างแนวโน้ม (น้อยกว่า 2 วัน)") st.subheader("📰 รายการข่าว") st.dataframe(news_df[["date", "source", "text", "sentiment", "url"]], use_container_width=True) # (แก้ไข Typo) return # 2. ดึงราคาหุ้น _, symbol = resolve_company_symbol(keyword) min_date = df_sorted["date_day"].min() max_date = df_sorted["date_day"].max() st.info(f"กำลังดึงราคาหุ้น {symbol} ระหว่างวันที่ {min_date.strftime('%Y-%m-%d')} ถึง {max_date.strftime('%Y-%m-%d')}...") stock_df = fetch_stock_price(symbol, min_date, max_date) # 3. (*** นี่คือตรรกะใหม่ที่สำคัญ ***) # Merge ข้อมูล 2 ชุด (Sentiment & Stock) ให้มีแกน X เดียวกัน plot_data = pd.merge( df_sorted, stock_df, left_on="date_day", right_on="date", how="left" # ยึดวันที่ของข่าว (ซ้าย) เป็นหลัก ) # (ตอนนี้ plot_data จะมีคอลัมน์ price ที่เป็น NaN ในวันที่ตลาดปิด) # 4. เทรนโมเดล Prediction (ใช้ข้อมูลที่ Merge แล้ว) plot_data["timestamp"] = (plot_data["date_day"] - plot_data["date_day"].min()).dt.days model = LinearRegression() model.fit(plot_data[["timestamp"]], plot_data["avg_sentiment"]) future_days = 7 future_timestamps = np.arange(plot_data["timestamp"].max() + 1, plot_data["timestamp"].max() + future_days + 1) future_dates = [plot_data["date_day"].max() + timedelta(days=i) for i in range(1, future_days + 1)] future_preds = model.predict(future_timestamps.reshape(-1, 1)) # 5. สร้างกราฟ (Plot) ด้วย Subplots (ใช้ 'plot_data' เป็นหลัก) fig = make_subplots(rows=2, cols=1, specs=[[{"secondary_y": True}], [{}]], row_heights=[0.7, 0.3], vertical_spacing=0.1, shared_xaxes=True) # --- กราฟส่วนบน (ราคา, Sentiment, Prediction) --- # Add stock price (Y-axis 1, สีเขียว) fig.add_trace( go.Scatter( x=plot_data["date_day"], y=plot_data["price"], # <--- ใช้ plot_data name=f"{symbol} Stock Price", mode="lines+markers", line=dict(color="green", width=2) ), row=1, col=1, secondary_y=False ) # Add daily sentiment score (Y-axis 2, สีน้ำเงิน) fig.add_trace( go.Scatter( x=plot_data["date_day"], y=plot_data["avg_sentiment"], # <--- ใช้ plot_data name="Actual Sentiment (Daily Avg)", mode="lines+markers", line=dict(color="blue", width=2) ), row=1, col=1, secondary_y=True ) # Add Predicted sentiment (Y-axis 2, สีส้ม) 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") ), row=1, col=1, secondary_y=True ) # --- กราฟส่วนล่าง (จำนวนข่าว) --- fig.add_trace(go.Bar(x=plot_data["date_day"], y=plot_data["neutral"], name="Neutral", marker_color='rgba(128, 128, 128, 0.7)'), row=2, col=1) # <--- ใช้ plot_data fig.add_trace(go.Bar(x=plot_data["date_day"], y=plot_data["negative"], name="Negative", marker_color='rgba(255, 0, 0, 0.7)'), row=2, col=1) # <--- ใช้ plot_data fig.add_trace(go.Bar(x=plot_data["date_day"], y=plot_data["positive"], name="Positive", marker_color='rgba(0, 128, 0, 0.7)'), row=2, col=1) # <--- ใช้ plot_data # 6. ตกแต่ง Layout fig.update_layout( title=f"แนวโน้มอารมณ์ข่าว & ราคาหุ้น '{keyword}'", template="plotly_white", hovermode="x unified", barmode='stack', legend=dict(orientation='h', yanchor='bottom', y=1.02, xanchor='right', x=1), height=600, margin=dict(l=20, r=20, t=80, b=20) ) fig.update_yaxes(title_text="Stock Price", row=1, col=1, secondary_y=False) fig.update_yaxes(title_text="Sentiment Score", range=[-1, 1], row=1, col=1, secondary_y=True) fig.update_yaxes(title_text="Article Count", row=2, col=1) fig.update_xaxes(title_text="วันที่", row=2, col=1) st.plotly_chart(fig, use_container_width=True) # แสดงข่าว (ยังใช้ news_df ตัวเต็ม) st.subheader("📰 รายการข่าว") st.dataframe(news_df[["date", "source", "text", "sentiment", "url"]], use_container_width=True) # (แก้ไข Typo) if __name__ == "__main__": nltk.download("stopwords", quiet=True) main()