AlanRex commited on
Commit
6e45e69
·
verified ·
1 Parent(s): 5d1614d

Delete app.py

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