aicodingfun commited on
Commit
8e3b455
·
verified ·
1 Parent(s): 10fad7b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +405 -0
app.py ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import yfinance as yf
3
+ import pandas as pd
4
+ import numpy as np
5
+ import matplotlib.pyplot as plt
6
+ from google import genai
7
+ import os
8
+ from datetime import datetime
9
+
10
+ GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
11
+ client = genai.Client(api_key=GOOGLE_API_KEY)
12
+ MODEL_NAME = "gemini-2.5-flash-lite-preview-06-17"
13
+ DEVELOPER_NAMES = "蔡O軒、張O崴、蔡O鴻、巫O喆"
14
+
15
+ # 支援的美國公司列表
16
+ US_STOCKS = {
17
+ "Apple (AAPL)": "AAPL",
18
+ "Microsoft (MSFT)": "MSFT",
19
+ "Google (GOOG)": "GOOG",
20
+ "Amazon (AMZN)": "AMZN",
21
+ "NVIDIA (NVDA)": "NVDA",
22
+ "Meta Platforms (META)": "META",
23
+ "Tesla (TSLA)": "TSLA",
24
+ "Berkshire Hathaway (BRK-B)": "BRK-B",
25
+ "JPMorgan Chase & Co. (JPM)": "JPM",
26
+ "Johnson & Johnson (JNJ)": "JNJ",
27
+ "Samsung Electronics Co., Ltd. (005930.KS)": "005930.KS"
28
+ }
29
+
30
+ # 支援的台灣公司列表
31
+ TW_STOCKS = {
32
+ "台積電": "2330.TW",
33
+ "鴻海": "2317.TW",
34
+ "聯發科": "2454.TW",
35
+ "富邦金": "2881.TW",
36
+ "台達電": "2308.TW",
37
+ "國泰金": "2882.TW",
38
+ "中華電": "2412.TW",
39
+ "日月光投控": "3711.TW",
40
+ "廣達": "2382.TW",
41
+ "台塑化": "6505.TW",
42
+ "聯電": "2303.TW",
43
+ "中信金": "2891.TW",
44
+ "兆豐金": "2886.TW",
45
+ "南亞": "1303.TW",
46
+ "統一": "1216.TW",
47
+ "台塑": "1301.TW",
48
+ "玉山金": "2884.TW",
49
+ "世芯‑KY": "3661.TW",
50
+ "華碩": "2357.TW",
51
+ "長榮": "2603.TW",
52
+ "智邦": "2345.TW",
53
+ "元大金": "2885.TW",
54
+ "第一金": "2892.TW",
55
+ "華南金": "2880.TW",
56
+ "合庫金": "5880.TW",
57
+ "台灣大": "3045.TW",
58
+ "緯創": "3231.TW",
59
+ "聯詠": "3034.TW",
60
+ "遠傳": "4904.TW",
61
+ "和泰車": "2207.TW",
62
+ "台光電": "2383.TW",
63
+ "大立光": "3008.TW",
64
+ "永豐金": "2890.TW",
65
+ "瑞昱": "2379.TW",
66
+ "奇鋐": "3017.TW",
67
+ "研華": "2395.TW",
68
+ "中鋼": "2002.TW",
69
+ "統一超": "2912.TW",
70
+ "萬海": "2615.TW",
71
+ "元太": "8069.TWO",
72
+ "國巨": "2327.TW",
73
+ "陽明": "2609.TW",
74
+ "光寶科": "2301.TW",
75
+ "凱基金": "2883.TW",
76
+ "鈊象": "3293.TWO",
77
+ "上海商銀": "5876.TW",
78
+ "長榮航": "2618.TW",
79
+ "中租‑KY": "5871.TW",
80
+ "彰銀": "2801.TW",
81
+ "健策": "3653.TW",
82
+ "台新金": "2887.TW",
83
+ "和碩": "4938.TW",
84
+ "新光金": "2888.TW",
85
+ "藥華藥": "6446.TW",
86
+ "川湖": "2059.TW",
87
+ "台泥": "1101.TW",
88
+ "信驊": "5274.TW",
89
+ "技嘉": "2376.TW",
90
+ "世界": "5347.TW",
91
+ "致茂": "2360.TW",
92
+ "力旺": "3529.TW",
93
+ "遠東新": "1402.TW",
94
+ "創意": "3443.TW",
95
+ "亞德客‑KY": "1590.TW",
96
+ "欣興": "3037.TW",
97
+ "華城": "1519.TW",
98
+ "台灣高鐵": "2633.TW",
99
+ "貿聯‑KY": "3665.TW",
100
+ "英業達": "2356.TW",
101
+ "南亞科": "2408.TW",
102
+ "亞泥": "1102.TW",
103
+ "嘉澤": "3533.TW",
104
+ "文曄": "3036.TW",
105
+ "環球晶": "6488.TW",
106
+ "臺企銀": "2834.TW",
107
+ "金像電": "2368.TW",
108
+ "可成": "2474.TW",
109
+ "祥碩": "5269.TW",
110
+ "矽力‑KY": "6415.TW",
111
+ "台化": "1326.TW",
112
+ "華航": "2610.TW",
113
+ "健鼎": "3044.TW",
114
+ "京元電子": "2449.TW",
115
+ "仁寶": "2324.TW",
116
+ "正新": "2105.TW",
117
+ "大聯大": "3702.TW",
118
+ "台中銀": "2812.TW",
119
+ "微星": "2377.TW",
120
+ "漢唐": "2404.TW",
121
+ "億豐": "8464.TWO",
122
+ "豐泰": "9910.TW",
123
+ "儒鴻": "1476.TW",
124
+ "旭隼": "6409.TW",
125
+ "聯強": "2347.TW",
126
+ "寶成": "9904.TW",
127
+ "東元": "1504.TW",
128
+ "群聯": "8299.TWO"
129
+ }
130
+
131
+ # 合併公司列表
132
+ COMPANY_TO_TICKER = {**US_STOCKS, **TW_STOCKS}
133
+ COMPANY_CHOICES = list(COMPANY_TO_TICKER.keys())
134
+
135
+ # --- 核心功能函式 (Core Functions) ---
136
+
137
+ def get_stock_data(company_name: str, period: str = "1y") -> tuple[pd.DataFrame | None, dict | None, str | None]:
138
+ """
139
+ 獲取並處理指定公司的股票數據與財務指標。
140
+
141
+ Args:
142
+ company_name: 公司顯示名稱或代號。
143
+ period: 數據期間 (例如 "1y", "6mo")。
144
+
145
+ Returns:
146
+ 一個包含 (DataFrame, dict, str) 的元組。
147
+ - DataFrame: 包含歷史股價和移動平均線的 pandas DataFrame。
148
+ - dict: 包含關鍵財務指標的字典。
149
+ - str: 用於顯示的公司名稱。
150
+ 如果失敗則回傳 (None, None, None)。
151
+ """
152
+ ticker_symbol = COMPANY_TO_TICKER.get(company_name, None)
153
+ display_name = company_name
154
+
155
+ if not ticker_symbol:
156
+ # 處理使用者手動輸入的代號
157
+ if "." in company_name.upper() or len(company_name) <= 6:
158
+ ticker_symbol = company_name.upper()
159
+ else:
160
+ return None, None, None
161
+
162
+ try:
163
+ ticker = yf.Ticker(ticker_symbol)
164
+ info = ticker.info
165
+
166
+ # 檢查是否能成功獲取資訊,若否,則此代號無效
167
+ if not info or info.get('regularMarketPrice') is None:
168
+ return None, None, None
169
+
170
+ hist_data = ticker.history(period=period)
171
+ if hist_data.empty:
172
+ return None, None, None
173
+
174
+ # 如果是手動輸入代號,則更新顯示名稱
175
+ if company_name not in COMPANY_TO_TICKER:
176
+ short_name = info.get('shortName', company_name)
177
+ display_name = f"{short_name} ({ticker_symbol})"
178
+
179
+ # 計算移動平均線
180
+ hist_data['SMA_20'] = hist_data['Close'].rolling(window=20).mean()
181
+ hist_data['SMA_60'] = hist_data['Close'].rolling(window=60).mean()
182
+
183
+ # 獲取財務指標
184
+ financial_metrics = {
185
+ '市值 (Market Cap)': info.get('marketCap'),
186
+ '本益比 (P/E)': info.get('trailingPE'),
187
+ '股價淨值比 (P/B)': info.get('priceToBook'),
188
+ '每股盈餘 (EPS)': info.get('trailingEps'),
189
+ '毛利率 (Gross Margin)': info.get('grossMargins'),
190
+ '營業利益率 (Operating Margin)': info.get('operatingMargins'),
191
+ '股東權益報酬率 (ROE)': info.get('returnOnEquity'),
192
+ '資產報酬率 (ROA)': info.get('returnOnAssets'),
193
+ '自由現金流 (Free Cash Flow)': info.get('freeCashflow'),
194
+ '營運現金流 (Operating Cash Flow)': info.get('operatingCashflow'),
195
+ '殖利率 (Yield)': info.get('dividendYield'),
196
+ }
197
+ return hist_data, financial_metrics, display_name
198
+ except Exception as e:
199
+ print(f"Error fetching data for {company_name}: {e}")
200
+ return None, None, None
201
+
202
+ def plot_stock_chart(df: pd.DataFrame, company_name: str) -> plt.Figure:
203
+ """
204
+ 根據 DataFrame 繪製股價走勢圖。
205
+ """
206
+ fig, ax = plt.subplots(figsize=(10, 6))
207
+
208
+ x = np.arange(df.shape[0])
209
+ ticks = [
210
+ tick.strftime('%Y/%m/%d') if i % max(int(df.shape[0] / 6), 1) == 0 else ''
211
+ for i, tick in enumerate(df.index)
212
+ ]
213
+
214
+ ax.plot(x, df['Close'], label='Close Price', color='royalblue', linewidth=2)
215
+ ax.plot(x, df['SMA_20'], label='20-Day SMA', color='orange', linestyle='--', alpha=0.8)
216
+ ax.plot(x, df['SMA_60'], label='60-Day SMA', color='green', linestyle='--', alpha=0.8)
217
+ ax.set_title(f'{company_name}', fontsize=16)
218
+ ax.set_xlabel('Date', fontsize=12)
219
+ ax.set_ylabel('Price', fontsize=12)
220
+ ax.legend()
221
+ ax.grid(True, linestyle='--', alpha=0.6)
222
+ plt.xticks(x, ticks, rotation=30)
223
+ plt.tight_layout()
224
+ return fig
225
+
226
+ def format_metrics_display(metrics: dict) -> str:
227
+ """
228
+ 將財務指標格式化為易於閱讀的 Markdown 字串。
229
+ """
230
+ if not metrics:
231
+ return "無法獲取財務指標。"
232
+
233
+ display_text = ""
234
+ for key, value in metrics.items():
235
+ if value is None or pd.isna(value):
236
+ formatted_value = "N/A"
237
+ elif key in ['股東權益報酬率 (ROE)', '資產報酬率 (ROA)', '毛利率 (Gross Margin)', '營業利益率 (Operating Margin)']:
238
+ formatted_value = f"{value:.2%}"
239
+ elif key in ['市值 (Market Cap)', '自由現金流 (Free Cash Flow)', '營運現金流 (Operating Cash Flow)']:
240
+ formatted_value = f"{value:,.0f}"
241
+ else:
242
+ formatted_value = f"{value:.2f}"
243
+ display_text += f"- **{key}**: {formatted_value}\n"
244
+ return display_text
245
+
246
+ def generate_trend_description(company_name: str, df: pd.DataFrame, metrics: dict) -> str:
247
+ """
248
+ 使用 Gemini API 生成趨勢描述。
249
+ """
250
+ if not GOOGLE_API_KEY:
251
+ return "### ⚠️ AI 分析失敗\nGoogle API 金鑰未設定。請在應用程式的環境變數中設定 GOOGLE_API_KEY。"
252
+
253
+ try:
254
+ latest_data = df.iloc[-1]
255
+
256
+ prompt = f"""
257
+ 您是一位專業的金融市場分析師。請根據以下關於「{company_name}」的近期歷史數據和提供的財務指標,提供一份深入淺出的**趨勢分析**。
258
+
259
+ **近期股價數據:**
260
+ - 最新收盤價: {latest_data['Close']:.2f}
261
+ - 20日移動平均線: {latest_data['SMA_20']:.2f}
262
+ - 60日移動平均線: {latest_data['SMA_60']:.2f}
263
+
264
+ **關鍵財務指標:**
265
+ {format_metrics_display(metrics)}
266
+
267
+ 請根據以上所有資訊,以繁體中文,詳細分析股價趨勢,例如目前股價與移動平均線的關係,是處於多頭還是空頭排列,並結合財務指標解釋其技術面與基本面的意義,描述可能對未來趨勢的潛在影響。請將分析內容分點說明,使其清晰易讀。
268
+
269
+ 重要提醒:此部分僅為基於數據的趨勢**描述性文字**,請勿提供具體的價格預測或投資建議。
270
+ """
271
+ response = client.models.generate_content(
272
+ model=MODEL_NAME,
273
+ contents=prompt
274
+ )
275
+ return response.text
276
+ except Exception as e:
277
+ return f"### ⚠️ AI 分析失敗\n呼叫 AI 模型時發生錯誤:{e}"
278
+
279
+ def generate_recommendation(company_name: str, metrics: dict) -> str:
280
+ """
281
+ 使用 Gemini API 生成投資建議。
282
+ """
283
+ if not GOOGLE_API_KEY:
284
+ return "### ⚠️ 建議生成失敗\nGoogle API 金鑰未設定。"
285
+
286
+ try:
287
+ prompt = f"""
288
+ 您是一位專業的金融市場分析師。請僅根據以下關於「{company_name}」的**關鍵財務指標**,提供一個簡潔的投資潛力評估。
289
+
290
+ **關鍵財務指標:**
291
+ {format_metrics_display(metrics)}
292
+
293
+ 請根據這些指標,給出一個總結性的建議,例如「建議觀望」、「建議長期持有」或「建議謹慎評估」。並在建議下方,簡要說明您是基於哪些指標(例如高 ROE、低 P/E 等)做出此判斷的。
294
+
295
+ 請以繁體中文回覆,並強調這僅是基於提供數據的**初步建議**,非投資決策依據。
296
+ """
297
+ response = client.models.generate_content(
298
+ model=MODEL_NAME,
299
+ contents=prompt
300
+ )
301
+ return response.text
302
+ except Exception as e:
303
+ return f"### ⚠️ 建議生成失敗\n呼叫 AI 模型時發生錯誤:{e}"
304
+
305
+ # --- Gradio 介面 (Gradio Interface) ---
306
+
307
+ def create_ui():
308
+ """建立並回傳 Gradio 應用程式介面。"""
309
+
310
+ custom_css = """
311
+ footer {display: none !important;}
312
+ .gradio-container {font-family: 'IBM Plex Sans', sans-serif;}
313
+ #student_footer {text-align: center; margin-top: 20px; color: #888;}
314
+ """
315
+
316
+ APP_DESCRIPTION = f"""
317
+ # AI 股市趨勢探索家 📈
318
+
319
+ **Designed by: {DEVELOPER_NAMES}**
320
+
321
+ 歡迎來到 AI 股市趨勢探索家!這是一個結合股票數據獲取、分析與 Google Gemini AI 技術的互動應用。
322
+
323
+ **如何使用:**
324
+ 1. 從下拉式選單中選擇一家您感興趣的公司或者輸入您想查詢的公司名稱。例如:台積電。
325
+ 2. 點擊「分析!」按鈕。
326
+ 3. 應用程式將會為您呈現該公司近期的股票走勢圖、關鍵財務指標,並由 AI 分析與見解!
327
+ """
328
+
329
+ with gr.Blocks(theme=gr.themes.Monochrome(), css=custom_css) as app:
330
+ gr.Markdown(APP_DESCRIPTION)
331
+
332
+ with gr.Row():
333
+ with gr.Column(scale=3):
334
+ company_input = gr.Dropdown(
335
+ choices=COMPANY_CHOICES,
336
+ label="選擇或輸入公司名稱/代號",
337
+ value=COMPANY_CHOICES[0],
338
+ allow_custom_value=True
339
+ )
340
+ with gr.Column(scale=1):
341
+ analyze_button = gr.Button("開始分析", variant="primary")
342
+
343
+ with gr.Row():
344
+ with gr.Column(scale=3):
345
+ output_plot = gr.Plot(label="股價走勢圖")
346
+
347
+ with gr.Column(scale=3):
348
+ with gr.Tabs():
349
+ with gr.TabItem("🤖 AI 趨勢洞察"):
350
+ output_ai_description = gr.Markdown()
351
+ with gr.TabItem("💡 AI 投資建議"):
352
+ output_ai_recommendation = gr.Markdown()
353
+ with gr.TabItem("📊 關鍵財務指標"):
354
+ output_metrics = gr.Markdown()
355
+
356
+ gr.Markdown(f"**Designed by: {DEVELOPER_NAMES}**", elem_id="student_footer")
357
+
358
+ def run_analysis(company_name):
359
+ if not company_name:
360
+ gr.Warning("請輸入或選擇一家公司!")
361
+ return None, "請先選擇一家公司。", "請先選擇一家公司。", "請先選擇一家公司。"
362
+
363
+ gr.Info("正在獲取數據並進行 AI 分析,請稍候...")
364
+
365
+ # 1. 獲取數據
366
+ stock_df, metrics, display_name = get_stock_data(company_name)
367
+
368
+ if stock_df is None:
369
+ err_msg = f"找不到「{company_name}」的相關數據,請確認公司名稱或代號是否正確。"
370
+ gr.Error(err_msg)
371
+ return None, err_msg, err_msg, err_msg
372
+
373
+ # 2. 繪製圖表
374
+ plot = plot_stock_chart(stock_df, display_name)
375
+
376
+ # 3. 格式化指標
377
+ metrics_display = format_metrics_display(metrics)
378
+
379
+ # 4. 進行 AI 分析 (拆分為兩步驟)
380
+ description = generate_trend_description(display_name, stock_df, metrics)
381
+ recommendation = generate_recommendation(display_name, metrics)
382
+
383
+ # 加上免責聲明
384
+ disclaimer = "\n\n<br>\n*免責聲明:本分析由 AI 模型生成,僅供參考,不構成任何投資建議。*"
385
+ description += disclaimer
386
+ recommendation += disclaimer
387
+
388
+ return plot, description, recommendation, metrics_display
389
+
390
+ analyze_button.click(
391
+ fn=run_analysis,
392
+ inputs=[company_input],
393
+ outputs=[output_plot, output_ai_description, output_ai_recommendation, output_metrics]
394
+ )
395
+
396
+ app.load(
397
+ fn=run_analysis,
398
+ inputs=[gr.Textbox(value=COMPANY_CHOICES[0], visible=False)],
399
+ outputs=[output_plot, output_ai_description, output_ai_recommendation, output_metrics]
400
+ )
401
+
402
+ return app
403
+
404
+ stock_analyzer_app = create_ui()
405
+ stock_analyzer_app.launch(show_error=True, show_api=False)