File size: 14,123 Bytes
7545f62
3439737
3970759
 
c1b77e9
 
76f40c6
c1b77e9
 
 
3439737
76f40c6
3970759
53bd0b8
86a59b0
3970759
 
 
 
d5b103e
53bd0b8
064e28f
3970759
6a9e024
3970759
c1b77e9
 
3439737
c1b77e9
 
 
5bb810d
c1b77e9
 
 
 
 
 
440f8bb
 
 
 
76f40c6
0456220
 
 
86a59b0
0456220
 
 
 
 
 
 
 
 
 
 
 
c1b77e9
 
0456220
 
 
 
 
86a59b0
6a9e024
c1b77e9
6a9e024
3970759
76f40c6
 
3970759
 
76f40c6
3970759
 
 
 
 
76f40c6
3970759
 
76f40c6
3970759
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86a59b0
3970759
b14206a
3970759
6a9e024
c1b77e9
6a9e024
76f40c6
7e7aab1
cecaf26
7e7aab1
 
 
de0116f
c1b77e9
7e7aab1
444db0b
 
 
 
 
cecaf26
c1b77e9
cecaf26
 
3970759
af300e5
3970759
 
d5b103e
c40e7ab
3970759
76f40c6
fb9ddf4
 
 
 
c40e7ab
c1b77e9
c40e7ab
 
c1b77e9
c40e7ab
c1b77e9
c40e7ab
c1b77e9
c40e7ab
c1b77e9
c40e7ab
 
c1b77e9
c40e7ab
c1b77e9
c40e7ab
 
c1b77e9
c40e7ab
 
 
fb9ddf4
c40e7ab
c1b77e9
c40e7ab
 
 
c1b77e9
 
 
 
 
5bb810d
c1b77e9
 
 
 
 
c40e7ab
 
 
 
 
 
 
 
 
 
c1b77e9
 
 
c40e7ab
c1b77e9
5bb810d
c1b77e9
 
 
 
c40e7ab
 
c1b77e9
 
 
c40e7ab
 
c1b77e9
c40e7ab
c1b77e9
 
 
c40e7ab
fb9ddf4
c1b77e9
 
 
 
 
 
 
 
c40e7ab
c1b77e9
c40e7ab
c1b77e9
 
 
 
 
 
 
 
 
 
 
c40e7ab
c1b77e9
 
 
 
 
 
 
 
 
 
 
 
fb9ddf4
c1b77e9
 
 
 
 
 
fb9ddf4
c1b77e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c40e7ab
5bb810d
c1b77e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5bb810d
c40e7ab
c1b77e9
 
 
76f40c6
3970759
76f40c6
c1b77e9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
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
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="📰 News Sentiment Analysis for Young Investor", 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()

# --------------------------
# แปลงชื่อ/ตัวย่อ → (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)

# --------------------------
# ดึงราคาหุ้นตามช่วงเวลาที่กำหนด (และ Flatten Header)
# --------------------------
@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()
        df_subset = df[['Date', 'Close']]
        df_subset.columns = ['date', 'price']
        df_subset["date"] = pd.to_datetime(df_subset["date"].dt.date)
        return df_subset
    except Exception as e:
        st.warning(f"ไม่สามารถดึงราคาหุ้นได้: {e}")
        return pd.DataFrame()

# --------------------------
# MAIN APP
# --------------------------
def main():
    st.title("📰 News Sentiment Analysis for Young Investor")
    st.markdown("วิเคราะห์แนวโน้มอารมณ์ของข่าวย้อนหลัง 7 วัน พร้อมราคาหุ้น")

    # Sidebar
    with st.sidebar:
        keyword = st.text_input("ค้นหา Stock Symbol (เช่น AAPL, 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)
        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)
    plot_data = pd.merge(
        df_sorted,
        stock_df,
        left_on="date_day",
        right_on="date",
        how="left"
    )

    # 4. (*** ใหม่ ***) คำนวณและตีความ Correlation
    correlation = plot_data['price'].corr(plot_data['avg_sentiment'])
    corr_text = "ไม่มีความสัมพันธ์กัน"
    corr_delta = f"Correlation = {correlation:.2f}"
    if pd.isna(correlation):
        corr_text = "ไม่สามารถคำนวณได้"
        corr_delta = "N/A"
    elif correlation > 0.3:
        corr_text = "มีความสัมพันธ์กันในทิศทางเดียวกัน"
    elif correlation < -0.3:
        corr_text = "มีความสัมพันธ์กันในทิศทางตรงข้าม"

    # 5. เทรนโมเดล Prediction (ใช้ข้อมูลที่ Merge แล้ว)
    plot_data["timestamp"] = (plot_data["date_day"] - plot_data["date_day"].min()).dt.days
    # แก้ปัญหา .fit() ถ้ามี NaN ใน sentiment
    train_data = plot_data.dropna(subset=['avg_sentiment', 'timestamp'])

    if len(train_data) < 2:
        st.warning("มีข้อมูลไม่พอสำหรับเทรนโมเดล")
    else:
        model = LinearRegression()
        model.fit(train_data[["timestamp"]], train_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))

    # 6. (*** ใหม่ ***) แสดงผล Correlation Metric
    st.metric(
        label="วิเคราะห์ความสัมพันธ์ (Sentiment vs Price)",
        value=corr_text,
        delta=corr_delta
    )

    # 7. สร้างกราฟ (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) ---
    fig.add_trace(
        go.Scatter(
            x=plot_data["date_day"],
            y=plot_data["price"],
            name=f"{symbol} Stock Price",
            mode="lines+markers",
            connectgaps=True,
            line=dict(color="orange", width=2)
        ),
        row=1, col=1,
        secondary_y=False
    )

    fig.add_trace(
        go.Scatter(
            x=plot_data["date_day"],
            y=plot_data["avg_sentiment"],
            name="Actual Sentiment (Daily Avg)",
            mode="lines+markers",
            line=dict(color="blue", width=2)
        ),
        row=1, col=1,
        secondary_y=True
    )

    # เพิ่มการตรวจสอบว่า future_preds ถูกสร้างหรือยัง
    if 'future_preds' in locals():
        fig.add_trace(go.Scatter(
            x=future_dates,
            y=future_preds,
            mode="lines+markers",
            name="Predicted Sentiment (7-day Forecast)",
            line=dict(color="#02caf7", dash="dash")
        ),
        row=1, col=1,
        secondary_y=True
        )

    # --- กราFส่วนล่าง (จำนวนข่าว) ---
    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)
    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)
    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)

    # 8. ตกแต่ง 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)

if __name__ == "__main__":
    nltk.download("stopwords", quiet=True)
    main()