File size: 3,621 Bytes
cc14865
 
10cd19c
 
cc14865
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10cd19c
cc14865
 
 
 
 
 
10cd19c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc14865
 
 
 
 
 
 
10cd19c
cc14865
 
10cd19c
 
 
 
cc14865
 
 
 
 
 
 
 
10cd19c
 
cc14865
10cd19c
 
 
 
cc14865
 
 
 
 
 
10cd19c
 
 
 
 
 
 
 
 
 
 
 
 
cc14865
10cd19c
 
 
 
 
 
 
 
 
 
 
 
 
 
cc14865
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
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()