import streamlit as st import twstock import pandas as pd import matplotlib.pyplot as plt def fetch_recent_stock_data(stock_code): """ 使用 twstock 獲取近期股票交易數據 """ try: stock = twstock.Stock(stock_code) recent_data = stock.fetch_31() # 抓取最近 31 天的交易數據 if not recent_data: st.warning(f"無法找到 {stock_code} 的交易數據。") return None # 將數據整理為 DataFrame 格式 data_list = [ { "Date": data.date.strftime('%Y-%m-%d'), "Open": data.open, "High": data.high, "Low": data.low, "Close": data.close, "Transaction": data.transaction, "Capacity": data.capacity, "Turnover": data.turnover } for data in recent_data ] df = pd.DataFrame(data_list) df['Date'] = pd.to_datetime(df['Date']) return df except Exception as e: st.error(f"發生錯誤: {e}") return None def plot_stock_price(df): """ 使用 matplotlib 繪製股價走勢 """ plt.figure(figsize=(12, 6)) plt.plot(df['Date'], df['Close'], label='收盤價') plt.plot(df['Date'], df['Close'].rolling(window=5).mean(), label='5日移動平均', linestyle='--') plt.title('股價走勢') plt.xlabel('日期') plt.ylabel('股價') plt.legend() plt.xticks(rotation=45) plt.tight_layout() return plt def main(): st.set_page_config(page_title="台股分析工具", page_icon=":chart_with_upwards_trend:", layout="wide") st.title("🚀 台股分析工具") # 側邊欄設置 with st.sidebar: st.header("股票分析") # 股票代碼輸入 stock_code = st.text_input( "股票代號", value="2330", placeholder="例如: 2330" ) # 股票分析頁籤 tab1, tab2 = st.tabs(["股價走勢圖", "近期交易數據"]) with tab1: # 股價走勢圖 if st.button("繪製股價走勢圖"): # 獲取股票數據 df = fetch_recent_stock_data(stock_code) if df is not None: # 繪製股價圖 fig = plot_stock_price(df) st.pyplot(fig) with tab2: # 近期交易數據 st.subheader("個股近期交易數據") if st.button("查詢交易數據"): # 獲取近期股票數據 df = fetch_recent_stock_data(stock_code) if df is not None: # 顯示數據 st.dataframe(df) # 統計資訊 st.subheader("基本統計") col1, col2, col3 = st.columns(3) with col1: st.metric("平均收盤價", f"{df['Close'].mean():.2f}") with col2: st.metric("最高價", f"{df['High'].max():.2f}") with col3: st.metric("最低價", f"{df['Low'].min():.2f}") # 匯出 CSV csv_data = df.to_csv(index=False).encode('utf-8-sig') st.download_button( label="下載CSV", data=csv_data, file_name=f"{stock_code}_recent_30days.csv", mime="text/csv" ) if __name__ == "__main__": main()