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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import yfinance as yf
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import numpy as np
|
| 5 |
+
from datetime import datetime, timedelta
|
| 6 |
+
import plotly.graph_objects as go
|
| 7 |
+
from plotly.subplots import make_subplots
|
| 8 |
+
import io
|
| 9 |
+
import warnings
|
| 10 |
+
warnings.filterwarnings('ignore')
|
| 11 |
+
|
| 12 |
+
# 設定頁面配置
|
| 13 |
+
st.set_page_config(page_title="股票技術分析系統", page_icon="📈", layout="wide")
|
| 14 |
+
|
| 15 |
+
# ==================== 技術指標計算函數 ====================
|
| 16 |
+
|
| 17 |
+
def calculate_ma(data, period):
|
| 18 |
+
"""計算移動平均線"""
|
| 19 |
+
return data.rolling(window=period).mean()
|
| 20 |
+
|
| 21 |
+
def calculate_rsi(data, period=14):
|
| 22 |
+
"""計算RSI指標"""
|
| 23 |
+
delta = data.diff()
|
| 24 |
+
gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
|
| 25 |
+
loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
|
| 26 |
+
rs = gain / loss
|
| 27 |
+
rsi = 100 - (100 / (1 + rs))
|
| 28 |
+
return rsi
|
| 29 |
+
|
| 30 |
+
def calculate_obv(close, volume):
|
| 31 |
+
"""計算OBV指標"""
|
| 32 |
+
obv = [0]
|
| 33 |
+
for i in range(1, len(close)):
|
| 34 |
+
if close.iloc[i] > close.iloc[i-1]:
|
| 35 |
+
obv.append(obv[-1] + volume.iloc[i])
|
| 36 |
+
elif close.iloc[i] < close.iloc[i-1]:
|
| 37 |
+
obv.append(obv[-1] - volume.iloc[i])
|
| 38 |
+
else:
|
| 39 |
+
obv.append(obv[-1])
|
| 40 |
+
return pd.Series(obv, index=close.index)
|
| 41 |
+
|
| 42 |
+
def calculate_bollinger_bands(data, period=20, std_dev=2):
|
| 43 |
+
"""計算布林通道"""
|
| 44 |
+
ma = data.rolling(window=period).mean()
|
| 45 |
+
std = data.rolling(window=period).std()
|
| 46 |
+
upper_band = ma + (std * std_dev)
|
| 47 |
+
lower_band = ma - (std * std_dev)
|
| 48 |
+
return upper_band, ma, lower_band
|
| 49 |
+
|
| 50 |
+
def calculate_percent_b(price, upper_band, lower_band):
|
| 51 |
+
"""計算%B指標"""
|
| 52 |
+
return (price - lower_band) / (upper_band - lower_band) * 100
|
| 53 |
+
|
| 54 |
+
def calculate_macd(data, fast=12, slow=26, signal=9):
|
| 55 |
+
"""計算MACD指標"""
|
| 56 |
+
ema_fast = data.ewm(span=fast).mean()
|
| 57 |
+
ema_slow = data.ewm(span=slow).mean()
|
| 58 |
+
macd_line = ema_fast - ema_slow
|
| 59 |
+
signal_line = macd_line.ewm(span=signal).mean()
|
| 60 |
+
histogram = macd_line - signal_line
|
| 61 |
+
return macd_line, signal_line, histogram
|
| 62 |
+
|
| 63 |
+
def calculate_kd(high, low, close, period=9, smooth_k=3, smooth_d=3):
|
| 64 |
+
"""計算KD指標"""
|
| 65 |
+
lowest_low = low.rolling(window=period).min()
|
| 66 |
+
highest_high = high.rolling(window=period).max()
|
| 67 |
+
rsv = ((close - lowest_low) / (highest_high - lowest_low)) * 100
|
| 68 |
+
k = rsv.ewm(span=smooth_k, adjust=False).mean()
|
| 69 |
+
d = k.ewm(span=smooth_d, adjust=False).mean()
|
| 70 |
+
return k, d
|
| 71 |
+
|
| 72 |
+
def calculate_cci(high, low, close, period=20):
|
| 73 |
+
"""計算CCI指標"""
|
| 74 |
+
tp = (high + low + close) / 3
|
| 75 |
+
ma_tp = tp.rolling(window=period).mean()
|
| 76 |
+
md = tp.rolling(window=period).apply(lambda x: np.abs(x - x.mean()).mean())
|
| 77 |
+
cci = (tp - ma_tp) / (0.015 * md)
|
| 78 |
+
return cci
|
| 79 |
+
|
| 80 |
+
def calculate_mfi(high, low, close, volume, period=14):
|
| 81 |
+
"""計算MFI指標"""
|
| 82 |
+
tp = (high + low + close) / 3
|
| 83 |
+
mf = tp * volume
|
| 84 |
+
positive_mf = []
|
| 85 |
+
negative_mf = []
|
| 86 |
+
for i in range(len(tp)):
|
| 87 |
+
if i == 0:
|
| 88 |
+
positive_mf.append(0)
|
| 89 |
+
negative_mf.append(0)
|
| 90 |
+
else:
|
| 91 |
+
if tp.iloc[i] > tp.iloc[i-1]:
|
| 92 |
+
positive_mf.append(mf.iloc[i])
|
| 93 |
+
negative_mf.append(0)
|
| 94 |
+
elif tp.iloc[i] < tp.iloc[i-1]:
|
| 95 |
+
positive_mf.append(0)
|
| 96 |
+
negative_mf.append(mf.iloc[i])
|
| 97 |
+
else:
|
| 98 |
+
positive_mf.append(0)
|
| 99 |
+
negative_mf.append(0)
|
| 100 |
+
positive_mf = pd.Series(positive_mf, index=close.index)
|
| 101 |
+
negative_mf = pd.Series(negative_mf, index=close.index)
|
| 102 |
+
positive_mf_sum = positive_mf.rolling(window=period).sum()
|
| 103 |
+
negative_mf_sum = negative_mf.rolling(window=period).sum()
|
| 104 |
+
mfi = 100 - (100 / (1 + (positive_mf_sum / negative_mf_sum)))
|
| 105 |
+
return mfi
|
| 106 |
+
|
| 107 |
+
def calculate_vwap(high, low, close, volume):
|
| 108 |
+
"""計算VWAP指標"""
|
| 109 |
+
tp = (high + low + close) / 3
|
| 110 |
+
vwap = (tp * volume).cumsum() / volume.cumsum()
|
| 111 |
+
return vwap
|
| 112 |
+
|
| 113 |
+
def calculate_atr(high, low, close, period=14):
|
| 114 |
+
"""計算ATR指標"""
|
| 115 |
+
tr_list = []
|
| 116 |
+
for i in range(len(close)):
|
| 117 |
+
if i == 0:
|
| 118 |
+
tr_list.append(high.iloc[i] - low.iloc[i])
|
| 119 |
+
else:
|
| 120 |
+
tr1 = high.iloc[i] - low.iloc[i]
|
| 121 |
+
tr2 = abs(high.iloc[i] - close.iloc[i-1])
|
| 122 |
+
tr3 = abs(low.iloc[i] - close.iloc[i-1])
|
| 123 |
+
tr_list.append(max(tr1, tr2, tr3))
|
| 124 |
+
tr = pd.Series(tr_list, index=close.index)
|
| 125 |
+
atr = tr.rolling(window=period).mean()
|
| 126 |
+
return atr
|
| 127 |
+
|
| 128 |
+
def detect_golden_cross(ma_short, ma_long):
|
| 129 |
+
"""檢測黃金交叉"""
|
| 130 |
+
golden_cross = [False]
|
| 131 |
+
for i in range(1, len(ma_short)):
|
| 132 |
+
if (ma_short.iloc[i-1] <= ma_long.iloc[i-1] and
|
| 133 |
+
ma_short.iloc[i] > ma_long.iloc[i] and
|
| 134 |
+
not pd.isna(ma_short.iloc[i]) and not pd.isna(ma_long.iloc[i])):
|
| 135 |
+
golden_cross.append(True)
|
| 136 |
+
else:
|
| 137 |
+
golden_cross.append(False)
|
| 138 |
+
return pd.Series(golden_cross, index=ma_short.index)
|
| 139 |
+
|
| 140 |
+
def detect_death_cross(ma_short, ma_long):
|
| 141 |
+
"""檢測死亡交叉"""
|
| 142 |
+
death_cross = [False]
|
| 143 |
+
for i in range(1, len(ma_short)):
|
| 144 |
+
if (ma_short.iloc[i-1] >= ma_long.iloc[i-1] and
|
| 145 |
+
ma_short.iloc[i] < ma_long.iloc[i] and
|
| 146 |
+
not pd.isna(ma_short.iloc[i]) and not pd.isna(ma_long.iloc[i])):
|
| 147 |
+
death_cross.append(True)
|
| 148 |
+
else:
|
| 149 |
+
death_cross.append(False)
|
| 150 |
+
return pd.Series(death_cross, index=ma_short.index)
|
| 151 |
+
|
| 152 |
+
def generate_investment_recommendation(row):
|
| 153 |
+
"""根據技術指標生成投資建議"""
|
| 154 |
+
buy_signals = 0
|
| 155 |
+
sell_signals = 0
|
| 156 |
+
reasons = []
|
| 157 |
+
|
| 158 |
+
if pd.notna(row['RSI']):
|
| 159 |
+
if row['RSI'] < 30:
|
| 160 |
+
buy_signals += 2
|
| 161 |
+
reasons.append(f"RSI超賣 ({row['RSI']:.2f})")
|
| 162 |
+
elif row['RSI'] > 70:
|
| 163 |
+
sell_signals += 2
|
| 164 |
+
reasons.append(f"RSI超買 ({row['RSI']:.2f})")
|
| 165 |
+
|
| 166 |
+
if pd.notna(row['MFI']):
|
| 167 |
+
if row['MFI'] < 20:
|
| 168 |
+
buy_signals += 2
|
| 169 |
+
reasons.append(f"MFI超賣 ({row['MFI']:.2f})")
|
| 170 |
+
elif row['MFI'] > 80:
|
| 171 |
+
sell_signals += 2
|
| 172 |
+
reasons.append(f"MFI超買 ({row['MFI']:.2f})")
|
| 173 |
+
|
| 174 |
+
if pd.notna(row['K']) and pd.notna(row['D']):
|
| 175 |
+
if row['K'] < 20 and row['D'] < 20:
|
| 176 |
+
buy_signals += 2
|
| 177 |
+
reasons.append(f"KD超賣 (K:{row['K']:.2f})")
|
| 178 |
+
elif row['K'] > 80 and row['D'] > 80:
|
| 179 |
+
sell_signals += 2
|
| 180 |
+
reasons.append(f"KD超買 (K:{row['K']:.2f})")
|
| 181 |
+
if row['K'] > row['D'] and row['K'] < 50:
|
| 182 |
+
buy_signals += 1
|
| 183 |
+
reasons.append("KD黃金交叉")
|
| 184 |
+
elif row['K'] < row['D'] and row['K'] > 50:
|
| 185 |
+
sell_signals += 1
|
| 186 |
+
reasons.append("KD死亡交叉")
|
| 187 |
+
|
| 188 |
+
if pd.notna(row['MACD']) and pd.notna(row['MACD_Signal']):
|
| 189 |
+
if row['MACD'] > row['MACD_Signal'] and row['MACD_Histogram'] > 0:
|
| 190 |
+
buy_signals += 1
|
| 191 |
+
reasons.append("MACD多頭")
|
| 192 |
+
elif row['MACD'] < row['MACD_Signal'] and row['MACD_Histogram'] < 0:
|
| 193 |
+
sell_signals += 1
|
| 194 |
+
reasons.append("MACD空頭")
|
| 195 |
+
|
| 196 |
+
if pd.notna(row['Percent_B']):
|
| 197 |
+
if row['Percent_B'] < 0:
|
| 198 |
+
buy_signals += 2
|
| 199 |
+
reasons.append("低於布林下軌")
|
| 200 |
+
elif row['Percent_B'] > 100:
|
| 201 |
+
sell_signals += 2
|
| 202 |
+
reasons.append("高於布林上軌")
|
| 203 |
+
|
| 204 |
+
if row['Golden_Cross']:
|
| 205 |
+
buy_signals += 3
|
| 206 |
+
reasons.append("均線黃金交叉")
|
| 207 |
+
|
| 208 |
+
if row.get('Death_Cross', False):
|
| 209 |
+
sell_signals += 3
|
| 210 |
+
reasons.append("均線死亡交叉")
|
| 211 |
+
|
| 212 |
+
if pd.notna(row['Close']) and pd.notna(row['MA5']) and pd.notna(row['MA20']):
|
| 213 |
+
if row['Close'] > row['MA5'] > row['MA20']:
|
| 214 |
+
buy_signals += 1
|
| 215 |
+
reasons.append("多頭排列")
|
| 216 |
+
elif row['Close'] < row['MA5'] < row['MA20']:
|
| 217 |
+
sell_signals += 1
|
| 218 |
+
reasons.append("空頭排列")
|
| 219 |
+
|
| 220 |
+
signal_diff = buy_signals - sell_signals
|
| 221 |
+
|
| 222 |
+
if signal_diff >= 4:
|
| 223 |
+
recommendation = "強烈買進"
|
| 224 |
+
elif signal_diff >= 2:
|
| 225 |
+
recommendation = "買進"
|
| 226 |
+
elif signal_diff <= -4:
|
| 227 |
+
recommendation = "強烈賣出"
|
| 228 |
+
elif signal_diff <= -2:
|
| 229 |
+
recommendation = "賣出"
|
| 230 |
+
else:
|
| 231 |
+
recommendation = "持有"
|
| 232 |
+
|
| 233 |
+
confidence = min(abs(signal_diff) * 10, 100)
|
| 234 |
+
|
| 235 |
+
return {
|
| 236 |
+
'recommendation': recommendation,
|
| 237 |
+
'buy_signals': buy_signals,
|
| 238 |
+
'sell_signals': sell_signals,
|
| 239 |
+
'confidence': confidence,
|
| 240 |
+
'reasons': ' | '.join(reasons) if reasons else '無明確訊號'
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
@st.cache_data(ttl=300)
|
| 244 |
+
def get_stock_data_and_analysis(symbol, days=30):
|
| 245 |
+
"""獲取股票資料並計算技術指標"""
|
| 246 |
+
try:
|
| 247 |
+
end_date = datetime.now()
|
| 248 |
+
start_date = end_date - timedelta(days=days+50)
|
| 249 |
+
|
| 250 |
+
stock = yf.Ticker(symbol)
|
| 251 |
+
df = stock.history(start=start_date, end=end_date)
|
| 252 |
+
|
| 253 |
+
if df.empty:
|
| 254 |
+
return None, None
|
| 255 |
+
|
| 256 |
+
df_full = df.copy()
|
| 257 |
+
|
| 258 |
+
# 計算技術指標
|
| 259 |
+
df_full['MA5'] = calculate_ma(df_full['Close'], 5)
|
| 260 |
+
df_full['MA10'] = calculate_ma(df_full['Close'], 10)
|
| 261 |
+
df_full['MA20'] = calculate_ma(df_full['Close'], 20)
|
| 262 |
+
df_full['RSI'] = calculate_rsi(df_full['Close'])
|
| 263 |
+
df_full['OBV'] = calculate_obv(df_full['Close'], df_full['Volume'])
|
| 264 |
+
|
| 265 |
+
bb_upper, bb_middle, bb_lower = calculate_bollinger_bands(df_full['Close'])
|
| 266 |
+
df_full['BB_Upper'] = bb_upper
|
| 267 |
+
df_full['BB_Middle'] = bb_middle
|
| 268 |
+
df_full['BB_Lower'] = bb_lower
|
| 269 |
+
df_full['Percent_B'] = calculate_percent_b(df_full['Close'], bb_upper, bb_lower)
|
| 270 |
+
|
| 271 |
+
macd_line, signal_line, histogram = calculate_macd(df_full['Close'])
|
| 272 |
+
df_full['MACD'] = macd_line
|
| 273 |
+
df_full['MACD_Signal'] = signal_line
|
| 274 |
+
df_full['MACD_Histogram'] = histogram
|
| 275 |
+
|
| 276 |
+
df_full['Bias_MA5'] = (df_full['Close'] - df_full['MA5']) / df_full['MA5'] * 100
|
| 277 |
+
df_full['Bias_MA20'] = (df_full['Close'] - df_full['MA20']) / df_full['MA20'] * 100
|
| 278 |
+
df_full['Golden_Cross'] = detect_golden_cross(df_full['MA5'], df_full['MA20'])
|
| 279 |
+
df_full['Death_Cross'] = detect_death_cross(df_full['MA5'], df_full['MA20'])
|
| 280 |
+
|
| 281 |
+
k, d = calculate_kd(df_full['High'], df_full['Low'], df_full['Close'])
|
| 282 |
+
df_full['K'] = k
|
| 283 |
+
df_full['D'] = d
|
| 284 |
+
|
| 285 |
+
df_full['CCI'] = calculate_cci(df_full['High'], df_full['Low'], df_full['Close'])
|
| 286 |
+
df_full['MFI'] = calculate_mfi(df_full['High'], df_full['Low'], df_full['Close'], df_full['Volume'])
|
| 287 |
+
df_full['VWAP'] = calculate_vwap(df_full['High'], df_full['Low'], df_full['Close'], df_full['Volume'])
|
| 288 |
+
df_full['ATR'] = calculate_atr(df_full['High'], df_full['Low'], df_full['Close'])
|
| 289 |
+
|
| 290 |
+
df_result = df_full.tail(days).copy()
|
| 291 |
+
|
| 292 |
+
# 生成投資建議
|
| 293 |
+
recommendations = []
|
| 294 |
+
for idx, row in df_result.iterrows():
|
| 295 |
+
rec = generate_investment_recommendation(row)
|
| 296 |
+
recommendations.append({
|
| 297 |
+
'日期': idx,
|
| 298 |
+
'收盤價': row['Close'],
|
| 299 |
+
'投資建議': rec['recommendation'],
|
| 300 |
+
'買進訊號數': rec['buy_signals'],
|
| 301 |
+
'賣出訊號數': rec['sell_signals'],
|
| 302 |
+
'信心度(%)': rec['confidence'],
|
| 303 |
+
'主要原因': rec['reasons']
|
| 304 |
+
})
|
| 305 |
+
|
| 306 |
+
df_recommendations = pd.DataFrame(recommendations)
|
| 307 |
+
df_recommendations.set_index('日期', inplace=True)
|
| 308 |
+
|
| 309 |
+
return df_result, df_recommendations
|
| 310 |
+
|
| 311 |
+
except Exception as e:
|
| 312 |
+
st.error(f"獲取 {symbol} 資料失敗: {e}")
|
| 313 |
+
return None, None
|
| 314 |
+
|
| 315 |
+
def create_candlestick_chart(df, symbol):
|
| 316 |
+
"""創建K線圖與技術指標圖表"""
|
| 317 |
+
fig = make_subplots(
|
| 318 |
+
rows=4, cols=1,
|
| 319 |
+
shared_xaxes=True,
|
| 320 |
+
vertical_spacing=0.05,
|
| 321 |
+
row_heights=[0.5, 0.2, 0.15, 0.15],
|
| 322 |
+
subplot_titles=(f'{symbol} K線圖與移動平均線', 'MACD', 'RSI', 'KD指標')
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
# K線圖
|
| 326 |
+
fig.add_trace(go.Candlestick(
|
| 327 |
+
x=df.index,
|
| 328 |
+
open=df['Open'],
|
| 329 |
+
high=df['High'],
|
| 330 |
+
low=df['Low'],
|
| 331 |
+
close=df['Close'],
|
| 332 |
+
name='K線'
|
| 333 |
+
), row=1, col=1)
|
| 334 |
+
|
| 335 |
+
# 移動平均線
|
| 336 |
+
fig.add_trace(go.Scatter(x=df.index, y=df['MA5'], name='MA5', line=dict(color='blue', width=1)), row=1, col=1)
|
| 337 |
+
fig.add_trace(go.Scatter(x=df.index, y=df['MA10'], name='MA10', line=dict(color='orange', width=1)), row=1, col=1)
|
| 338 |
+
fig.add_trace(go.Scatter(x=df.index, y=df['MA20'], name='MA20', line=dict(color='red', width=1)), row=1, col=1)
|
| 339 |
+
|
| 340 |
+
# 布林通道
|
| 341 |
+
fig.add_trace(go.Scatter(x=df.index, y=df['BB_Upper'], name='BB上軌', line=dict(color='gray', width=1, dash='dash')), row=1, col=1)
|
| 342 |
+
fig.add_trace(go.Scatter(x=df.index, y=df['BB_Lower'], name='BB下軌', line=dict(color='gray', width=1, dash='dash')), row=1, col=1)
|
| 343 |
+
|
| 344 |
+
# MACD
|
| 345 |
+
fig.add_trace(go.Scatter(x=df.index, y=df['MACD'], name='MACD', line=dict(color='blue', width=1)), row=2, col=1)
|
| 346 |
+
fig.add_trace(go.Scatter(x=df.index, y=df['MACD_Signal'], name='Signal', line=dict(color='red', width=1)), row=2, col=1)
|
| 347 |
+
colors = ['green' if val >= 0 else 'red' for val in df['MACD_Histogram']]
|
| 348 |
+
fig.add_trace(go.Bar(x=df.index, y=df['MACD_Histogram'], name='Histogram', marker_color=colors), row=2, col=1)
|
| 349 |
+
|
| 350 |
+
# RSI
|
| 351 |
+
fig.add_trace(go.Scatter(x=df.index, y=df['RSI'], name='RSI', line=dict(color='purple', width=2)), row=3, col=1)
|
| 352 |
+
fig.add_hline(y=70, line_dash="dash", line_color="red", row=3, col=1)
|
| 353 |
+
fig.add_hline(y=30, line_dash="dash", line_color="green", row=3, col=1)
|
| 354 |
+
|
| 355 |
+
# KD
|
| 356 |
+
fig.add_trace(go.Scatter(x=df.index, y=df['K'], name='K', line=dict(color='blue', width=1)), row=4, col=1)
|
| 357 |
+
fig.add_trace(go.Scatter(x=df.index, y=df['D'], name='D', line=dict(color='red', width=1)), row=4, col=1)
|
| 358 |
+
fig.add_hline(y=80, line_dash="dash", line_color="red", row=4, col=1)
|
| 359 |
+
fig.add_hline(y=20, line_dash="dash", line_color="green", row=4, col=1)
|
| 360 |
+
|
| 361 |
+
fig.update_layout(
|
| 362 |
+
height=1000,
|
| 363 |
+
showlegend=True,
|
| 364 |
+
xaxis_rangeslider_visible=False
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
return fig
|
| 368 |
+
|
| 369 |
+
def style_dataframe(df, df_type='technical'):
|
| 370 |
+
"""為DataFrame添加樣式"""
|
| 371 |
+
def highlight_rsi(val):
|
| 372 |
+
if pd.isna(val):
|
| 373 |
+
return ''
|
| 374 |
+
if val < 30:
|
| 375 |
+
return 'background-color: yellow'
|
| 376 |
+
elif val > 70:
|
| 377 |
+
return 'background-color: purple; color: white'
|
| 378 |
+
return ''
|
| 379 |
+
|
| 380 |
+
def highlight_kd(val):
|
| 381 |
+
if pd.isna(val):
|
| 382 |
+
return ''
|
| 383 |
+
if val < 20:
|
| 384 |
+
return 'background-color: yellow'
|
| 385 |
+
elif val > 80:
|
| 386 |
+
return 'background-color: purple; color: white'
|
| 387 |
+
return ''
|
| 388 |
+
|
| 389 |
+
def highlight_recommendation(val):
|
| 390 |
+
if val == '強烈買進':
|
| 391 |
+
return 'background-color: green; color: white; font-weight: bold'
|
| 392 |
+
elif val == '買進':
|
| 393 |
+
return 'background-color: lightgreen; font-weight: bold'
|
| 394 |
+
elif val == '強烈賣出':
|
| 395 |
+
return 'background-color: red; color: white; font-weight: bold'
|
| 396 |
+
elif val == '賣出':
|
| 397 |
+
return 'background-color: lightcoral; font-weight: bold'
|
| 398 |
+
elif val == '持有':
|
| 399 |
+
return 'background-color: lightyellow; font-weight: bold'
|
| 400 |
+
return ''
|
| 401 |
+
|
| 402 |
+
styled = df.style
|
| 403 |
+
|
| 404 |
+
if 'RSI' in df.columns:
|
| 405 |
+
styled = styled.applymap(highlight_rsi, subset=['RSI'])
|
| 406 |
+
if 'K' in df.columns:
|
| 407 |
+
styled = styled.applymap(highlight_kd, subset=['K'])
|
| 408 |
+
if 'D' in df.columns:
|
| 409 |
+
styled = styled.applymap(highlight_kd, subset=['D'])
|
| 410 |
+
if '投資建議' in df.columns:
|
| 411 |
+
styled = styled.applymap(highlight_recommendation, subset=['投資建議'])
|
| 412 |
+
|
| 413 |
+
return styled.format({col: '{:.2f}' for col in df.select_dtypes(include=[np.number]).columns})
|
| 414 |
+
|
| 415 |
+
# ==================== Streamlit UI ====================
|
| 416 |
+
|
| 417 |
+
st.title("📈 股票技術分析系統")
|
| 418 |
+
st.markdown("---")
|
| 419 |
+
|
| 420 |
+
# 側邊欄設定
|
| 421 |
+
with st.sidebar:
|
| 422 |
+
st.header("⚙️ 分析設定")
|
| 423 |
+
|
| 424 |
+
analysis_mode = st.radio("選擇分析模式", ["單一股票分析", "批次股票分析"])
|
| 425 |
+
|
| 426 |
+
if analysis_mode == "單一股票分析":
|
| 427 |
+
stock_symbol = st.text_input("輸入股票代碼", value="2330.TW", help="例如: 2330.TW, AAPL")
|
| 428 |
+
days = st.slider("分析天數", min_value=10, max_value=90, value=30)
|
| 429 |
+
|
| 430 |
+
if st.button("🔍 開始分析", type="primary"):
|
| 431 |
+
st.session_state.analyze_single = True
|
| 432 |
+
st.session_state.stock_symbol = stock_symbol
|
| 433 |
+
st.session_state.days = days
|
| 434 |
+
|
| 435 |
+
else:
|
| 436 |
+
st.markdown("### 預設股票清單")
|
| 437 |
+
default_stocks = [
|
| 438 |
+
"2330.TW", "2454.TW", "3661.TW", "3443.TW", "3035.TW",
|
| 439 |
+
"3017.TW", "3324.TW", "2379.TW", "3037.TW", "3189.TW",
|
| 440 |
+
"2317.TW", "2382.TW", "3231.TW", "6669.TW", "2356.TW",
|
| 441 |
+
"2376.TW", "2308.TW", "3533.TW", "2357.TW", "2377.TW",
|
| 442 |
+
"2353.TW", "2395.TW", "6811.TW", "6841.TW", "2359.TW"
|
| 443 |
+
]
|
| 444 |
+
|
| 445 |
+
custom_stocks = st.text_area(
|
| 446 |
+
"自訂股票清單(每行一個代碼)",
|
| 447 |
+
value="\n".join(default_stocks),
|
| 448 |
+
height=200
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
days_batch = st.slider("分析天數", min_value=10, max_value=90, value=30, key="batch_days")
|
| 452 |
+
|
| 453 |
+
if st.button("🚀 開始批次分析", type="primary"):
|
| 454 |
+
stock_list = [s.strip() for s in custom_stocks.split("\n") if s.strip()]
|
| 455 |
+
st.session_state.analyze_batch = True
|
| 456 |
+
st.session_state.stock_list = stock_list
|
| 457 |
+
st.session_state.days_batch = days_batch
|
| 458 |
+
|
| 459 |
+
# 單一股票分析
|
| 460 |
+
if hasattr(st.session_state, 'analyze_single') and st.session_state.analyze_single:
|
| 461 |
+
st.header(f"📊 {st.session_state.stock_symbol} 技術分析")
|
| 462 |
+
|
| 463 |
+
with st.spinner('正在獲取數據並計算指標...'):
|
| 464 |
+
df, df_rec = get_stock_data_and_analysis(st.session_state.stock_symbol, st.session_state.days)
|
| 465 |
+
|
| 466 |
+
if df is not None and df_rec is not None:
|
| 467 |
+
# 最新投資建議
|
| 468 |
+
latest_rec = df_rec.iloc[-1]
|
| 469 |
+
latest_data = df.iloc[-1]
|
| 470 |
+
|
| 471 |
+
col1, col2, col3, col4 = st.columns(4)
|
| 472 |
+
|
| 473 |
+
with col1:
|
| 474 |
+
st.metric("收盤價", f"${latest_data['Close']:.2f}")
|
| 475 |
+
with col2:
|
| 476 |
+
rec_color = {
|
| 477 |
+
'強烈買進': '🟢', '買進': '🟡',
|
| 478 |
+
'持有': '⚪', '賣出': '🟠', '強烈賣出': '🔴'
|
| 479 |
+
}
|
| 480 |
+
st.metric("投資建議", f"{rec_color.get(latest_rec['投資建議'], '')} {latest_rec['投資建議']}")
|
| 481 |
+
with col3:
|
| 482 |
+
st.metric("信心度", f"{latest_rec['信心度(%)']:.0f}%")
|
| 483 |
+
with col4:
|
| 484 |
+
st.metric("RSI", f"{latest_data['RSI']:.2f}")
|
| 485 |
+
|
| 486 |
+
st.info(f"**主要原因:** {latest_rec['主要原因']}")
|
| 487 |
+
|
| 488 |
+
# 圖表
|
| 489 |
+
st.plotly_chart(create_candlestick_chart(df, st.session_state.stock_symbol), use_container_width=True)
|
| 490 |
+
|
| 491 |
+
# 技術指標表格
|
| 492 |
+
tab1, tab2 = st.tabs(["📋 技術指標", "💡 投資建議"])
|
| 493 |
+
|
| 494 |
+
with tab1:
|
| 495 |
+
st.dataframe(style_dataframe(df.tail(10)), use_container_width=True, height=400)
|
| 496 |
+
|
| 497 |
+
with tab2:
|
| 498 |
+
st.dataframe(style_dataframe(df_rec.tail(10), 'recommendation'), use_container_width=True, height=400)
|
| 499 |
+
|
| 500 |
+
# 下載按鈕
|
| 501 |
+
st.markdown("---")
|
| 502 |
+
col1, col2 = st.columns(2)
|
| 503 |
+
|
| 504 |
+
with col1:
|
| 505 |
+
csv = df.to_csv(encoding='utf-8-sig')
|
| 506 |
+
st.download_button(
|
| 507 |
+
"📥 下載技術指標 CSV",
|
| 508 |
+
csv,
|
| 509 |
+
f"{st.session_state.stock_symbol}_技術指標.csv",
|
| 510 |
+
"text/csv"
|
| 511 |
+
)
|
| 512 |
+
|
| 513 |
+
with col2:
|
| 514 |
+
csv_rec = df_rec.to_csv(encoding='utf-8-sig')
|
| 515 |
+
st.download_button(
|
| 516 |
+
"📥 下載投資建議 CSV",
|
| 517 |
+
csv_rec,
|
| 518 |
+
f"{st.session_state.stock_symbol}_投資建議.csv",
|
| 519 |
+
"text/csv"
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
# 批次股票分析
|
| 523 |
+
elif hasattr(st.session_state, 'analyze_batch') and st.session_state.analyze_batch:
|
| 524 |
+
st.header(f"🔍 批次股票分析(共 {len(st.session_state.stock_list)} 支)")
|
| 525 |
+
|
| 526 |
+
progress_bar = st.progress(0)
|
| 527 |
+
status_text = st.empty()
|
| 528 |
+
|
| 529 |
+
summary_data = []
|
| 530 |
+
|
| 531 |
+
for i, symbol in enumerate(st.session_state.stock_list):
|
| 532 |
+
progress = (i + 1) / len(st.session_state.stock_list)
|
| 533 |
+
progress_bar.progress(progress)
|
| 534 |
+
status_text.text(f"正在分析 {symbol} ({i+1}/{len(st.session_state.stock_list)})")
|
| 535 |
+
|
| 536 |
+
df, df_rec = get_stock_data_and_analysis(symbol, st.session_state.days_batch)
|
| 537 |
+
|
| 538 |
+
if df is not None and df_rec is not None:
|
| 539 |
+
latest = df.iloc[-1]
|
| 540 |
+
latest_rec = df_rec.iloc[-1]
|
| 541 |
+
|
| 542 |
+
summary_data.append({
|
| 543 |
+
'股票代號': symbol,
|
| 544 |
+
'收盤價': latest['Close'],
|
| 545 |
+
'RSI': latest['RSI'],
|
| 546 |
+
'K': latest['K'],
|
| 547 |
+
'D': latest['D'],
|
| 548 |
+
'MACD': latest['MACD'],
|
| 549 |
+
'投資建議': latest_rec['投資建議'],
|
| 550 |
+
'信心度(%)': latest_rec['信心度(%)'],
|
| 551 |
+
'買進訊號': latest_rec['買進訊號數'],
|
| 552 |
+
'賣出訊號': latest_rec['賣出訊號數'],
|
| 553 |
+
'黃金交叉': '是' if latest['Golden_Cross'] else '否',
|
| 554 |
+
'死亡交叉': '是' if latest['Death_Cross'] else '否',
|
| 555 |
+
'主要原因': latest_rec['主要原因']
|
| 556 |
+
})
|
| 557 |
+
|
| 558 |
+
progress_bar.empty()
|
| 559 |
+
status_text.empty()
|
| 560 |
+
|
| 561 |
+
if summary_data:
|
| 562 |
+
df_summary = pd.DataFrame(summary_data)
|
| 563 |
+
|
| 564 |
+
st.success(f"✅ 成功分析 {len(summary_data)} 支股票!")
|
| 565 |
+
|
| 566 |
+
# 統計圖表
|
| 567 |
+
st.subheader("📊 投資建議統計")
|
| 568 |
+
rec_counts = df_summary['投資建議'].value_counts()
|
| 569 |
+
|
| 570 |
+
fig_pie = go.Figure(data=[go.Pie(labels=rec_counts.index, values=rec_counts.values)])
|
| 571 |
+
fig_pie.update_layout(title="投資建議分布")
|
| 572 |
+
st.plotly_chart(fig_pie, use_container_width=True)
|
| 573 |
+
|
| 574 |
+
# 總覽表格
|
| 575 |
+
st.subheader("📋 股票總覽")
|
| 576 |
+
st.dataframe(style_dataframe(df_summary, 'recommendation'), use_container_width=True, height=600)
|
| 577 |
+
|
| 578 |
+
# 下載CSV
|
| 579 |
+
csv_summary = df_summary.to_csv(index=False, encoding='utf-8-sig')
|
| 580 |
+
st.download_button(
|
| 581 |
+
"📥 下載批次分析結果 CSV",
|
| 582 |
+
csv_summary,
|
| 583 |
+
f"批次分析_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
|
| 584 |
+
"text/csv"
|
| 585 |
+
)
|
| 586 |
+
|
| 587 |
+
else:
|
| 588 |
+
st.info("👈 請在左側選擇分析模式並設定參數後開始分析")
|
| 589 |
+
|
| 590 |
+
st.markdown("""
|
| 591 |
+
### 功能說明
|
| 592 |
+
|
| 593 |
+
**單一股票分析**
|
| 594 |
+
- 提供完整的技術指標圖表
|
| 595 |
+
- 顯示 K線圖、MACD、RS
|