AlanRex commited on
Commit
fbf93bc
·
verified ·
1 Parent(s): 0dc4c93

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +1078 -0
app.py ADDED
@@ -0,0 +1,1078 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HUGING_FACE_V3.1.2.py (整合 Bert_predict 和 XGBoost 版本)
2
+
3
+ # 系統套件
4
+ import os
5
+ from datetime import datetime, timedelta
6
+ import google.generativeai as genai
7
+ import pandas as pd
8
+ import numpy as np
9
+ import yfinance as yf
10
+ from dash import Dash, dcc, html, callback
11
+ import dash
12
+ import plotly.express as px
13
+ import plotly.graph_objects as go
14
+ from plotly.subplots import make_subplots
15
+ import re
16
+ from bs4 import BeautifulSoup
17
+ import requests
18
+ import time # 引用 time 模組以處理時間戳
19
+
20
+ # ========================= 引用外部模組 START =========================
21
+ # 引用您組員的預測器程式
22
+ from Bert_predict import BertPredictor
23
+
24
+ # 引用新的模型預測器
25
+ from model_predictor import XGBoostModel
26
+ # ========================== 引用外部模組 END ==========================
27
+
28
+ # ========================= 全域設定 START =========================
29
+ # 【【【模型切換開關】】】
30
+ # False: 使用簡易統計模型 (預設)
31
+ # True: 使用 model_predictor.py 中的進階 XGBoost 模型
32
+ USE_ADVANCED_MODEL = False
33
+
34
+ # ========================= CACHE 設定 START =========================
35
+ # 分析結果的快取字典
36
+ ANALYSIS_CACHE = {}
37
+ # 快取有效時間(秒),例如:4 小時 = 4 * 60 * 60 = 14400 秒
38
+ CACHE_DURATION_SECONDS = 8 * 60 * 60
39
+ # ========================== CACHE 設定 END ==========================
40
+ # ========================== 全域設定 END ==========================
41
+
42
+ # 台股代號對應表 (移除台指期,因為它現在是獨立個塊)
43
+ TAIWAN_STOCKS = {
44
+ '元大台灣50': '0050.TW',
45
+ '台積電': '2330.TW',
46
+ '聯發科': '2454.TW',
47
+ '鴻海': '2317.TW',
48
+ '台達電': '2308.TW',
49
+ '廣達': '2382.TW',
50
+ '富邦金': '2881.TW',
51
+ '中信金': '2891.TW',
52
+ '國泰金': '2882.TW',
53
+ '聯電': '2303.TW',
54
+ '中華電': '2412.TW',
55
+ '玉山金': '2884.TW',
56
+ '兆豐金': '2886.TW',
57
+ '日月光投控': '3711.TW',
58
+ '華碩': '2357.TW',
59
+ '統一': '1216.TW',
60
+ '元大金': '2885.TW',
61
+ '智邦': '2345.TW',
62
+ '緯創': '3231.TW',
63
+ '聯詠': '3034.TW',
64
+ '第一金': '2892.TW',
65
+ '瑞昱': '2379.TW',
66
+ '緯穎': '6669.TWO',
67
+ '永豐金': '2890.TW',
68
+ '合庫金': '5880.TW',
69
+ '華南金': '2880.TW',
70
+ '台光電': '2383.TW',
71
+ '世芯-KY': '3661.TWO',
72
+ '奇鋐': '3017.TW',
73
+ '凱基金': '2883.TW',
74
+ '大立光': '3008.TW',
75
+ '長榮': '2603.TW',
76
+ '光寶科': '2301.TW',
77
+ '中鋼': '2002.TW',
78
+ '中租-KY': '5871.TW',
79
+ '國巨': '2327.TW',
80
+ '台新金': '2887.TW',
81
+ '上海商銀': '5876.TW',
82
+ '台泥': '1101.TW',
83
+ '台灣大': '3045.TW',
84
+ '和碩': '4938.TW',
85
+ '遠傳': '4904.TW',
86
+ '和泰車': '2207.TW',
87
+ '研華': '2395.TW',
88
+ '台塑': '1301.TW',
89
+ '統一超': '2912.TW',
90
+ '藥華藥': '6446.TWO',
91
+ '南亞': '1303.TW',
92
+ '陽明': '2609.TW',
93
+ '萬海': '2615.TW',
94
+ '台塑化': '6505.TW',
95
+ '慧洋-KY': '2637.TW',
96
+ '上銀': '2049.TW',
97
+ '南亞科': '2408.TW',
98
+ '旺宏': '2337.TW',
99
+ '譜瑞-KY': '4966.TWO',
100
+ '貿聯-KY': '3665.TW',
101
+ '驊訊': '6870.TWO',
102
+ '穩懋': '3105.TWO'
103
+ }
104
+
105
+ # 產業分類
106
+ INDUSTRY_MAPPING = {
107
+ '0050.TW': 'ETF',
108
+ '2330.TW': '半導體',
109
+ '2454.TW': '半導體',
110
+ '2317.TW': '電子組件',
111
+ '2308.TW': '電子',
112
+ '2382.TW': '電子',
113
+ '2881.TW': '金融',
114
+ '2891.TW': '金融',
115
+ '2882.TW': '金融',
116
+ '2303.TW': '半導體',
117
+ '2412.TW': '電信',
118
+ '2884.TW': '金融',
119
+ '2886.TW': '金融',
120
+ '3711.TW': '半導體',
121
+ '2357.TW': '電子',
122
+ '1216.TW': '食品',
123
+ '2885.TW': '金融',
124
+ '2345.TW': '網通設備',
125
+ '3231.TW': '電子',
126
+ '3034.TW': '半導體',
127
+ '2892.TW': '金融',
128
+ '2379.TW': '半導體',
129
+ '6669.TWO': '電子',
130
+ '2890.TW': '金融',
131
+ '5880.TW': '金融',
132
+ '2880.TW': '金融',
133
+ '2383.TW': '電子',
134
+ '3661.TWO': '半導體',
135
+ '3017.TW': '電子',
136
+ '2883.TW': '金融',
137
+ '3008.TW': '光學',
138
+ '2603.TW': '航運',
139
+ '2301.TW': '電子',
140
+ '2002.TW': '鋼鐵',
141
+ '5871.TW': '金融',
142
+ '2327.TW': '電子被動元件',
143
+ '2887.TW': '金融',
144
+ '5876.TW': '金融',
145
+ '1101.TW': '營建',
146
+ '3045.TW': '電信',
147
+ '4938.TW': '電子',
148
+ '4904.TW': '電信',
149
+ '2207.TW': '汽車',
150
+ '2395.TW': '電腦周邊',
151
+ '1301.TW': '塑膠',
152
+ '2912.TW': '百貨',
153
+ '6446.TWO': '生技',
154
+ '1303.TW': '塑膠',
155
+ '2609.TW': '航運',
156
+ '2615.TW': '航運',
157
+ '6505.TW': '塑膠',
158
+ '2637.TW': '散裝航運',
159
+ '2049.TW': '工具機',
160
+ '2408.TW': 'DRAM',
161
+ '2337.TW': 'NFLSH',
162
+ '4966.TWO': '高速傳輸',
163
+ '3665.TW': '連接器',
164
+ '6870.TWO': '軟體整合',
165
+ '3105.TWO': 'PA功率'
166
+ }
167
+
168
+ def get_stock_data(symbol, period='1y'):
169
+ """獲取股票資料"""
170
+ try:
171
+ stock = yf.Ticker(symbol)
172
+ data = stock.history(period=period)
173
+ if data.empty and symbol == 'TXF=F':
174
+ stock = yf.Ticker('0050.TW')
175
+ data = stock.history(period=period)
176
+ if data.empty:
177
+ stock = yf.Ticker('^TWII')
178
+ data = stock.history(period=period)
179
+ return data
180
+ except:
181
+ return pd.DataFrame()
182
+
183
+ def get_us_market_data():
184
+ """獲取美股指數數據"""
185
+ try:
186
+ indices = {
187
+ 'DJI': '^DJI', # 道瓊指數
188
+ 'NAS': '^IXIC', # 那斯達克
189
+ 'SOX': '^SOX', # 費城半導體
190
+ 'S&P_500': '^GSPC', # S&P 500
191
+ 'TSM_ADR': 'TSM' # 台積電ADR
192
+ }
193
+
194
+ market_data = {}
195
+ for name, symbol in indices.items():
196
+ try:
197
+ data = yf.Ticker(symbol).history(period='5d')
198
+ if not data.empty:
199
+ market_data[name] = data['Close'].iloc[-1]
200
+ else:
201
+ market_data[name] = 0
202
+ except:
203
+ market_data[name] = 0
204
+
205
+ return market_data
206
+ except Exception as e:
207
+ print(f"獲取美股數據時發生錯誤: {e}")
208
+ return {'DJI': 0, 'NAS': 0, 'SOX': 0, 'S&P_500': 0, 'TSM_ADR': 0}
209
+
210
+ def get_exchange_rate():
211
+ """獲取台幣匯率 (USD/TWD)"""
212
+ try:
213
+ data = yf.Ticker('USDTWD=X').history(period='5d')
214
+ if not data.empty:
215
+ return data['Close'].iloc[-1]
216
+ else:
217
+ return 31.5 # 預設值
218
+ except:
219
+ return 31.5
220
+
221
+ def simple_statistical_predict(data, predict_days=5):
222
+ """【備用模型】簡化的統計預測模型。"""
223
+ if len(data) < 60:
224
+ return None
225
+
226
+ prices = data['Close'].values
227
+ ma_short = np.mean(prices[-5:])
228
+ ma_medium = np.mean(prices[-20:])
229
+ ma_long = np.mean(prices[-60:])
230
+ recent_trend = np.polyfit(range(20), prices[-20:], 1)[0]
231
+ volatility = np.std(prices[-20:]) / np.mean(prices[-20:])
232
+ base_change = recent_trend * predict_days
233
+ trend_factor = 1.0 + (0.02 if ma_short > ma_medium > ma_long else -0.02 if ma_short < ma_medium < ma_long else 0)
234
+ noise_factor = np.random.normal(1, volatility * 0.1)
235
+ predicted_price = prices[-1] * trend_factor + base_change + (prices[-1] * noise_factor * 0.01)
236
+ change_pct = ((predicted_price - prices[-1]) / prices[-1]) * 100
237
+ return {
238
+ 'predicted_price': predicted_price,
239
+ 'change_pct': change_pct,
240
+ 'confidence': max(0.6, 1 - volatility * 2)
241
+ }
242
+
243
+ def advanced_xgboost_predict(predict_days=5):
244
+ """
245
+ 【進階模型】使用 XGBoost 模型進行預測
246
+ """
247
+ try:
248
+ print(f"開始使用 XGBoost 模型進行 {predict_days} 天預測...")
249
+
250
+ # 初始化 XGBoost 模型
251
+ xgb_model = XGBoostModel()
252
+
253
+ # 獲取台指期數據 (作為主要標的)
254
+ taiex_data = get_stock_data('^TWII', '2y')
255
+ if taiex_data.empty or len(taiex_data) < 60:
256
+ print("台指期數據不足,無法進行XGBoost預測")
257
+ return None
258
+
259
+ # 計算技術指標
260
+ taiex_data = calculate_technical_indicators(taiex_data)
261
+
262
+ # 獲取美股市場數據
263
+ us_market = get_us_market_data()
264
+
265
+ # 獲取匯率數據
266
+ exchange_rate = get_exchange_rate()
267
+
268
+ # 獲取新聞情緒分數
269
+ try:
270
+ if predictor is not None:
271
+ sentiment_score_raw = predictor.get_news_index()
272
+ if sentiment_score_raw is None:
273
+ sentiment_score_raw = 0
274
+ else:
275
+ sentiment_score_raw = 0
276
+ except:
277
+ sentiment_score_raw = 0
278
+
279
+ # 準備特徵數據 (使用最新的數據點)
280
+ latest_data = taiex_data.iloc[-1]
281
+
282
+ # 建立特徵向量 (按照訓練數據記錄的順序)
283
+ features_list = [
284
+ latest_data['Close'], # close
285
+ latest_data['Volume'], # volume
286
+ exchange_rate, # rate
287
+ us_market['DJI'], # DJI
288
+ us_market['NAS'], # NAS
289
+ us_market['SOX'], # SOX
290
+ us_market['S&P_500'], # S&P_500
291
+ us_market['TSM_ADR'], # TSM_ADR
292
+ sentiment_score_raw, # NEWS (使用原始 sentiment_score_raw)
293
+ latest_data['RSI'] if not pd.isna(latest_data['RSI']) else 50, # RSI
294
+ latest_data['MACD'] if not pd.isna(latest_data['MACD']) else 0, # MACD
295
+ latest_data['MACD_Signal'] if not pd.isna(latest_data['MACD_Signal']) else 0, # MACDsign
296
+ latest_data['MACD_Histogram'] if not pd.isna(latest_data['MACD_Histogram']) else 0, # MACDvol
297
+ latest_data['K'] if not pd.isna(latest_data['K']) else 50, # K
298
+ latest_data['D'] if not pd.isna(latest_data['D']) else 50, # D
299
+ latest_data['+DI'] if not pd.isna(latest_data['+DI']) else 25, # +DI
300
+ latest_data['-DI'] if not pd.isna(latest_data['-DI']) else 25, # -DI
301
+ latest_data['ADX'] if not pd.isna(latest_data['ADX']) else 25, # ADX
302
+ 15, # business_climate (手動填入值)
303
+ 46.7 # PMI (手動填入值)
304
+ ]
305
+
306
+ # 轉換為 DataFrame (XGBoost 模型期望的格式)
307
+ column_names = [
308
+ 'close', 'volume', 'rate', 'DJI', 'NAS', 'SOX', 'S&P_500', 'TSM_ADR',
309
+ 'NEWS', 'RSI', 'MACD', 'MACDsign', 'MACDvol', 'K', 'D',
310
+ '+DI', '-DI', 'ADX', 'business_climate', 'PMI'
311
+ ]
312
+
313
+ input_df = pd.DataFrame([features_list], columns=column_names)
314
+
315
+ print("特徵數據準備完成:")
316
+ print(f"- 收盤價: {features_list[0]:.2f}")
317
+ print(f"- 成交量: {features_list[1]:,.0f}")
318
+ print(f"- 匯率: {features_list[2]:.2f}")
319
+ print(f"- 道瓊指數: {features_list[3]:.2f}")
320
+ print(f"- 新聞情緒: {features_list[8]:.4f}")
321
+ print(f"- RSI: {features_list[9]:.2f}")
322
+
323
+ # 進行預測
324
+ predictions = xgb_model.predict('xgboost_model', input_df)
325
+
326
+ # 根據預測天數選擇對應的預測值
327
+ pred_mapping = {
328
+ 1: 'Close_t0_pred',
329
+ 5: 'Close_t5_pred',
330
+ 10: 'Close_t10_pred',
331
+ 20: 'Close_t20_pred'
332
+ }
333
+
334
+ # 找到最接近的預測天數
335
+ available_days = [1, 5, 10, 20]
336
+ closest_day = min(available_days, key=lambda x: abs(x - predict_days))
337
+ pred_key = pred_mapping[closest_day]
338
+
339
+ predicted_price = predictions[pred_key]
340
+ current_price = features_list[0] # close price
341
+ change_pct = ((predicted_price - current_price) / current_price) * 100
342
+
343
+ print(f"XGBoost 預測完成:")
344
+ print(f"- 預測天數: {predict_days} (使用 {closest_day} 天模型)")
345
+ print(f"- 當前價格: {current_price:.2f}")
346
+ print(f"- 預測價格: {predicted_price:.2f}")
347
+ print(f"- 預測變化: {change_pct:+.2f}%")
348
+
349
+ return {
350
+ 'predicted_price': predicted_price,
351
+ 'change_pct': change_pct,
352
+ 'confidence': 0.75 # XGBoost 模型的信心度
353
+ }
354
+
355
+ except Exception as e:
356
+ print(f"XGBoost 預測時發生錯誤: {e}")
357
+ import traceback
358
+ traceback.print_exc()
359
+ return None
360
+
361
+ def get_prediction(data, predict_days=5):
362
+ """
363
+ 【【模型預測控制器】】
364
+ 根據 USE_ADVANCED_MODEL 的設定,呼叫對應的預測模型。
365
+ """
366
+ if USE_ADVANCED_MODEL:
367
+ print(f"模式: 進階XGBoost模型 | 預測天期: {predict_days}天")
368
+ prediction = advanced_xgboost_predict(predict_days)
369
+ # 如果進階模型預測失敗,則自動降級使用簡易模型
370
+ if prediction is not None:
371
+ return prediction
372
+ else:
373
+ print("進階模型預測失敗,自動降級為簡易統計模型。")
374
+
375
+ # 預設或降級時執行簡易模型
376
+ print(f"模式: 簡易統計模型 | 預測天期: {predict_days}天")
377
+ return simple_statistical_predict(data, predict_days)
378
+
379
+ def calculate_technical_indicators(df):
380
+ """計算技術指標"""
381
+ if df.empty: return df
382
+
383
+ # 移動平均線
384
+ df['MA5'] = df['Close'].rolling(window=5).mean()
385
+ df['MA20'] = df['Close'].rolling(window=20).mean()
386
+
387
+ # RSI
388
+ delta = df['Close'].diff()
389
+ gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
390
+ loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
391
+ rs = gain / loss
392
+ df['RSI'] = 100 - (100 / (1 + rs))
393
+
394
+ # MACD
395
+ exp1 = df['Close'].ewm(span=12).mean()
396
+ exp2 = df['Close'].ewm(span=26).mean()
397
+ df['MACD'] = exp1 - exp2
398
+ df['MACD_Signal'] = df['MACD'].ewm(span=9).mean()
399
+ df['MACD_Histogram'] = df['MACD'] - df['MACD_Signal']
400
+
401
+ # 布林通道
402
+ df['BB_Middle'] = df['Close'].rolling(window=20).mean()
403
+ bb_std = df['Close'].rolling(window=20).std()
404
+ df['BB_Upper'] = df['BB_Middle'] + (bb_std * 2)
405
+ df['BB_Lower'] = df['BB_Middle'] - (bb_std * 2)
406
+
407
+ # KD 指標
408
+ low_min = df['Low'].rolling(window=9).min()
409
+ high_max = df['High'].rolling(window=9).max()
410
+ rsv = (df['Close'] - low_min) / (high_max - low_min) * 100
411
+ df['K'] = rsv.ewm(com=2).mean()
412
+ df['D'] = df['K'].ewm(com=2).mean()
413
+
414
+ # 威廉指標
415
+ low_min_14 = df['Low'].rolling(window=14).min()
416
+ high_max_14 = df['High'].rolling(window=14).max()
417
+ df['Williams_R'] = -100 * (high_max_14 - df['Close']) / (high_max_14 - low_min_14)
418
+
419
+ # DMI 指標
420
+ df['up_move'] = df['High'] - df['High'].shift(1)
421
+ df['down_move'] = df['Low'].shift(1) - df['Low']
422
+ df['+DM'] = np.where((df['up_move'] > df['down_move']) & (df['up_move'] > 0), df['up_move'], 0)
423
+ df['-DM'] = np.where((df['down_move'] > df['up_move']) & (df['down_move'] > 0), df['down_move'], 0)
424
+ df['TR'] = np.max([df['High'] - df['Low'], abs(df['High'] - df['Close'].shift(1)), abs(df['Low'] - df['Close'].shift(1))], axis=0)
425
+ df['+DI'] = (df['+DM'].ewm(com=13, adjust=False).mean() / df['TR'].ewm(com=13, adjust=False).mean()) * 100
426
+ df['-DI'] = (df['-DM'].ewm(com=13, adjust=False).mean() / df['TR'].ewm(com=13, adjust=False).mean()) * 100
427
+ df['DX'] = abs(df['+DI'] - df['-DI']) / (df['+DI'] + df['-DI']) * 100
428
+ df['ADX'] = df['DX'].ewm(com=13, adjust=False).mean()
429
+
430
+ return df
431
+
432
+ def calculate_volume_profile(df, num_bins=50):
433
+ if df.empty or 'High' not in df.columns or 'Low' not in df.columns or 'Volume' not in df.columns:
434
+ return None, None, None
435
+ all_prices = np.concatenate([df['High'].values, df['Low'].values])
436
+ min_price, max_price = all_prices.min(), all_prices.max()
437
+ price_for_volume = (df['High'] + df['Low'] + df['Close']) / 3
438
+ df_vol_profile = df.copy()
439
+ df_vol_profile['Price_Indicator'] = price_for_volume
440
+ hist, bin_edges = np.histogram(df_vol_profile['Price_Indicator'], bins=num_bins, range=(min_price, max_price), weights=df_vol_profile['Volume'])
441
+ price_centers = (bin_edges[:-1] + bin_edges[1:]) / 2
442
+ return bin_edges, hist, price_centers
443
+
444
+ def get_business_climate_data():
445
+ try:
446
+ if not os.path.exists('business_climate.csv'): return pd.DataFrame()
447
+ df = pd.read_csv('business_climate.csv')
448
+ if 'Date' not in df.columns: df.columns = ['Date', 'Index'] if len(df.columns) == 2 else df.columns
449
+ if 'Date' in df.columns:
450
+ try: df['Date'] = pd.to_datetime(df['Date'] + '-01', format='%Y-%m-%d', errors='coerce')
451
+ except: df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
452
+ df = df.dropna(subset=['Date'])
453
+ return df
454
+ except Exception as e:
455
+ print(f"無法獲取景氣燈號資料: {str(e)}")
456
+ return pd.DataFrame()
457
+
458
+ def get_pmi_data():
459
+ try:
460
+ if not os.path.exists('taiwan_pmi.csv'): return pd.DataFrame()
461
+ df = pd.read_csv('taiwan_pmi.csv')
462
+ if 'DATE' in df.columns: df = df.rename(columns={'DATE': 'Date', 'INDEX': 'Index'})
463
+ elif len(df.columns) == 2: df.columns = ['Date', 'Index']
464
+ if 'Date' in df.columns:
465
+ try: df['Date'] = pd.to_datetime(df['Date'] + '-01', format='%Y-%m-%d', errors='coerce')
466
+ except: df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
467
+ df = df.dropna(subset=['Date'])
468
+ return df
469
+ except Exception as e:
470
+ print(f"無法獲取 PMI 資料: {str(e)}")
471
+ return pd.DataFrame()
472
+
473
+ def generate_gemini_analysis(stock_name, stock_symbol, period, data):
474
+ """
475
+ 使用 Gemini API 生成基本面和市場展望分析。
476
+ """
477
+ api_key = os.getenv("GEMINI_API_KEY")
478
+ if not api_key:
479
+ return "無法讀取 GEMINI API 金鑰", "請在系統環境變數中設定您的金鑰"
480
+
481
+ try:
482
+ genai.configure(api_key=api_key)
483
+ model = genai.GenerativeModel('gemini-1.5-flash')
484
+
485
+ price_change = ((data['Close'].iloc[-1] - data['Close'].iloc[0]) / data['Close'].iloc[0]) * 100
486
+ rsi_current = data['RSI'].iloc[-1]
487
+ macd_current = data['MACD'].iloc[-1]
488
+ macd_signal_current = data['MACD_Signal'].iloc[-1]
489
+ industry = INDUSTRY_MAPPING.get(stock_symbol, '綜合')
490
+
491
+ prompt = f"""
492
+ 請扮演一位專業、資深的台灣股市金融分析師。
493
+ 我將提供一檔台股的即時技術指標數據,請你基於這些數據,結合你對這家公司、其所在產業以及當前市場趨勢的理解,為我生成一段專業的「基本面分析」和一段「市場展望與投資建議」。
494
+
495
+ **股票資訊:**
496
+ - **公司名稱:** {stock_name} ({stock_symbol})
497
+ - **分析期間:** 最近 {period}
498
+ - **所屬產業:** {industry}
499
+ - **期間價格變動:** {price_change:+.2f}%
500
+ - **目前 RSI 指標:** {rsi_current:.2f}
501
+ - **目前 MACD 指標:** MACD線為 {macd_current:.3f}, 信號線為 {macd_signal_current:.3f}
502
+
503
+ **你的任務:**
504
+ 1. **基本面分析 (約 150 字):**
505
+ - 評論這家公司的產業地位、近期營運亮點或挑戰。
506
+ - 提及任何可能影響其基本面的關鍵因素 (例如:財報、法說會、政策、供應鏈變化等)。
507
+ - 請用專業、客觀的語氣撰寫。
508
+
509
+ 2. **市場展望與投資建議 (約 150 字):**
510
+ - 基於上述所有資訊,提供對該股票的短期和中期市場展望。
511
+ - 提出具體的投資建議,例如:適合何種類型的投資人、潛在的風險點。
512
+ - 請直接提供分析內容,不要包含任何問候語。
513
+
514
+ **輸出格式:**
515
+ 請嚴格按照以下格式回傳,使用"$$"作為兩個段落之間的分隔符:
516
+ [基本面分析內容]$$[市場展望與投資建議內容]
517
+ """
518
+
519
+ response = model.generate_content(prompt)
520
+ parts = response.text.split('$$')
521
+ if len(parts) == 2:
522
+ fundamental_analysis = parts[0].strip()
523
+ market_outlook = parts[1].strip()
524
+ return dcc.Markdown(fundamental_analysis), dcc.Markdown(market_outlook)
525
+ else:
526
+ # Fallback for unexpected response format
527
+ return dcc.Markdown("無法解析 Gemini 回應,請稍後再試。"), dcc.Markdown(response.text)
528
+
529
+ except Exception as e:
530
+ error_message = f"呼叫 Gemini API 時發生錯誤: {str(e)}"
531
+ print(error_message)
532
+ return dcc.Markdown(error_message), dcc.Markdown("請檢查後台日誌或 API 金鑰設定")
533
+
534
+ # 建立 Dash 應用程式
535
+ app = dash.Dash(__name__, suppress_callback_exceptions=True)
536
+
537
+ # 初始化模型
538
+ try:
539
+ print("正在初始化新聞情緒分析模型...")
540
+ predictor = BertPredictor(max_news_per_keyword=5)
541
+ print("新聞情緒分析模型初始化成功。")
542
+ except Exception as e:
543
+ print(f"錯誤:新聞情緒分析模型初始化失敗 - {e}")
544
+ predictor = None
545
+
546
+ # 應用程式佈局
547
+ app.layout = html.Div([
548
+ html.H1("台股分析儀表板", style={'text-align': 'center', 'margin-bottom': '30px'}),
549
+ html.Div([
550
+ html.H2("🤖 AI深度學習預測 - 台指期指數", style={'text-align': 'center','color': '#FFCC22','margin-bottom': '25px'}),
551
+ html.Div([
552
+ html.Div([
553
+ html.Label("預測期間:", style={'font-weight': 'bold', 'color': '#FFCC22'}),
554
+ dcc.Dropdown(id='taiex-prediction-period',
555
+ options=[
556
+ {'label': '1日後預測', 'value': 1},{'label': '5日後預測', 'value': 5},
557
+ {'label': '10日後預測', 'value': 10},{'label': '20日後預測', 'value': 20},
558
+ {'label': '60日後預測', 'value': 60}], value=5,
559
+ style={'margin-bottom': '10px', 'color': '#272727'})
560
+ ], style={'width': '30%', 'display': 'inline-block'}),
561
+ html.Div(id='taiex-prediction-results', style={'width': '65%', 'display': 'inline-block', 'margin-left': '5%'})
562
+ ]),
563
+ html.Div([dcc.Graph(id='taiex-prediction-chart')], style={'margin-top': '20px'})
564
+ ], style={'background': 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)','padding': '25px','border-radius': '15px','box-shadow': '0 8px 25px rgba(0,0,0,0.15)','color': 'white','margin-bottom': '40px'}),
565
+
566
+ html.Div([
567
+ html.H3("📰 市場情緒與新聞分析", style={'color': '#E74C3C', 'margin-bottom': '20px'}),
568
+ html.Div([
569
+ html.Div([
570
+ html.H4("市場情緒指標", style={'color': '#8E44AD'}),
571
+ html.Div(id='sentiment-gauge')
572
+ ], style={'width': '48%', 'display': 'inline-block'}),
573
+ html.Div([
574
+ html.H4("關鍵新聞摘要", style={'color': '#27AE60'}),
575
+ html.Div(id='news-summary', style={'background': '#f8f9fa','padding': '15px','border-radius': '8px','max-height': '200px','overflow-y': 'auto'})
576
+ ], style={'width': '48%', 'display': 'inline-block', 'margin-left': '4%'})
577
+ ])
578
+ ], style={'margin-top': '30px','padding': '20px','background': 'white','border-radius': '10px','box-shadow': '0 2px 10px rgba(0,0,0,0.1)'}),
579
+
580
+ html.Div([
581
+ html.H3("景氣燈號與 PMI 分析"),
582
+ html.Div([
583
+ html.Div([dcc.Graph(id='business-climate-chart')], style={'width': '48%', 'display': 'inline-block'}),
584
+ html.Div([dcc.Graph(id='pmi-chart')], style={'width': '48%', 'display': 'inline-block', 'margin-left': '2%'})
585
+ ])
586
+ ], style={'margin-top': '30px'}),
587
+
588
+ html.Div([
589
+ html.Div([
590
+ html.Label("選擇股票:"),
591
+ dcc.Dropdown(id='stock-dropdown', options=[{'label': name, 'value': symbol} for name, symbol in TAIWAN_STOCKS.items()], value='2330.TW', style={'margin-bottom': '10px'})
592
+ ], style={'width': '30%', 'display': 'inline-block', 'vertical-align': 'top'}),
593
+ html.Div([
594
+ html.Label("時間範圍:"),
595
+ dcc.Dropdown(id='period-dropdown',
596
+ options=[{'label': '1個月', 'value': '1mo'},{'label': '3個月', 'value': '3mo'},{'label': '6個月', 'value': '6mo'},{'label': '1年', 'value': '1y'},{'label': '2年', 'value': '2y'}],
597
+ value='1mo', style={'margin-bottom': '10px'})
598
+ ], style={'width': '30%', 'display': 'inline-block', 'margin-left': '5%', 'vertical-align': 'top'}),
599
+ html.Div([
600
+ html.Label("圖表類型:"),
601
+ dcc.Dropdown(id='chart-type', options=[{'label': '線圖', 'value': 'line'},{'label': '蠟燭圖', 'value': 'candlestick'}], value='candlestick', style={'margin-bottom': '10px'})
602
+ ], style={'width': '30%', 'display': 'inline-block', 'margin-left': '5%', 'vertical-align': 'top'})
603
+ ], style={'margin-bottom': '30px'}),
604
+
605
+ html.Div(id='stock-info-cards', style={'margin-bottom': '30px'}),
606
+ html.Div([html.Div([dcc.Graph(id='price-chart')], style={'width': '100%', 'display': 'inline-block', 'vertical-align': 'top'})]),
607
+ html.Div([
608
+ html.H3("📊 進階技術指標分析", style={'margin-bottom': '20px'}),
609
+ html.Div([
610
+ html.Label("選擇技術指標:", style={'font-weight': 'bold', 'margin-right': '10px'}),
611
+ dcc.Dropdown(id='technical-indicator-selector',
612
+ options=[{'label': 'RSI 相對強弱指標', 'value': 'RSI'},{'label': 'MACD 指數平滑異同移動平均線', 'value': 'MACD'},{'label': '布林通道 Bollinger Bands', 'value': 'BB'},
613
+ {'label': 'KD 隨機指標', 'value': 'KD'},{'label': '威廉指標 %R', 'value': 'WR'},{'label': 'DMI 動向指標', 'value': 'DMI'}],
614
+ value='RSI', style={'width': '100%'})
615
+ ], style={'margin-bottom': '20px'}),
616
+ html.Div([dcc.Graph(id='advanced-technical-chart')])
617
+ ], style={'margin-top': '20px','padding': '20px','background': 'white','border-radius': '10px','box-shadow': '0 2px 10px rgba(0,0,0,0.1)'}),
618
+ html.Div([dcc.Graph(id='volume-chart')], style={'margin-top': '20px'}),
619
+ html.Div([html.H3("產業表現分析"), dcc.Graph(id='industry-analysis')], style={'margin-top': '30px'}),
620
+ html.Div([
621
+ html.H3("📊 分析師觀點與市場解讀", style={'color': '#2E86AB', 'margin-bottom': '20px'}),
622
+ html.Div([
623
+ html.Div([
624
+ html.H4("📝 技術面分析", style={'color': '#A23B72', 'margin-bottom': '15px'}),
625
+ html.Div(id='technical-analysis-text', style={'background': '#f8f9fa','padding': '15px','border-radius': '8px','border-left': '4px solid #A23B72','min-height': '150px','font-size': '14px','line-height': '1.6'})
626
+ ], style={'width': '48%', 'display': 'inline-block', 'vertical-align': 'top'}),
627
+ html.Div([
628
+ html.H4("📈 基本面分析 (AI 生成)", style={'color': '#F18F01', 'margin-bottom': '15px'}),
629
+ html.Div(id='fundamental-analysis-text', style={'background': '#f8f9fa','padding': '15px','border-radius': '8px','border-left': '4px solid #F18F01','min-height': '150px','font-size': '14px','line-height': '1.6'})
630
+ ], style={'width': '48%', 'display': 'inline-block', 'margin-left': '4%', 'vertical-align': 'top'})
631
+ ]),
632
+ html.Div([
633
+ html.H4("🎯 市場展望與投資建議 (AI 生成)", style={'color': '#C73E1D', 'margin-bottom': '15px', 'margin-top': '25px'}),
634
+ html.Div(id='market-outlook-text', style={'background': 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)','color': 'white','padding': '20px','border-radius': '10px','min-height': '100px','font-size': '15px','line-height': '1.7','box-shadow': '0 4px 15px rgba(0,0,0,0.1)'})
635
+ ])
636
+ ], style={'margin-top': '30px','padding': '25px','background': 'white','border-radius': '12px','box-shadow': '0 4px 20px rgba(0,0,0,0.08)','border': '1px solid #e9ecef'}),
637
+ html.Div([
638
+ html.H3("📊 多檔股票比較分析", style={'margin-bottom': '20px'}),
639
+ html.Div([
640
+ html.Div([
641
+ html.Label("選擇比較股票(最多5檔):", style={'font-weight': 'bold'}),
642
+ dcc.Dropdown(id='comparison-stocks', options=[{'label': name, 'value': symbol} for name, symbol in TAIWAN_STOCKS.items()], value=['0050.TW', '2330.TW', '2454.TW'], multi=True, style={'margin-bottom': '5px'}),
643
+ html.Small('(元大台灣50 (0050.TW) 為固定比較基準,不可移除)', style={'display': 'block', 'font-style': 'italic', 'color': 'gray'})
644
+ ], style={'width': '60%', 'display': 'inline-block'}),
645
+ html.Div([
646
+ html.Label("比較期間:", style={'font-weight': 'bold'}),
647
+ dcc.Dropdown(id='comparison-period', options=[{'label': '1個月', 'value': '1mo'},{'label': '3個月', 'value': '3mo'},{'label': '6個月', 'value': '6mo'},{'label': '1年', 'value': '1y'}], value='3mo')
648
+ ], style={'width': '35%', 'display': 'inline-block', 'margin-left': '5%', 'vertical-align': 'top'})
649
+ ]),
650
+ html.Div([
651
+ html.Div([dcc.Graph(id='comparison-chart')], style={'width': '65%', 'display': 'inline-block'}),
652
+ html.Div([html.H4("比較結果", style={'color': '#2E86AB'}), html.Div(id='comparison-table')], style={'width': '33%', 'display': 'inline-block', 'margin-left': '2%', 'vertical-align': 'top'})
653
+ ])
654
+ ], style={'margin-top': '30px','padding': '20px','background': 'white','border-radius': '10px','box-shadow': '0 2px 10px rgba(0,0,0,0.1)'}),
655
+ ])
656
+
657
+ # 回調函數區域
658
+ @app.callback(
659
+ [dash.dependencies.Output('taiex-prediction-results', 'children'),
660
+ dash.dependencies.Output('taiex-prediction-chart', 'figure')],
661
+ [dash.dependencies.Input('taiex-prediction-period', 'value')]
662
+ )
663
+ def update_taiex_prediction(predict_days):
664
+ data = get_stock_data('^TWII', '2y')
665
+ if data.empty: return html.Div("無法獲取台指期資料"), {}
666
+
667
+ # === 修改點:統一呼叫 get_prediction 控制器 ===
668
+ final_prediction = get_prediction(data, predict_days)
669
+
670
+ if final_prediction is None: return html.Div("資料不足,無法進行預測"), {}
671
+ current_price, last_date = data['Close'].iloc[-1], data.index[-1]
672
+ predicted_price, change_pct, confidence = final_prediction['predicted_price'], final_prediction['change_pct'], final_prediction['confidence']
673
+
674
+ prediction_paths = {1: [1], 5: [1, 5], 10: [1, 5, 10], 20: [1, 10, 20], 60: [1, 10, 20, 60]}
675
+ intervals_to_predict = prediction_paths.get(predict_days, [predict_days])
676
+ prediction_dates, prediction_prices = [last_date], [current_price]
677
+
678
+ for days in intervals_to_predict:
679
+ # === 修改點:迴圈內也使用統一的預測控制器 ===
680
+ interim_prediction = get_prediction(data, days)
681
+ if interim_prediction:
682
+ prediction_dates.append(last_date + timedelta(days=days))
683
+ prediction_prices.append(interim_prediction['predicted_price'])
684
+
685
+ # 後續繪圖邏輯不變
686
+ color, arrow = ('red', '📈') if change_pct >= 0 else ('green', '📉')
687
+ result_card = html.Div([
688
+ html.H4(f"{predict_days}日後預測結果", style={'margin': '0 0 15px 0', 'color': 'white'}),
689
+ html.Div([html.Span(f"{arrow} ", style={'font-size': '24px'}), html.Span(f"{change_pct:+.2f}%", style={'font-size': '28px','font-weight': 'bold','color': color})], style={'margin': '10px 0'}),
690
+ html.P(f"目前價格: {current_price:.2f}", style={'margin': '5px 0'}), html.P(f"預測價格: {predicted_price:.2f}", style={'margin': '5px 0'}),
691
+ html.P(f"信心度: {confidence:.1%}", style={'margin': '5px 0', 'font-size': '14px'})
692
+ ], style={'background': 'rgba(255,255,255,0.1)','padding': '20px','border-radius': '10px','border': '1px solid rgba(255,255,255,0.2)'})
693
+ fig = go.Figure()
694
+ recent_data = data.tail(30)
695
+ fig.add_trace(go.Scatter(x=recent_data.index, y=recent_data['Close'], mode='lines', name='歷史價格', line=dict(color='#FFA726', width=2)))
696
+ fig.add_trace(go.Scatter(x=prediction_dates, y=prediction_prices, mode='lines+markers', name=f'{predict_days}日預測路徑', line=dict(color=color, width=3, dash='dash'), marker=dict(size=8)))
697
+ fig.update_layout(title=f'台指期 {predict_days}日預測走勢', xaxis_title='日期', yaxis_title='指數點位', height=350, plot_bgcolor='rgba(0,0,0,0)', paper_bgcolor='rgba(0,0,0,0)', font=dict(color='white'))
698
+ return result_card, fig
699
+
700
+ @app.callback(
701
+ dash.dependencies.Output('stock-info-cards', 'children'),
702
+ [dash.dependencies.Input('stock-dropdown', 'value')]
703
+ )
704
+ def update_stock_info(selected_stock):
705
+ data = get_stock_data(selected_stock, '5d')
706
+ if data.empty: return html.Div("無法獲取股票資料")
707
+ current_price = data['Close'].iloc[-1]
708
+ prev_price = data['Close'].iloc[-2] if len(data) > 1 else current_price
709
+ change = current_price - prev_price
710
+ change_pct = (change / prev_price) * 100
711
+ stock_name = [name for name, symbol in TAIWAN_STOCKS.items() if symbol == selected_stock][0]
712
+ color, arrow = ('red', '▲') if change >= 0 else ('green', '▼')
713
+ return html.Div([
714
+ html.Div([
715
+ html.H3(f"{stock_name} ({selected_stock})", style={'margin': '0'}),
716
+ html.H2(f"${current_price:.2f}", style={'margin': '5px 0', 'color': color}),
717
+ html.P(f"{arrow} {change:+.2f} ({change_pct:+.2f}%)", style={'margin': '0', 'color': color, 'font-weight': 'bold'})
718
+ ], style={'background': 'white','padding': '20px','border-radius': '10px','box-shadow': '0 2px 10px rgba(0,0,0,0.1)','display': 'inline-block','margin-right': '20px'}),
719
+ html.Div([
720
+ html.H4("今日統計", style={'margin': '0 0 10px 0'}),
721
+ html.P(f"最高: ${data['High'].iloc[-1]:.2f}", style={'margin': '5px 0'}),
722
+ html.P(f"最低: ${data['Low'].iloc[-1]:.2f}", style={'margin': '5px 0'}),
723
+ html.P(f"成交量: {data['Volume'].iloc[-1]:,.0f}", style={'margin': '5px 0'})
724
+ ], style={'background': 'white','padding': '20px','border-radius': '10px','box-shadow': '0 2px 10px rgba(0,0,0,0.1)','display': 'inline-block'})
725
+ ])
726
+
727
+ @app.callback(
728
+ dash.dependencies.Output('price-chart', 'figure'),
729
+ [dash.dependencies.Input('stock-dropdown', 'value'),
730
+ dash.dependencies.Input('period-dropdown', 'value'),
731
+ dash.dependencies.Input('chart-type', 'value')]
732
+ )
733
+ def update_price_chart(selected_stock, period, chart_type):
734
+ data = get_stock_data(selected_stock, period)
735
+ if data.empty: return {}
736
+ data = calculate_technical_indicators(data)
737
+ stock_name = [name for name, symbol in TAIWAN_STOCKS.items() if symbol == selected_stock][0]
738
+ fig = make_subplots(rows=1, cols=2, shared_yaxes=True, column_widths=[0.8, 0.2], horizontal_spacing=0.01)
739
+ if chart_type == 'candlestick':
740
+ fig.add_trace(go.Candlestick(x=data.index, open=data['Open'], high=data['High'], low=data['Low'], close=data['Close'], name=stock_name, increasing_line_color='red', decreasing_line_color='green'), row=1, col=1)
741
+ else:
742
+ fig.add_trace(px.line(data, y='Close').data[0], row=1, col=1)
743
+ fig.add_trace(go.Scatter(x=data.index, y=data['MA5'], mode='lines', name='MA5', line=dict(color='orange')), row=1, col=1)
744
+ fig.add_trace(go.Scatter(x=data.index, y=data['MA20'], mode='lines', name='MA20', line=dict(color='blue')), row=1, col=1)
745
+ bin_edges, volume_per_bin, price_centers = calculate_volume_profile(data, num_bins=50)
746
+ if volume_per_bin is not None:
747
+ fig.add_trace(go.Bar(orientation='h', y=price_centers, x=volume_per_bin, name='Volume Profile', text=[f'{vol/1000:.0f}k' for vol in volume_per_bin], textposition='auto', marker=dict(color='rgba(173, 216, 230, 0.6)', line=dict(color='rgba(30, 144, 255, 0.8)', width=1))), row=1, col=2)
748
+ fig.update_layout(title_text=f'{stock_name} 股價走勢與成交量分佈', height=500, showlegend=True, xaxis1=dict(title='日期', type='date', rangeslider_visible=False), yaxis1=dict(title='價格 (TWD)'), xaxis2=dict(title='成交量', showticklabels=True), yaxis2=dict(showticklabels=False), bargap=0.05)
749
+ return fig
750
+
751
+ @app.callback(
752
+ dash.dependencies.Output('advanced-technical-chart', 'figure'),
753
+ [dash.dependencies.Input('technical-indicator-selector', 'value'),
754
+ dash.dependencies.Input('stock-dropdown', 'value'),
755
+ dash.dependencies.Input('period-dropdown', 'value')]
756
+ )
757
+ def update_advanced_technical_chart(indicator, selected_stock, period):
758
+ data = get_stock_data(selected_stock, period)
759
+ if data.empty: return {}
760
+ data = calculate_technical_indicators(data)
761
+ stock_name = [name for name, symbol in TAIWAN_STOCKS.items() if symbol == selected_stock][0]
762
+ fig = go.Figure()
763
+ if indicator == 'RSI':
764
+ fig = go.Figure()
765
+ fig.add_trace(go.Scatter(x=data.index, y=data['RSI'], mode='lines', name='RSI', line=dict(color='purple', width=2)))
766
+ fig.add_hline(y=70, line_dash="dash", line_color="green", annotation_text="超買線(70)")
767
+ fig.add_hline(y=30, line_dash="dash", line_color="red", annotation_text="超賣線(30)")
768
+ fig.add_hline(y=50, line_dash="dot", line_color="gray", annotation_text="中線(50)")
769
+ fig.update_layout(title=f'{stock_name} - RSI 相對強弱指標', xaxis_title='日期', yaxis_title='RSI', height=450, yaxis=dict(range=[0, 100]))
770
+ elif indicator == 'MACD':
771
+ fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1, row_heights=[0.7, 0.3], subplot_titles=('價格走勢', 'MACD 指標'))
772
+ fig.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='收盤價', line=dict(color='black', width=1.5)), row=1, col=1)
773
+ fig.add_trace(go.Scatter(x=data.index, y=data['MACD'], mode='lines', name='MACD (快線)', line=dict(color='blue', width=2)), row=2, col=1)
774
+ fig.add_trace(go.Scatter(x=data.index, y=data['MACD_Signal'], mode='lines', name='Signal (慢線)', line=dict(color='red', width=2)), row=2, col=1)
775
+ colors = ['red' if x >= 0 else 'green' for x in data['MACD_Histogram']]
776
+ fig.add_trace(go.Bar(x=data.index, y=data['MACD_Histogram'], name='MACD柱狀圖', marker_color=colors), row=2, col=1)
777
+ fig.update_layout(title_text=f'{stock_name} - MACD 指數平滑異同移動平均線', height=550)
778
+ elif indicator == 'BB':
779
+ fig = go.Figure()
780
+ fig.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='收盤價', line=dict(color='black', width=2)))
781
+ fig.add_trace(go.Scatter(x=data.index, y=data['BB_Upper'], mode='lines', name='上軌', line=dict(color='red', width=1, dash='dash')))
782
+ fig.add_trace(go.Scatter(x=data.index, y=data['BB_Middle'], mode='lines', name='中軌(MA20)', line=dict(color='blue', width=1)))
783
+ fig.add_trace(go.Scatter(x=data.index, y=data['BB_Lower'], mode='lines', name='下軌', line=dict(color='green', width=1, dash='dash')))
784
+ fig.update_layout(title=f'{stock_name} - 布林通道 (20日, 2σ)', xaxis_title='日期', yaxis_title='價格 (TWD)', height=450)
785
+ elif indicator == 'KD':
786
+ fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1, row_heights=[0.6, 0.4], subplot_titles=('價格走勢', 'KD指標'))
787
+ fig.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='收盤價', line=dict(color='black', width=1)), row=1, col=1)
788
+ fig.add_trace(go.Scatter(x=data.index, y=data['K'], mode='lines', name='K線', line=dict(color='blue', width=2)), row=2, col=1)
789
+ fig.add_trace(go.Scatter(x=data.index, y=data['D'], mode='lines', name='D線', line=dict(color='red', width=2)), row=2, col=1)
790
+ fig.add_hline(y=80, line_dash="dash", line_color="green", annotation_text="超買線(80)", row=2, col=1)
791
+ fig.add_hline(y=20, line_dash="dash", line_color="red", annotation_text="超賣線(20)", row=2, col=1)
792
+ fig.update_layout(title=f'{stock_name} - KD 隨機指標 (9,3,3)', height=500, yaxis2_range=[0, 100])
793
+ elif indicator == 'WR':
794
+ fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1, row_heights=[0.6, 0.4], subplot_titles=('價格走勢', '威廉指標 %R'))
795
+ fig.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='收盤價', line=dict(color='black', width=1)), row=1, col=1)
796
+ fig.add_trace(go.Scatter(x=data.index, y=data['Williams_R'], mode='lines', name='威廉%R', line=dict(color='purple', width=2)), row=2, col=1)
797
+ fig.add_hline(y=-20, line_dash="dash", line_color="green", annotation_text="超買線(-20)", row=2, col=1)
798
+ fig.add_hline(y=-80, line_dash="dash", line_color="red", annotation_text="超賣線(-80)", row=2, col=1)
799
+ fig.update_layout(title=f'{stock_name} - 威廉指標 %R (14日)', height=500, yaxis2_range=[-100, 0])
800
+ elif indicator == 'DMI':
801
+ fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1, row_heights=[0.6, 0.4], subplot_titles=('價格走勢', 'DMI 指標'))
802
+ data_filtered = data.iloc[14:]
803
+ fig.add_trace(go.Scatter(x=data_filtered.index, y=data_filtered['Close'], mode='lines', name='收盤價', line=dict(color='black', width=1)), row=1, col=1)
804
+ fig.add_trace(go.Scatter(x=data_filtered.index, y=data_filtered['+DI'], mode='lines', name='+DI', line=dict(color='red', width=2)), row=2, col=1)
805
+ fig.add_trace(go.Scatter(x=data_filtered.index, y=data_filtered['-DI'], mode='lines', name='-DI', line=dict(color='green', width=2)), row=2, col=1)
806
+ fig.add_trace(go.Scatter(x=data_filtered.index, y=data_filtered['ADX'], mode='lines', name='ADX', line=dict(color='blue', width=2, dash='dot')), row=2, col=1)
807
+ fig.update_layout(title=f'{stock_name} - DMI 動向指標 (14日)', height=500, showlegend=True, yaxis2_range=[0, 100])
808
+ return fig
809
+
810
+ @app.callback(
811
+ dash.dependencies.Output('volume-chart', 'figure'),
812
+ [dash.dependencies.Input('stock-dropdown', 'value'),
813
+ dash.dependencies.Input('period-dropdown', 'value')]
814
+ )
815
+ def update_volume_chart(selected_stock, period):
816
+ data = get_stock_data(selected_stock, period)
817
+ if data.empty: return {}
818
+ stock_name = [name for name, symbol in TAIWAN_STOCKS.items() if symbol == selected_stock][0]
819
+ colors = ['red' if data['Close'].iloc[i] > data['Open'].iloc[i] else 'green' for i in range(len(data))]
820
+ fig = go.Figure(go.Bar(x=data.index, y=data['Volume'], marker_color=colors, name='成交量'))
821
+ fig.update_layout(title=f'{stock_name} 成交量', xaxis_title='日期', yaxis_title='成交量', height=300)
822
+ return fig
823
+
824
+ @app.callback(
825
+ dash.dependencies.Output('industry-analysis', 'figure'),
826
+ [dash.dependencies.Input('stock-dropdown', 'value')]
827
+ )
828
+ def update_industry_analysis(selected_stock):
829
+ performance_data = []
830
+ for name, symbol in TAIWAN_STOCKS.items():
831
+ data = get_stock_data(symbol, '1mo')
832
+ if not data.empty and len(data) > 1:
833
+ return_pct = ((data['Close'].iloc[-1] - data['Close'].iloc[0]) / data['Close'].iloc[0]) * 100
834
+ performance_data.append({
835
+ '股票': name,
836
+ '代碼': symbol,
837
+ '月報酬率(%)': return_pct,
838
+ '絕對波動': abs(return_pct)
839
+ })
840
+ if not performance_data:
841
+ fig = go.Figure().add_annotation(text="無法計算產業資料", showarrow=False)
842
+ fig.update_layout(title="近一月市場波動最大標的", height=400)
843
+ return fig
844
+ df_performance = pd.DataFrame(performance_data)
845
+ df_top_movers = df_performance.sort_values(by='絕對波動', ascending=False).head(10)
846
+ fig = px.pie(
847
+ df_top_movers,
848
+ values='絕對波動',
849
+ names='股票',
850
+ title='近一月市場波動最大 Top 10 標的',
851
+ hover_data={'月報酬率(%)': ':.2f'}
852
+ )
853
+ fig.update_traces(
854
+ textposition='inside',
855
+ textinfo='percent+label',
856
+ hovertemplate="<b>%{label}</b><br>月報酬率: %{customdata[0]:.2f}%<extra></extra>"
857
+ )
858
+ fig.update_layout(height=400, showlegend=False)
859
+ return fig
860
+
861
+ @app.callback(
862
+ dash.dependencies.Output('business-climate-chart', 'figure'),
863
+ [dash.dependencies.Input('stock-dropdown', 'value')]
864
+ )
865
+ def update_business_climate_chart(selected_stock):
866
+ df = get_business_climate_data()
867
+ if df.empty:
868
+ fig = go.Figure().add_annotation(text="無法載入景氣燈號資料", showarrow=False)
869
+ fig.update_layout(title="台灣景氣燈號", height=300)
870
+ return fig
871
+ def get_light_color(score):
872
+ if score >= 32: return 'red'
873
+ elif score >= 24: return 'orange'
874
+ elif score >= 17: return 'yellow'
875
+ elif score >= 10: return 'lightgreen'
876
+ else: return 'blue'
877
+ colors = [get_light_color(score) for score in df['Index']]
878
+ fig = go.Figure()
879
+ fig.add_trace(go.Scatter(x=df['Date'], y=df['Index'], mode='lines+markers', name='景氣燈號', line=dict(color='darkblue', width=2), marker=dict(size=8, color=colors, line=dict(width=2, color='darkblue'))))
880
+ fig.add_hline(y=32, line_dash="dash", line_color="red", annotation_text="紅燈(32)")
881
+ fig.add_hline(y=17, line_dash="dash", line_color="yellow", annotation_text="黃燈(17)")
882
+ fig.update_layout(title="台灣景氣燈號走勢", xaxis_title='日期', yaxis_title='燈號分數', height=300, yaxis=dict(range=[0, 40]))
883
+ return fig
884
+
885
+ # ========================= MODIFIED SECTION START (CACHE INTEGRATED) =========================
886
+ @app.callback(
887
+ [dash.dependencies.Output('technical-analysis-text', 'children'),
888
+ dash.dependencies.Output('fundamental-analysis-text', 'children'),
889
+ dash.dependencies.Output('market-outlook-text', 'children')],
890
+ [dash.dependencies.Input('stock-dropdown', 'value'),
891
+ dash.dependencies.Input('period-dropdown', 'value')]
892
+ )
893
+ def update_analysis_text(selected_stock, period):
894
+ # 建立快取的唯一鍵值
895
+ cache_key = f"{selected_stock}-{period}"
896
+ current_time = time.time()
897
+
898
+ # 1. 檢查快取
899
+ if cache_key in ANALYSIS_CACHE:
900
+ cached_data = ANALYSIS_CACHE[cache_key]
901
+ if current_time - cached_data['timestamp'] < CACHE_DURATION_SECONDS:
902
+ print(f"從快取載入分析: {cache_key}")
903
+ # 直接回傳快取的內容
904
+ return cached_data['technical'], cached_data['fundamental'], cached_data['outlook']
905
+
906
+ print(f"重新生成分析: {cache_key}")
907
+ # --- 如果快取沒有,才繼續執行以下程式 ---
908
+
909
+ data = get_stock_data(selected_stock, period)
910
+ stock_name = [name for name, symbol in TAIWAN_STOCKS.items() if symbol == selected_stock][0]
911
+ if data.empty or len(data) < 20:
912
+ return "資料不足,無法分析", "資料不足,無法分析", "資料不足,無法分析"
913
+
914
+ data = calculate_technical_indicators(data)
915
+
916
+ # 2. 技術面分析
917
+ price_change = ((data['Close'].iloc[-1] - data['Close'].iloc[0]) / data['Close'].iloc[0]) * 100
918
+ rsi_current = data['RSI'].iloc[-1] if not pd.isna(data['RSI'].iloc[-1]) else 50
919
+ macd_current = data['MACD'].iloc[-1] if not pd.isna(data['MACD'].iloc[-1]) else 0
920
+ macd_signal_current = data['MACD_Signal'].iloc[-1] if not pd.isna(data['MACD_Signal'].iloc[-1]) else 0
921
+
922
+ technical_text = html.Div([
923
+ html.P([html.Strong("價格趨勢:"), f"在最近 {period} 期間內,{stock_name} 股價呈現", html.Span(f"{'上漲' if price_change > 5 else '下跌' if price_change < -5 else '盤整'}", style={'color': 'red' if price_change > 5 else 'green' if price_change < -5 else 'orange', 'font-weight': 'bold'}), f"走勢,累計變動 {price_change:+.1f}%。"]),
924
+ html.P([html.Strong("RSI 指標:"), f"目前的 RSI 值為 {rsi_current:.1f},", html.Span("處於超買區(>70)" if rsi_current > 70 else "處於超賣區(<30)" if rsi_current < 30 else "在正常範圍內", style={'color': 'green' if rsi_current > 70 else 'red' if rsi_current < 30 else 'blue', 'font-weight': 'bold'}), "。"]),
925
+ html.P([html.Strong("MACD 指標:"), f"MACD 快線 ({macd_current:.3f}) 目前", html.Span("高於" if macd_current > macd_signal_current else "低於", style={'color': 'red' if macd_current > macd_signal_current else 'green', 'font-weight': 'bold'}), f" Signal 慢線 ({macd_signal_current:.3f}),", f"顯示市場動能偏向{'多頭' if macd_current > macd_signal_current else '空頭'}。"]),
926
+ ])
927
+
928
+ # 3. 基本面與展望分析 (呼叫 Gemini)
929
+ fundamental_text, market_outlook_text = generate_gemini_analysis(stock_name, selected_stock, period, data)
930
+
931
+ # 4. 將新產生的結果存入快取
932
+ ANALYSIS_CACHE[cache_key] = {
933
+ 'technical': technical_text,
934
+ 'fundamental': fundamental_text,
935
+ 'outlook': market_outlook_text,
936
+ 'timestamp': current_time
937
+ }
938
+
939
+ return technical_text, fundamental_text, market_outlook_text
940
+ # ========================== MODIFIED SECTION END ==========================
941
+
942
+ @app.callback(
943
+ dash.dependencies.Output('pmi-chart', 'figure'),
944
+ [dash.dependencies.Input('stock-dropdown', 'value')]
945
+ )
946
+ def update_pmi_chart(selected_stock):
947
+ df = get_pmi_data()
948
+ if df.empty:
949
+ fig = go.Figure().add_annotation(text="無法載入PMI資料", showarrow=False)
950
+ fig.update_layout(title="台灣PMI指數", height=300)
951
+ return fig
952
+ colors = ['red' if value >= 50 else 'green' for value in df['Index']]
953
+ fig = go.Figure()
954
+ fig.add_trace(go.Scatter(x=df['Date'], y=df['Index'], mode='lines+markers', name='PMI指數', line=dict(color='darkblue', width=2), marker=dict(size=8, color=colors, line=dict(width=2, color='darkblue'))))
955
+ fig.add_hline(y=50, line_dash="dash", line_color="black", annotation_text="榮枯線(50)")
956
+ fig.update_layout(title="台灣PMI指數走勢", xaxis_title='日期', yaxis_title='PMI指數', height=300, yaxis=dict(range=[35, 60]))
957
+ return fig
958
+
959
+ def summarize_news_with_gemini(news_list: list) -> str:
960
+ """
961
+ 使用 Gemini API 將英文新聞標題列表摘要成一段繁體中文。
962
+ """
963
+ api_key = os.getenv("GEMINI_API_KEY")
964
+ if not api_key:
965
+ return "錯誤:找不到 GEMINI_API_KEY。請在 Hugging Face Secrets 中設定。"
966
+
967
+ try:
968
+ genai.configure(api_key=api_key)
969
+ model = genai.GenerativeModel('gemini-1.5-flash')
970
+
971
+ formatted_news = "\n".join([f"- {news}" for news in news_list])
972
+
973
+ prompt = f"""
974
+ 請扮演一位專業的金融市場分析師。
975
+ 以下是幾則最新的英文財經新聞標題,請將它們整合成一段簡潔、流���、約 200 字的繁體中文市場動態摘要,與利多哪些產業,利空哪些產業。
976
+ 提供3段重點,
977
+ 請專注於可能影響市場情緒和股價的關鍵資訊,並直接提供摘要內容,不要包含任何額外的問候語或說明。
978
+
979
+ 英文新聞標題如下:
980
+ {formatted_news}
981
+ """
982
+
983
+ response = model.generate_content(prompt)
984
+ return response.text
985
+
986
+ except Exception as e:
987
+ print(f"呼叫 Gemini API 時發生錯誤: {e}")
988
+ return f"無法生成新聞摘要,請稍後再試。錯誤訊息:{e}"
989
+
990
+ @app.callback(
991
+ [dash.dependencies.Output('comparison-chart', 'figure'),
992
+ dash.dependencies.Output('comparison-table', 'children')],
993
+ [dash.dependencies.Input('comparison-stocks', 'value'),
994
+ dash.dependencies.Input('comparison-period', 'value')]
995
+ )
996
+ def update_comparison_analysis(selected_stocks, period):
997
+ fixed_stock = '0050.TW'
998
+ if not selected_stocks: selected_stocks = [fixed_stock]
999
+ elif fixed_stock not in selected_stocks: selected_stocks.insert(0, fixed_stock)
1000
+ selected_stocks = selected_stocks[:5]
1001
+ fig = go.Figure()
1002
+ comparison_data = []
1003
+ for stock in selected_stocks:
1004
+ data = get_stock_data(stock, period)
1005
+ if not data.empty:
1006
+ stock_name = next((name for name, symbol in TAIWAN_STOCKS.items() if symbol == stock), stock)
1007
+ normalized_prices = (data['Close'] / data['Close'].iloc[0]) * 100
1008
+ fig.add_trace(go.Scatter(x=data.index, y=normalized_prices, mode='lines', name=stock_name, line=dict(width=2)))
1009
+ total_return = ((data['Close'].iloc[-1] / data['Close'].iloc[0]) - 1) * 100
1010
+ volatility = data['Close'].pct_change().std() * np.sqrt(252) * 100
1011
+ comparison_data.append({'name': stock_name, 'return': total_return, 'volatility': volatility, 'current_price': data['Close'].iloc[-1]})
1012
+ fig.update_layout(title=f'股票績效比較 - {period}', xaxis_title='日期', yaxis_title='相對績效 (基期=100)', height=400, hovermode='x unified')
1013
+ if comparison_data:
1014
+ table_rows = []
1015
+ for item in sorted(comparison_data, key=lambda x: x['return'], reverse=True):
1016
+ color = 'red' if item['return'] > 0 else 'green'
1017
+ table_rows.append(html.Tr([html.Td(item['name'], style={'font-weight': 'bold'}), html.Td(f"{item['return']:+.1f}%", style={'color': color, 'font-weight': 'bold'}), html.Td(f"{item['volatility']:.1f}%"), html.Td(f"${item['current_price']:.2f}")]))
1018
+ table = html.Table([html.Thead(html.Tr([html.Th("股票"), html.Th("報酬率"), html.Th("波動率"), html.Th("現價")])), html.Tbody(table_rows)], style={'width': '100%'})
1019
+ return fig, table
1020
+ return fig, html.Div("無可比較資料")
1021
+
1022
+ @app.callback(
1023
+ [dash.dependencies.Output('sentiment-gauge', 'children'),
1024
+ dash.dependencies.Output('news-summary', 'children')],
1025
+ [dash.dependencies.Input('stock-dropdown', 'value')]
1026
+ )
1027
+ def update_sentiment_analysis(selected_stock):
1028
+ if predictor is None:
1029
+ error_fig = go.Figure().add_annotation(text="情緒指標模型載入失敗", showarrow=False)
1030
+ error_fig.update_layout(height=200)
1031
+ return dcc.Graph(figure=error_fig), html.P("新聞分析模型載入失敗,請檢查後台日誌。")
1032
+
1033
+ sentiment_score_raw = predictor.get_news_index()
1034
+
1035
+ if sentiment_score_raw is not None:
1036
+ sentiment_score_normalized = (sentiment_score_raw + 1) * 50
1037
+ sentiment_score_normalized = max(0, min(100, sentiment_score_normalized))
1038
+ if sentiment_score_normalized >= 65:
1039
+ bar_color, level_text = "#5cb85c", "樂觀"
1040
+ elif sentiment_score_normalized >= 35:
1041
+ bar_color, level_text = "#f0ad4e", "中性"
1042
+ else:
1043
+ bar_color, level_text = "#d9534f", "悲觀"
1044
+ gauge_fig = go.Figure(go.Indicator(
1045
+ mode = "gauge+number", value = sentiment_score_normalized,
1046
+ domain = {'x': [0, 1], 'y': [0, 1]},
1047
+ title = {'text': f"昨日市場情緒: {level_text}", 'font': {'size': 18}},
1048
+ gauge = {'axis': {'range': [0, 100]}, 'bar': {'color': bar_color},
1049
+ 'steps': [{'range': [0, 35], 'color': "rgba(217, 83, 79, 0.2)"},
1050
+ {'range': [35, 65], 'color': "rgba(240, 173, 78, 0.2)"},
1051
+ {'range': [65, 100], 'color': "rgba(92, 184, 92, 0.2)"}]}
1052
+ ))
1053
+ gauge_fig.update_layout(height=200, margin=dict(l=30, r=30, t=50, b=20))
1054
+ gauge_content = dcc.Graph(figure=gauge_fig)
1055
+ else:
1056
+ error_fig = go.Figure().add_annotation(text="今日尚無情緒分數", showarrow=False)
1057
+ error_fig.update_layout(height=200)
1058
+ gauge_content = dcc.Graph(figure=error_fig)
1059
+
1060
+ top_news_list = predictor.get_news()
1061
+ news_content = None
1062
+
1063
+ if top_news_list and isinstance(top_news_list, list):
1064
+ summary_text = summarize_news_with_gemini(top_news_list)
1065
+ news_content = dcc.Markdown(summary_text, style={
1066
+ 'margin': '8px 0', 'padding-left': '5px',
1067
+ 'font-size': '15px', 'line-height': '1.7'
1068
+ })
1069
+ elif top_news_list == []:
1070
+ news_content = html.P("昨日無重大相關新聞。", style={'text-align': 'center', 'padding-top': '50px'})
1071
+ else:
1072
+ news_content = html.P("讀取新聞時發生錯誤。", style={'text-align': 'center', 'padding-top': '50px'})
1073
+
1074
+ return gauge_content, news_content
1075
+
1076
+ # 主程式執行
1077
+ if __name__ == '__main__':
1078
+ app.run(host="0.0.0.0", port=7860, debug=False)