KYTHY commited on
Commit
7d4fb83
·
verified ·
1 Parent(s): 7e7aab1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -14
app.py CHANGED
@@ -11,7 +11,7 @@ from io import BytesIO
11
  import numpy as np
12
  from sklearn.linear_model import LinearRegression
13
  import plotly.graph_objects as go
14
- from plotly.subplots import make_subplots # Import สิ่งนี้
15
  import yfinance as yf
16
 
17
  # --------------------------
@@ -119,14 +119,10 @@ def fetch_financial_news(keyword):
119
 
120
 
121
  # --------------------------
122
- # (*** ส่วนที่แก้ไข ***)
123
  # ดึงราคาหุ้นตามช่วงเวลาที่กำหนด
124
  # --------------------------
125
  @st.cache_data(ttl=3600)
126
  def fetch_stock_price(symbol, start_date, end_date):
127
- """
128
- แก้ไข: รับ start_date และ end_date เพื่อดึงข้อมูลให้ตรงกัน
129
- """
130
  try:
131
  start_str = (start_date - timedelta(days=2)).strftime('%Y-%m-%d')
132
  end_str = (end_date + timedelta(days=1)).strftime('%Y-%m-%d')
@@ -139,7 +135,6 @@ def fetch_stock_price(symbol, start_date, end_date):
139
 
140
  df = df.reset_index()[["Date", "Close"]]
141
  df.rename(columns={"Date": "date", "Close": "price"}, inplace=True)
142
- # Normalize วันที่ให้เป็น .dt.date
143
  df["date"] = pd.to_datetime(df["date"].dt.date)
144
  return df
145
  except Exception as e:
@@ -148,7 +143,7 @@ def fetch_stock_price(symbol, start_date, end_date):
148
 
149
 
150
  # --------------------------
151
- # MAIN APP (*** ส่วนที่แก้ไขทั้งหมด ***)
152
  # --------------------------
153
  def main():
154
  st.title("📰 SentimentSync NewsAI")
@@ -195,7 +190,7 @@ def main():
195
  st.image(f"data:image/png;base64,{img}", use_column_width=True)
196
 
197
  # -----------------------------------------------------------------
198
- # (ส่วนที่แก้ไข) กราฟไฮบริด (Ref1 + Prediction)
199
  # -----------------------------------------------------------------
200
  st.subheader("📈 แนวโน้มอารมณ์ของข่าว & ราคาหุ้น")
201
 
@@ -221,8 +216,14 @@ def main():
221
  if col not in daily_data.columns:
222
  daily_data[col] = 0
223
 
224
- # 2. (ใหม่) เทรนโมเดล Prediction โดยใช้ข้อมูล "รายวัน"
225
  df_sorted = daily_data.sort_values("date_day").copy()
 
 
 
 
 
 
226
  df_sorted["timestamp"] = (df_sorted["date_day"] - df_sorted["date_day"].min()).dt.days
227
 
228
  model = LinearRegression()
@@ -254,7 +255,7 @@ def main():
254
  go.Scatter(
255
  x=stock_df["date"], y=stock_df["price"],
256
  name=f"{symbol} Stock Price",
257
- line=dict(color="green", width=2) # ใช้สีเขียวตามโค้ดเดิม
258
  ),
259
  row=1, col=1, secondary_y=False
260
  )
@@ -265,18 +266,22 @@ def main():
265
  x=df_sorted["date_day"], y=df_sorted["avg_sentiment"],
266
  name="Actual Sentiment (Daily Avg)",
267
  mode="lines+markers",
268
- line=dict(color="blue", width=2) # ใช้สีน้ำเงินตามโค้ดเดิม
269
  ),
270
  row=1, col=1, secondary_y=True
271
  )
272
 
273
  # (ใหม่) Add Predicted sentiment (Y-axis 2, สีส้ม)
 
274
  fig.add_trace(go.Scatter(
275
  x=future_dates, y=future_preds,
276
  mode="lines+markers", name="Predicted Sentiment (7-day Forecast)",
277
- line=dict(color="orange", dash="dash"),
278
- secondary_y=True # <-- สำคัญ: ต้องอยู่แกน Y เดียวกับ Actual
279
- ))
 
 
 
280
 
281
  # --- กราฟส่วนล่าง (จำนวนข่าว) ---
282
  fig.add_trace(go.Bar(x=df_sorted["date_day"], y=df_sorted["neutral"], name="Neutral", marker_color='rgba(128, 128, 128, 0.7)'), row=2, col=1)
 
11
  import numpy as np
12
  from sklearn.linear_model import LinearRegression
13
  import plotly.graph_objects as go
14
+ from plotly.subplots import make_subplots
15
  import yfinance as yf
16
 
17
  # --------------------------
 
119
 
120
 
121
  # --------------------------
 
122
  # ดึงราคาหุ้นตามช่วงเวลาที่กำหนด
123
  # --------------------------
124
  @st.cache_data(ttl=3600)
125
  def fetch_stock_price(symbol, start_date, end_date):
 
 
 
126
  try:
127
  start_str = (start_date - timedelta(days=2)).strftime('%Y-%m-%d')
128
  end_str = (end_date + timedelta(days=1)).strftime('%Y-%m-%d')
 
135
 
136
  df = df.reset_index()[["Date", "Close"]]
137
  df.rename(columns={"Date": "date", "Close": "price"}, inplace=True)
 
138
  df["date"] = pd.to_datetime(df["date"].dt.date)
139
  return df
140
  except Exception as e:
 
143
 
144
 
145
  # --------------------------
146
+ # MAIN APP
147
  # --------------------------
148
  def main():
149
  st.title("📰 SentimentSync NewsAI")
 
190
  st.image(f"data:image/png;base64,{img}", use_column_width=True)
191
 
192
  # -----------------------------------------------------------------
193
+ # กราฟไฮบริด (Ref1 + Prediction)
194
  # -----------------------------------------------------------------
195
  st.subheader("📈 แนวโน้มอารมณ์ของข่าว & ราคาหุ้น")
196
 
 
216
  if col not in daily_data.columns:
217
  daily_data[col] = 0
218
 
219
+ # 2. เทรนโมเดล Prediction โดยใช้ข้อมูล "รายวัน"
220
  df_sorted = daily_data.sort_values("date_day").copy()
221
+
222
+ # ป้องกัน Error ถ้ามีข้อมูลน้อยกว่า 2 วัน
223
+ if len(df_sorted) < 2:
224
+ st.warning("มีข้อมูลข่าวไม่เพียงพอที่จะสร้างแนวโน้ม (น้อยกว่า 2 วัน)")
225
+ return
226
+
227
  df_sorted["timestamp"] = (df_sorted["date_day"] - df_sorted["date_day"].min()).dt.days
228
 
229
  model = LinearRegression()
 
255
  go.Scatter(
256
  x=stock_df["date"], y=stock_df["price"],
257
  name=f"{symbol} Stock Price",
258
+ line=dict(color="green", width=2)
259
  ),
260
  row=1, col=1, secondary_y=False
261
  )
 
266
  x=df_sorted["date_day"], y=df_sorted["avg_sentiment"],
267
  name="Actual Sentiment (Daily Avg)",
268
  mode="lines+markers",
269
+ line=dict(color="blue", width=2)
270
  ),
271
  row=1, col=1, secondary_y=True
272
  )
273
 
274
  # (ใหม่) Add Predicted sentiment (Y-axis 2, สีส้ม)
275
+ # ----- (นี่คือส่วนที่แก้ไข) -----
276
  fig.add_trace(go.Scatter(
277
  x=future_dates, y=future_preds,
278
  mode="lines+markers", name="Predicted Sentiment (7-day Forecast)",
279
+ line=dict(color="orange", dash="dash")
280
+ ),
281
+ row=1, col=1, # <-- เพิ่มบรรทัดนี้
282
+ secondary_y=True # <-- ย้ายมาไว้ตรงนี้
283
+ )
284
+ # ------------------------------
285
 
286
  # --- กราฟส่วนล่าง (จำนวนข่าว) ---
287
  fig.add_trace(go.Bar(x=df_sorted["date_day"], y=df_sorted["neutral"], name="Neutral", marker_color='rgba(128, 128, 128, 0.7)'), row=2, col=1)