Spaces:
Runtime error

StockStreamlit / app.py
Robert1224's picture
Update app.py
8d09888 verified
Raw History Blame Contribute Delete
24 kB
import streamlit as st
import yfinance as yf
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import io
import warnings
warnings.filterwarnings('ignore')
# 設定頁面配置
st.set_page_config(page_title="股票技術分析系統", page_icon="📈", layout="wide")
# ==================== 技術指標計算函數 ====================
def calculate_ma(data, period):
"""計算移動平均線"""
return data.rolling(window=period).mean()
def calculate_rsi(data, period=14):
"""計算RSI指標"""
delta = data.diff()
gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
rs = gain / loss
rsi = 100 - (100 / (1 + rs))
return rsi
def calculate_obv(close, volume):
"""計算OBV指標"""
obv = [0]
for i in range(1, len(close)):
if close.iloc[i] > close.iloc[i-1]:
obv.append(obv[-1] + volume.iloc[i])
elif close.iloc[i] < close.iloc[i-1]:
obv.append(obv[-1] - volume.iloc[i])
else:
obv.append(obv[-1])
return pd.Series(obv, index=close.index)
def calculate_bollinger_bands(data, period=20, std_dev=2):
"""計算布林通道"""
ma = data.rolling(window=period).mean()
std = data.rolling(window=period).std()
upper_band = ma + (std * std_dev)
lower_band = ma - (std * std_dev)
return upper_band, ma, lower_band
def calculate_percent_b(price, upper_band, lower_band):
"""計算%B指標"""
return (price - lower_band) / (upper_band - lower_band) * 100
def calculate_macd(data, fast=12, slow=26, signal=9):
"""計算MACD指標"""
ema_fast = data.ewm(span=fast).mean()
ema_slow = data.ewm(span=slow).mean()
macd_line = ema_fast - ema_slow
signal_line = macd_line.ewm(span=signal).mean()
histogram = macd_line - signal_line
return macd_line, signal_line, histogram
def calculate_kd(high, low, close, period=9, smooth_k=3, smooth_d=3):
"""計算KD指標"""
lowest_low = low.rolling(window=period).min()
highest_high = high.rolling(window=period).max()
rsv = ((close - lowest_low) / (highest_high - lowest_low)) * 100
k = rsv.ewm(span=smooth_k, adjust=False).mean()
d = k.ewm(span=smooth_d, adjust=False).mean()
return k, d
def calculate_cci(high, low, close, period=20):
"""計算CCI指標"""
tp = (high + low + close) / 3
ma_tp = tp.rolling(window=period).mean()
md = tp.rolling(window=period).apply(lambda x: np.abs(x - x.mean()).mean())
cci = (tp - ma_tp) / (0.015 * md)
return cci
def calculate_mfi(high, low, close, volume, period=14):
"""計算MFI指標"""
tp = (high + low + close) / 3
mf = tp * volume
positive_mf = []
negative_mf = []
for i in range(len(tp)):
if i == 0:
positive_mf.append(0)
negative_mf.append(0)
else:
if tp.iloc[i] > tp.iloc[i-1]:
positive_mf.append(mf.iloc[i])
negative_mf.append(0)
elif tp.iloc[i] < tp.iloc[i-1]:
positive_mf.append(0)
negative_mf.append(mf.iloc[i])
else:
positive_mf.append(0)
negative_mf.append(0)
positive_mf = pd.Series(positive_mf, index=close.index)
negative_mf = pd.Series(negative_mf, index=close.index)
positive_mf_sum = positive_mf.rolling(window=period).sum()
negative_mf_sum = negative_mf.rolling(window=period).sum()
mfi = 100 - (100 / (1 + (positive_mf_sum / negative_mf_sum)))
return mfi
def calculate_vwap(high, low, close, volume):
"""計算VWAP指標"""
tp = (high + low + close) / 3
vwap = (tp * volume).cumsum() / volume.cumsum()
return vwap
def calculate_atr(high, low, close, period=14):
"""計算ATR指標"""
tr_list = []
for i in range(len(close)):
if i == 0:
tr_list.append(high.iloc[i] - low.iloc[i])
else:
tr1 = high.iloc[i] - low.iloc[i]
tr2 = abs(high.iloc[i] - close.iloc[i-1])
tr3 = abs(low.iloc[i] - close.iloc[i-1])
tr_list.append(max(tr1, tr2, tr3))
tr = pd.Series(tr_list, index=close.index)
atr = tr.rolling(window=period).mean()
return atr
def detect_golden_cross(ma_short, ma_long):
"""檢測黃金交叉"""
golden_cross = [False]
for i in range(1, len(ma_short)):
if (ma_short.iloc[i-1] <= ma_long.iloc[i-1] and
ma_short.iloc[i] > ma_long.iloc[i] and
not pd.isna(ma_short.iloc[i]) and not pd.isna(ma_long.iloc[i])):
golden_cross.append(True)
else:
golden_cross.append(False)
return pd.Series(golden_cross, index=ma_short.index)
def detect_death_cross(ma_short, ma_long):
"""檢測死亡交叉"""
death_cross = [False]
for i in range(1, len(ma_short)):
if (ma_short.iloc[i-1] >= ma_long.iloc[i-1] and
ma_short.iloc[i] < ma_long.iloc[i] and
not pd.isna(ma_short.iloc[i]) and not pd.isna(ma_long.iloc[i])):
death_cross.append(True)
else:
death_cross.append(False)
return pd.Series(death_cross, index=ma_short.index)
def generate_investment_recommendation(row):
"""根據技術指標生成投資建議"""
buy_signals = 0
sell_signals = 0
reasons = []
if pd.notna(row['RSI']):
if row['RSI'] < 30:
buy_signals += 2
reasons.append(f"RSI超賣 ({row['RSI']:.2f})")
elif row['RSI'] > 70:
sell_signals += 2
reasons.append(f"RSI超買 ({row['RSI']:.2f})")
if pd.notna(row['MFI']):
if row['MFI'] < 20:
buy_signals += 2
reasons.append(f"MFI超賣 ({row['MFI']:.2f})")
elif row['MFI'] > 80:
sell_signals += 2
reasons.append(f"MFI超買 ({row['MFI']:.2f})")
if pd.notna(row['K']) and pd.notna(row['D']):
if row['K'] < 20 and row['D'] < 20:
buy_signals += 2
reasons.append(f"KD超賣 (K:{row['K']:.2f})")
elif row['K'] > 80 and row['D'] > 80:
sell_signals += 2
reasons.append(f"KD超買 (K:{row['K']:.2f})")
if row['K'] > row['D'] and row['K'] < 50:
buy_signals += 1
reasons.append("KD黃金交叉")
elif row['K'] < row['D'] and row['K'] > 50:
sell_signals += 1
reasons.append("KD死亡交叉")
if pd.notna(row['MACD']) and pd.notna(row['MACD_Signal']):
if row['MACD'] > row['MACD_Signal'] and row['MACD_Histogram'] > 0:
buy_signals += 1
reasons.append("MACD多頭")
elif row['MACD'] < row['MACD_Signal'] and row['MACD_Histogram'] < 0:
sell_signals += 1
reasons.append("MACD空頭")
if pd.notna(row['Percent_B']):
if row['Percent_B'] < 0:
buy_signals += 2
reasons.append("低於布林下軌")
elif row['Percent_B'] > 100:
sell_signals += 2
reasons.append("高於布林上軌")
if row['Golden_Cross']:
buy_signals += 3
reasons.append("均線黃金交叉")
if row.get('Death_Cross', False):
sell_signals += 3
reasons.append("均線死亡交叉")
if pd.notna(row['Close']) and pd.notna(row['MA5']) and pd.notna(row['MA20']):
if row['Close'] > row['MA5'] > row['MA20']:
buy_signals += 1
reasons.append("多頭排列")
elif row['Close'] < row['MA5'] < row['MA20']:
sell_signals += 1
reasons.append("空頭排列")
signal_diff = buy_signals - sell_signals
if signal_diff >= 4:
recommendation = "強烈買進"
elif signal_diff >= 2:
recommendation = "買進"
elif signal_diff <= -4:
recommendation = "強烈賣出"
elif signal_diff <= -2:
recommendation = "賣出"
else:
recommendation = "持有"
confidence = min(abs(signal_diff) * 10, 100)
return {
'recommendation': recommendation,
'buy_signals': buy_signals,
'sell_signals': sell_signals,
'confidence': confidence,
'reasons': ' | '.join(reasons) if reasons else '無明確訊號'
}
@st.cache_data(ttl=300)
def get_stock_data_and_analysis(symbol, days=30):
"""獲取股票資料並計算技術指標"""
try:
end_date = datetime.now()
start_date = end_date - timedelta(days=days+50)
stock = yf.Ticker(symbol)
df = stock.history(start=start_date, end=end_date)
if df.empty:
return None, None
df_full = df.copy()
# 計算技術指標
df_full['MA5'] = calculate_ma(df_full['Close'], 5)
df_full['MA10'] = calculate_ma(df_full['Close'], 10)
df_full['MA20'] = calculate_ma(df_full['Close'], 20)
df_full['RSI'] = calculate_rsi(df_full['Close'])
df_full['OBV'] = calculate_obv(df_full['Close'], df_full['Volume'])
bb_upper, bb_middle, bb_lower = calculate_bollinger_bands(df_full['Close'])
df_full['BB_Upper'] = bb_upper
df_full['BB_Middle'] = bb_middle
df_full['BB_Lower'] = bb_lower
df_full['Percent_B'] = calculate_percent_b(df_full['Close'], bb_upper, bb_lower)
macd_line, signal_line, histogram = calculate_macd(df_full['Close'])
df_full['MACD'] = macd_line
df_full['MACD_Signal'] = signal_line
df_full['MACD_Histogram'] = histogram
df_full['Bias_MA5'] = (df_full['Close'] - df_full['MA5']) / df_full['MA5'] * 100
df_full['Bias_MA20'] = (df_full['Close'] - df_full['MA20']) / df_full['MA20'] * 100
df_full['Golden_Cross'] = detect_golden_cross(df_full['MA5'], df_full['MA20'])
df_full['Death_Cross'] = detect_death_cross(df_full['MA5'], df_full['MA20'])
k, d = calculate_kd(df_full['High'], df_full['Low'], df_full['Close'])
df_full['K'] = k
df_full['D'] = d
df_full['CCI'] = calculate_cci(df_full['High'], df_full['Low'], df_full['Close'])
df_full['MFI'] = calculate_mfi(df_full['High'], df_full['Low'], df_full['Close'], df_full['Volume'])
df_full['VWAP'] = calculate_vwap(df_full['High'], df_full['Low'], df_full['Close'], df_full['Volume'])
df_full['ATR'] = calculate_atr(df_full['High'], df_full['Low'], df_full['Close'])
df_result = df_full.tail(days).copy()
# 生成投資建議
recommendations = []
for idx, row in df_result.iterrows():
rec = generate_investment_recommendation(row)
recommendations.append({
'日期': idx,
'收盤價': row['Close'],
'投資建議': rec['recommendation'],
'買進訊號數': rec['buy_signals'],
'賣出訊號數': rec['sell_signals'],
'信心度(%)': rec['confidence'],
'主要原因': rec['reasons']
})
df_recommendations = pd.DataFrame(recommendations)
df_recommendations.set_index('日期', inplace=True)
return df_result, df_recommendations
except Exception as e:
st.error(f"獲取 {symbol} 資料失敗: {e}")
return None, None
def create_candlestick_chart(df, symbol):
"""創建K線圖與技術指標圖表"""
fig = make_subplots(
rows=4, cols=1,
shared_xaxes=True,
vertical_spacing=0.05,
row_heights=[0.5, 0.2, 0.15, 0.15],
subplot_titles=(f'{symbol} K線圖與移動平均線', 'MACD', 'RSI', 'KD指標')
)
# K線圖
fig.add_trace(go.Candlestick(
x=df.index,
open=df['Open'],
high=df['High'],
low=df['Low'],
close=df['Close'],
name='K線'
), row=1, col=1)
# 移動平均線
fig.add_trace(go.Scatter(x=df.index, y=df['MA5'], name='MA5', line=dict(color='blue', width=1)), row=1, col=1)
fig.add_trace(go.Scatter(x=df.index, y=df['MA10'], name='MA10', line=dict(color='orange', width=1)), row=1, col=1)
fig.add_trace(go.Scatter(x=df.index, y=df['MA20'], name='MA20', line=dict(color='red', width=1)), row=1, col=1)
# 布林通道
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)
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)
# MACD
fig.add_trace(go.Scatter(x=df.index, y=df['MACD'], name='MACD', line=dict(color='blue', width=1)), row=2, col=1)
fig.add_trace(go.Scatter(x=df.index, y=df['MACD_Signal'], name='Signal', line=dict(color='red', width=1)), row=2, col=1)
colors = ['green' if val >= 0 else 'red' for val in df['MACD_Histogram']]
fig.add_trace(go.Bar(x=df.index, y=df['MACD_Histogram'], name='Histogram', marker_color=colors), row=2, col=1)
# RSI
fig.add_trace(go.Scatter(x=df.index, y=df['RSI'], name='RSI', line=dict(color='purple', width=2)), row=3, col=1)
fig.add_hline(y=70, line_dash="dash", line_color="red", row=3, col=1)
fig.add_hline(y=30, line_dash="dash", line_color="green", row=3, col=1)
# KD
fig.add_trace(go.Scatter(x=df.index, y=df['K'], name='K', line=dict(color='blue', width=1)), row=4, col=1)
fig.add_trace(go.Scatter(x=df.index, y=df['D'], name='D', line=dict(color='red', width=1)), row=4, col=1)
fig.add_hline(y=80, line_dash="dash", line_color="red", row=4, col=1)
fig.add_hline(y=20, line_dash="dash", line_color="green", row=4, col=1)
fig.update_layout(
height=1000,
showlegend=True,
xaxis_rangeslider_visible=False
)
return fig
def style_dataframe(df, df_type='technical'):
"""為DataFrame添加樣式"""
def highlight_rsi(val):
if pd.isna(val):
return ''
if val < 30:
return 'background-color: yellow'
elif val > 70:
return 'background-color: purple; color: white'
return ''
def highlight_kd(val):
if pd.isna(val):
return ''
if val < 20:
return 'background-color: yellow'
elif val > 80:
return 'background-color: purple; color: white'
return ''
def highlight_recommendation(val):
if val == '強烈買進':
return 'background-color: green; color: white; font-weight: bold'
elif val == '買進':
return 'background-color: lightgreen; font-weight: bold'
elif val == '強烈賣出':
return 'background-color: red; color: white; font-weight: bold'
elif val == '賣出':
return 'background-color: lightcoral; font-weight: bold'
elif val == '持有':
return 'background-color: lightyellow; font-weight: bold'
return ''
styled = df.style
if 'RSI' in df.columns:
styled = styled.applymap(highlight_rsi, subset=['RSI'])
if 'K' in df.columns:
styled = styled.applymap(highlight_kd, subset=['K'])
if 'D' in df.columns:
styled = styled.applymap(highlight_kd, subset=['D'])
if '投資建議' in df.columns:
styled = styled.applymap(highlight_recommendation, subset=['投資建議'])
return styled.format({col: '{:.2f}' for col in df.select_dtypes(include=[np.number]).columns})
# ==================== Streamlit UI ====================
st.title("📈 股票技術分析系統")
st.markdown("---")
# 側邊欄設定
with st.sidebar:
st.header("⚙️ 分析設定")
analysis_mode = st.radio("選擇分析模式", ["單一股票分析", "批次股票分析"])
if analysis_mode == "單一股票分析":
stock_symbol = st.text_input("輸入股票代碼", value="2330.TW", help="例如: 2330.TW, AAPL")
days = st.slider("分析天數", min_value=10, max_value=90, value=30)
if st.button("🔍 開始分析", type="primary"):
st.session_state.analyze_single = True
st.session_state.stock_symbol = stock_symbol
st.session_state.days = days
else:
st.markdown("### 預設股票清單")
default_stocks = [
"2330.TW", "2454.TW", "3661.TW", "3443.TW", "3035.TW",
"3017.TW", "3324.TW", "2379.TW", "3037.TW", "3189.TW",
"2317.TW", "2382.TW", "3231.TW", "6669.TW", "2356.TW",
"2376.TW", "2308.TW", "3533.TW", "2357.TW", "2377.TW",
"2353.TW", "2395.TW", "6811.TW", "6841.TW", "2359.TW"
]
custom_stocks = st.text_area(
"自訂股票清單(每行一個代碼)",
value="\n".join(default_stocks),
height=200
)
days_batch = st.slider("分析天數", min_value=10, max_value=90, value=30, key="batch_days")
if st.button("🚀 開始批次分析", type="primary"):
stock_list = [s.strip() for s in custom_stocks.split("\n") if s.strip()]
st.session_state.analyze_batch = True
st.session_state.stock_list = stock_list
st.session_state.days_batch = days_batch
# 單一股票分析
if hasattr(st.session_state, 'analyze_single') and st.session_state.analyze_single:
st.header(f"📊 {st.session_state.stock_symbol} 技術分析")
with st.spinner('正在獲取數據並計算指標...'):
df, df_rec = get_stock_data_and_analysis(st.session_state.stock_symbol, st.session_state.days)
if df is not None and df_rec is not None:
# 最新投資建議
latest_rec = df_rec.iloc[-1]
latest_data = df.iloc[-1]
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("收盤價", f"${latest_data['Close']:.2f}")
with col2:
rec_color = {
'強烈買進': '🟢', '買進': '🟡',
'持有': '⚪', '賣出': '🟠', '強烈賣出': '🔴'
}
st.metric("投資建議", f"{rec_color.get(latest_rec['投資建議'], '')} {latest_rec['投資建議']}")
with col3:
st.metric("信心度", f"{latest_rec['信心度(%)']:.0f}%")
with col4:
st.metric("RSI", f"{latest_data['RSI']:.2f}")
st.info(f"**主要原因:** {latest_rec['主要原因']}")
# 圖表
st.plotly_chart(create_candlestick_chart(df, st.session_state.stock_symbol), use_container_width=True)
# 技術指標表格
tab1, tab2 = st.tabs(["📋 技術指標", "💡 投資建議"])
with tab1:
st.dataframe(style_dataframe(df.tail(10)), use_container_width=True, height=400)
with tab2:
st.dataframe(style_dataframe(df_rec.tail(10), 'recommendation'), use_container_width=True, height=400)
# 下載按鈕
st.markdown("---")
col1, col2 = st.columns(2)
with col1:
csv = df.to_csv(encoding='utf-8-sig')
st.download_button(
"📥 下載技術指標 CSV",
csv,
f"{st.session_state.stock_symbol}_技術指標.csv",
"text/csv"
)
with col2:
csv_rec = df_rec.to_csv(encoding='utf-8-sig')
st.download_button(
"📥 下載投資建議 CSV",
csv_rec,
f"{st.session_state.stock_symbol}_投資建議.csv",
"text/csv"
)
# 批次股票分析
elif hasattr(st.session_state, 'analyze_batch') and st.session_state.analyze_batch:
st.header(f"🔍 批次股票分析(共 {len(st.session_state.stock_list)} 支)")
progress_bar = st.progress(0)
status_text = st.empty()
summary_data = []
for i, symbol in enumerate(st.session_state.stock_list):
progress = (i + 1) / len(st.session_state.stock_list)
progress_bar.progress(progress)
status_text.text(f"正在分析 {symbol} ({i+1}/{len(st.session_state.stock_list)})")
df, df_rec = get_stock_data_and_analysis(symbol, st.session_state.days_batch)
if df is not None and df_rec is not None:
latest = df.iloc[-1]
latest_rec = df_rec.iloc[-1]
summary_data.append({
'股票代號': symbol,
'收盤價': latest['Close'],
'RSI': latest['RSI'],
'K': latest['K'],
'D': latest['D'],
'MACD': latest['MACD'],
'投資建議': latest_rec['投資建議'],
'信心度(%)': latest_rec['信心度(%)'],
'買進訊號': latest_rec['買進訊號數'],
'賣出訊號': latest_rec['賣出訊號數'],
'黃金交叉': '是' if latest['Golden_Cross'] else '否',
'死亡交叉': '是' if latest['Death_Cross'] else '否',
'主要原因': latest_rec['主要原因']
})
progress_bar.empty()
status_text.empty()
if summary_data:
df_summary = pd.DataFrame(summary_data)
st.success(f"✅ 成功分析 {len(summary_data)} 支股票!")
# 統計圖表
st.subheader("📊 投資建議統計")
rec_counts = df_summary['投資建議'].value_counts()
fig_pie = go.Figure(data=[go.Pie(labels=rec_counts.index, values=rec_counts.values)])
fig_pie.update_layout(title="投資建議分布")
st.plotly_chart(fig_pie, use_container_width=True)
# 總覽表格
st.subheader("📋 股票總覽")
st.dataframe(style_dataframe(df_summary, 'recommendation'), use_container_width=True, height=600)
# 下載CSV
csv_summary = df_summary.to_csv(index=False, encoding='utf-8-sig')
st.download_button(
"📥 下載批次分析結果 CSV",
csv_summary,
f"批次分析_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
"text/csv"
)
else:
st.info("👈 請在左側選擇分析模式並設定參數後開始分析")
st.markdown("""
### 功能說明
**單一股票分析**
- 提供完整的技術指標圖表
- 顯示 K線圖、MACD、RSI、KD 等多種技術指標
- 自動生成投資建議與信心度評估
- 支援黃金交叉與死亡交叉偵測
- 可下載技術指標與投資建議 CSV 報表
**批次股票分析**
- 同時分析多支股票
- 快速比較投資建議
- 視覺化投資建議分布統計
- 匯出完整批次分析結果
### 技術指標說明
- **MA (移動平均線)**: MA5、MA10、MA20 短中長期趨勢
- **RSI (相對強弱指標)**: 超買 >70,超賣 <30
- **MACD**: 趨勢追蹤指標,觀察多空動能
- **KD (隨機指標)**: 超買 >80,超賣 <20
- **布林通道**: 價格波動區間,突破上下軌為訊號
- **MFI (資金流量指標)**: 結合價量的超買超賣指標
- **CCI (商品通道指標)**: 衡量價格偏離程度
- **OBV (能量潮)**: 累積成交量變化
- **VWAP (成交量加權平均價)**: 當日平均成本
- **ATR (真實波動幅度)**: 衡量價格波動程度
### 投資建議判斷邏輯
系統會綜合多個技術指標產生投資建議:
- **強烈買進**: 多個指標顯示強烈超賣或黃金交叉
- **買進**: 偏多訊號較明顯
- **持有**: 多空訊號相當
- **賣出**: 偏空訊號較明顯
- **強烈賣出**: 多個指標顯示強烈超買或死亡交叉
---
⚠️ **風險提示**: 本系統僅供參考,不構成投資建議。投資有風險,請謹慎評估。
""")