Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -21,12 +21,12 @@ import time # 引用 time 模組以處理時間戳
|
|
| 21 |
# 引用您組員的預測器程式
|
| 22 |
from Bert_predict import BertPredictor
|
| 23 |
|
| 24 |
-
#
|
| 25 |
from model_predictor import XGBoostModel
|
| 26 |
# ========================== 引用外部模組 END ==========================
|
| 27 |
|
| 28 |
# ========================= 全域設定 START =========================
|
| 29 |
-
#
|
| 30 |
USE_ADVANCED_MODEL = True
|
| 31 |
|
| 32 |
# ========================= CACHE 設定 START =========================
|
|
@@ -36,7 +36,7 @@ ANALYSIS_CACHE = {}
|
|
| 36 |
CACHE_DURATION_SECONDS = 8 * 60 * 60
|
| 37 |
# ========================== CACHE 設定 END ==========================
|
| 38 |
|
| 39 |
-
#
|
| 40 |
try:
|
| 41 |
print("正在初始化 XGBoost 預測模型...")
|
| 42 |
xgb_model = XGBoostModel(default_model='xgboost_model')
|
|
@@ -47,10 +47,9 @@ except Exception as e:
|
|
| 47 |
USE_ADVANCED_MODEL = False
|
| 48 |
xgb_model = None
|
| 49 |
print("警告:已自動切換回簡易統計模型模式。")
|
| 50 |
-
|
| 51 |
# ========================== 全域設定 END ==========================
|
| 52 |
|
| 53 |
-
# 台股代號對應表
|
| 54 |
TAIWAN_STOCKS = {
|
| 55 |
'元大台灣50': '0050.TW', '台積電': '2330.TW', '聯發科': '2454.TW',
|
| 56 |
'鴻海': '2317.TW', '台達電': '2308.TW', '廣達': '2382.TW', '富邦金': '2881.TW',
|
|
@@ -69,7 +68,7 @@ TAIWAN_STOCKS = {
|
|
| 69 |
'譜瑞-KY': '4966.TWO', '貿聯-KY': '3665.TW', '騰雲': '6870.TWO', '穩懋': '3105.TWO'
|
| 70 |
}
|
| 71 |
|
| 72 |
-
# 產業分類
|
| 73 |
INDUSTRY_MAPPING = {
|
| 74 |
'0050.TW': 'ETF', '2330.TW': '半導體', '2454.TW': '半導體', '2317.TW': '電子組件',
|
| 75 |
'2308.TW': '電子', '2382.TW': '電子', '2881.TW': '金融', '2891.TW': '金融',
|
|
@@ -88,7 +87,6 @@ INDUSTRY_MAPPING = {
|
|
| 88 |
'3665.TW': '連接器', '6870.TWO': '軟體整合', '3105.TWO': 'PA功率'
|
| 89 |
}
|
| 90 |
|
| 91 |
-
|
| 92 |
def get_stock_data(symbol, period='1y'):
|
| 93 |
"""獲取股票資料"""
|
| 94 |
try:
|
|
@@ -120,7 +118,7 @@ def simple_statistical_predict(data, predict_days=5):
|
|
| 120 |
change_pct = ((predicted_price - prices[-1]) / prices[-1]) * 100
|
| 121 |
return {'predicted_price': predicted_price, 'change_pct': change_pct, 'confidence': max(0.6, 1 - volatility * 2)}
|
| 122 |
|
| 123 |
-
#
|
| 124 |
def advanced_xgboost_predict(data, predict_days):
|
| 125 |
"""
|
| 126 |
【進階模型橋接函式】
|
|
@@ -179,7 +177,7 @@ def get_prediction(data, predict_days=5):
|
|
| 179 |
"""
|
| 180 |
if USE_ADVANCED_MODEL:
|
| 181 |
print(f"模式: 進階XGBoost模型 | 預測天期: {predict_days}天")
|
| 182 |
-
#
|
| 183 |
prediction = advanced_xgboost_predict(data, predict_days)
|
| 184 |
# 如果進階模型預測失敗,則自動降級使用簡易模型
|
| 185 |
if prediction is not None:
|
|
@@ -191,9 +189,6 @@ def get_prediction(data, predict_days=5):
|
|
| 191 |
print(f"模式: 簡易統計模型 | 預測天期: {predict_days}天")
|
| 192 |
return simple_statistical_predict(data, predict_days)
|
| 193 |
|
| 194 |
-
# (後續所有函式,如 calculate_technical_indicators, generate_gemini_analysis 等,都保持不變)
|
| 195 |
-
# ... (此處省略所有未修改的函式,以節省篇幅) ...
|
| 196 |
-
# ... (您的 calculate_technical_indicators, calculate_volume_profile, get_business_climate_data, get_pmi_data, generate_gemini_analysis 等函式放在這裡) ...
|
| 197 |
def calculate_technical_indicators(df):
|
| 198 |
"""計算技術指標"""
|
| 199 |
if df.empty: return df
|
|
@@ -273,20 +268,27 @@ def get_pmi_data():
|
|
| 273 |
return pd.DataFrame()
|
| 274 |
|
| 275 |
def generate_gemini_analysis(stock_name, stock_symbol, period, data):
|
|
|
|
|
|
|
|
|
|
| 276 |
api_key = os.getenv("GEMINI_API_KEY")
|
| 277 |
if not api_key:
|
| 278 |
return "無法讀取 GEMINI API 金鑰", "請在系統環境變數中設定您的金鑰"
|
|
|
|
| 279 |
try:
|
| 280 |
genai.configure(api_key=api_key)
|
| 281 |
model = genai.GenerativeModel('gemini-1.5-flash')
|
|
|
|
| 282 |
price_change = ((data['Close'].iloc[-1] - data['Close'].iloc[0]) / data['Close'].iloc[0]) * 100
|
| 283 |
rsi_current = data['RSI'].iloc[-1]
|
| 284 |
macd_current = data['MACD'].iloc[-1]
|
| 285 |
macd_signal_current = data['MACD_Signal'].iloc[-1]
|
| 286 |
industry = INDUSTRY_MAPPING.get(stock_symbol, '綜合')
|
|
|
|
| 287 |
prompt = f"""
|
| 288 |
請扮演一位專業、資深的台灣股市金融分析師。
|
| 289 |
我將提供一檔台股的即時技術指標數據,請你基於這些數據,結合你對這家公司、其所在產業以及當前市場趨勢的理解,為我生成一段專業的��基本面分析」和一段「市場展望與投資建議」。
|
|
|
|
| 290 |
**股票資訊:**
|
| 291 |
- **公司名稱:** {stock_name} ({stock_symbol})
|
| 292 |
- **分析期間:** 最近 {period}
|
|
@@ -294,19 +296,23 @@ def generate_gemini_analysis(stock_name, stock_symbol, period, data):
|
|
| 294 |
- **期間價格變動:** {price_change:+.2f}%
|
| 295 |
- **目前 RSI 指標:** {rsi_current:.2f}
|
| 296 |
- **目前 MACD 指標:** MACD線為 {macd_current:.3f}, 信號線為 {macd_signal_current:.3f}
|
|
|
|
| 297 |
**你的任務:**
|
| 298 |
1. **基本面分析 (約 150 字):**
|
| 299 |
- 評論這家公司的產業地位、近期營運亮點或挑戰。
|
| 300 |
- 提及任何可能影響其基本面的關鍵因素 (例如:財報、法說會、政策、供應鏈變化等)。
|
| 301 |
- 請用專業、客觀的語氣撰寫。
|
|
|
|
| 302 |
2. **市場展望與投資建議 (約 150 字):**
|
| 303 |
- 基於上述所有資訊,提供對該股票的短期和中期市場展望。
|
| 304 |
- 提出具體的投資建議,例如:適合何種類型的投資人、潛在的風險點。
|
| 305 |
- 請直接提供分析內容,不要包含任何問候語。
|
|
|
|
| 306 |
**輸出格式:**
|
| 307 |
請嚴格按照以下格式回傳,使用"$$"作為兩個段落之間的分隔符:
|
| 308 |
[基本面分析內容]$$[市場展望與投資建議內容]
|
| 309 |
"""
|
|
|
|
| 310 |
response = model.generate_content(prompt)
|
| 311 |
parts = response.text.split('$$')
|
| 312 |
if len(parts) == 2:
|
|
@@ -314,7 +320,9 @@ def generate_gemini_analysis(stock_name, stock_symbol, period, data):
|
|
| 314 |
market_outlook = parts[1].strip()
|
| 315 |
return dcc.Markdown(fundamental_analysis), dcc.Markdown(market_outlook)
|
| 316 |
else:
|
|
|
|
| 317 |
return dcc.Markdown("無法解析 Gemini 回應,請稍後再試。"), dcc.Markdown(response.text)
|
|
|
|
| 318 |
except Exception as e:
|
| 319 |
error_message = f"呼叫 Gemini API 時發生錯誤: {str(e)}"
|
| 320 |
print(error_message)
|
|
@@ -331,8 +339,7 @@ except Exception as e:
|
|
| 331 |
print(f"錯誤:新聞情緒分析模型初始化失敗 - {e}")
|
| 332 |
predictor = None
|
| 333 |
|
| 334 |
-
#
|
| 335 |
-
# ... (此處省略整個 app.layout 區塊,與您原檔案相同) ...
|
| 336 |
app.layout = html.Div([
|
| 337 |
html.H1("台股分析儀表板", style={'text-align': 'center', 'margin-bottom': '30px'}),
|
| 338 |
html.Div([
|
|
@@ -343,9 +350,8 @@ app.layout = html.Div([
|
|
| 343 |
dcc.Dropdown(id='taiex-prediction-period',
|
| 344 |
options=[
|
| 345 |
{'label': '1日後預測', 'value': 1},{'label': '5日後預測', 'value': 5},
|
| 346 |
-
{'label': '10日後預測', 'value': 10},{'label': '20日後預測', 'value': 20},
|
| 347 |
-
|
| 348 |
-
], value=5,
|
| 349 |
style={'margin-bottom': '10px', 'color': '#272727'})
|
| 350 |
], style={'width': '30%', 'display': 'inline-block'}),
|
| 351 |
html.Div(id='taiex-prediction-results', style={'width': '65%', 'display': 'inline-block', 'margin-left': '5%'})
|
|
@@ -353,7 +359,6 @@ app.layout = html.Div([
|
|
| 353 |
html.Div([dcc.Graph(id='taiex-prediction-chart')], style={'margin-top': '20px'})
|
| 354 |
], 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'}),
|
| 355 |
|
| 356 |
-
# ... (後續 layout 省略,與您原檔案相同)
|
| 357 |
html.Div([
|
| 358 |
html.H3("📰 市場情緒與新聞分析", style={'color': '#E74C3C', 'margin-bottom': '20px'}),
|
| 359 |
html.Div([
|
|
@@ -445,9 +450,6 @@ app.layout = html.Div([
|
|
| 445 |
], style={'margin-top': '30px','padding': '20px','background': 'white','border-radius': '10px','box-shadow': '0 2px 10px rgba(0,0,0,0.1)'}),
|
| 446 |
])
|
| 447 |
|
| 448 |
-
|
| 449 |
-
# (所有 Callback 函式保持不變,除了 update_taiex_prediction 內部的邏輯已透過 get_prediction 更新)
|
| 450 |
-
# ... (此處省略所有未修改的 Callback 函式) ...
|
| 451 |
@app.callback(
|
| 452 |
[dash.dependencies.Output('taiex-prediction-results', 'children'),
|
| 453 |
dash.dependencies.Output('taiex-prediction-chart', 'figure')],
|
|
@@ -460,7 +462,7 @@ def update_taiex_prediction(predict_days):
|
|
| 460 |
# === 呼叫 get_prediction 控制器,它會自動選擇模型 ===
|
| 461 |
final_prediction = get_prediction(data, predict_days)
|
| 462 |
|
| 463 |
-
if final_prediction is None: return html.Div("
|
| 464 |
current_price, last_date = data['Close'].iloc[-1], data.index[-1]
|
| 465 |
predicted_price, change_pct, confidence = final_prediction['predicted_price'], final_prediction['change_pct'], final_prediction['confidence']
|
| 466 |
|
|
@@ -475,6 +477,7 @@ def update_taiex_prediction(predict_days):
|
|
| 475 |
prediction_dates.append(last_date + timedelta(days=days))
|
| 476 |
prediction_prices.append(interim_prediction['predicted_price'])
|
| 477 |
|
|
|
|
| 478 |
color, arrow = ('red', '📈') if change_pct >= 0 else ('green', '📉')
|
| 479 |
result_card = html.Div([
|
| 480 |
html.H4(f"{predict_days}日後預測結果", style={'margin': '0 0 15px 0', 'color': 'white'}),
|
|
@@ -489,7 +492,6 @@ def update_taiex_prediction(predict_days):
|
|
| 489 |
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'))
|
| 490 |
return result_card, fig
|
| 491 |
|
| 492 |
-
# ... (其他所有 callback 函式都無需修改)
|
| 493 |
@app.callback(
|
| 494 |
dash.dependencies.Output('stock-info-cards', 'children'),
|
| 495 |
[dash.dependencies.Input('stock-dropdown', 'value')]
|
|
@@ -516,7 +518,229 @@ def update_stock_info(selected_stock):
|
|
| 516 |
html.P(f"成交量: {data['Volume'].iloc[-1]:,.0f}", style={'margin': '5px 0'})
|
| 517 |
], style={'background': 'white','padding': '20px','border-radius': '10px','box-shadow': '0 2px 10px rgba(0,0,0,0.1)','display': 'inline-block'})
|
| 518 |
])
|
| 519 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 520 |
def summarize_news_with_gemini(news_list: list) -> str:
|
| 521 |
"""
|
| 522 |
使用 Gemini API 將英文新聞標題列表摘要成一段繁體中文。
|
|
@@ -546,4 +770,94 @@ def summarize_news_with_gemini(news_list: list) -> str:
|
|
| 546 |
|
| 547 |
except Exception as e:
|
| 548 |
print(f"呼叫 Gemini API 時發生錯誤: {e}")
|
| 549 |
-
return f"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
# 引用您組員的預測器程式
|
| 22 |
from Bert_predict import BertPredictor
|
| 23 |
|
| 24 |
+
# 【修改 1】: 匯入 XGBoostModel 類別
|
| 25 |
from model_predictor import XGBoostModel
|
| 26 |
# ========================== 引用外部模組 END ==========================
|
| 27 |
|
| 28 |
# ========================= 全域設定 START =========================
|
| 29 |
+
# 【修改 2】: 將開關設為 True 來啟用您的 XGBoost 模型
|
| 30 |
USE_ADVANCED_MODEL = True
|
| 31 |
|
| 32 |
# ========================= CACHE 設定 START =========================
|
|
|
|
| 36 |
CACHE_DURATION_SECONDS = 8 * 60 * 60
|
| 37 |
# ========================== CACHE 設定 END ==========================
|
| 38 |
|
| 39 |
+
# 【修改 3】: 在應用程式啟動時,預先載入 XGBoost 模型
|
| 40 |
try:
|
| 41 |
print("正在初始化 XGBoost 預測模型...")
|
| 42 |
xgb_model = XGBoostModel(default_model='xgboost_model')
|
|
|
|
| 47 |
USE_ADVANCED_MODEL = False
|
| 48 |
xgb_model = None
|
| 49 |
print("警告:已自動切換回簡易統計模型模式。")
|
|
|
|
| 50 |
# ========================== 全域設定 END ==========================
|
| 51 |
|
| 52 |
+
# 台股代號對應表
|
| 53 |
TAIWAN_STOCKS = {
|
| 54 |
'元大台灣50': '0050.TW', '台積電': '2330.TW', '聯發科': '2454.TW',
|
| 55 |
'鴻海': '2317.TW', '台達電': '2308.TW', '廣達': '2382.TW', '富邦金': '2881.TW',
|
|
|
|
| 68 |
'譜瑞-KY': '4966.TWO', '貿聯-KY': '3665.TW', '騰雲': '6870.TWO', '穩懋': '3105.TWO'
|
| 69 |
}
|
| 70 |
|
| 71 |
+
# 產業分類
|
| 72 |
INDUSTRY_MAPPING = {
|
| 73 |
'0050.TW': 'ETF', '2330.TW': '半導體', '2454.TW': '半導體', '2317.TW': '電子組件',
|
| 74 |
'2308.TW': '電子', '2382.TW': '電子', '2881.TW': '金融', '2891.TW': '金融',
|
|
|
|
| 87 |
'3665.TW': '連接器', '6870.TWO': '軟體整合', '3105.TWO': 'PA功率'
|
| 88 |
}
|
| 89 |
|
|
|
|
| 90 |
def get_stock_data(symbol, period='1y'):
|
| 91 |
"""獲取股票資料"""
|
| 92 |
try:
|
|
|
|
| 118 |
change_pct = ((predicted_price - prices[-1]) / prices[-1]) * 100
|
| 119 |
return {'predicted_price': predicted_price, 'change_pct': change_pct, 'confidence': max(0.6, 1 - volatility * 2)}
|
| 120 |
|
| 121 |
+
# 【修改 4】: 建立一個新的函式來處理 XGBoost 模型的輸入和輸出
|
| 122 |
def advanced_xgboost_predict(data, predict_days):
|
| 123 |
"""
|
| 124 |
【進階模型橋接函式】
|
|
|
|
| 177 |
"""
|
| 178 |
if USE_ADVANCED_MODEL:
|
| 179 |
print(f"模式: 進階XGBoost模型 | 預測天期: {predict_days}天")
|
| 180 |
+
# 【修改 5】: 呼叫新的 XGBoost 橋接函式
|
| 181 |
prediction = advanced_xgboost_predict(data, predict_days)
|
| 182 |
# 如果進階模型預測失敗,則自動降級使用簡易模型
|
| 183 |
if prediction is not None:
|
|
|
|
| 189 |
print(f"模式: 簡易統計模型 | 預測天期: {predict_days}天")
|
| 190 |
return simple_statistical_predict(data, predict_days)
|
| 191 |
|
|
|
|
|
|
|
|
|
|
| 192 |
def calculate_technical_indicators(df):
|
| 193 |
"""計算技術指標"""
|
| 194 |
if df.empty: return df
|
|
|
|
| 268 |
return pd.DataFrame()
|
| 269 |
|
| 270 |
def generate_gemini_analysis(stock_name, stock_symbol, period, data):
|
| 271 |
+
"""
|
| 272 |
+
使用 Gemini API 生成基本面和市場展望分析。
|
| 273 |
+
"""
|
| 274 |
api_key = os.getenv("GEMINI_API_KEY")
|
| 275 |
if not api_key:
|
| 276 |
return "無法讀取 GEMINI API 金鑰", "請在系統環境變數中設定您的金鑰"
|
| 277 |
+
|
| 278 |
try:
|
| 279 |
genai.configure(api_key=api_key)
|
| 280 |
model = genai.GenerativeModel('gemini-1.5-flash')
|
| 281 |
+
|
| 282 |
price_change = ((data['Close'].iloc[-1] - data['Close'].iloc[0]) / data['Close'].iloc[0]) * 100
|
| 283 |
rsi_current = data['RSI'].iloc[-1]
|
| 284 |
macd_current = data['MACD'].iloc[-1]
|
| 285 |
macd_signal_current = data['MACD_Signal'].iloc[-1]
|
| 286 |
industry = INDUSTRY_MAPPING.get(stock_symbol, '綜合')
|
| 287 |
+
|
| 288 |
prompt = f"""
|
| 289 |
請扮演一位專業、資深的台灣股市金融分析師。
|
| 290 |
我將提供一檔台股的即時技術指標數據,請你基於這些數據,結合你對這家公司、其所在產業以及當前市場趨勢的理解,為我生成一段專業的��基本面分析」和一段「市場展望與投資建議」。
|
| 291 |
+
|
| 292 |
**股票資訊:**
|
| 293 |
- **公司名稱:** {stock_name} ({stock_symbol})
|
| 294 |
- **分析期間:** 最近 {period}
|
|
|
|
| 296 |
- **期間價格變動:** {price_change:+.2f}%
|
| 297 |
- **目前 RSI 指標:** {rsi_current:.2f}
|
| 298 |
- **目前 MACD 指標:** MACD線為 {macd_current:.3f}, 信號線為 {macd_signal_current:.3f}
|
| 299 |
+
|
| 300 |
**你的任務:**
|
| 301 |
1. **基本面分析 (約 150 字):**
|
| 302 |
- 評論這家公司的產業地位、近期營運亮點或挑戰。
|
| 303 |
- 提及任何可能影響其基本面的關鍵因素 (例如:財報、法說會、政策、供應鏈變化等)。
|
| 304 |
- 請用專業、客觀的語氣撰寫。
|
| 305 |
+
|
| 306 |
2. **市場展望與投資建議 (約 150 字):**
|
| 307 |
- 基於上述所有資訊,提供對該股票的短期和中期市場展望。
|
| 308 |
- 提出具體的投資建議,例如:適合何種類型的投資人、潛在的風險點。
|
| 309 |
- 請直接提供分析內容,不要包含任何問候語。
|
| 310 |
+
|
| 311 |
**輸出格式:**
|
| 312 |
請嚴格按照以下格式回傳,使用"$$"作為兩個段落之間的分隔符:
|
| 313 |
[基本面分析內容]$$[市場展望與投資建議內容]
|
| 314 |
"""
|
| 315 |
+
|
| 316 |
response = model.generate_content(prompt)
|
| 317 |
parts = response.text.split('$$')
|
| 318 |
if len(parts) == 2:
|
|
|
|
| 320 |
market_outlook = parts[1].strip()
|
| 321 |
return dcc.Markdown(fundamental_analysis), dcc.Markdown(market_outlook)
|
| 322 |
else:
|
| 323 |
+
# Fallback for unexpected response format
|
| 324 |
return dcc.Markdown("無法解析 Gemini 回應,請稍後再試。"), dcc.Markdown(response.text)
|
| 325 |
+
|
| 326 |
except Exception as e:
|
| 327 |
error_message = f"呼叫 Gemini API 時發生錯誤: {str(e)}"
|
| 328 |
print(error_message)
|
|
|
|
| 339 |
print(f"錯誤:新聞情緒分析模型初始化失敗 - {e}")
|
| 340 |
predictor = None
|
| 341 |
|
| 342 |
+
# 應用程式佈局
|
|
|
|
| 343 |
app.layout = html.Div([
|
| 344 |
html.H1("台股分析儀表板", style={'text-align': 'center', 'margin-bottom': '30px'}),
|
| 345 |
html.Div([
|
|
|
|
| 350 |
dcc.Dropdown(id='taiex-prediction-period',
|
| 351 |
options=[
|
| 352 |
{'label': '1日後預測', 'value': 1},{'label': '5日後預測', 'value': 5},
|
| 353 |
+
{'label': '10日後預測', 'value': 10},{'label': '20日後預測', 'value': 20}],
|
| 354 |
+
value=5,
|
|
|
|
| 355 |
style={'margin-bottom': '10px', 'color': '#272727'})
|
| 356 |
], style={'width': '30%', 'display': 'inline-block'}),
|
| 357 |
html.Div(id='taiex-prediction-results', style={'width': '65%', 'display': 'inline-block', 'margin-left': '5%'})
|
|
|
|
| 359 |
html.Div([dcc.Graph(id='taiex-prediction-chart')], style={'margin-top': '20px'})
|
| 360 |
], 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'}),
|
| 361 |
|
|
|
|
| 362 |
html.Div([
|
| 363 |
html.H3("📰 市場情緒與新聞分析", style={'color': '#E74C3C', 'margin-bottom': '20px'}),
|
| 364 |
html.Div([
|
|
|
|
| 450 |
], style={'margin-top': '30px','padding': '20px','background': 'white','border-radius': '10px','box-shadow': '0 2px 10px rgba(0,0,0,0.1)'}),
|
| 451 |
])
|
| 452 |
|
|
|
|
|
|
|
|
|
|
| 453 |
@app.callback(
|
| 454 |
[dash.dependencies.Output('taiex-prediction-results', 'children'),
|
| 455 |
dash.dependencies.Output('taiex-prediction-chart', 'figure')],
|
|
|
|
| 462 |
# === 呼叫 get_prediction 控制器,它會自動選擇模型 ===
|
| 463 |
final_prediction = get_prediction(data, predict_days)
|
| 464 |
|
| 465 |
+
if final_prediction is None: return html.Div("資料不足,無法進行預測"), {}
|
| 466 |
current_price, last_date = data['Close'].iloc[-1], data.index[-1]
|
| 467 |
predicted_price, change_pct, confidence = final_prediction['predicted_price'], final_prediction['change_pct'], final_prediction['confidence']
|
| 468 |
|
|
|
|
| 477 |
prediction_dates.append(last_date + timedelta(days=days))
|
| 478 |
prediction_prices.append(interim_prediction['predicted_price'])
|
| 479 |
|
| 480 |
+
# (後續繪圖邏輯不變)
|
| 481 |
color, arrow = ('red', '📈') if change_pct >= 0 else ('green', '📉')
|
| 482 |
result_card = html.Div([
|
| 483 |
html.H4(f"{predict_days}日後預測結果", style={'margin': '0 0 15px 0', 'color': 'white'}),
|
|
|
|
| 492 |
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'))
|
| 493 |
return result_card, fig
|
| 494 |
|
|
|
|
| 495 |
@app.callback(
|
| 496 |
dash.dependencies.Output('stock-info-cards', 'children'),
|
| 497 |
[dash.dependencies.Input('stock-dropdown', 'value')]
|
|
|
|
| 518 |
html.P(f"成交量: {data['Volume'].iloc[-1]:,.0f}", style={'margin': '5px 0'})
|
| 519 |
], style={'background': 'white','padding': '20px','border-radius': '10px','box-shadow': '0 2px 10px rgba(0,0,0,0.1)','display': 'inline-block'})
|
| 520 |
])
|
| 521 |
+
|
| 522 |
+
@app.callback(
|
| 523 |
+
dash.dependencies.Output('price-chart', 'figure'),
|
| 524 |
+
[dash.dependencies.Input('stock-dropdown', 'value'),
|
| 525 |
+
dash.dependencies.Input('period-dropdown', 'value'),
|
| 526 |
+
dash.dependencies.Input('chart-type', 'value')]
|
| 527 |
+
)
|
| 528 |
+
def update_price_chart(selected_stock, period, chart_type):
|
| 529 |
+
data = get_stock_data(selected_stock, period)
|
| 530 |
+
if data.empty: return {}
|
| 531 |
+
data = calculate_technical_indicators(data)
|
| 532 |
+
stock_name = [name for name, symbol in TAIWAN_STOCKS.items() if symbol == selected_stock][0]
|
| 533 |
+
fig = make_subplots(rows=1, cols=2, shared_yaxes=True, column_widths=[0.8, 0.2], horizontal_spacing=0.01)
|
| 534 |
+
if chart_type == 'candlestick':
|
| 535 |
+
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)
|
| 536 |
+
else:
|
| 537 |
+
fig.add_trace(px.line(data, y='Close').data[0], row=1, col=1)
|
| 538 |
+
fig.add_trace(go.Scatter(x=data.index, y=data['MA5'], mode='lines', name='MA5', line=dict(color='orange')), row=1, col=1)
|
| 539 |
+
fig.add_trace(go.Scatter(x=data.index, y=data['MA20'], mode='lines', name='MA20', line=dict(color='blue')), row=1, col=1)
|
| 540 |
+
bin_edges, volume_per_bin, price_centers = calculate_volume_profile(data, num_bins=50)
|
| 541 |
+
if volume_per_bin is not None:
|
| 542 |
+
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)
|
| 543 |
+
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)
|
| 544 |
+
return fig
|
| 545 |
+
|
| 546 |
+
@app.callback(
|
| 547 |
+
dash.dependencies.Output('advanced-technical-chart', 'figure'),
|
| 548 |
+
[dash.dependencies.Input('technical-indicator-selector', 'value'),
|
| 549 |
+
dash.dependencies.Input('stock-dropdown', 'value'),
|
| 550 |
+
dash.dependencies.Input('period-dropdown', 'value')]
|
| 551 |
+
)
|
| 552 |
+
def update_advanced_technical_chart(indicator, selected_stock, period):
|
| 553 |
+
data = get_stock_data(selected_stock, period)
|
| 554 |
+
if data.empty: return {}
|
| 555 |
+
data = calculate_technical_indicators(data)
|
| 556 |
+
stock_name = [name for name, symbol in TAIWAN_STOCKS.items() if symbol == selected_stock][0]
|
| 557 |
+
fig = go.Figure()
|
| 558 |
+
if indicator == 'RSI':
|
| 559 |
+
fig = go.Figure()
|
| 560 |
+
fig.add_trace(go.Scatter(x=data.index, y=data['RSI'], mode='lines', name='RSI', line=dict(color='purple', width=2)))
|
| 561 |
+
fig.add_hline(y=70, line_dash="dash", line_color="green", annotation_text="超買線(70)")
|
| 562 |
+
fig.add_hline(y=30, line_dash="dash", line_color="red", annotation_text="超賣線(30)")
|
| 563 |
+
fig.add_hline(y=50, line_dash="dot", line_color="gray", annotation_text="中線(50)")
|
| 564 |
+
fig.update_layout(title=f'{stock_name} - RSI 相對強弱指標', xaxis_title='日期', yaxis_title='RSI', height=450, yaxis=dict(range=[0, 100]))
|
| 565 |
+
elif indicator == 'MACD':
|
| 566 |
+
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1, row_heights=[0.7, 0.3], subplot_titles=('價格走勢', 'MACD 指標'))
|
| 567 |
+
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)
|
| 568 |
+
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)
|
| 569 |
+
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)
|
| 570 |
+
colors = ['red' if x >= 0 else 'green' for x in data['MACD_Histogram']]
|
| 571 |
+
fig.add_trace(go.Bar(x=data.index, y=data['MACD_Histogram'], name='MACD柱狀圖', marker_color=colors), row=2, col=1)
|
| 572 |
+
fig.update_layout(title_text=f'{stock_name} - MACD 指數平滑異同移動平均線', height=550)
|
| 573 |
+
elif indicator == 'BB':
|
| 574 |
+
fig = go.Figure()
|
| 575 |
+
fig.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='收盤價', line=dict(color='black', width=2)))
|
| 576 |
+
fig.add_trace(go.Scatter(x=data.index, y=data['BB_Upper'], mode='lines', name='上軌', line=dict(color='red', width=1, dash='dash')))
|
| 577 |
+
fig.add_trace(go.Scatter(x=data.index, y=data['BB_Middle'], mode='lines', name='中軌(MA20)', line=dict(color='blue', width=1)))
|
| 578 |
+
fig.add_trace(go.Scatter(x=data.index, y=data['BB_Lower'], mode='lines', name='下軌', line=dict(color='green', width=1, dash='dash')))
|
| 579 |
+
fig.update_layout(title=f'{stock_name} - 布林通道 (20日, 2σ)', xaxis_title='日期', yaxis_title='價格 (TWD)', height=450)
|
| 580 |
+
elif indicator == 'KD':
|
| 581 |
+
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1, row_heights=[0.6, 0.4], subplot_titles=('價格走勢', 'KD指標'))
|
| 582 |
+
fig.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='收盤價', line=dict(color='black', width=1)), row=1, col=1)
|
| 583 |
+
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)
|
| 584 |
+
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)
|
| 585 |
+
fig.add_hline(y=80, line_dash="dash", line_color="green", annotation_text="超買線(80)", row=2, col=1)
|
| 586 |
+
fig.add_hline(y=20, line_dash="dash", line_color="red", annotation_text="超賣線(20)", row=2, col=1)
|
| 587 |
+
fig.update_layout(title=f'{stock_name} - KD 隨機指標 (9,3,3)', height=500, yaxis2_range=[0, 100])
|
| 588 |
+
elif indicator == 'WR':
|
| 589 |
+
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1, row_heights=[0.6, 0.4], subplot_titles=('價格走勢', '威廉指標 %R'))
|
| 590 |
+
fig.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='收盤價', line=dict(color='black', width=1)), row=1, col=1)
|
| 591 |
+
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)
|
| 592 |
+
fig.add_hline(y=-20, line_dash="dash", line_color="green", annotation_text="超買線(-20)", row=2, col=1)
|
| 593 |
+
fig.add_hline(y=-80, line_dash="dash", line_color="red", annotation_text="超賣線(-80)", row=2, col=1)
|
| 594 |
+
fig.update_layout(title=f'{stock_name} - 威廉指標 %R (14日)', height=500, yaxis2_range=[-100, 0])
|
| 595 |
+
elif indicator == 'DMI':
|
| 596 |
+
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1, row_heights=[0.6, 0.4], subplot_titles=('價格走勢', 'DMI 指標'))
|
| 597 |
+
data_filtered = data.iloc[14:]
|
| 598 |
+
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)
|
| 599 |
+
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)
|
| 600 |
+
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)
|
| 601 |
+
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)
|
| 602 |
+
fig.update_layout(title=f'{stock_name} - DMI 動向指標 (14日)', height=500, showlegend=True, yaxis2_range=[0, 100])
|
| 603 |
+
return fig
|
| 604 |
+
|
| 605 |
+
@app.callback(
|
| 606 |
+
dash.dependencies.Output('volume-chart', 'figure'),
|
| 607 |
+
[dash.dependencies.Input('stock-dropdown', 'value'),
|
| 608 |
+
dash.dependencies.Input('period-dropdown', 'value')]
|
| 609 |
+
)
|
| 610 |
+
def update_volume_chart(selected_stock, period):
|
| 611 |
+
data = get_stock_data(selected_stock, period)
|
| 612 |
+
if data.empty: return {}
|
| 613 |
+
stock_name = [name for name, symbol in TAIWAN_STOCKS.items() if symbol == selected_stock][0]
|
| 614 |
+
colors = ['red' if data['Close'].iloc[i] > data['Open'].iloc[i] else 'green' for i in range(len(data))]
|
| 615 |
+
fig = go.Figure(go.Bar(x=data.index, y=data['Volume'], marker_color=colors, name='成交量'))
|
| 616 |
+
fig.update_layout(title=f'{stock_name} 成交量', xaxis_title='日期', yaxis_title='成交量', height=300)
|
| 617 |
+
return fig
|
| 618 |
+
|
| 619 |
+
@app.callback(
|
| 620 |
+
dash.dependencies.Output('industry-analysis', 'figure'),
|
| 621 |
+
[dash.dependencies.Input('stock-dropdown', 'value')]
|
| 622 |
+
)
|
| 623 |
+
def update_industry_analysis(selected_stock):
|
| 624 |
+
performance_data = []
|
| 625 |
+
for name, symbol in TAIWAN_STOCKS.items():
|
| 626 |
+
data = get_stock_data(symbol, '1mo')
|
| 627 |
+
if not data.empty and len(data) > 1:
|
| 628 |
+
return_pct = ((data['Close'].iloc[-1] - data['Close'].iloc[0]) / data['Close'].iloc[0]) * 100
|
| 629 |
+
performance_data.append({
|
| 630 |
+
'股票': name,
|
| 631 |
+
'代碼': symbol,
|
| 632 |
+
'月報酬率(%)': return_pct,
|
| 633 |
+
'絕對波動': abs(return_pct)
|
| 634 |
+
})
|
| 635 |
+
if not performance_data:
|
| 636 |
+
fig = go.Figure().add_annotation(text="無法計算產業資料", showarrow=False)
|
| 637 |
+
fig.update_layout(title="近一月市場波動最大標的", height=400)
|
| 638 |
+
return fig
|
| 639 |
+
df_performance = pd.DataFrame(performance_data)
|
| 640 |
+
df_top_movers = df_performance.sort_values(by='絕對波動', ascending=False).head(10)
|
| 641 |
+
fig = px.pie(
|
| 642 |
+
df_top_movers,
|
| 643 |
+
values='絕對波動',
|
| 644 |
+
names='股票',
|
| 645 |
+
title='近一月市場波動最大 Top 10 標的',
|
| 646 |
+
hover_data={'月報酬率(%)': ':.2f'}
|
| 647 |
+
)
|
| 648 |
+
fig.update_traces(
|
| 649 |
+
textposition='inside',
|
| 650 |
+
textinfo='percent+label',
|
| 651 |
+
hovertemplate="<b>%{label}</b><br>月報酬率: %{customdata[0]:.2f}%<extra></extra>"
|
| 652 |
+
)
|
| 653 |
+
fig.update_layout(height=400, showlegend=False)
|
| 654 |
+
return fig
|
| 655 |
+
|
| 656 |
+
@app.callback(
|
| 657 |
+
dash.dependencies.Output('business-climate-chart', 'figure'),
|
| 658 |
+
[dash.dependencies.Input('stock-dropdown', 'value')]
|
| 659 |
+
)
|
| 660 |
+
def update_business_climate_chart(selected_stock):
|
| 661 |
+
df = get_business_climate_data()
|
| 662 |
+
if df.empty:
|
| 663 |
+
fig = go.Figure().add_annotation(text="無法載入景氣燈號資料", showarrow=False)
|
| 664 |
+
fig.update_layout(title="台灣景氣燈號", height=300)
|
| 665 |
+
return fig
|
| 666 |
+
def get_light_color(score):
|
| 667 |
+
if score >= 32: return 'red'
|
| 668 |
+
elif score >= 24: return 'orange'
|
| 669 |
+
elif score >= 17: return 'yellow'
|
| 670 |
+
elif score >= 10: return 'lightgreen'
|
| 671 |
+
else: return 'blue'
|
| 672 |
+
colors = [get_light_color(score) for score in df['Index']]
|
| 673 |
+
fig = go.Figure()
|
| 674 |
+
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'))))
|
| 675 |
+
fig.add_hline(y=32, line_dash="dash", line_color="red", annotation_text="紅燈(32)")
|
| 676 |
+
fig.add_hline(y=17, line_dash="dash", line_color="yellow", annotation_text="黃燈(17)")
|
| 677 |
+
fig.update_layout(title="台灣景氣燈號走勢", xaxis_title='日期', yaxis_title='燈號分數', height=300, yaxis=dict(range=[0, 40]))
|
| 678 |
+
return fig
|
| 679 |
+
|
| 680 |
+
@app.callback(
|
| 681 |
+
[dash.dependencies.Output('technical-analysis-text', 'children'),
|
| 682 |
+
dash.dependencies.Output('fundamental-analysis-text', 'children'),
|
| 683 |
+
dash.dependencies.Output('market-outlook-text', 'children')],
|
| 684 |
+
[dash.dependencies.Input('stock-dropdown', 'value'),
|
| 685 |
+
dash.dependencies.Input('period-dropdown', 'value')]
|
| 686 |
+
)
|
| 687 |
+
def update_analysis_text(selected_stock, period):
|
| 688 |
+
cache_key = f"{selected_stock}-{period}"
|
| 689 |
+
current_time = time.time()
|
| 690 |
+
|
| 691 |
+
if cache_key in ANALYSIS_CACHE:
|
| 692 |
+
cached_data = ANALYSIS_CACHE[cache_key]
|
| 693 |
+
if current_time - cached_data['timestamp'] < CACHE_DURATION_SECONDS:
|
| 694 |
+
print(f"從快取載入分析: {cache_key}")
|
| 695 |
+
return cached_data['technical'], cached_data['fundamental'], cached_data['outlook']
|
| 696 |
+
|
| 697 |
+
print(f"重新生成分析: {cache_key}")
|
| 698 |
+
data = get_stock_data(selected_stock, period)
|
| 699 |
+
stock_name = [name for name, symbol in TAIWAN_STOCKS.items() if symbol == selected_stock][0]
|
| 700 |
+
if data.empty or len(data) < 20:
|
| 701 |
+
return "資料不足,無法分析", "資料不足,無法分析", "資料不足,無法分析"
|
| 702 |
+
|
| 703 |
+
data = calculate_technical_indicators(data)
|
| 704 |
+
|
| 705 |
+
price_change = ((data['Close'].iloc[-1] - data['Close'].iloc[0]) / data['Close'].iloc[0]) * 100
|
| 706 |
+
rsi_current = data['RSI'].iloc[-1] if not pd.isna(data['RSI'].iloc[-1]) else 50
|
| 707 |
+
macd_current = data['MACD'].iloc[-1] if not pd.isna(data['MACD'].iloc[-1]) else 0
|
| 708 |
+
macd_signal_current = data['MACD_Signal'].iloc[-1] if not pd.isna(data['MACD_Signal'].iloc[-1]) else 0
|
| 709 |
+
|
| 710 |
+
technical_text = html.Div([
|
| 711 |
+
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}%。"]),
|
| 712 |
+
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'}), "。"]),
|
| 713 |
+
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 '空頭'}。"]),
|
| 714 |
+
])
|
| 715 |
+
|
| 716 |
+
fundamental_text, market_outlook_text = generate_gemini_analysis(stock_name, selected_stock, period, data)
|
| 717 |
+
|
| 718 |
+
ANALYSIS_CACHE[cache_key] = {
|
| 719 |
+
'technical': technical_text,
|
| 720 |
+
'fundamental': fundamental_text,
|
| 721 |
+
'outlook': market_outlook_text,
|
| 722 |
+
'timestamp': current_time
|
| 723 |
+
}
|
| 724 |
+
|
| 725 |
+
return technical_text, fundamental_text, market_outlook_text
|
| 726 |
+
|
| 727 |
+
@app.callback(
|
| 728 |
+
dash.dependencies.Output('pmi-chart', 'figure'),
|
| 729 |
+
[dash.dependencies.Input('stock-dropdown', 'value')]
|
| 730 |
+
)
|
| 731 |
+
def update_pmi_chart(selected_stock):
|
| 732 |
+
df = get_pmi_data()
|
| 733 |
+
if df.empty:
|
| 734 |
+
fig = go.Figure().add_annotation(text="無法載入PMI資料", showarrow=False)
|
| 735 |
+
fig.update_layout(title="台灣PMI指數", height=300)
|
| 736 |
+
return fig
|
| 737 |
+
colors = ['red' if value >= 50 else 'green' for value in df['Index']]
|
| 738 |
+
fig = go.Figure()
|
| 739 |
+
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'))))
|
| 740 |
+
fig.add_hline(y=50, line_dash="dash", line_color="black", annotation_text="榮枯線(50)")
|
| 741 |
+
fig.update_layout(title="台灣PMI指數走勢", xaxis_title='日期', yaxis_title='PMI指數', height=300, yaxis=dict(range=[35, 60]))
|
| 742 |
+
return fig
|
| 743 |
+
|
| 744 |
def summarize_news_with_gemini(news_list: list) -> str:
|
| 745 |
"""
|
| 746 |
使用 Gemini API 將英文新聞標題列表摘要成一段繁體中文。
|
|
|
|
| 770 |
|
| 771 |
except Exception as e:
|
| 772 |
print(f"呼叫 Gemini API 時發生錯誤: {e}")
|
| 773 |
+
return f"無法生成新聞摘要,請稍後再試。錯誤訊息:{e}"
|
| 774 |
+
|
| 775 |
+
@app.callback(
|
| 776 |
+
[dash.dependencies.Output('comparison-chart', 'figure'),
|
| 777 |
+
dash.dependencies.Output('comparison-table', 'children')],
|
| 778 |
+
[dash.dependencies.Input('comparison-stocks', 'value'),
|
| 779 |
+
dash.dependencies.Input('comparison-period', 'value')]
|
| 780 |
+
)
|
| 781 |
+
def update_comparison_analysis(selected_stocks, period):
|
| 782 |
+
fixed_stock = '0050.TW'
|
| 783 |
+
if not selected_stocks: selected_stocks = [fixed_stock]
|
| 784 |
+
elif fixed_stock not in selected_stocks: selected_stocks.insert(0, fixed_stock)
|
| 785 |
+
selected_stocks = selected_stocks[:5]
|
| 786 |
+
fig = go.Figure()
|
| 787 |
+
comparison_data = []
|
| 788 |
+
for stock in selected_stocks:
|
| 789 |
+
data = get_stock_data(stock, period)
|
| 790 |
+
if not data.empty:
|
| 791 |
+
stock_name = next((name for name, symbol in TAIWAN_STOCKS.items() if symbol == stock), stock)
|
| 792 |
+
normalized_prices = (data['Close'] / data['Close'].iloc[0]) * 100
|
| 793 |
+
fig.add_trace(go.Scatter(x=data.index, y=normalized_prices, mode='lines', name=stock_name, line=dict(width=2)))
|
| 794 |
+
total_return = ((data['Close'].iloc[-1] / data['Close'].iloc[0]) - 1) * 100
|
| 795 |
+
volatility = data['Close'].pct_change().std() * np.sqrt(252) * 100
|
| 796 |
+
comparison_data.append({'name': stock_name, 'return': total_return, 'volatility': volatility, 'current_price': data['Close'].iloc[-1]})
|
| 797 |
+
fig.update_layout(title=f'股票績效比較 - {period}', xaxis_title='日期', yaxis_title='相對績效 (基期=100)', height=400, hovermode='x unified')
|
| 798 |
+
if comparison_data:
|
| 799 |
+
table_rows = []
|
| 800 |
+
for item in sorted(comparison_data, key=lambda x: x['return'], reverse=True):
|
| 801 |
+
color = 'red' if item['return'] > 0 else 'green'
|
| 802 |
+
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}")]))
|
| 803 |
+
table = html.Table([html.Thead(html.Tr([html.Th("股票"), html.Th("報酬率"), html.Th("波動率"), html.Th("現價")])), html.Tbody(table_rows)], style={'width': '100%'})
|
| 804 |
+
return fig, table
|
| 805 |
+
return fig, html.Div("無可比較資料")
|
| 806 |
+
|
| 807 |
+
@app.callback(
|
| 808 |
+
[dash.dependencies.Output('sentiment-gauge', 'children'),
|
| 809 |
+
dash.dependencies.Output('news-summary', 'children')],
|
| 810 |
+
[dash.dependencies.Input('stock-dropdown', 'value')]
|
| 811 |
+
)
|
| 812 |
+
def update_sentiment_analysis(selected_stock):
|
| 813 |
+
if predictor is None:
|
| 814 |
+
error_fig = go.Figure().add_annotation(text="情緒指標模型載入失敗", showarrow=False)
|
| 815 |
+
error_fig.update_layout(height=200)
|
| 816 |
+
return dcc.Graph(figure=error_fig), html.P("新聞分析模型載入失敗,請檢查後台日誌。")
|
| 817 |
+
|
| 818 |
+
sentiment_score_raw = predictor.get_news_index()
|
| 819 |
+
|
| 820 |
+
if sentiment_score_raw is not None:
|
| 821 |
+
sentiment_score_normalized = (sentiment_score_raw + 1) * 50
|
| 822 |
+
sentiment_score_normalized = max(0, min(100, sentiment_score_normalized))
|
| 823 |
+
if sentiment_score_normalized >= 65:
|
| 824 |
+
bar_color, level_text = "#5cb85c", "樂觀"
|
| 825 |
+
elif sentiment_score_normalized >= 35:
|
| 826 |
+
bar_color, level_text = "#f0ad4e", "中性"
|
| 827 |
+
else:
|
| 828 |
+
bar_color, level_text = "#d9534f", "悲觀"
|
| 829 |
+
gauge_fig = go.Figure(go.Indicator(
|
| 830 |
+
mode = "gauge+number", value = sentiment_score_normalized,
|
| 831 |
+
domain = {'x': [0, 1], 'y': [0, 1]},
|
| 832 |
+
title = {'text': f"昨日市場情緒: {level_text}", 'font': {'size': 18}},
|
| 833 |
+
gauge = {'axis': {'range': [0, 100]}, 'bar': {'color': bar_color},
|
| 834 |
+
'steps': [{'range': [0, 35], 'color': "rgba(217, 83, 79, 0.2)"},
|
| 835 |
+
{'range': [35, 65], 'color': "rgba(240, 173, 78, 0.2)"},
|
| 836 |
+
{'range': [65, 100], 'color': "rgba(92, 184, 92, 0.2)"}]}
|
| 837 |
+
))
|
| 838 |
+
gauge_fig.update_layout(height=200, margin=dict(l=30, r=30, t=50, b=20))
|
| 839 |
+
gauge_content = dcc.Graph(figure=gauge_fig)
|
| 840 |
+
else:
|
| 841 |
+
error_fig = go.Figure().add_annotation(text="今日尚無情緒分數", showarrow=False)
|
| 842 |
+
error_fig.update_layout(height=200)
|
| 843 |
+
gauge_content = dcc.Graph(figure=error_fig)
|
| 844 |
+
|
| 845 |
+
top_news_list = predictor.get_news()
|
| 846 |
+
news_content = None
|
| 847 |
+
|
| 848 |
+
if top_news_list and isinstance(top_news_list, list):
|
| 849 |
+
summary_text = summarize_news_with_gemini(top_news_list)
|
| 850 |
+
news_content = dcc.Markdown(summary_text, style={
|
| 851 |
+
'margin': '8px 0', 'padding-left': '5px',
|
| 852 |
+
'font-size': '15px', 'line-height': '1.7'
|
| 853 |
+
})
|
| 854 |
+
elif top_news_list == []:
|
| 855 |
+
news_content = html.P("昨日無重大相關新聞。", style={'text-align': 'center', 'padding-top': '50px'})
|
| 856 |
+
else:
|
| 857 |
+
news_content = html.P("讀取新聞時發生錯誤。", style={'text-align': 'center', 'padding-top': '50px'})
|
| 858 |
+
|
| 859 |
+
return gauge_content, news_content
|
| 860 |
+
|
| 861 |
+
# 主程式執行
|
| 862 |
+
if __name__ == '__main__':
|
| 863 |
+
app.run(host="0.0.0.0", port=7860, debug=False)
|