AlanRex commited on
Commit
3a147b9
·
verified ·
1 Parent(s): 2ded77c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -18
app.py CHANGED
@@ -13,6 +13,14 @@ import dash
13
  import plotly.express as px
14
  import plotly.graph_objects as go
15
  from plotly.subplots import make_subplots
 
 
 
 
 
 
 
 
16
 
17
  # 台股代號對應表 (移除台指期,因為它現在是獨立區塊)
18
  TAIWAN_STOCKS = {
@@ -583,26 +591,42 @@ app.layout = html.Div([
583
 
584
  # 台指期獨立預測回調函數 (新版本)
585
  @app.callback(
586
- [dash.dependencies.Output('taiex-prediction-results', 'children'),
587
- dash.dependencies.Output('taiex-prediction-chart', 'figure')],
588
- [dash.dependencies.Input('taiex-prediction-period', 'value')]
 
589
  )
590
- def update_taiex_prediction(predict_days):
591
- # 獲取台指期歷史資料
592
- data = get_stock_data('^TWII', '2y')
593
- if data.empty:
594
- return html.Div("無法獲取台指期資料"), {}
595
-
596
- # 執行最終日的預測,用於顯示在結果卡片上
597
- final_prediction = simple_lstm_predict(data, predict_days)
598
- if final_prediction is None:
599
- return html.Div("資料不足,無法進行預測"), {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
600
 
601
- current_price = data['Close'].iloc[-1]
602
- last_date = data.index[-1]
603
- predicted_price = final_prediction['predicted_price']
604
- change_pct = final_prediction['change_pct']
605
- confidence = final_prediction['confidence']
606
 
607
  # --- 主要修改處:計算預測路徑 ---
608
  # 1. 定義不同預測天期所包含的中間節點
 
13
  import plotly.express as px
14
  import plotly.graph_objects as go
15
  from plotly.subplots import make_subplots
16
+ import json
17
+ from predictor_logic import StockPredictor
18
+ try:
19
+ stock_predictor = StockPredictor()
20
+ print("模型和歷史數據載入成功!")
21
+ except FileNotFoundError as e:
22
+ print(f"初始化預測器失敗:{e}。請確認您的檔案路徑正確。")
23
+ stock_predictor = None
24
 
25
  # 台股代號對應表 (移除台指期,因為它現在是獨立區塊)
26
  TAIWAN_STOCKS = {
 
591
 
592
  # 台指期獨立預測回調函數 (新版本)
593
  @app.callback(
594
+ # 這裡的 Output 需要根據您儀表板的實際 component id 進行調整
595
+ # 如果您只顯示單一結果,只需保留 'taiex-prediction' 這個 id 即可
596
+ Output('taiex-prediction', 'children'),
597
+ [Input('taiex-predict-button', 'n_clicks')]
598
  )
599
+ def update_taiex_prediction(n_clicks):
600
+ """
601
+ 這個回調函數使用新匯入的 StockPredictor 類別來執行預測。
602
+ 它會自動抓取最新資料作為模型的輸入。
603
+ """
604
+ if not n_clicks or not stock_predictor:
605
+ return html.Div("請點擊按鈕以載入預測結果。", style={'text-align': 'center', 'margin-top': '20px'})
606
+
607
+ try:
608
+ # 使用 yfinance 抓取最新的台指期 (^TWII) 資料作為預測輸入
609
+ latest_data = yf.download('^TWII', period='5d', interval='1d')
610
+
611
+ if latest_data.empty:
612
+ raise ValueError("無法取得最新的台指期資料。")
613
+
614
+ # 取得最後一筆數據的日期,作為 predict 函式的輸入
615
+ last_date = latest_data.index[-1]
616
+
617
+ # 呼叫預測器物件的 predict 方法
618
+ # predictor_logic.py 會自動從 historical_df 中找到此日期前一筆數據進行預測
619
+ predicted_price = stock_predictor.predict(last_date.strftime('%Y-%m-%d'))
620
+
621
+ return html.Div([
622
+ html.P("【XGBoost 模型預測】", style={'font-size': '1.5em', 'font-weight': 'bold', 'color': '#28a745'}),
623
+ html.P(f"最後已知日期:{last_date.strftime('%Y-%m-%d')}", style={'font-size': '1.2em', 'font-weight': 'bold'}),
624
+ html.P(f"預測隔日收盤價:{predicted_price:.2f}", style={'font-size': '1.5em', 'font-weight': 'bold', 'color': '#17a2b8'})
625
+ ], style={'text-align': 'center', 'margin-top': '20px'})
626
+
627
+ except (ValueError, IndexError) as e:
628
+ return html.Div(f"預測失敗:{e}", style={'text-align': 'center', 'margin-top': '20px', 'color': 'red'})
629
 
 
 
 
 
 
630
 
631
  # --- 主要修改處:計算預測路徑 ---
632
  # 1. 定義不同預測天期所包含的中間節點